{"id":13478188,"url":"https://github.com/huggingface/safetensors","last_synced_at":"2025-05-05T22:56:00.602Z","repository":{"id":59915607,"uuid":"540033828","full_name":"huggingface/safetensors","owner":"huggingface","description":"Simple, safe way to store and distribute tensors","archived":false,"fork":false,"pushed_at":"2025-05-05T19:35:27.000Z","size":1416,"stargazers_count":3251,"open_issues_count":25,"forks_count":247,"subscribers_count":41,"default_branch":"main","last_synced_at":"2025-05-05T22:55:47.090Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://huggingface.co/docs/safetensors","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/huggingface.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2022-09-22T14:54:51.000Z","updated_at":"2025-05-05T19:32:43.000Z","dependencies_parsed_at":"2024-01-04T11:32:19.942Z","dependency_job_id":"0e568219-c85e-4734-960e-5a7d2c9a23fb","html_url":"https://github.com/huggingface/safetensors","commit_stats":{"total_commits":295,"total_committers":47,"mean_commits":6.276595744680851,"dds":0.2915254237288135,"last_synced_commit":"f5839b6aee407652aa3078d91206b618dd84e3c2"},"previous_names":[],"tags_count":38,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/huggingface%2Fsafetensors","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/huggingface%2Fsafetensors/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/huggingface%2Fsafetensors/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/huggingface%2Fsafetensors/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/huggingface","download_url":"https://codeload.github.com/huggingface/safetensors/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252590551,"owners_count":21772936,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T16:01:53.660Z","updated_at":"2025-05-05T22:56:00.580Z","avatar_url":"https://github.com/huggingface.png","language":"Python","funding_links":[],"categories":["Open Source Security Tools","Python","General","Machine Learning","Data Storage Optimisation","Libraries by Language","Repos","Other Versions of YOLO","Summary","Frameworks","Tokenization \u0026 ML","Official Resources","其他_机器学习与深度学习","Built On","Language Models","Machine Learning \u0026 AI","1. Core Frameworks \u0026 Libraries"],"sub_categories":["Python","`GET /v1/metrics` — Performance stats","Model Formats"],"readme":"\u003cp align=\"center\"\u003e\n  \u003cpicture\u003e\n    \u003csource media=\"(prefers-color-scheme: dark)\" srcset=\"https://huggingface.co/datasets/safetensors/assets/raw/main/banner-dark.svg\"\u003e\n    \u003csource media=\"(prefers-color-scheme: light)\" srcset=\"https://huggingface.co/datasets/safetensors/assets/raw/main/banner-light.svg\"\u003e\n    \u003cimg alt=\"Hugging Face Safetensors Library\" src=\"https://huggingface.co/datasets/safetensors/assets/raw/main/banner-light.svg\" style=\"max-width: 100%;\"\u003e\n  \u003c/picture\u003e\n  \u003cbr/\u003e\n  \u003cbr/\u003e\n\u003c/p\u003e\n\nPython\n[![Pypi](https://img.shields.io/pypi/v/safetensors.svg)](https://pypi.org/pypi/safetensors/)\n[![Documentation](https://img.shields.io/website/http/huggingface.co/docs/safetensors/index.svg?label=docs)](https://huggingface.co/docs/safetensors/index)\n[![Codecov](https://codecov.io/github/huggingface/safetensors/coverage.svg?branch=main)](https://codecov.io/gh/huggingface/safetensors)\n[![Downloads](https://static.pepy.tech/badge/safetensors/month)](https://pepy.tech/project/safetensors)\n\nRust\n[![Crates.io](https://img.shields.io/crates/v/safetensors.svg)](https://crates.io/crates/safetensors)\n[![Documentation](https://docs.rs/safetensors/badge.svg)](https://docs.rs/safetensors/)\n[![Codecov](https://codecov.io/github/huggingface/safetensors/coverage.svg?branch=main)](https://codecov.io/gh/huggingface/safetensors)\n[![Dependency status](https://deps.rs/repo/github/huggingface/safetensors/status.svg?path=safetensors)](https://deps.rs/repo/github/huggingface/safetensors?path=safetensors)\n\n# safetensors\n\n## Safetensors\n\nThis repository implements a new simple format for storing tensors\nsafely (as opposed to pickle) and that is still fast (zero-copy).\n\n### Installation\n#### Pip\n\nYou can install safetensors via the pip manager:\n\n```bash\npip install safetensors\n```\n\n#### From source\n\nFor the sources, you need Rust\n\n```bash\n# Install Rust\ncurl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh\n# Make sure it's up to date and using stable channel\nrustup update\ngit clone https://github.com/huggingface/safetensors\ncd safetensors/bindings/python\npip install setuptools_rust\npip install -e .\n```\n\n### Getting started\n\n```python\nimport torch\nfrom safetensors import safe_open\nfrom safetensors.torch import save_file\n\ntensors = {\n   \"weight1\": torch.zeros((1024, 1024)),\n   \"weight2\": torch.zeros((1024, 1024))\n}\nsave_file(tensors, \"model.safetensors\")\n\ntensors = {}\nwith safe_open(\"model.safetensors\", framework=\"pt\", device=\"cpu\") as f:\n   for key in f.keys():\n       tensors[key] = f.get_tensor(key)\n```\n\n[Python documentation](https://huggingface.co/docs/safetensors/index)\n\n\n### Format\n\n- 8 bytes: `N`, an unsigned little-endian 64-bit integer, containing the size of the header\n- N bytes: a JSON UTF-8 string representing the header.\n  - The header data MUST begin with a `{` character (0x7B).\n  - The header data MAY be trailing padded with whitespace (0x20).\n  - The header is a dict like `{\"TENSOR_NAME\": {\"dtype\": \"F16\", \"shape\": [1, 16, 256], \"data_offsets\": [BEGIN, END]}, \"NEXT_TENSOR_NAME\": {...}, ...}`,\n    - `data_offsets` point to the tensor data relative to the beginning of the byte buffer (i.e. not an absolute position in the file),\n      with `BEGIN` as the starting offset and `END` as the one-past offset (so total tensor byte size = `END - BEGIN`).\n  - A special key `__metadata__` is allowed to contain free form string-to-string map. Arbitrary JSON is not allowed, all values must be strings.\n- Rest of the file: byte-buffer.\n\nNotes:\n - Duplicate keys are disallowed. Not all parsers may respect this.\n - In general the subset of JSON is implicitly decided by `serde_json` for\n   this library. Anything obscure might be modified at a later time, that odd ways\n   to represent integer, newlines and escapes in utf-8 strings. This would only\n   be done for safety concerns\n - Tensor values are not checked against, in particular NaN and +/-Inf could\n   be in the file\n - Empty tensors (tensors with 1 dimension being 0) are allowed.\n   They are not storing any data in the databuffer, yet retaining size in the header.\n   They don't really bring a lot of values but are accepted since they are valid tensors\n   from traditional tensor libraries perspective (torch, tensorflow, numpy, ..).\n - 0-rank Tensors (tensors with shape `[]`) are allowed, they are merely a scalar.\n - The byte buffer needs to be entirely indexed, and cannot contain holes. This prevents\n   the creation of polyglot files.\n - Endianness: Little-endian.\n   moment.\n - Order: 'C' or row-major.\n\n\n### Yet another format ?\n\nThe main rationale for this crate is to remove the need to use\n`pickle` on `PyTorch` which is used by default.\nThere are other formats out there used by machine learning and more general\nformats.\n\n\nLet's take a look at alternatives and why this format is deemed interesting.\nThis is my very personal and probably biased view:\n\n| Format                  | Safe | Zero-copy | Lazy loading | No file size limit | Layout control | Flexibility | Bfloat16/Fp8\n| ----------------------- | --- | --- | --- | --- | --- | --- | --- |\n| pickle (PyTorch)        | ✗ | ✗ | ✗ | 🗸 | ✗ | 🗸 | 🗸 |\n| H5 (Tensorflow)         | 🗸 | ✗ | 🗸 | 🗸 | ~ | ~ | ✗ |\n| SavedModel (Tensorflow) | 🗸 | ✗ | ✗ | 🗸 | 🗸 | ✗ | 🗸 |\n| MsgPack (flax)          | 🗸 | 🗸 | ✗ | 🗸 | ✗ | ✗ | 🗸 |\n| Protobuf (ONNX)         | 🗸 | ✗ | ✗ | ✗ | ✗ | ✗ | 🗸 |\n| Cap'n'Proto             | 🗸 | 🗸 | ~ | 🗸 | 🗸 | ~ | ✗ |\n| Arrow                   | ? | ? | ? | ? | ? | ? | ✗ |\n| Numpy (npy,npz)         | 🗸 | ? | ? | ✗ | 🗸 | ✗ | ✗ |\n| pdparams (Paddle)       | ✗ | ✗ | ✗ | 🗸 | ✗ | 🗸 | 🗸 |\n| SafeTensors             | 🗸 | 🗸 | 🗸 | 🗸 | 🗸 | ✗ | 🗸 |\n\n- Safe: Can I use a file randomly downloaded and expect not to run arbitrary code ?\n- Zero-copy: Does reading the file require more memory than the original file ?\n- Lazy loading: Can I inspect the file without loading everything ? And loading only\n  some tensors in it without scanning the whole file (distributed setting) ?\n- Layout control: Lazy loading, is not necessarily enough since if the information about tensors is spread out in your file, then even if the information is lazily accessible you might have to access most of your file to read the available tensors (incurring many DISK -\u003e RAM copies). Controlling the layout to keep fast access to single tensors is important.\n- No file size limit: Is there a limit to the file size ?\n- Flexibility: Can I save custom code in the format and be able to use it later with zero extra code ? (~ means we can store more than pure tensors, but no custom code)\n- Bfloat16/Fp8: Does the format support native bfloat16/fp8 (meaning no weird workarounds are\n  necessary)? This is becoming increasingly important in the ML world.\n\n\n### Main oppositions\n\n- Pickle: Unsafe, runs arbitrary code\n- H5: Apparently now discouraged for TF/Keras. Seems like a great fit otherwise actually. Some classic use after free issues: \u003chttps://www.cvedetails.com/vulnerability-list/vendor_id-15991/product_id-35054/Hdfgroup-Hdf5.html\u003e. On a very different level than pickle security-wise. Also 210k lines of code vs ~400 lines for this lib currently.\n- SavedModel: Tensorflow specific (it contains TF graph information).\n- MsgPack: No layout control to enable lazy loading (important for loading specific parts in distributed setting)\n- Protobuf: Hard 2Go max file size limit\n- Cap'n'proto: Float16 support is not present [link](https://capnproto.org/language.html#built-in-types) so using a manual wrapper over a byte-buffer would be necessary. Layout control seems possible but not trivial as buffers have limitations [link](https://stackoverflow.com/questions/48458839/capnproto-maximum-filesize).\n- Numpy (npz): No `bfloat16` support. Vulnerable to zip bombs (DOS). Not zero-copy.\n- Arrow: No `bfloat16` support.\n\n### Notes\n\n- Zero-copy: No format is really zero-copy in ML, it needs to go from disk to RAM/GPU RAM (that takes time). On CPU, if the file is already in cache, then it can\n  truly be zero-copy, whereas on GPU there is not such disk cache, so a copy is always required\n  but you can bypass allocating all the tensors on CPU at any given point.\n  SafeTensors is not zero-copy for the header. The choice of JSON is pretty arbitrary, but since deserialization is \u003c\u003c\u003c of the time required to load the actual tensor data and is readable I went that way, (also space is \u003c\u003c\u003c to the tensor data).\n\n- Endianness: Little-endian. This can be modified later, but it feels really unnecessary at the\n  moment.\n- Order: 'C' or row-major. This seems to have won. We can add that information later if needed.\n- Stride: No striding, all tensors need to be packed before being serialized. I have yet to see a case where it seems useful to have a strided tensor stored in serialized format.\n\n### Benefits\n\nSince we can invent a new format we can propose additional benefits:\n\n- Prevent DOS attacks: We can craft the format in such a way that it's almost\n  impossible to use malicious files to DOS attack a user. Currently, there's a limit\n  on the size of the header of 100MB to prevent parsing extremely large JSON.\n  Also when reading the file, there's a guarantee that addresses in the file\n  do not overlap in any way, meaning when you're loading a file you should never\n  exceed the size of the file in memory\n\n- Faster load: PyTorch seems to be the fastest file to load out in the major\n  ML formats. However, it does seem to have an extra copy on CPU, which we\n  can bypass in this lib by using `torch.UntypedStorage.from_file`.\n  Currently, CPU loading times are extremely fast with this lib compared to pickle.\n  GPU loading times are as fast or faster than PyTorch equivalent.\n  Loading first on CPU with memmapping with torch, and then moving all tensors to GPU seems\n  to be faster too somehow (similar behavior in torch pickle)\n\n- Lazy loading: in distributed (multi-node or multi-gpu) settings, it's nice to be able to\n  load only part of the tensors on the various models. For\n  [BLOOM](https://huggingface.co/bigscience/bloom) using this format enabled\n  to load the model on 8 GPUs from 10mn with regular PyTorch weights down to 45s.\n  This really speeds up feedbacks loops when developing on the model. For instance\n  you don't have to have separate copies of the weights when changing the distribution\n  strategy (for instance Pipeline Parallelism vs Tensor Parallelism).\n\nLicense: Apache-2.0\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhuggingface%2Fsafetensors","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhuggingface%2Fsafetensors","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhuggingface%2Fsafetensors/lists"}