Skip to main content

Module serialize

Module serialize 

Source
Expand description

Model Serialization

Save and load tensors in the safetensors format, which PyTorch and the Hugging Face ecosystem read and write, and round-trip a module’s parameters through a state dict keyed by Module::named_parameters.

§Example

use ferrotensor::prelude::*;
use ferrotensor::serialize::{load_module, save_module};

let device = Device::cpu();
let model = nn::Sequential::new(&device)
    .add(nn::Linear::new(4, 8, &device))
    .add(nn::ReLU)
    .add(nn::Linear::new(8, 2, &device));

let path = std::env::temp_dir().join("ferrotensor_doc_model.safetensors");
save_module(&model, &path).unwrap();

let restored = nn::Sequential::new(&device)
    .add(nn::Linear::new(4, 8, &device))
    .add(nn::ReLU)
    .add(nn::Linear::new(8, 2, &device));
load_module(&restored, &path).unwrap();
let x = Tensor::randn(&[3, 4], &device);
assert_eq!(model.forward(&x).to_vec(), restored.forward(&x).to_vec());

Enums§

SerializeError
Error type for serialization operations.

Traits§

Saveable
Trait for types that can be saved/loaded as a state dict.

Functions§

load_model
Load a Saveable from a safetensors file.
load_module
Load a module’s parameters from a safetensors file (strict, in place).
load_state_dict
Copy state into the module’s parameters in place.
load_tensors
Load every tensor in a safetensors file onto device.
save_model
Save a Saveable to a safetensors file.
save_module
Save a module’s parameters to a safetensors file.
save_tensors
Save named tensors to a safetensors file (as F32).
state_dict
A module’s parameters keyed by Module::named_parameters.