Save tensors and objects
Persist a tensor or other serializable object to disk for later loading.
PyTorch · Function
Serializes a PyTorch object to a file path or file-like destination. It uses Python pickling and defaults to a newer ZIP-based file format.
PyTorch serializes the supplied object with Python pickling and writes it either to a filesystem path or to a file-like object. The default format is a newer ZIP-based archive; the pickle implementation and protocol can be customized, and the legacy format can be selected explicitly with the private compatibility flag.
torch.save(obj, f, pickle_module=pickle, pickle_protocol=2, _use_new_zipfile_serialization=True)| Name | Type | Description |
|---|---|---|
obj | object | Object to serialize and save. |
f | file-like object | str | os.PathLike | A file-like object implementing write and flush, or a string or os.PathLike filename. |
pickle_module | module | Module used for pickling metadata and objects. |
pickle_protocol | int | Optional pickle protocol override. |
_use_new_zipfile_serialization | bool | Selects the newer ZIP-based serialization when true; set false for the old format. |
import io
import torch
x = torch.tensor([0, 1, 2, 3, 4])
torch.save(x, "tensor.pt")
buffer = io.BytesIO()
torch.save(x, buffer)Saves the same tensor both to a conventional .pt file and to an in-memory file-like buffer.
Persist a tensor or other serializable object to disk for later loading.
Write serialized data into an in-memory stream for further handling.
Create a checkpoint containing model state or training data.
It accepts the object to serialize and a destination, which may be a path-like value or a file-like object. A file-like destination must implement write and flush.
Follow-up: What format does it use by default? It uses the newer ZIP-based serialization format; setting _use_new_zipfile_serialization=False selects the old format.
pickle_module chooses the module used to pickle metadata and objects. pickle_protocol overrides the default pickle protocol when supplied.
Follow-up: Why might the pickle protocol matter? It controls the pickle representation and can affect compatibility with consumers that support only particular protocol versions.
torch.save uses a ZIP-based file format by default, a behavior introduced in PyTorch 1.6. The saved object can be a tensor or another Python object supported by the selected pickling mechanism.
Follow-up: How would you preserve compatibility with code expecting the old format? Pass _use_new_zipfile_serialization=False, then load the result with torch.load.
torch.loadpickleio.BytesIO