Skip to content

load_torch_file

load_torch_file(path: Union[str, PathLike]) -> Any

Loads a file saved with torch.save (or a plain pickle file) without PyTorch, with every tensor converted to a numpy.ndarray.

Both the zip-based format (default since PyTorch 1.6) and the legacy format are supported. Only tensors (on any device, read on the CPU), containers (lists, tuples, dicts), NumPy arrays and SciPy COO matrices (read as SparseCOOMatrix) can be loaded: any other object raises a pickle.UnpicklingError, which makes the loader safe to use on untrusted files. bfloat16 and complex tensors are not supported.

Parameters:

Name Type Description Default
path Union[str, PathLike]

Path of the file.

required

Returns:

Type Description
Any

The saved object, with tensors as NumPy arrays.

Example:

from mlx_graphs.datasets.utils import load_torch_file

graphs = load_torch_file("peptidesfunc/train.pt")
node_features, edge_features, edge_index, y = graphs[0]
Source code in mlx_graphs/datasets/utils/torch_serialization.py
def load_torch_file(path: Union[str, os.PathLike]) -> Any:
    """Loads a file saved with ``torch.save`` (or a plain pickle file) without
    PyTorch, with every tensor converted to a :class:`numpy.ndarray`.

    Both the zip-based format (default since PyTorch 1.6) and the legacy
    format are supported. Only tensors (on any device, read on the CPU),
    containers (lists, tuples, dicts), NumPy arrays and SciPy COO matrices
    (read as :class:`SparseCOOMatrix`) can be loaded: any other object raises
    a :class:`pickle.UnpicklingError`, which makes the loader safe to use on
    untrusted files. ``bfloat16`` and complex tensors are not supported.

    Args:
        path: Path of the file.

    Returns:
        The saved object, with tensors as NumPy arrays.

    Example:

    .. code-block:: python

        from mlx_graphs.datasets.utils import load_torch_file

        graphs = load_torch_file("peptidesfunc/train.pt")
        node_features, edge_features, edge_index, y = graphs[0]
    """
    path = os.fspath(path)
    if zipfile.is_zipfile(path):
        return _load_zip(path)
    with open(path, "rb") as f:
        first = f.read(64)
        f.seek(0)
        # A legacy torch file starts with the pickled magic number, which is a
        # LONG1 opcode (``\x8a``) right after the protocol header.
        if len(first) > 2 and first[0] == 0x80 and first[2] == 0x8A:
            return _load_legacy(f)
        return _materialize(_RestrictedUnpickler(f, {}).load())

from mlx_graphs.datasets.utils.torch_serialization import load_torch_file · mlx_graphs/datasets/utils/torch_serialization.py