Skip to content

pytorch.PyTorchDataset

kedro_datasets_experimental.pytorch.PyTorchDataset

PyTorchDataset(
    *,
    filepath,
    load_args=None,
    save_args=None,
    version=None,
    credentials=None,
    fs_args=None,
    metadata=None
)

Bases: AbstractVersionedDataset[Any, Any]

PyTorchDataset loads and saves PyTorch models' state_dict using torch.save and torch.load.

Warning

Loading is not safe for untrusted files. torch.load deserializes a pickle stream (the zipfile produced by torch.save is only a container around that pickle), so a maliciously crafted .pt file can execute arbitrary code on load. To mitigate this, PyTorchDataset enforces weights_only=True by default, which restricts loading to tensors and a small allow-list of safe types. Only set load_args: {weights_only: false} for files you fully trust, and prefer torch>=2.6 (where weights_only=True is also the upstream default) or a non-pickle format such as safetensors when handling untrusted inputs.

Example usage for the YAML API:
model:
    type: kedro_datasets_experimental.pytorch.PyTorchDataset
    filepath: data/06_models/model.pt
Example usage for the Python API
from kedro_datasets_experimental.pytorch import PyTorchDataset
import torch

# Define your model
model: torch.nn.Module
model = torch.nn.Sequential(torch.nn.Linear(10, 10), torch.nn.ReLU())

# Save model state dict
dataset = PyTorchDataset(filepath="data/06_models/model.pt")
dataset.save(model)

# Reload model state dict
reloaded = TheModelClass(*args, **kwargs)
reloaded.load_state_dict(dataset.load())
Source code in kedro_datasets_experimental/pytorch/pytorch_dataset.py
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
def __init__(  # noqa: PLR0913
        self,
        *,
        filepath,
        load_args: dict[str, Any] = None,
        save_args: dict[str, Any] = None,
        version: Version | None = None,
        credentials: dict[str, Any] = None,
        fs_args: dict[str, Any] = None,
        metadata: dict[str, Any] = None,
):
    _fs_args = deepcopy(fs_args) or {}
    _fs_open_args_load = _fs_args.pop("open_args_load", {})
    _fs_open_args_save = _fs_args.pop("open_args_save", {})
    # PyTorch serialization is binary; open in binary mode by default.
    _fs_open_args_load.setdefault("mode", "rb")
    _fs_open_args_save.setdefault("mode", "wb")
    _credentials = deepcopy(credentials) or {}

    protocol, path = get_protocol_and_path(filepath, version)
    if protocol == "file":
        _fs_args.setdefault("auto_mkdir", True)

    self._protocol = protocol
    self._fs = fsspec.filesystem(self._protocol, **_credentials, **_fs_args)

    self.metadata = metadata

    super().__init__(
        filepath=PurePosixPath(path),
        version=version,
        exists_function=self._fs.exists,
        glob_function=self._fs.glob,
    )

    # Handle default load and save arguments
    self._load_args = deepcopy(self.DEFAULT_LOAD_ARGS)
    if load_args is not None:
        self._load_args.update(load_args)
    self._save_args = deepcopy(self.DEFAULT_SAVE_ARGS)
    if save_args is not None:
        self._save_args.update(save_args)

    self._fs_open_args_load = _fs_open_args_load
    self._fs_open_args_save = _fs_open_args_save

DEFAULT_LOAD_ARGS class-attribute instance-attribute

DEFAULT_LOAD_ARGS = {'weights_only': True}

DEFAULT_SAVE_ARGS class-attribute instance-attribute

DEFAULT_SAVE_ARGS = {}

metadata instance-attribute

metadata = metadata

load

load()
Source code in kedro_datasets_experimental/pytorch/pytorch_dataset.py
125
126
127
128
129
130
131
def load(self) -> Any:
    load_path = get_filepath_str(self._get_load_path(), self._protocol)
    with self._fs.open(load_path, **self._fs_open_args_load) as fs_file:
        # Suppression of B614 - weights_only defaults to True via DEFAULT_LOAD_ARGS,
        # restricting deserialisation to safe types. Users may override via
        # load_args only for files they fully trust.
        return torch.load(fs_file, **self._load_args)  # nosec: B614

save

save(data)
Source code in kedro_datasets_experimental/pytorch/pytorch_dataset.py
133
134
135
136
137
138
def save(self, data: torch.nn.Module) -> None:
    save_path = get_filepath_str(self._get_save_path(), self._protocol)
    with self._fs.open(save_path, **self._fs_open_args_save) as fs_file:
        torch.save(data.state_dict(), fs_file, **self._save_args)

    self._invalidate_cache()