Files
pytorch/docs/cpp/source/api/serialize/archives.md
T
Svetlana Karslioglu 19da3da3d3 Restructure C++ docs (#174096)
The fix-cpp-build branch is a major restructuring that:

- Drops Exhale (which auto-generated API docs but caused OOM in CI) in favor of hand-written RST pages using Breathe directives
- Reorganizes notes into a hierarchical API reference with proper categories
- Adds new content: XPU docs, stable ABI docs, DeviceGuard/Stream docs
- Always runs Doxygen instead of gating on an env var

Pull Request resolved: https://github.com/pytorch/pytorch/pull/174096
Approved by: https://github.com/janeyx99, https://github.com/seemethere, https://github.com/albanD
2026-04-07 17:24:38 +00:00

1.7 KiB

myst
myst
html_meta
description keywords
Serialization archives in PyTorch C++ — InputArchive and OutputArchive for model serialization. PyTorch, C++, InputArchive, OutputArchive, serialization, archive

Archives

Archives provide a lower-level interface for serialization, allowing you to save multiple values to a single file with named keys.

OutputArchive

:members:
:undoc-members:

Example:

torch::serialize::OutputArchive archive;
archive.write("tensor1", tensor1);
archive.write("tensor2", tensor2);
archive.save_to("multi_tensor.pt");

InputArchive

:members:
:undoc-members:

Example:

torch::serialize::InputArchive archive;
archive.load_from("multi_tensor.pt");

torch::Tensor tensor1, tensor2;
archive.read("tensor1", tensor1);
archive.read("tensor2", tensor2);

Saving Multiple Values

Archives are useful when you need to save multiple related values together:

// Save multiple tensors and metadata
torch::serialize::OutputArchive out_archive;
out_archive.write("weights", model_weights);
out_archive.write("biases", model_biases);
out_archive.write("epoch", torch::tensor(current_epoch));
out_archive.write("loss", torch::tensor(best_loss));
out_archive.save_to("training_state.pt");

// Load them back
torch::serialize::InputArchive in_archive;
in_archive.load_from("training_state.pt");

torch::Tensor weights, biases, epoch_tensor, loss_tensor;
in_archive.read("weights", weights);
in_archive.read("biases", biases);
in_archive.read("epoch", epoch_tensor);
in_archive.read("loss", loss_tensor);

int epoch = epoch_tensor.item<int>();
float loss = loss_tensor.item<float>();