torch.from_file — PyTorch 2.7 documentation (original) (raw)

torch.from_file(filename, shared=None, size=0, *, dtype=None, layout=None, device=None, pin_memory=False)

Creates a CPU tensor with a storage backed by a memory-mapped file.

If shared is True, then memory is shared between processes. All changes are written to the file. If shared is False, then changes to the tensor do not affect the file.

size is the number of elements in the Tensor. If shared is False, then the file must contain at least size * sizeof(dtype) bytes. If shared is True the file will be created if needed.

Note

Only CPU tensors can be mapped to files.

Note

For now, tensors with storages backed by a memory-mapped file cannot be created in pinned memory.

Parameters

Keyword Arguments

Example::

t = torch.randn(2, 5, dtype=torch.float64) t.numpy().tofile('storage.pt') t_mapped = torch.from_file('storage.pt', shared=False, size=10, dtype=torch.float64)