Skip to main content

ruxla_nn/
weights.rs

1//! Loading weights saved by JAX programs: safetensors files and Flax's
2//! MessagePack format.
3
4use std::collections::BTreeMap;
5
6use ruxla_core::{Array, Element, Native, NativeArray};
7use ruxla_ir::{DType, HostArray, Shape};
8
9use crate::msgpack::{MsgValue, decode};
10
11/// An error from loading weights.
12#[derive(Debug, thiserror::Error)]
13#[non_exhaustive]
14pub enum WeightsError {
15    /// The file is not valid safetensors.
16    #[error("invalid safetensors data: {0}")]
17    Safetensors(String),
18    /// The file is not valid Flax MessagePack data.
19    #[error("invalid Flax MessagePack data: {0}")]
20    Msgpack(String),
21    /// An element type that ruxla does not have.
22    #[error("unsupported element type `{0}` of `{1}`")]
23    UnsupportedType(String, String),
24    /// No weight has the name.
25    #[error("no weight named `{0}`")]
26    Missing(String),
27    /// The weight has another type or shape than expected.
28    #[error("the weight `{name}` is {actual}, expected {expected}")]
29    Mismatch {
30        /// The name of the weight.
31        name: String,
32        /// Its type and shape.
33        actual: String,
34        /// The expected type and shape.
35        expected: String,
36    },
37}
38
39/// Named weights, such as the parameters of a Flax model with names like
40/// `params/Dense_0/kernel` (the keys of the parameter tree joined by `/`).
41///
42/// # Examples
43///
44/// ```
45/// use ruxla_ir::HostArray;
46/// use ruxla_nn::Weights;
47///
48/// let mut w = Weights::default();
49/// w.insert("params/Dense_0/bias", HostArray::from_vec(vec![0.5f32, -1.0], [2]));
50/// let bias = w.array::<f32>("params/Dense_0/bias", &[2]).unwrap();
51/// assert_eq!(bias.to_vec(), [0.5, -1.0]);
52/// ```
53#[derive(Clone, Debug, Default)]
54pub struct Weights {
55    arrays: BTreeMap<String, HostArray>,
56}
57
58impl Weights {
59    /// Reads a safetensors file (little-endian, as written by
60    /// `safetensors.numpy.save_file` or `safetensors.flax.save_file`).
61    ///
62    /// # Errors
63    ///
64    /// Returns an error if the data is not valid safetensors or has an
65    /// element type that ruxla does not have.
66    pub fn from_safetensors(bytes: &[u8]) -> Result<Self, WeightsError> {
67        use safetensors::Dtype as D;
68        let file = safetensors::SafeTensors::deserialize(bytes)
69            .map_err(|e| WeightsError::Safetensors(e.to_string()))?;
70        let mut arrays = BTreeMap::new();
71        for (name, view) in file.tensors() {
72            let dtype = match view.dtype() {
73                D::BOOL => DType::Bool,
74                D::I8 => DType::I8,
75                D::I16 => DType::I16,
76                D::I32 => DType::I32,
77                D::I64 => DType::I64,
78                D::U8 => DType::U8,
79                D::U16 => DType::U16,
80                D::U32 => DType::U32,
81                D::U64 => DType::U64,
82                D::F16 => DType::F16,
83                D::BF16 => DType::BF16,
84                D::F32 => DType::F32,
85                D::F64 => DType::F64,
86                other => {
87                    return Err(WeightsError::UnsupportedType(format!("{other:?}"), name));
88                }
89            };
90            let array = from_le_bytes(view.data(), view.shape(), dtype)
91                .map_err(|e| WeightsError::Safetensors(format!("{name}: {e}")))?;
92            arrays.insert(name, array);
93        }
94        Ok(Self { arrays })
95    }
96
97    /// Reads weights serialized by Flax (`flax.serialization.to_bytes` of a
98    /// parameter tree): nested maps whose leaves are arrays.
99    ///
100    /// # Errors
101    ///
102    /// Returns an error if the data is not valid MessagePack, is not a tree
103    /// of maps and arrays, or has an element type that ruxla does not have.
104    pub fn from_flax_msgpack(bytes: &[u8]) -> Result<Self, WeightsError> {
105        let (value, _) = decode(bytes).map_err(WeightsError::Msgpack)?;
106        let mut arrays = BTreeMap::new();
107        walk(&value, String::new(), &mut arrays)?;
108        Ok(Self { arrays })
109    }
110
111    /// Adds or replaces a weight.
112    pub fn insert(&mut self, name: impl Into<String>, array: HostArray) {
113        self.arrays.insert(name.into(), array);
114    }
115
116    /// The names of the weights, in sorted order.
117    pub fn names(&self) -> impl Iterator<Item = &str> {
118        self.arrays.keys().map(String::as_str)
119    }
120
121    /// Whether there is a weight with a name.
122    pub fn contains(&self, name: &str) -> bool {
123        self.arrays.contains_key(name)
124    }
125
126    /// The weight with a name.
127    ///
128    /// # Errors
129    ///
130    /// Returns an error if there is no such weight.
131    pub fn get(&self, name: &str) -> Result<&HostArray, WeightsError> {
132        self.arrays
133            .get(name)
134            .ok_or_else(|| WeightsError::Missing(name.to_string()))
135    }
136
137    /// The weight with a name as a native array of type `T` and the given
138    /// shape.
139    ///
140    /// # Errors
141    ///
142    /// Returns an error if there is no such weight or it has another type or
143    /// shape.
144    pub fn array<T: Element>(
145        &self,
146        name: &str,
147        shape: &[usize],
148    ) -> Result<Array<Native, T>, WeightsError> {
149        let h = self.get(name)?;
150        if h.dtype() != T::DTYPE || h.shape().dims() != shape {
151            return Err(WeightsError::Mismatch {
152                name: name.to_string(),
153                actual: h.aval().to_string(),
154                expected: format!("{}[{}]", T::DTYPE, Shape::from(shape)),
155            });
156        }
157        Ok(Array::from_repr(NativeArray::from_host(h)))
158    }
159}
160
161/// Builds an array from little-endian bytes.
162fn from_le_bytes(bytes: &[u8], shape: &[usize], dtype: DType) -> Result<HostArray, String> {
163    let size = dtype.size_in_bytes();
164    if cfg!(target_endian = "little") {
165        return HostArray::from_bytes(bytes, shape.to_vec(), dtype).map_err(|e| e.to_string());
166    }
167    let swapped: Vec<u8> = bytes
168        .chunks_exact(size)
169        .flat_map(|c| c.iter().rev().copied())
170        .collect();
171    HostArray::from_bytes(&swapped, shape.to_vec(), dtype).map_err(|e| e.to_string())
172}
173
174/// Collects the arrays of a Flax tree, naming them by their path.
175fn walk(
176    value: &MsgValue,
177    path: String,
178    out: &mut BTreeMap<String, HostArray>,
179) -> Result<(), WeightsError> {
180    match value {
181        MsgValue::Map(entries) => {
182            for (k, v) in entries {
183                let MsgValue::Str(k) = k else {
184                    return Err(WeightsError::Msgpack(format!(
185                        "a key of `{path}` is not a string"
186                    )));
187                };
188                let child = if path.is_empty() {
189                    k.clone()
190                } else {
191                    format!("{path}/{k}")
192                };
193                walk(v, child, out)?;
194            }
195            Ok(())
196        }
197        // Flax's extension types: 1 is an ndarray `(shape, dtype, bytes)`,
198        // 3 is a NumPy scalar `(dtype, bytes)`.
199        MsgValue::Ext(code @ (1 | 3), data) => {
200            let (inner, _) = decode(data).map_err(WeightsError::Msgpack)?;
201            let MsgValue::Array(items) = inner else {
202                return Err(WeightsError::Msgpack(format!("`{path}` is not an array")));
203            };
204            let (shape, dtype, buffer) = match (code, items.as_slice()) {
205                (1, [MsgValue::Array(shape), dtype, MsgValue::Bin(buffer)]) => (
206                    shape
207                        .iter()
208                        .map(|d| match d {
209                            MsgValue::Int(d) if *d >= 0 => Ok(*d as usize),
210                            _ => Err(WeightsError::Msgpack(format!("bad shape of `{path}`"))),
211                        })
212                        .collect::<Result<Vec<_>, _>>()?,
213                    dtype,
214                    buffer,
215                ),
216                (3, [dtype, MsgValue::Bin(buffer)]) => (Vec::new(), dtype, buffer),
217                _ => return Err(WeightsError::Msgpack(format!("bad array `{path}`"))),
218            };
219            let name = match dtype {
220                MsgValue::Str(s) => s.clone(),
221                MsgValue::Bin(b) => String::from_utf8_lossy(b).into_owned(),
222                _ => return Err(WeightsError::Msgpack(format!("bad dtype of `{path}`"))),
223            };
224            let dtype = DType::from_name(&numpy_dtype(&name))
225                .ok_or_else(|| WeightsError::UnsupportedType(name.clone(), path.clone()))?;
226            let array = from_le_bytes(buffer, &shape, dtype).map_err(WeightsError::Msgpack)?;
227            out.insert(path, array);
228            Ok(())
229        }
230        other => Err(WeightsError::Msgpack(format!(
231            "unexpected value at `{path}`: {other:?}"
232        ))),
233    }
234}
235
236/// The ruxla name of a NumPy dtype name.
237fn numpy_dtype(name: &str) -> String {
238    match name {
239        "float16" => "f16",
240        "bfloat16" => "bf16",
241        "float32" => "f32",
242        "float64" => "f64",
243        "int8" => "i8",
244        "int16" => "i16",
245        "int32" => "i32",
246        "int64" => "i64",
247        "uint8" => "u8",
248        "uint16" => "u16",
249        "uint32" => "u32",
250        "uint64" => "u64",
251        "bool" => "bool",
252        other => other,
253    }
254    .to_string()
255}
256
257#[cfg(test)]
258mod tests {
259    use super::*;
260
261    #[test]
262    fn errors_name_the_weight() {
263        let mut w = Weights::default();
264        w.insert("a/kernel", HostArray::from_vec(vec![1.0f32; 6], [2, 3]));
265        assert!(matches!(w.get("b"), Err(WeightsError::Missing(n)) if n == "b"));
266        let e = w.array::<f32>("a/kernel", &[3, 2]).unwrap_err();
267        assert!(
268            e.to_string().contains("a/kernel") && e.to_string().contains("f32[2,3]"),
269            "{e}"
270        );
271        assert!(w.array::<f64>("a/kernel", &[2, 3]).is_err());
272        assert!(Weights::from_safetensors(b"not safetensors").is_err());
273        assert!(Weights::from_flax_msgpack(&[0xc1]).is_err());
274        // A map whose leaf is not an array.
275        assert!(Weights::from_flax_msgpack(&[0x81, 0xa1, b'a', 0x01]).is_err());
276    }
277}