diff --git a/crates/maia/src/lib.rs b/crates/maia/src/lib.rs index 36ee1cd..16e1f12 100644 --- a/crates/maia/src/lib.rs +++ b/crates/maia/src/lib.rs @@ -26,14 +26,23 @@ pub struct Maia { impl Maia { /// Reads the checkpoint (`maia3-5m.pt`). pub fn load(path: &std::path::Path) -> Result { - let bytes = std::fs::read(path).map_err(WeightsError::Io)?; - Maia::from_bytes(&bytes) + // The file's bytes are let go once read into tensors, and the tensors move into + // the network: at most two copies of the weights at once (the large model: its + // 316 MB twice, not three times). + let w = { + let bytes = std::fs::read(path).map_err(WeightsError::Io)?; + weights::Weights::parse(&bytes)? + }; + Maia::from_weights(w) } pub fn from_bytes(bytes: &[u8]) -> Result { - let w = weights::Weights::parse(bytes)?; + Maia::from_weights(weights::Weights::parse(bytes)?) + } + + fn from_weights(mut w: weights::Weights) -> Result { Ok(Maia { - net: net::Net::new(&w)?, + net: net::Net::new(&mut w)?, }) } diff --git a/crates/maia/src/net.rs b/crates/maia/src/net.rs index 5eff3f9..9f4deed 100644 --- a/crates/maia/src/net.rs +++ b/crates/maia/src/net.rs @@ -65,7 +65,7 @@ struct Linear { impl Linear { fn load( - w: &Weights, + w: &mut Weights, name: &str, out: usize, inp: usize, @@ -152,7 +152,7 @@ struct LayerNorm { } impl LayerNorm { - fn load(w: &Weights, name: &str, n: usize) -> Result { + fn load(w: &mut Weights, name: &str, n: usize) -> Result { Ok(LayerNorm { w: w.get(&format!("{name}.weight"), &[n])?, b: w.get(&format!("{name}.bias"), &[n])?, @@ -246,7 +246,7 @@ pub struct Prediction { } impl Net { - pub fn new(w: &Weights) -> Result { + pub fn new(w: &mut Weights) -> Result { let dims = Dims::read(w)?; let Dims { d, diff --git a/crates/maia/src/weights.rs b/crates/maia/src/weights.rs index 6e9fea2..dbc0dc3 100644 --- a/crates/maia/src/weights.rs +++ b/crates/maia/src/weights.rs @@ -44,11 +44,11 @@ impl Weights { shape.get(axis).copied().ok_or(WeightsError::Format) } - /// The tensor `name` of this shape. - pub fn get(&self, name: &str, shape: &[usize]) -> Result, WeightsError> { + /// 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 - .get(name) + .remove(name) .ok_or_else(|| WeightsError::Missing(name.to_owned()))?; if t.shape != shape { return Err(WeightsError::Shape( @@ -57,6 +57,6 @@ impl Weights { shape.to_vec(), )); } - Ok(t.data.clone()) + Ok(t.data) } }