class
safe_open
safe_open(filename: str | os.PathLike[str], device: str | _device_cls = 'cpu')Read a SafeTensors file's header and tensors one at a time.
The file's header is read and validated when the object is made; each tensor's bytes are read only when it is asked for, so a single tensor or the metadata of a large checkpoint can be had without loading the rest. It is a context manager for parity with the reference reader, but holds no file handle: leaving the block releases nothing.
Parameters
filenamestr or os.PathLikePath to a
.safetensors file.devicestr or device= 'cpu'Device the tensors
get_tensor returns are placed on,
parsed as device parses it. Default "cpu".Raises
ValueErrorIf
device names no Lucid device or the file is malformed, as
for load_safetensors.TypeErrorIf
device is not a string or a device.Examples
>>> import lucid
>>> lucid.serialization.save_safetensors(
... {"w": lucid.ones(3)}, "/tmp/meta.safetensors", metadata={"format": "lucid"}
... )
>>> with lucid.serialization.safe_open("/tmp/meta.safetensors") as f:
... f.metadata()
... f.keys()
... f.get_tensor("w").tolist()
{'format': 'lucid'}
['w']
[1.0, 1.0, 1.0]Constructors
1Instance methods
3The tensor stored as name.
Raises
KeyErrorIf the file holds no tensor of that name.
The tensor names, in file order.
The string metadata save_safetensors stored, or None if there is none.