interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-inference-abi / src / weights.rs

1019 lines · 40636 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//! Native weight data structures and zero-dependency loaders for transformer models.
17
18use crate::resident::{MatrixRef, MatrixWeight};
19use crate::tensor::{
20 apply_rope_params, matmul_vec, rmsnorm, rmsnorm_heads_in_place,
21 scaled_dot_product_attention_single, swiglu,
22};
23use crate::ModelConfig;
24use aien_kv_cache::KvDType;
25use serde_json::Value;
26
27#[derive(Debug, Clone, Default)]
28pub struct LayerKvCache {
29 pub cached_k: Vec<Vec<f32>>,
30 pub cached_v: Vec<Vec<f32>>,
31 pub flat_k: Vec<f32>,
32 pub flat_v: Vec<f32>,
33}
34
35#[derive(Debug, Clone, Default)]
36pub struct SequenceState {
37 pub tokens: Vec<u32>,
38 pub layers: Vec<LayerKvCache>,
39 /// Element type K/V are rounded to the moment they are produced, before any
40 /// reader (dense cache, pool write, attention) sees them. The pool's dtype when
41 /// a physical pool is attached, else the backend's `kv_dtype` (default `Fp32`).
42 pub kv_dtype: KvDType,
43}
44
45#[derive(Debug, Clone)]
46pub struct TransformerLayerWeights {
47 pub input_layernorm: Vec<f32>,
48 pub q_proj: MatrixWeight,
49 pub k_proj: MatrixWeight,
50 pub v_proj: MatrixWeight,
51 pub o_proj: MatrixWeight,
52 pub post_attention_layernorm: Vec<f32>,
53 pub gate_proj: MatrixWeight,
54 pub up_proj: MatrixWeight,
55 pub down_proj: MatrixWeight,
56 /// Resident loader only (sc#384 decode speed): q, k and v rows in one device matrix
57 /// `[q_dim + 2*kv_dim, hidden]`. The forward paths use it when present (one launch
58 /// instead of three), else the three matrices above. Same kernel, same arithmetic per row.
59 pub qkv_proj: Option<MatrixWeight>,
60 /// Resident loader only: gate rows then up rows, `[2*inter, hidden]`, one launch.
61 pub gate_up_proj: Option<MatrixWeight>,
62 /// Qwen3 per-head RMSNorm weights `[head_dim]` for Q and K (`config.qk_norm`); `None` for
63 /// Llama-architecture models.
64 pub q_norm: Option<Vec<f32>>,
65 pub k_norm: Option<Vec<f32>>,
66}
67
68impl TransformerLayerWeights {
69 /// Qwen3: RMSNorm each query head and each key head over `head_dim`, in place, right
70 /// after the projections and before RoPE (Hugging Face `modeling_qwen3.py`
71 /// `Qwen3Attention.forward`: `q_norm(q_proj(x).view(.., head_dim))`, then rotary).
72 /// A no-op for models without q_norm/k_norm.
73 pub fn apply_qk_norm(&self, q: &mut [f32], k: &mut [f32], head_dim: usize, eps: f32) {
74 if let Some(w) = &self.q_norm {
75 rmsnorm_heads_in_place(q, w, head_dim, eps);
76 }
77 if let Some(w) = &self.k_norm {
78 rmsnorm_heads_in_place(k, w, head_dim, eps);
79 }
80 }
81
82 /// [`Self::apply_qk_norm`] through `backend` (`TensorBackend::rmsnorm_heads`), so a device
83 /// backend runs it and accounts for it like any other op. A no-op without q_norm/k_norm.
84 pub fn apply_qk_norm_on(
85 &self,
86 backend: &dyn crate::backend::TensorBackend,
87 q: &mut [f32],
88 k: &mut [f32],
89 head_dim: usize,
90 eps: f32,
91 ) {
92 if let Some(w) = &self.q_norm {
93 backend.rmsnorm_heads(q, w, head_dim, eps);
94 }
95 if let Some(w) = &self.k_norm {
96 backend.rmsnorm_heads(k, w, head_dim, eps);
97 }
98 }
99}
100
101#[derive(Debug, Clone)]
102pub struct TransformerWeights {
103 pub config: ModelConfig,
104 pub embed_tokens: Vec<f32>,
105 pub layers: Vec<TransformerLayerWeights>,
106 pub final_norm: Vec<f32>,
107 /// Output projection `[vocab, hidden]`. `None` when `config.tie_word_embeddings` on the host
108 /// path: the projection is `embed_tokens` itself (no second copy). On the GB10 resident path
109 /// it is `Some(Resident)` even for tied models (the embedding's own device copy). Read it
110 /// through [`TransformerWeights::output_matrix`].
111 pub lm_head: Option<MatrixWeight>,
112}
113
114/// Diagnostic capture of intermediate activations and shapes across all transformer layers.
115#[derive(Debug, Clone, Default)]
116pub struct ForwardDiagnostics {
117 pub activations: std::collections::HashMap<String, Vec<f32>>,
118 pub shapes: std::collections::HashMap<String, Vec<usize>>,
119}
120
121impl TransformerWeights {
122 /// The `[vocab, hidden]` matrix that projects the final hidden state to logits:
123 /// `lm_head`, or `embed_tokens` for a model with tied word embeddings.
124 #[inline]
125 pub fn output_projection(&self) -> &[f32] {
126 self.output_matrix().host_or_refuse("output_projection")
127 }
128
129 /// [`Self::output_projection`] as host values or a device handle; what the backends take.
130 #[inline]
131 pub fn output_matrix(&self) -> MatrixRef<'_> {
132 match &self.lm_head {
133 Some(lm_head) => lm_head.as_ref(),
134 None => MatrixRef::Host(&self.embed_tokens),
135 }
136 }
137
138 /// Copies the embedding vector for a given token ID into a destination slice.
139 #[inline]
140 pub fn embed_token(&self, token_id: u32, out: &mut [f32]) {
141 let hidden_dim = self.config.hidden_dim();
142 let token_idx = (token_id as usize) % self.config.vocab_size();
143 let start = token_idx * hidden_dim;
144 let end = start + hidden_dim;
145 out.copy_from_slice(&self.embed_tokens[start..end]);
146 }
147
148 /// Returns a direct slice reference to the token embedding.
149 #[inline]
150 pub fn token_embedding(&self, token_id: u32) -> &[f32] {
151 let hidden_dim = self.config.hidden_dim();
152 let token_idx = (token_id as usize) % self.config.vocab_size();
153 let start = token_idx * hidden_dim;
154 let end = start + hidden_dim;
155 &self.embed_tokens[start..end]
156 }
157
158 /// Creates deterministically initialized weights for tests and headless verification.
159 pub fn reference_test_weights(config: &ModelConfig) -> Self {
160 let hidden_dim = config.hidden_dim();
161 let q_dim = config.num_heads * config.head_dim;
162 let kv_dim = config.num_kv_heads * config.head_dim;
163 let intermediate_dim = config.intermediate_dim();
164 let vocab_size = config.vocab_size();
165
166 let mut lcg_state: u64 = 42;
167 let mut next_float = || -> f32 {
168 lcg_state = lcg_state
169 .wrapping_mul(6364136223846793005)
170 .wrapping_add(1442695040888963407);
171 let val = ((lcg_state >> 33) as f32) / ((1u64 << 31) as f32);
172 (val - 0.5) * 0.05
173 };
174
175 let mut embed_tokens = vec![0.0f32; vocab_size * hidden_dim];
176 for v in embed_tokens.iter_mut() {
177 *v = next_float();
178 }
179
180 let mut layers = Vec::with_capacity(config.num_layers);
181 for _ in 0..config.num_layers {
182 let mut input_layernorm = vec![1.0f32; hidden_dim];
183 for v in input_layernorm.iter_mut() {
184 *v = 1.0 + next_float() * 0.1;
185 }
186
187 let mut q_proj = vec![0.0f32; hidden_dim * q_dim];
188 for v in q_proj.iter_mut() {
189 *v = next_float();
190 }
191
192 let mut k_proj = vec![0.0f32; hidden_dim * kv_dim];
193 for v in k_proj.iter_mut() {
194 *v = next_float();
195 }
196
197 let mut v_proj = vec![0.0f32; hidden_dim * kv_dim];
198 for v in v_proj.iter_mut() {
199 *v = next_float();
200 }
201
202 let mut o_proj = vec![0.0f32; q_dim * hidden_dim];
203 for v in o_proj.iter_mut() {
204 *v = next_float();
205 }
206
207 let mut post_attention_layernorm = vec![1.0f32; hidden_dim];
208 for v in post_attention_layernorm.iter_mut() {
209 *v = 1.0 + next_float() * 0.1;
210 }
211
212 let mut gate_proj = vec![0.0f32; hidden_dim * intermediate_dim];
213 for v in gate_proj.iter_mut() {
214 *v = next_float();
215 }
216
217 let mut up_proj = vec![0.0f32; hidden_dim * intermediate_dim];
218 for v in up_proj.iter_mut() {
219 *v = next_float();
220 }
221
222 let mut down_proj = vec![0.0f32; intermediate_dim * hidden_dim];
223 for v in down_proj.iter_mut() {
224 *v = next_float();
225 }
226
227 layers.push(TransformerLayerWeights {
228 input_layernorm,
229 q_proj: q_proj.into(),
230 k_proj: k_proj.into(),
231 v_proj: v_proj.into(),
232 o_proj: o_proj.into(),
233 post_attention_layernorm,
234 gate_proj: gate_proj.into(),
235 up_proj: up_proj.into(),
236 down_proj: down_proj.into(),
237 qkv_proj: None,
238 gate_up_proj: None,
239 q_norm: config.qk_norm.then(|| vec![1.0f32; config.head_dim]),
240 k_norm: config.qk_norm.then(|| vec![1.0f32; config.head_dim]),
241 });
242 }
243
244 let mut final_norm = vec![1.0f32; hidden_dim];
245 for v in final_norm.iter_mut() {
246 *v = 1.0 + next_float() * 0.1;
247 }
248
249 let lm_head = (!config.tie_word_embeddings).then(|| {
250 let mut lm_head = vec![0.0f32; hidden_dim * vocab_size];
251 for v in lm_head.iter_mut() {
252 *v = next_float();
253 }
254 lm_head
255 });
256
257 Self {
258 config: config.clone(),
259 embed_tokens,
260 layers,
261 final_norm,
262 lm_head: lm_head.map(Into::into),
263 }
264 }
265
266 /// Single-token forward pass through all transformer layers.
267 /// Returns the output vector after final RMSNorm of shape [hidden_dim].
268 pub fn forward_token(
269 &self,
270 token_id: u32,
271 pos: usize,
272 seq_state: &mut SequenceState,
273 ) -> Vec<f32> {
274 let hidden_dim = self.config.hidden_dim();
275 let num_heads = self.config.num_heads;
276 let num_kv_heads = self.config.num_kv_heads;
277 let head_dim = self.config.head_dim;
278 let q_dim = num_heads * head_dim;
279 let kv_dim = num_kv_heads * head_dim;
280 let intermediate_dim = self.config.intermediate_dim();
281 let eps = self.config.rms_norm_eps;
282 let rope = self.config.rope();
283
284 // 1. Embedding lookup: x = embed_tokens[token_id]
285 let token_idx = (token_id as usize) % self.config.vocab_size();
286 let embed_slice = &self.embed_tokens[token_idx * hidden_dim..(token_idx + 1) * hidden_dim];
287 let mut x = embed_slice.to_vec();
288
289 // 2. Transformer layers
290 for (layer_idx, layer_w) in self.layers.iter().enumerate() {
291 let kv_cache = &mut seq_state.layers[layer_idx];
292
293 // 2a. Input RMSNorm
294 let mut x_norm = vec![0.0f32; hidden_dim];
295 rmsnorm(&x, &layer_w.input_layernorm, eps, &mut x_norm);
296
297 // 2b. Q, K, V Projections
298 let mut q = vec![0.0f32; q_dim];
299 let mut k = vec![0.0f32; kv_dim];
300 let mut v = vec![0.0f32; kv_dim];
301 matmul_vec(&x_norm, &layer_w.q_proj, &mut q, hidden_dim, q_dim);
302 matmul_vec(&x_norm, &layer_w.k_proj, &mut k, hidden_dim, kv_dim);
303 matmul_vec(&x_norm, &layer_w.v_proj, &mut v, hidden_dim, kv_dim);
304
305 layer_w.apply_qk_norm(&mut q, &mut k, head_dim, eps);
306
307 // 2c. Rotary Positional Embeddings (RoPE)
308 apply_rope_params(
309 &mut q,
310 &mut k,
311 pos,
312 num_heads,
313 num_kv_heads,
314 head_dim,
315 &rope,
316 );
317
318 // 2d. Append to KV Cache
319 kv_cache.cached_k.push(k);
320 kv_cache.cached_v.push(v);
321
322 // 2e. Scaled Dot-Product Attention
323 let mut attn_out = vec![0.0f32; q_dim];
324 scaled_dot_product_attention_single(
325 &q,
326 &kv_cache.cached_k,
327 &kv_cache.cached_v,
328 num_heads,
329 num_kv_heads,
330 head_dim,
331 &mut attn_out,
332 );
333
334 // 2f. Output projection and residual connection
335 let mut attn_proj = vec![0.0f32; hidden_dim];
336 matmul_vec(
337 &attn_out,
338 &layer_w.o_proj,
339 &mut attn_proj,
340 q_dim,
341 hidden_dim,
342 );
343 for i in 0..hidden_dim {
344 x[i] += attn_proj[i];
345 }
346
347 // 2g. Post-Attention RMSNorm
348 let mut post_norm = vec![0.0f32; hidden_dim];
349 rmsnorm(&x, &layer_w.post_attention_layernorm, eps, &mut post_norm);
350
351 // 2h. SwiGLU MLP and residual connection
352 let mut mlp_out = vec![0.0f32; hidden_dim];
353 swiglu(
354 &post_norm,
355 &layer_w.gate_proj,
356 &layer_w.up_proj,
357 &layer_w.down_proj,
358 hidden_dim,
359 intermediate_dim,
360 &mut mlp_out,
361 );
362 for i in 0..hidden_dim {
363 x[i] += mlp_out[i];
364 }
365 }
366
367 // 3. Final RMSNorm
368 let mut x_final = vec![0.0f32; hidden_dim];
369 rmsnorm(&x, &self.final_norm, eps, &mut x_final);
370 x_final
371 }
372
373 /// Projects hidden states through LM Head and computes real vocabulary logits.
374 pub fn compute_logits(&self, hidden_state: &[f32]) -> Vec<f32> {
375 let hidden_dim = self.config.hidden_dim();
376 let vocab_size = self.config.vocab_size();
377 let mut logits = vec![0.0f32; vocab_size];
378 matmul_vec(
379 hidden_state,
380 self.output_projection(),
381 &mut logits,
382 hidden_dim,
383 vocab_size,
384 );
385 logits
386 }
387
388 /// Executes sequence forward pass capturing all intermediate activations and logits.
389 pub fn forward_sequence_with_diagnostics(&self, tokens: &[u32]) -> ForwardDiagnostics {
390 let n = tokens.len();
391 let hidden_dim = self.config.hidden_dim();
392 let num_heads = self.config.num_heads;
393 let num_kv_heads = self.config.num_kv_heads;
394 let head_dim = self.config.head_dim;
395 let q_dim = num_heads * head_dim;
396 let kv_dim = num_kv_heads * head_dim;
397 let intermediate_dim = self.config.intermediate_dim();
398 let vocab_size = self.config.vocab_size();
399 let eps = self.config.rms_norm_eps;
400 let rope = self.config.rope();
401
402 let mut activations = std::collections::HashMap::new();
403 let mut shapes = std::collections::HashMap::new();
404
405 // Register tensor shapes
406 shapes.insert("embed_tokens".to_string(), vec![1, n, hidden_dim]);
407 shapes.insert("final_norm".to_string(), vec![1, n, hidden_dim]);
408 shapes.insert("logits".to_string(), vec![1, n, vocab_size]);
409 shapes.insert("last_token_logits".to_string(), vec![vocab_size]);
410
411 for layer_idx in 0..self.config.num_layers {
412 let prefix = format!("layers.{}", layer_idx);
413 shapes.insert(format!("{}.post_rmsnorm", prefix), vec![1, n, hidden_dim]);
414 shapes.insert(
415 format!("{}.post_rope_q", prefix),
416 vec![1, num_heads, n, head_dim],
417 );
418 shapes.insert(
419 format!("{}.post_rope_k", prefix),
420 vec![1, num_kv_heads, n, head_dim],
421 );
422 shapes.insert(format!("{}.post_attention", prefix), vec![1, n, hidden_dim]);
423 shapes.insert(
424 format!("{}.post_attn_residual", prefix),
425 vec![1, n, hidden_dim],
426 );
427 shapes.insert(format!("{}.post_attn_norm", prefix), vec![1, n, hidden_dim]);
428 shapes.insert(format!("{}.post_swiglu", prefix), vec![1, n, hidden_dim]);
429 shapes.insert(format!("{}.post_residual", prefix), vec![1, n, hidden_dim]);
430 }
431
432 // Allocate output buffers
433 let mut embed_tokens_buf = vec![0.0f32; n * hidden_dim];
434 let mut final_norm_buf = vec![0.0f32; n * hidden_dim];
435 let mut logits_buf = vec![0.0f32; n * vocab_size];
436
437 let mut post_rmsnorm_bufs: Vec<Vec<f32>> = (0..self.config.num_layers)
438 .map(|_| vec![0.0f32; n * hidden_dim])
439 .collect();
440 let mut post_rope_q_bufs: Vec<Vec<f32>> = (0..self.config.num_layers)
441 .map(|_| vec![0.0f32; num_heads * n * head_dim])
442 .collect();
443 let mut post_rope_k_bufs: Vec<Vec<f32>> = (0..self.config.num_layers)
444 .map(|_| vec![0.0f32; num_kv_heads * n * head_dim])
445 .collect();
446 let mut post_attention_bufs: Vec<Vec<f32>> = (0..self.config.num_layers)
447 .map(|_| vec![0.0f32; n * hidden_dim])
448 .collect();
449 let mut post_attn_residual_bufs: Vec<Vec<f32>> = (0..self.config.num_layers)
450 .map(|_| vec![0.0f32; n * hidden_dim])
451 .collect();
452 let mut post_attn_norm_bufs: Vec<Vec<f32>> = (0..self.config.num_layers)
453 .map(|_| vec![0.0f32; n * hidden_dim])
454 .collect();
455 let mut post_swiglu_bufs: Vec<Vec<f32>> = (0..self.config.num_layers)
456 .map(|_| vec![0.0f32; n * hidden_dim])
457 .collect();
458 let mut post_residual_bufs: Vec<Vec<f32>> = (0..self.config.num_layers)
459 .map(|_| vec![0.0f32; n * hidden_dim])
460 .collect();
461
462 let mut seq_state = SequenceState {
463 tokens: Vec::with_capacity(n),
464 layers: vec![LayerKvCache::default(); self.config.num_layers],
465 kv_dtype: KvDType::Fp32,
466 };
467
468 for (pos, &token_id) in tokens.iter().enumerate() {
469 seq_state.tokens.push(token_id);
470
471 // 1. Embedding lookup
472 let token_idx = (token_id as usize) % vocab_size;
473 let embed_slice =
474 &self.embed_tokens[token_idx * hidden_dim..(token_idx + 1) * hidden_dim];
475 embed_tokens_buf[pos * hidden_dim..(pos + 1) * hidden_dim].copy_from_slice(embed_slice);
476 let mut x = embed_slice.to_vec();
477
478 // 2. Transformer layers
479 for (layer_idx, layer_w) in self.layers.iter().enumerate() {
480 let kv_cache = &mut seq_state.layers[layer_idx];
481
482 // 2a. Input RMSNorm
483 let mut x_norm = vec![0.0f32; hidden_dim];
484 rmsnorm(&x, &layer_w.input_layernorm, eps, &mut x_norm);
485 post_rmsnorm_bufs[layer_idx][pos * hidden_dim..(pos + 1) * hidden_dim]
486 .copy_from_slice(&x_norm);
487
488 // 2b. Q, K, V Projections
489 let mut q = vec![0.0f32; q_dim];
490 let mut k = vec![0.0f32; kv_dim];
491 let mut v = vec![0.0f32; kv_dim];
492 matmul_vec(&x_norm, &layer_w.q_proj, &mut q, hidden_dim, q_dim);
493 matmul_vec(&x_norm, &layer_w.k_proj, &mut k, hidden_dim, kv_dim);
494 matmul_vec(&x_norm, &layer_w.v_proj, &mut v, hidden_dim, kv_dim);
495
496 layer_w.apply_qk_norm(&mut q, &mut k, head_dim, eps);
497
498 // 2c. Rotary Positional Embeddings (RoPE)
499 apply_rope_params(
500 &mut q,
501 &mut k,
502 pos,
503 num_heads,
504 num_kv_heads,
505 head_dim,
506 &rope,
507 );
508
509 // Store RoPE Q in [1, num_heads, n, head_dim] layout
510 for h in 0..num_heads {
511 let src_slice = &q[h * head_dim..(h + 1) * head_dim];
512 let dst_idx = h * (n * head_dim) + pos * head_dim;
513 post_rope_q_bufs[layer_idx][dst_idx..dst_idx + head_dim]
514 .copy_from_slice(src_slice);
515 }
516
517 // Store RoPE K in [1, num_kv_heads, n, head_dim] layout
518 for kv_h in 0..num_kv_heads {
519 let src_slice = &k[kv_h * head_dim..(kv_h + 1) * head_dim];
520 let dst_idx = kv_h * (n * head_dim) + pos * head_dim;
521 post_rope_k_bufs[layer_idx][dst_idx..dst_idx + head_dim]
522 .copy_from_slice(src_slice);
523 }
524
525 // 2d. Append to KV Cache
526 kv_cache.cached_k.push(k);
527 kv_cache.cached_v.push(v);
528
529 // 2e. Scaled Dot-Product Attention
530 let mut attn_out = vec![0.0f32; q_dim];
531 scaled_dot_product_attention_single(
532 &q,
533 &kv_cache.cached_k,
534 &kv_cache.cached_v,
535 num_heads,
536 num_kv_heads,
537 head_dim,
538 &mut attn_out,
539 );
540
541 // 2f. Output projection and residual connection
542 let mut attn_proj = vec![0.0f32; hidden_dim];
543 matmul_vec(
544 &attn_out,
545 &layer_w.o_proj,
546 &mut attn_proj,
547 q_dim,
548 hidden_dim,
549 );
550 post_attention_bufs[layer_idx][pos * hidden_dim..(pos + 1) * hidden_dim]
551 .copy_from_slice(&attn_proj);
552
553 for i in 0..hidden_dim {
554 x[i] += attn_proj[i];
555 }
556 post_attn_residual_bufs[layer_idx][pos * hidden_dim..(pos + 1) * hidden_dim]
557 .copy_from_slice(&x);
558
559 // 2g. Post-Attention RMSNorm
560 let mut post_norm = vec![0.0f32; hidden_dim];
561 rmsnorm(&x, &layer_w.post_attention_layernorm, eps, &mut post_norm);
562 post_attn_norm_bufs[layer_idx][pos * hidden_dim..(pos + 1) * hidden_dim]
563 .copy_from_slice(&post_norm);
564
565 // 2h. SwiGLU MLP and residual connection
566 let mut mlp_out = vec![0.0f32; hidden_dim];
567 swiglu(
568 &post_norm,
569 &layer_w.gate_proj,
570 &layer_w.up_proj,
571 &layer_w.down_proj,
572 hidden_dim,
573 intermediate_dim,
574 &mut mlp_out,
575 );
576 post_swiglu_bufs[layer_idx][pos * hidden_dim..(pos + 1) * hidden_dim]
577 .copy_from_slice(&mlp_out);
578
579 for i in 0..hidden_dim {
580 x[i] += mlp_out[i];
581 }
582 post_residual_bufs[layer_idx][pos * hidden_dim..(pos + 1) * hidden_dim]
583 .copy_from_slice(&x);
584 }
585
586 // 3. Final RMSNorm
587 let mut x_final = vec![0.0f32; hidden_dim];
588 rmsnorm(&x, &self.final_norm, eps, &mut x_final);
589 final_norm_buf[pos * hidden_dim..(pos + 1) * hidden_dim].copy_from_slice(&x_final);
590
591 // 4. LM Head Logits
592 let tok_logits = self.compute_logits(&x_final);
593 logits_buf[pos * vocab_size..(pos + 1) * vocab_size].copy_from_slice(&tok_logits);
594 }
595
596 let last_token_logits = logits_buf[(n - 1) * vocab_size..n * vocab_size].to_vec();
597
598 activations.insert("embed_tokens".to_string(), embed_tokens_buf);
599 activations.insert("final_norm".to_string(), final_norm_buf);
600 activations.insert("logits".to_string(), logits_buf);
601 activations.insert("last_token_logits".to_string(), last_token_logits);
602
603 for layer_idx in 0..self.config.num_layers {
604 let prefix = format!("layers.{}", layer_idx);
605 activations.insert(
606 format!("{}.post_rmsnorm", prefix),
607 post_rmsnorm_bufs[layer_idx].clone(),
608 );
609 activations.insert(
610 format!("{}.post_rope_q", prefix),
611 post_rope_q_bufs[layer_idx].clone(),
612 );
613 activations.insert(
614 format!("{}.post_rope_k", prefix),
615 post_rope_k_bufs[layer_idx].clone(),
616 );
617 activations.insert(
618 format!("{}.post_attention", prefix),
619 post_attention_bufs[layer_idx].clone(),
620 );
621 activations.insert(
622 format!("{}.post_attn_residual", prefix),
623 post_attn_residual_bufs[layer_idx].clone(),
624 );
625 activations.insert(
626 format!("{}.post_attn_norm", prefix),
627 post_attn_norm_bufs[layer_idx].clone(),
628 );
629 activations.insert(
630 format!("{}.post_swiglu", prefix),
631 post_swiglu_bufs[layer_idx].clone(),
632 );
633 activations.insert(
634 format!("{}.post_residual", prefix),
635 post_residual_bufs[layer_idx].clone(),
636 );
637 }
638
639 ForwardDiagnostics {
640 activations,
641 shapes,
642 }
643 }
644
645 /// Autoregressive greedy decode for a given sequence of prompt tokens.
646 pub fn generate_greedy(&self, prompt_tokens: &[u32], num_steps: usize) -> Vec<u32> {
647 let mut seq_state = SequenceState {
648 tokens: Vec::with_capacity(prompt_tokens.len() + num_steps),
649 layers: vec![LayerKvCache::default(); self.config.num_layers],
650 kv_dtype: KvDType::Fp32,
651 };
652
653 let mut last_hidden = Vec::new();
654 for (idx, &token_id) in prompt_tokens.iter().enumerate() {
655 seq_state.tokens.push(token_id);
656 last_hidden = self.forward_token(token_id, idx, &mut seq_state);
657 }
658
659 let mut generated = Vec::with_capacity(num_steps);
660 let mut logits = self.compute_logits(&last_hidden);
661 let (mut next_tok, _) = crate::tensor::sample_argmax(&logits);
662 generated.push(next_tok);
663
664 for _ in 1..num_steps {
665 let pos = seq_state.tokens.len();
666 seq_state.tokens.push(next_tok);
667 let hidden = self.forward_token(next_tok, pos, &mut seq_state);
668 logits = self.compute_logits(&hidden);
669 next_tok = crate::tensor::sample_argmax(&logits).0;
670 generated.push(next_tok);
671 }
672
673 generated
674 }
675
676 /// Loads model weights directly from a standard safetensors binary buffer.
677 pub fn from_safetensors_bytes(bytes: &[u8], config: &ModelConfig) -> Result<Self, String> {
678 if bytes.len() < 8 {
679 return Err(
680 "Invalid safetensors binary: buffer smaller than 8 bytes header".to_string(),
681 );
682 }
683
684 let header_len = u64::from_le_bytes(bytes[0..8].try_into().unwrap()) as usize;
685 if bytes.len() < 8 + header_len {
686 return Err("Invalid safetensors binary: header length exceeds buffer".to_string());
687 }
688
689 let header_str = std::str::from_utf8(&bytes[8..8 + header_len])
690 .map_err(|e| format!("Safetensors header is not valid UTF-8: {}", e))?;
691
692 let header: Value = serde_json::from_str(header_str)
693 .map_err(|e| format!("Failed to parse safetensors JSON header: {}", e))?;
694
695 let data_offset = 8 + header_len;
696 let data_bytes = &bytes[data_offset..];
697
698 let extract_tensor = |name: &str| -> Option<Vec<f32>> {
699 let info = header.get(name)?;
700 let offsets = info.get("data_offsets")?.as_array()?;
701 let start = offsets.first()?.as_u64()? as usize;
702 let end = offsets.get(1)?.as_u64()? as usize;
703 let dtype = info.get("dtype")?.as_str()?;
704
705 if end > data_bytes.len() || start > end {
706 return None;
707 }
708
709 let raw_slice = &data_bytes[start..end];
710 match dtype {
711 "F32" => {
712 let count = (end - start) / 4;
713 let mut floats = Vec::with_capacity(count);
714 for chunk in raw_slice.chunks_exact(4) {
715 floats.push(f32::from_le_bytes(chunk.try_into().unwrap()));
716 }
717 Some(floats)
718 }
719 "BF16" => {
720 let count = (end - start) / 2;
721 let mut floats = Vec::with_capacity(count);
722 for chunk in raw_slice.chunks_exact(2) {
723 let bits = u16::from_le_bytes(chunk.try_into().unwrap());
724 floats.push(f32::from_bits((bits as u32) << 16));
725 }
726 Some(floats)
727 }
728 "F16" => {
729 let count = (end - start) / 2;
730 let mut floats = Vec::with_capacity(count);
731 for chunk in raw_slice.chunks_exact(2) {
732 let bits = u16::from_le_bytes(chunk.try_into().unwrap());
733 floats.push(half_to_float(bits));
734 }
735 Some(floats)
736 }
737 _ => None,
738 }
739 };
740
741 let mut weights = Self::reference_test_weights(config);
742
743 if let Some(t) = extract_tensor("model.embed_tokens.weight") {
744 weights.embed_tokens = t;
745 }
746
747 for (idx, layer) in weights.layers.iter_mut().enumerate() {
748 let prefix = format!("model.layers.{}", idx);
749 if let Some(t) = extract_tensor(&format!("{}.input_layernorm.weight", prefix)) {
750 layer.input_layernorm = t;
751 }
752 if let Some(t) = extract_tensor(&format!("{}.self_attn.q_proj.weight", prefix)) {
753 layer.q_proj = t.into();
754 }
755 if let Some(t) = extract_tensor(&format!("{}.self_attn.k_proj.weight", prefix)) {
756 layer.k_proj = t.into();
757 }
758 if let Some(t) = extract_tensor(&format!("{}.self_attn.v_proj.weight", prefix)) {
759 layer.v_proj = t.into();
760 }
761 if let Some(t) = extract_tensor(&format!("{}.self_attn.o_proj.weight", prefix)) {
762 layer.o_proj = t.into();
763 }
764 if let Some(t) = extract_tensor(&format!("{}.post_attention_layernorm.weight", prefix))
765 {
766 layer.post_attention_layernorm = t;
767 }
768 if let Some(t) = extract_tensor(&format!("{}.mlp.gate_proj.weight", prefix)) {
769 layer.gate_proj = t.into();
770 }
771 if let Some(t) = extract_tensor(&format!("{}.mlp.up_proj.weight", prefix)) {
772 layer.up_proj = t.into();
773 }
774 if let Some(t) = extract_tensor(&format!("{}.mlp.down_proj.weight", prefix)) {
775 layer.down_proj = t.into();
776 }
777 if config.qk_norm {
778 layer.q_norm = extract_tensor(&format!("{}.self_attn.q_norm.weight", prefix));
779 layer.k_norm = extract_tensor(&format!("{}.self_attn.k_norm.weight", prefix));
780 }
781 }
782
783 if let Some(t) = extract_tensor("model.norm.weight") {
784 weights.final_norm = t;
785 }
786
787 if !config.tie_word_embeddings {
788 if let Some(t) = extract_tensor("lm_head.weight") {
789 weights.lm_head = Some(t.into());
790 }
791 }
792
793 Ok(weights)
794 }
795
796 /// Loads weights strictly from a pre-validated LoadedCheckpoint without synthetic fallback.
797 /// FP32 tensors are decoded from the checkpoint capsule on demand. They are not stored twice.
798 pub fn from_loaded_checkpoint(
799 checkpoint: &crate::checkpoint::LoadedCheckpoint,
800 config: &ModelConfig,
801 ) -> Result<Self, crate::checkpoint::CheckpointError> {
802 let decode = |name: &str| -> Result<Vec<f32>, crate::checkpoint::CheckpointError> {
803 checkpoint.decode_fp32(name).map_err(|err| match err {
804 crate::capsule::CapsuleError::MissingTensor(name) => {
805 crate::checkpoint::CheckpointError::MissingTensor(name)
806 }
807 other => crate::checkpoint::CheckpointError::Capsule(other.to_string()),
808 })
809 };
810
811 let embed_tokens = decode("model.embed_tokens.weight")?;
812
813 let mut layers = Vec::with_capacity(config.num_layers);
814 for idx in 0..config.num_layers {
815 let prefix = format!("model.layers.{}", idx);
816
817 let input_layernorm = decode(&format!("{}.input_layernorm.weight", prefix))?;
818 let q_proj = decode(&format!("{}.self_attn.q_proj.weight", prefix))?;
819 let k_proj = decode(&format!("{}.self_attn.k_proj.weight", prefix))?;
820 let v_proj = decode(&format!("{}.self_attn.v_proj.weight", prefix))?;
821 let o_proj = decode(&format!("{}.self_attn.o_proj.weight", prefix))?;
822 let post_attention_layernorm =
823 decode(&format!("{}.post_attention_layernorm.weight", prefix))?;
824 let gate_proj = decode(&format!("{}.mlp.gate_proj.weight", prefix))?;
825 let up_proj = decode(&format!("{}.mlp.up_proj.weight", prefix))?;
826 let down_proj = decode(&format!("{}.mlp.down_proj.weight", prefix))?;
827 let (q_norm, k_norm) = if config.qk_norm {
828 (
829 Some(decode(&format!("{}.self_attn.q_norm.weight", prefix))?),
830 Some(decode(&format!("{}.self_attn.k_norm.weight", prefix))?),
831 )
832 } else {
833 (None, None)
834 };
835
836 layers.push(TransformerLayerWeights {
837 input_layernorm,
838 q_proj: q_proj.into(),
839 k_proj: k_proj.into(),
840 v_proj: v_proj.into(),
841 o_proj: o_proj.into(),
842 post_attention_layernorm,
843 gate_proj: gate_proj.into(),
844 up_proj: up_proj.into(),
845 down_proj: down_proj.into(),
846 qkv_proj: None,
847 gate_up_proj: None,
848 q_norm,
849 k_norm,
850 });
851 }
852
853 let final_norm = decode("model.norm.weight")?;
854 let lm_head = if config.tie_word_embeddings {
855 None
856 } else {
857 Some(decode("lm_head.weight")?)
858 };
859
860 Ok(Self {
861 config: config.clone(),
862 embed_tokens,
863 layers,
864 final_norm,
865 lm_head: lm_head.map(Into::into),
866 })
867 }
868
869 /// Loads model weights strictly from a safetensors checkpoint on disk, validated against
870 /// the tensor catalog `config` describes (`checkpoint::llama_catalog`). `path` is one
871 /// `.safetensors` file or a sharded `model.safetensors.index.json`.
872 pub fn load_from_safetensors<P: AsRef<std::path::Path>>(
873 path: P,
874 config: &ModelConfig,
875 ) -> Result<Self, crate::checkpoint::CheckpointError> {
876 let catalog = crate::checkpoint::llama_catalog(config);
877 let checkpoint = crate::checkpoint::load_checkpoint_with_catalog(path, &catalog)?;
878 Self::from_loaded_checkpoint(&checkpoint, config)
879 }
880}
881
882/// Converts IEEE 754 half-precision float (f16) bits to f32.
883fn half_to_float(bits: u16) -> f32 {
884 let sign = ((bits >> 15) & 1) as u32;
885 let exp = ((bits >> 10) & 0x1f) as u32;
886 let frac = (bits & 0x3ff) as u32;
887
888 if exp == 0 {
889 if frac == 0 {
890 f32::from_bits(sign << 31)
891 } else {
892 let mut f = frac;
893 let mut shift = 0;
894 while (f & 0x400) == 0 {
895 f <<= 1;
896 shift += 1;
897 }
898 let exp32 = (127 - 15 - shift + 1) as u32;
899 let frac32 = (f & 0x3ff) << 13;
900 f32::from_bits((sign << 31) | (exp32 << 23) | frac32)
901 }
902 } else if exp == 31 {
903 f32::from_bits((sign << 31) | (0xff << 23) | (frac << 13))
904 } else {
905 let exp32 = exp + 127 - 15;
906 let frac32 = frac << 13;
907 f32::from_bits((sign << 31) | (exp32 << 23) | frac32)
908 }
909}
910
911#[cfg(test)]
912mod tests {
913 use super::*;
914
915 #[test]
916 fn test_reference_weights_initialization() {
917 let config = ModelConfig {
918 model_id: "test-llama".to_string(),
919 max_sequence_length: 2048,
920 block_size: 16,
921 num_layers: 2,
922 num_heads: 4,
923 head_dim: 16,
924 num_kv_heads: 4,
925 hidden_dim: 64,
926 intermediate_dim: 128,
927 vocab_size: 256,
928 rms_norm_eps: 1e-5,
929 rope_theta: 10000.0,
930 rope_scaling: None,
931 tie_word_embeddings: false,
932 eos_token_ids: Vec::new(),
933 qk_norm: false,
934 };
935
936 let weights = TransformerWeights::reference_test_weights(&config);
937 assert_eq!(weights.embed_tokens.len(), 256 * 64);
938 assert_eq!(weights.layers.len(), 2);
939 assert_eq!(weights.layers[0].q_proj.len(), 64 * 64);
940 assert_eq!(weights.layers[0].k_proj.len(), 64 * 64);
941 assert_eq!(weights.layers[0].v_proj.len(), 64 * 64);
942 assert_eq!(weights.layers[0].gate_proj.len(), 64 * 128);
943 assert_eq!(weights.layers[0].down_proj.len(), 128 * 64);
944 assert_eq!(weights.final_norm.len(), 64);
945 assert_eq!(weights.output_projection().len(), 64 * 256);
946 }
947
948 #[test]
949 fn test_from_loaded_checkpoint_success_and_missing_key() {
950 let config = ModelConfig {
951 model_id: "test-llama".to_string(),
952 max_sequence_length: 2048,
953 block_size: 16,
954 num_layers: 1,
955 num_heads: 4,
956 head_dim: 16,
957 num_kv_heads: 4,
958 hidden_dim: 64,
959 intermediate_dim: 128,
960 vocab_size: 256,
961 rms_norm_eps: 1e-5,
962 rope_theta: 10000.0,
963 rope_scaling: None,
964 tie_word_embeddings: false,
965 eos_token_ids: Vec::new(),
966 qk_norm: false,
967 };
968
969 // 1. Missing tensor fails loudly with CheckpointError::MissingTensor
970 let empty_checkpoint = crate::checkpoint::LoadedCheckpoint::new();
971 let err =
972 TransformerWeights::from_loaded_checkpoint(&empty_checkpoint, &config).unwrap_err();
973 assert_eq!(
974 err,
975 crate::checkpoint::CheckpointError::MissingTensor(
976 "model.embed_tokens.weight".to_string()
977 )
978 );
979
980 // 2. Populated checkpoint loads correctly.
981 // Values are exact in bf16 so decode_fp32 round-trips without rounding.
982 let bf16_filled = |name: &str, shape: Vec<usize>, value: f32| {
983 let n: usize = shape.iter().product();
984 let values = vec![value; n];
985 (
986 name.to_string(),
987 shape,
988 crate::checkpoint::encode_fp32_to_bf16(&values),
989 )
990 };
991 let checkpoint = crate::checkpoint::LoadedCheckpoint::from_bf16_tensors(vec![
992 bf16_filled("model.embed_tokens.weight", vec![256, 64], 0.5),
993 bf16_filled("model.layers.0.input_layernorm.weight", vec![64], 1.0),
994 bf16_filled("model.layers.0.self_attn.q_proj.weight", vec![64, 64], 2.0),
995 bf16_filled("model.layers.0.self_attn.k_proj.weight", vec![64, 64], 0.5),
996 bf16_filled("model.layers.0.self_attn.v_proj.weight", vec![64, 64], 1.0),
997 bf16_filled("model.layers.0.self_attn.o_proj.weight", vec![64, 64], 0.5),
998 bf16_filled(
999 "model.layers.0.post_attention_layernorm.weight",
1000 vec![64],
1001 1.0,
1002 ),
1003 bf16_filled("model.layers.0.mlp.gate_proj.weight", vec![128, 64], 2.0),
1004 bf16_filled("model.layers.0.mlp.up_proj.weight", vec![128, 64], 0.5),
1005 bf16_filled("model.layers.0.mlp.down_proj.weight", vec![64, 128], 1.0),
1006 bf16_filled("model.norm.weight", vec![64], 1.0),
1007 bf16_filled("lm_head.weight", vec![256, 64], 0.5),
1008 ]);
1009
1010 let weights = TransformerWeights::from_loaded_checkpoint(&checkpoint, &config).unwrap();
1011 assert_eq!(weights.embed_tokens.len(), 256 * 64);
1012 assert_eq!(weights.embed_tokens[0], 0.5);
1013 assert_eq!(weights.layers.len(), 1);
1014 assert_eq!(weights.layers[0].q_proj[0], 2.0);
1015 assert_eq!(weights.final_norm.len(), 64);
1016 assert_eq!(weights.final_norm[0], 1.0);
1017 assert_eq!(weights.output_projection()[0], 0.5);
1018 }
1019}