interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / crates / aienos-infer / src / model.rs

253 lines · 8723 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Llama weights bound to a GGUF slice (aienos#34 lane 2).
17//!
18//! Nothing is copied except the small f32 vectors (norm weights, rope
19//! frequency factors). Matrices stay quantized inside the borrowed file and
20//! are read one row at a time.
21
22use alloc::format;
23use alloc::string::String;
24use alloc::vec;
25use alloc::vec::Vec;
26
27use crate::dotprod::{self, DotProd, Q8Act};
28use crate::gguf::{plain_to_f32, GgmlType, Gguf, GgufError, LlamaParams};
29use crate::quant::{self, QuantError};
30
31/// Why a model could not be bound or run.
32#[derive(Debug, Clone, PartialEq)]
33pub enum InferError {
34 Gguf(GgufError),
35 Quant(QuantError),
36 /// Required tensor absent.
37 MissingTensor(String),
38 /// Tensor shape or type does not fit this architecture.
39 BadTensor(String),
40 /// Hyperparameters are inconsistent (head sizes, odd rope dim, ...).
41 BadParams(&'static str),
42 /// Token id outside the vocabulary.
43 BadToken(u32),
44 /// The KV cache is full.
45 ContextFull,
46}
47
48impl From<GgufError> for InferError {
49 fn from(e: GgufError) -> Self {
50 Self::Gguf(e)
51 }
52}
53impl From<QuantError> for InferError {
54 fn from(e: QuantError) -> Self {
55 Self::Quant(e)
56 }
57}
58
59/// A 2-D weight matrix inside the GGUF data: `rows` rows of `cols` weights.
60#[derive(Clone, Copy)]
61pub struct Weight<'a> {
62 data: &'a [u8],
63 ty: GgmlType,
64 pub rows: usize,
65 pub cols: usize,
66 row_bytes: usize,
67}
68
69impl<'a> Weight<'a> {
70 fn bind(g: &Gguf<'a>, name: &str, rows: usize, cols: usize) -> Result<Self, InferError> {
71 let t = g
72 .tensor(name)
73 .ok_or_else(|| InferError::MissingTensor(String::from(name)))?;
74 let bad = || InferError::BadTensor(format!("{name}: want {cols}x{rows}"));
75 if t.n_dims != 2 || t.dims[0] as usize != cols || t.dims[1] as usize != rows {
76 return Err(bad());
77 }
78 let (bw, _) = t.ty.block();
79 if cols % bw != 0 {
80 return Err(bad());
81 }
82 match t.ty {
83 GgmlType::Q4K | GgmlType::Q6K | GgmlType::F32 | GgmlType::F16 | GgmlType::BF16 => {}
84 _ => return Err(bad()),
85 }
86 let data = g.tensor_data(t);
87 let row_bytes = t.row_bytes() as usize;
88 if data.len() != row_bytes * rows {
89 return Err(bad());
90 }
91 Ok(Self {
92 data,
93 ty: t.ty,
94 rows,
95 cols,
96 row_bytes,
97 })
98 }
99
100 fn row(&self, i: usize) -> &'a [u8] {
101 &self.data[i * self.row_bytes..(i + 1) * self.row_bytes]
102 }
103
104 /// Dequantize row `i` into `out` (`cols` long).
105 pub fn row_into(&self, i: usize, out: &mut [f32]) -> Result<(), InferError> {
106 if i >= self.rows || out.len() != self.cols {
107 return Err(InferError::BadToken(i as u32));
108 }
109 if !plain_to_f32(self.ty, self.row(i), out) {
110 quant::dequantize(self.ty, self.row(i), out)?;
111 }
112 Ok(())
113 }
114
115 /// `out[r] = row_r . x` for every row. `scratch` is `cols` long and is
116 /// used only for the plain float types.
117 pub fn matvec(
118 &self,
119 x: &[f32],
120 out: &mut [f32],
121 scratch: &mut [f32],
122 ) -> Result<(), InferError> {
123 if x.len() != self.cols || out.len() != self.rows || scratch.len() < self.cols {
124 return Err(InferError::BadParams("matvec shape"));
125 }
126 for (r, o) in out.iter_mut().enumerate() {
127 *o = match self.ty {
128 GgmlType::Q4K | GgmlType::Q6K => quant::dot_row(self.ty, self.row(r), x)?,
129 _ => {
130 let s = &mut scratch[..self.cols];
131 plain_to_f32(self.ty, self.row(r), s);
132 s.iter().zip(x).map(|(a, b)| a * b).sum()
133 }
134 };
135 }
136 Ok(())
137 }
138
139 /// True for the K-quant types the SDOT path handles.
140 pub fn is_kquant(&self) -> bool {
141 matches!(self.ty, GgmlType::Q4K | GgmlType::Q6K)
142 }
143
144 /// `out[r] = row_r . x` on int8 activations with SDOT (K-quant weights
145 /// only; `q8` holds the quantized `x`). The capability token proves the
146 /// CPU has dotprod.
147 pub fn matvec_q8(&self, t: DotProd, q8: &Q8Act, out: &mut [f32]) -> Result<(), InferError> {
148 if !self.is_kquant() || out.len() != self.rows || q8.blocks() * 256 != self.cols {
149 return Err(InferError::BadParams("matvec_q8 shape"));
150 }
151 for (r, o) in out.iter_mut().enumerate() {
152 *o = dotprod::dot_row_q8(t, self.ty, self.row(r), q8)?;
153 }
154 Ok(())
155 }
156}
157
158/// One transformer block's tensors.
159pub struct Layer<'a> {
160 pub attn_norm: Vec<f32>,
161 pub wq: Weight<'a>,
162 pub wk: Weight<'a>,
163 pub wv: Weight<'a>,
164 pub wo: Weight<'a>,
165 pub ffn_norm: Vec<f32>,
166 pub w_gate: Weight<'a>,
167 pub w_up: Weight<'a>,
168 pub w_down: Weight<'a>,
169}
170
171/// A Llama model bound to a GGUF file.
172pub struct Model<'a> {
173 pub params: LlamaParams,
174 pub head_dim: usize,
175 pub kv_dim: usize,
176 pub layers: Vec<Layer<'a>>,
177 pub tok_embd: Weight<'a>,
178 /// Output projection: `output.weight` if present, else tied `token_embd`.
179 pub output: Weight<'a>,
180 pub output_norm: Vec<f32>,
181 /// Per rope pair divisors from `rope_freqs.weight` (llama3 scaling as
182 /// precomputed by the converter), or empty when absent.
183 pub rope_factors: Vec<f32>,
184}
185
186fn load_vec(g: &Gguf<'_>, name: &str, n: usize) -> Result<Vec<f32>, InferError> {
187 let t = g
188 .tensor(name)
189 .ok_or_else(|| InferError::MissingTensor(String::from(name)))?;
190 if t.n_dims != 1 || t.dims[0] as usize != n || t.ty != GgmlType::F32 {
191 return Err(InferError::BadTensor(format!("{name}: want f32[{n}]")));
192 }
193 let mut v = vec![0f32; n];
194 plain_to_f32(t.ty, g.tensor_data(t), &mut v);
195 Ok(v)
196}
197
198impl<'a> Model<'a> {
199 pub fn new(g: &Gguf<'a>) -> Result<Self, InferError> {
200 let p = g.llama_params()?;
201 let (n_embd, n_head, n_kv, n_ff, vocab) = (
202 p.embedding_length as usize,
203 p.head_count as usize,
204 p.head_count_kv as usize,
205 p.feed_forward_length as usize,
206 p.vocab_size as usize,
207 );
208 if n_head == 0 || n_kv == 0 || n_embd % n_head != 0 || n_head % n_kv != 0 {
209 return Err(InferError::BadParams("head counts"));
210 }
211 let head_dim = n_embd / n_head;
212 if head_dim % 2 != 0 {
213 return Err(InferError::BadParams("odd head dim"));
214 }
215 let kv_dim = n_kv * head_dim;
216 let tok_embd = Weight::bind(g, "token_embd.weight", vocab, n_embd)?;
217 let output = if g.tensor("output.weight").is_some() {
218 Weight::bind(g, "output.weight", vocab, n_embd)?
219 } else {
220 tok_embd
221 };
222 let mut layers = Vec::with_capacity(p.block_count as usize);
223 for l in 0..p.block_count {
224 let n = |s: &str| format!("blk.{l}.{s}.weight");
225 layers.push(Layer {
226 attn_norm: load_vec(g, &n("attn_norm"), n_embd)?,
227 wq: Weight::bind(g, &n("attn_q"), n_embd, n_embd)?,
228 wk: Weight::bind(g, &n("attn_k"), kv_dim, n_embd)?,
229 wv: Weight::bind(g, &n("attn_v"), kv_dim, n_embd)?,
230 wo: Weight::bind(g, &n("attn_output"), n_embd, n_embd)?,
231 ffn_norm: load_vec(g, &n("ffn_norm"), n_embd)?,
232 w_gate: Weight::bind(g, &n("ffn_gate"), n_ff, n_embd)?,
233 w_up: Weight::bind(g, &n("ffn_up"), n_ff, n_embd)?,
234 w_down: Weight::bind(g, &n("ffn_down"), n_embd, n_ff)?,
235 });
236 }
237 let rope_factors = if g.tensor("rope_freqs.weight").is_some() {
238 load_vec(g, "rope_freqs.weight", head_dim / 2)?
239 } else {
240 Vec::new()
241 };
242 Ok(Self {
243 params: p,
244 head_dim,
245 kv_dim,
246 layers,
247 tok_embd,
248 output,
249 output_norm: load_vec(g, "output_norm.weight", n_embd)?,
250 rope_factors,
251 })
252 }
253}