Numpy API

safetensors.numpy.load_file

< >

( filename: Union ) Dict[str, np.ndarray]

Parameters

  • filename (str, or os.PathLike)) — The name of the file which contains the tensors

Returns

Dict[str, np.ndarray]

dictionary that contains name as key, value as np.ndarray

Loads a safetensors file into numpy format.

Example:

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]

Parameters

  • data (bytes) — The content of a safetensors file

Returns

Dict[str, np.ndarray]

dictionary that contains name as key, value as np.ndarray on cpu

Loads a safetensors file into numpy format from pure bytes.

Example:

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: Dict filename: Union metadata: Optional = None ) None

Parameters

  • tensor_dict (Dict[str, np.ndarray]) — The incoming tensors. Tensors need to be contiguous and dense.
  • filename (str, or os.PathLike)) — The filename we’re saving into.
  • metadata (Dict[str, str], optional, defaults to None) — Optional text only metadata you might want to save in your header. For instance it can be useful to specify more about the underlying tensors. This is purely informative and does not affect tensor loading.

Returns

None

Saves a dictionary of tensors into raw bytes in safetensors format.

Example:

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: Dict metadata: Optional = None ) bytes

Parameters

  • tensor_dict (Dict[str, np.ndarray]) — The incoming tensors. Tensors need to be contiguous and dense.
  • metadata (Dict[str, str], optional, defaults to None) — Optional text only metadata you might want to save in your header. For instance it can be useful to specify more about the underlying tensors. This is purely informative and does not affect tensor loading.

Returns

bytes

The raw bytes representing the format

Saves a dictionary of tensors into raw bytes in safetensors format.

Example:

from safetensors.numpy import save
import numpy as np

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