Safetensors documentation

Numpy API

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v0.5.0-rc.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Numpy API

safetensors.numpy.load_file

< >

( filename: typing.Union[str, os.PathLike]backend: str = 'mmap' ) → Dict[str, np.ndarray]

参数

  • filename (str,或 os.PathLike) — 包含张量的文件的名称
  • backend (str,可选,默认为 "mmap") — 用于提供张量字节的存储后端。"mmap"(默认) 和 "pread" 使用 pread(2) 读取张量字节。

返回值

Dict[str, np.ndarray]

一个字典,其中键为名称,值为np.ndarray

将 safetensors 文件加载为 numpy 格式。

示例:

from safetensors.numpy import load_file

file_path = "./my_folder/bert.safetensors"
loaded = load_file(file_path)

safetensors.numpy.load

< >

( data: bytes ) → Dict[str, np.ndarray]

参数

  • data (bytes) — safetensors 文件的内容

返回值

Dict[str, np.ndarray]

一个字典,其中键为名称,值为位于 cpu 上的 np.ndarray

从纯字节数据加载 safetensors 文件并转换为 numpy 格式。

示例:

from safetensors.numpy import load

file_path = "./my_folder/bert.safetensors"
with open(file_path, "rb") as f:
    data = f.read()

loaded = load(data)

safetensors.numpy.save_file

< >

( tensor_dict: typing.Dict[str, numpy.ndarray]filename: typing.Union[str, os.PathLike]metadata: typing.Optional[typing.Dict[str, str]] = None ) → None

参数

  • tensor_dict (Dict[str, np.ndarray]) — 传入的张量。张量需要是连续的且稠密的。
  • filename (str 或 os.PathLike) — 要保存到的文件名。
  • metadata (Dict[str, str],可选,默认为 None) — 可选的纯文本元数据,您可以将其保存在头部中。例如,它可以用于提供有关底层张量的更多说明。此字段仅用于信息展示,不会影响张量的加载。

返回值

None

将张量字典保存为 safetensors 格式的原始字节。

示例:

from safetensors.numpy import save_file
import numpy as np

tensors = {"embedding": np.zeros((512, 1024)), "attention": np.zeros((256, 256))}
save_file(tensors, "model.safetensors")

safetensors.numpy.save

< >

( tensor_dict: typing.Dict[str, numpy.ndarray]metadata: typing.Optional[typing.Dict[str, str]] = None ) → bytes

参数

  • tensor_dict (Dict[str, np.ndarray]) — 传入的张量。张量需要是连续的且稠密的。
  • metadata (Dict[str, str],可选,默认为 None) — 可选的纯文本元数据,您可以将其保存在头部中。例如,它可以用于提供有关底层张量的更多说明。此字段仅用于信息展示,不会影响张量的加载。

返回值

bytes

表示格式的原始字节

将张量字典保存为 safetensors 格式的原始字节。

示例:

from safetensors.numpy import save
import numpy as np

tensors = {"embedding": np.zeros((512, 1024)), "attention": np.zeros((256, 256))}
byte_data = save(tensors)
Update on GitHub