Skip to content
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.PathLike
Path 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

ValueError
If device names no Lucid device or the file is malformed, as for load_safetensors.
TypeError
If 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

1
dunder

__init__

→None
__init__(filename: str | os.PathLike[str], device: str | _device_cls = 'cpu')

Instance methods

3
fn

get_tensor

→_T
get_tensor(name: str)

The tensor stored as name.

Raises

KeyError
If the file holds no tensor of that name.
fn

keys

→list[str]
keys()

The tensor names, in file order.

fn

metadata

→dict[str, str] | None
metadata()

The string metadata save_safetensors stored, or None if there is none.

Dunder methods

2
dunder

__exit__

→None
__exit__(exc_info: object = ())