Skip to content
fn

load_safetensors

→dict of str to Tensor
load_safetensors(path: str | os.PathLike[str], device: str | _device_cls = 'cpu')

Load a SafeTensors file into a flat state dict.

Reads the header and each tensor's bytes directly, builds a Lucid Tensor of the stored dtype — bfloat16 included — optionally relocates it to the requested device, and restores any zero-rank scalars that were promoted to shape (1,) during save_safetensors.

Parameters

pathstr
Path to a .safetensors file.
devicestr or device= 'cpu'
Target device for every loaded tensor, parsed as device parses it: "cpu" (default), "metal" or "metal:0".

Returns

dict of str to Tensor

Flat state dict suitable for model.load_state_dict().

Raises

ValueError
If device names no Lucid device, if the file is not a well-formed SafeTensors file, or if it stores a dtype Lucid cannot represent (the 8-bit floats). A header whose offsets leave the file, overlap, leave gaps or stop short of the end of the file is malformed; the message names the file and the tensor.
TypeError
If device is not a string or a device.

Notes

Unsigned integers have no Lucid dtype and widen losslessly: U8 to int16, U16 to int32, U32 to int64 (U64 to int64, refused past its range).

Examples

>>> import lucid
>>> sd = {"w": lucid.ones(3)}
>>> lucid.serialization.save_safetensors(sd, "/tmp/weights.safetensors")
>>> loaded = lucid.serialization.load_safetensors("/tmp/weights.safetensors")
>>> loaded["w"].tolist()
[1.0, 1.0, 1.0]

Used by 2