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.