Safetensors 文档

元数据解析

您正在查看 main 版本,该版本需要从源代码安装。如果您想使用常规 pip 安装,请查看最新的稳定版本 (v0.5.0-rc.0)。
Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

元数据解析

鉴于格式的简洁性,使用小的 (Range) HTTP 请求来获取和解析关于 Safetensors 权重的元数据(即张量列表、它们的类型以及它们的形状或参数数量)非常简单高效。

此解析已在 huggingface.js 的 JS 中实现(示例如下),但在任何语言中都类似。

示例用例

可能有很多潜在的用例。例如,我们在 HuggingFace 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]
#   },
#   ...
# }

示例输出

例如,以下是 HuggingFace Hub 上一些模型的每种 dtype 的参数数量。另请参阅 此问题以获取更多用法示例。

模型 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 上更新