1use 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#[derive(Debug, thiserror::Error)]
13#[non_exhaustive]
14pub enum WeightsError {
15 #[error("invalid safetensors data: {0}")]
17 Safetensors(String),
18 #[error("invalid Flax MessagePack data: {0}")]
20 Msgpack(String),
21 #[error("unsupported element type `{0}` of `{1}`")]
23 UnsupportedType(String, String),
24 #[error("no weight named `{0}`")]
26 Missing(String),
27 #[error("the weight `{name}` is {actual}, expected {expected}")]
29 Mismatch {
30 name: String,
32 actual: String,
34 expected: String,
36 },
37}
38
39#[derive(Clone, Debug, Default)]
54pub struct Weights {
55 arrays: BTreeMap<String, HostArray>,
56}
57
58impl Weights {
59 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 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 pub fn insert(&mut self, name: impl Into<String>, array: HostArray) {
113 self.arrays.insert(name.into(), array);
114 }
115
116 pub fn names(&self) -> impl Iterator<Item = &str> {
118 self.arrays.keys().map(String::as_str)
119 }
120
121 pub fn contains(&self, name: &str) -> bool {
123 self.arrays.contains_key(name)
124 }
125
126 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 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
161fn 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
174fn 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 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
236fn 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 assert!(Weights::from_flax_msgpack(&[0x81, 0xa1, b'a', 0x01]).is_err());
276 }
277}