SafeTensors Format Guide

    由 HuggingFace 開發的安全快速模型權重儲存格式

    Model Weights

    Specification

    SafeTensors 是由 Hugging Face 開發的二進位檔案格式,用於安全地儲存和載入機器學習模型權重。作為 2023 年推出的 Python 基於 pickle 格式(PyTorch .bin、.pt 檔案)的安全替代方案,SafeTensors 消除了 pickle 反序列化固有的任意程式碼執行漏洞。當您載入基於 pickle 的模型檔案時,嵌入在檔案中的任意 Python 程式碼會自動執行——從不受信任的來源載入模型時這是一個嚴重的安全風險。SafeTensors 僅儲存張量資料和中繼資料,使嵌入可執行程式碼成為不可能。

    SafeTensors 格式使用簡單的結構:一個 8 位元組的標頭大小(小端 uint64)、一個包含張量中繼資料(名稱、資料型別、形狀和位元組偏移)的 JSON 標頭,以及原始張量資料。該格式支援所有常見的數值型別,包括 float32、float16、bfloat16、int8、int32 和 int64。張量在記憶體中連續儲存,透過記憶體映射實現零複製載入——張量資料可以直接從磁碟存取,無需將其複製到單獨的記憶體緩衝區。

    SafeTensors 已被採納為 Hugging Face Hub 上的預設模型格式,大多數模型儲存庫可進行自動轉換。包括 PyTorch、TensorFlow、JAX 和 ONNX Runtime 在內的主要機器學習框架都支援載入 SafeTensors 檔案。該格式還支援分片儲存,其中單一模型的權重分布在多個檔案中,並有一個索引檔案將張量名稱映射到各自的分片——這對於太大而無法放入單一檔案的模型至關重要。

    When to Use SafeTensors

    SafeTensors 應該是您在開發期間儲存和分發模型權重以及基於 GPU 推論的預設格式。它是 Hugging Face Hub 上的標準格式,並受到所有主要訓練和推論框架的支援。每當您儲存訓練檢查點、與協作者分享模型、將模型上傳到模型註冊表,或使用 vLLM、TGI 或 Triton 等 GPU 推論伺服器部署模型時,都請使用 SafeTensors。

    出於安全考量,選擇 SafeTensors 而非基於 pickle 的 PyTorch 格式(.bin、.pt)——SafeTensors 不能包含可執行程式碼,消除了透過惡意模型檔案進行供應鏈攻擊的風險。當您需要全精度權重用於繼續訓練或 GPU 加速推論時,選擇 SafeTensors 而非 GGUF,因為 GGUF 是為量化 CPU 推論設計的。由於記憶體映射和無反序列化開銷,SafeTensors 的載入速度顯著快於 pickle 檔案。

    當您的目標部署是基於 CPU 的本地推論(請改用 GGUF)或需要帶有運行時最佳化的跨框架可攜性(考慮 ONNX)時,SafeTensors 不太適合。對於格式開銷比例較大的非常小的模型,它也不是正確的選擇,儘管在實踐中這很少是一個問題。

    Schema / Structure

    json
    {
      "__metadata__": {
        "format": "pt"
      },
      "model.embed_tokens.weight": {
        "dtype": "F16",
        "shape": [32000, 4096],
        "data_offsets": [0, 262144000]
      },
      "model.layers.0.self_attn.q_proj.weight": {
        "dtype": "F16",
        "shape": [4096, 4096],
        "data_offsets": [262144000, 295698432]
      },
      "model.layers.0.self_attn.k_proj.weight": {
        "dtype": "F16",
        "shape": [4096, 4096],
        "data_offsets": [295698432, 329252864]
      }
    }
    SafeTensors JSON 標頭,展示張量中繼資料,包含名稱、資料型別、形狀和位元組偏移

    Example Data

    python
    from safetensors.torch import save_file, load_file
    import torch
    
    # Save model weights to SafeTensors
    tensors = {
        "model.embed_tokens.weight": torch.randn(32000, 4096, dtype=torch.float16),
        "model.layers.0.self_attn.q_proj.weight": torch.randn(4096, 4096, dtype=torch.float16),
        "model.layers.0.self_attn.v_proj.weight": torch.randn(4096, 4096, dtype=torch.float16),
        "lm_head.weight": torch.randn(32000, 4096, dtype=torch.float16),
    }
    metadata = {"format": "pt", "model_type": "llama"}
    save_file(tensors, "model.safetensors", metadata=metadata)
    
    # Load weights (zero-copy with memory mapping)
    loaded = load_file("model.safetensors", device="cuda:0")
    print(loaded["model.embed_tokens.weight"].shape)  # torch.Size([32000, 4096])
    
    # Load a Hugging Face model using SafeTensors
    from transformers import AutoModelForCausalLM
    model = AutoModelForCausalLM.from_pretrained(
        "meta-llama/Llama-3-8B",
        torch_dtype=torch.float16,
        use_safetensors=True  # default on HF Hub
    )
    使用 PyTorch 和 Hugging Face Transformers 儲存、載入和使用 SafeTensors

    Ertas Support

    每個 Ertas Studio 訓練任務都會產出 safetensors 檔案。訓練出的 LoRA 介面卡會存成 safetensors(LoRA 下載套件中的 adapter_model.safetensors);若在送出訓練任務前,於 Training Config 勾選「Export full model (16-bit safetensors)」,完整的合併檢查點(基礎權重加上您的介面卡)也會一併存入 Hub,並附上 config.json 與分詞器檔案。

    合併後的 safetensors 匯出有兩個用途。它是您在 GPU 基礎架構上以 vLLM 或其他相容 Transformers 的伺服器提供服務的檢查點,也是您接續訓練的檢查點:合併後的模型可透過 Continue from your models 選為下一次訓練的基礎模型,每一輪訓練都把新的介面卡併入一個屬於您的模型。若需要裝置端使用的檔案,同一個檢查點也能用 llama.cpp 轉換為 GGUF。

    Related Resources

    Ship AI that runs on your users' devices.

    Start free with 150 credits after card verification. Paid plans from $20/mo USD.