chessbaseLinux/crates/maia/src/weights.rs
vrubelroman a94de00199
Some checks are pending
CI / check (push) Waiting to run
CI / windows-build (push) Waiting to run
CI / macos-build (push) Waiting to run
maia: the weights move into the network (no copy), the file's bytes go once read
Peak memory while loading: 79M 940 → 636 MB, 5M 72 → 52 MB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 00:09:21 +03:00

62 lines
1.8 KiB
Rust

//! The network's tensors by name, read from the published checkpoint.
use std::collections::HashMap;
#[derive(Debug, thiserror::Error)]
pub enum WeightsError {
#[error("cannot read the weights: {0}")]
Io(std::io::Error),
#[error("not a Maia checkpoint")]
Format,
#[error("the weights lack {0}")]
Missing(String),
#[error("{0} has the shape {1:?}, expected {2:?}")]
Shape(String, Vec<usize>, Vec<usize>),
}
pub struct Tensor {
pub shape: Vec<usize>,
pub data: Vec<f32>,
}
pub struct Weights {
tensors: HashMap<String, Tensor>,
}
impl Weights {
/// The tensors of a PyTorch checkpoint (`maia3-5m.pt`, `maia3-79m.pt`).
pub fn parse(bytes: &[u8]) -> Result<Weights, WeightsError> {
Ok(Weights {
tensors: crate::checkpoint::read(bytes)?,
})
}
/// The shape of the tensor `name`, if there is one.
pub fn shape(&self, name: &str) -> Option<&[usize]> {
self.tensors.get(name).map(|t| t.shape.as_slice())
}
/// The size `axis` of the tensor `name`.
pub fn dim(&self, name: &str, axis: usize) -> Result<usize, WeightsError> {
let shape = self
.shape(name)
.ok_or_else(|| WeightsError::Missing(name.to_owned()))?;
shape.get(axis).copied().ok_or(WeightsError::Format)
}
/// The tensor `name` of this shape, taken out (each is used once: no copy).
pub fn get(&mut self, name: &str, shape: &[usize]) -> Result<Vec<f32>, WeightsError> {
let t = self
.tensors
.remove(name)
.ok_or_else(|| WeightsError::Missing(name.to_owned()))?;
if t.shape != shape {
return Err(WeightsError::Shape(
name.to_owned(),
t.shape.clone(),
shape.to_vec(),
));
}
Ok(t.data)
}
}