{
  "schemaVersion": "1.0",
  "canonicalPage": "https://fileformat.co/ext/safetensors",
  "inspectorUrl": "https://fileformat.co/inspect",
  "spec": {
    "slug": "safetensors",
    "extension": ".safetensors",
    "aliases": [],
    "name": "SafeTensors Zero-Copy Model Weights",
    "shortName": "SafeTensors",
    "category": "ai-ml",
    "tier": 1,
    "summary": "Hugging Face's memory-safe, zero-copy tensor serialization format designed to replace Pickle-based PyTorch checkpoints without arbitrary code execution risks.",
    "technicalNotes": "Starts with an 8-byte unsigned little-endian integer N giving the exact byte length of the UTF-8 JSON header at [8 .. 8+N], followed immediately by raw aligned tensor byte buffers. Apple Silicon MLX quantized checkpoints reuse this exact framing (`__metadata__.format = 'mlx'`): 4-bit/8-bit weights are packed into U32 tensors (8 or 4 nibbles per lane) alongside per-group F16/BF16 `scales` and `biases` entries, with `quantization_bits`/`quantization_group_size` declared in `__metadata__`. There is no separate `.mlx` container extension—`.mlx` is MATLAB Live Script (a ZIP/OPC package); MLX weight files are distributed as `.safetensors` or `.npz`.",
    "mimeTypes": [
      "application/octet-stream"
    ],
    "identifiers": {
      "specUrl": "https://huggingface.co/docs/safetensors/index"
    },
    "binarySignature": {
      "endianness": "little",
      "magicBytes": [
        {
          "offset": 8,
          "hex": "7B 22",
          "ascii": "{\"",
          "description": "UTF-8 JSON header object opening immediately after uint64_le header_size"
        }
      ],
      "containerFamily": null,
      "headerLayout": [
        {
          "offset": "0x00 - 0x07",
          "byteOffset": 0,
          "byteLength": 8,
          "lengthLabel": "8 B",
          "dataType": "uint64_le",
          "fieldName": "header_size",
          "description": "Byte length N of the UTF-8 JSON header"
        },
        {
          "offset": "0x08 - 8+N",
          "byteOffset": 8,
          "byteLength": 32,
          "lengthLabel": "N B (dynamic)",
          "dataType": "utf8_json",
          "fieldName": "json_header",
          "description": "Tensor dtype, shape, data_offsets & optional __metadata__"
        }
      ]
    },
    "securityProfile": {
      "riskLevel": "low",
      "allowsArbitraryCodeOrMacros": false,
      "xxeRisk": false,
      "polyglotPrependRisk": false,
      "pickleDeserializationRisk": false,
      "uploadValidationNotes": "Cap header_size N (e.g. <= 100 MB) before allocating buffer, parse UTF-8 JSON without duplicate keys, and verify every tensor's [begin, end] offset is non-overlapping and <= file_size - 8 - N."
    },
    "codeSnippets": {
      "python": "import json, struct, sys\nwith open(sys.argv[1], \"rb\") as f:\n    (n,) = struct.unpack(\"<Q\", f.read(8))\n    header = json.loads(f.read(n).decode(\"utf-8\"))\n    tensors = [k for k in header if k != \"__metadata__\"]\n    print(f\"SafeTensors header={n}B, tensors={len(tensors)}\")",
      "typescript": "export async function readSafeTensorsIndex(file: File) {\n  const lenView = new DataView(await file.slice(0, 8).arrayBuffer());\n  const n = Number(lenView.getBigUint64(0, true));\n  const jsonText = new TextDecoder().decode(await file.slice(8, 8 + n).arrayBuffer());\n  return JSON.parse(jsonText);\n}",
      "rust": "use std::{fs::File, io::Read};\nfn main() -> std::io::Result<()> {\n    let mut f = File::open(std::env::args().nth(1).expect(\"usage: <prog> <file>\"))?;\n    let mut len_b = [0u8; 8]; f.read_exact(&mut len_b)?;\n    let n = u64::from_le_bytes(len_b) as usize;\n    let mut hdr = vec![0u8; n]; f.read_exact(&mut hdr)?;\n    println!(\"Header JSON: {} bytes\", hdr.len());\n    Ok(())\n}",
      "go": "package main\nimport (\"encoding/binary\"; \"fmt\"; \"io\"; \"os\")\nfunc main() {\n    f, err := os.Open(os.Args[1])\n    if err != nil {\n        fmt.Fprintln(os.Stderr, \"open:\", err)\n        os.Exit(1)\n    }\n    defer f.Close()\n    var n uint64; if err := binary.Read(f, binary.LittleEndian, &n); err != nil {\n        fmt.Fprintln(os.Stderr, \"read header:\", err)\n        os.Exit(1)\n    }\n    buf := make([]byte, n)\n    if _, err := io.ReadFull(f, buf); err != nil {\n        fmt.Fprintln(os.Stderr, \"read:\", err)\n        os.Exit(1)\n    }\n    fmt.Printf(\"SafeTensors JSON (%d B)\\n\", n)\n}"
    },
    "relatedFormats": [
      "gguf",
      "pt",
      "npz"
    ],
    "verifiedAt": "2026-11-14T16:09:03Z"
  },
  "samples": [
    {
      "id": "safetensors-minimal",
      "filename": "minimal-bf16.safetensors",
      "variant": "minimal",
      "title": "Minimal BF16/F16/F32 SafeTensors",
      "description": "Real safetensors.torch output with __metadata__ and 3 tensors across BF16, F16, and F32 dtypes.",
      "localPath": "/fixtures/v1/safetensors/minimal-bf16.safetensors",
      "cdnUrl": "https://fileformat.co/fixtures/v1/safetensors/minimal-bf16.safetensors",
      "sizeBytes": 432,
      "sha256": "0d9894b505b77ec0d719fa112eead1695c8a2be9e1820c81267dfe1a64a2214b",
      "expectValid": true
    },
    {
      "id": "safetensors-realistic",
      "filename": "weights-bf16.safetensors",
      "variant": "realistic",
      "title": "Realistic Transformer Layer SafeTensors",
      "description": "Multi-layer transformer weight shard written by safetensors.torch with exact contiguous data_offsets.",
      "localPath": "/fixtures/v1/safetensors/weights-bf16.safetensors",
      "cdnUrl": "https://fileformat.co/fixtures/v1/safetensors/weights-bf16.safetensors",
      "sizeBytes": 3560,
      "sha256": "7594cbd039f2978e74012d1e761368a7d18f2f6efe6038e11a869f6d1c5a6b7f",
      "expectValid": true
    },
    {
      "id": "safetensors-edge-case",
      "filename": "unaligned-truncated.safetensors",
      "variant": "edge-case",
      "title": "Unaligned Offsets & Truncated Tensor Payload",
      "description": "Negative fixture with non-zero starting data_offsets [3, 8195] and truncated 24-byte body — safetensors must raise.",
      "localPath": "/fixtures/v1/safetensors/unaligned-truncated.safetensors",
      "cdnUrl": "https://fileformat.co/fixtures/v1/safetensors/unaligned-truncated.safetensors",
      "sizeBytes": 138,
      "sha256": "70d504e4e3dc7cc38bf0d72fe83b78badaf96f16be32402100c1450a9bb2e004",
      "expectValid": false,
      "edgeCaseTag": "Unaligned + Truncated EOF"
    }
  ]
}