Safetensors 文件

元資料解析

您正在檢視的是需要從原始碼安裝。如果你想透過 pip 常規安裝,請檢視最新的穩定版本(v0.5.0-rc.0)。
Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

元資料解析

鑑於該格式的簡潔性,使用小範圍的 (Range)HTTP 請求 來獲取和解析 Safetensors 權重的元資料(即張量列表、它們的型別、形狀或引數數量)非常簡單和高效。

此解析功能已在 huggingface.js 中用 JS 實現(示例程式碼如下),但在任何其他語言中實現也類似。

用例示例

可能會有很多潛在的用例。例如,我們在 Hugging Face Hub 上使用它來顯示具有 safetensors 權重的模型資訊。

用法

http
javascript
python

🤗 Hub 上,你可以使用 HTTP 範圍請求 獲取模型的元資料,而無需下載包含所有權重的整個 safetensors 檔案。在下面的這個 python 指令碼示例中(你可以使用任何支援 HTTP 請求的語言),我們正在解析 gpt2 的元資料。

import requests # pip install requests
import struct

def parse_single_file(url):
    # Fetch the first 8 bytes of the file
    headers = {'Range': 'bytes=0-7'}
    response = requests.get(url, headers=headers)
    # Interpret the bytes as a little-endian unsigned 64-bit integer
    length_of_header = struct.unpack('<Q', response.content)[0]
    # Fetch length_of_header bytes starting from the 9th byte
    headers = {'Range': f'bytes=8-{7 + length_of_header}'}
    response = requests.get(url, headers=headers)
    # Interpret the response as a JSON object
    header = response.json()
    return header

url = "https://huggingface.co/gpt2/resolve/main/model.safetensors"
header = parse_single_file(url)

print(header)
# {
#   "__metadata__": { "format": "pt" },
#   "h.10.ln_1.weight": {
#     "dtype": "F32",
#     "shape": [768],
#     "data_offsets": [223154176, 223157248]
#   },
#   ...
# }

輸出示例

例如,這裡是 Hugging Face Hub 上一些模型按 dtype 分類的引數數量。更多用法示例,請參見 此 issue

模型 safetensors 引數
gpt2 單檔案 { ‘F32’ => 137022720 }
roberta-base 單檔案 { ‘F32’ => 124697433, ‘I64’ => 514 }
Jean-Baptiste/camembert-ner 單檔案 { ‘F32’ => 110035205, ‘I64’ => 514 }
roberta-large 單檔案 { ‘F32’ => 355412057, ‘I64’ => 514 }
distilbert-base-german-cased 單檔案 { ‘F32’ => 67431550 }
EleutherAI/gpt-neox-20b 分片 { ‘F16’ => 20554568208, ‘U8’ => 184549376 }
bigscience/bloom-560m 單檔案 { ‘F16’ => 559214592 }
bigscience/bloom 分片 { ‘BF16’ => 176247271424 }
bigscience/bloom-3b 單檔案 { ‘F16’ => 3002557440 }
< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.