//! 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, Vec), } pub struct Tensor { pub shape: Vec, pub data: Vec, } pub struct Weights { tensors: HashMap, } impl Weights { /// The tensors of a PyTorch checkpoint (`maia3-5m.pt`, `maia3-79m.pt`). pub fn parse(bytes: &[u8]) -> Result { 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 { 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, 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) } }