Skip to main content

kime_cpu/
compat.rs

1//! The Laya compat graph on the reference kernels: ModernBERT or mmBERT, the type embedding, the
2//! two layer decision head, the option scorer and the act head, as `DecisionModel.forward` in
3//! Laya 0.3.7 runs them in FP32.
4//!
5//! This is the correctness reference. It allocates its buffers per call and converts the F16
6//! weights to f32 once at load, which costs 1.7 GB for Laya English. The fast paths are checked
7//! against it.
8
9use kime_model::Model;
10use kime_model::laya::{Affine, LayaGraph, LayaSpec};
11
12use crate::attention::{HEAD, attention};
13use crate::gemm::linear;
14use crate::ops::{Rope, add, geglu, gelu, layer_norm};
15use crate::par;
16
17/// PyTorch's LayerNorm default, which the head and scorer use.
18const TORCH_EPS: f64 = 1e-5;
19
20/// One question, laid out as Laya lays it out.
21#[derive(Debug, Clone, Copy)]
22pub struct Input<'a> {
23    /// Token ids, `[CLS] ... [SEP]`.
24    pub ids: &'a [u32],
25    /// The position of each option's mask token.
26    pub markers: &'a [u32],
27    /// 0 for choice, 1 for score, 2 for noul.
28    pub qtype: usize,
29}
30
31/// What the model says about one question, before temperature.
32#[derive(Debug, Clone, PartialEq)]
33pub struct Output {
34    /// One logit per marker.
35    pub logits: Vec<f32>,
36    /// The act head's two logits.
37    pub act: [f32; 2],
38}
39
40/// A compat checkpoint ready to run on the CPU.
41#[derive(Debug)]
42pub struct Compat {
43    spec: LayaSpec,
44    graph: LayaGraph,
45    w: Vec<Vec<f32>>,
46    threads: usize,
47}
48
49impl Compat {
50    /// Converts the weights of `model` to f32, on `threads` threads, which the forward pass uses
51    /// too.
52    #[must_use]
53    pub fn new(model: &Model, threads: usize) -> Self {
54        let t = &model.tensors;
55        let w = par::map(t.entries().len(), threads, |i| t.view(i).to_f32());
56        Self { spec: model.spec.clone(), graph: model.graph.clone(), w, threads: threads.max(1) }
57    }
58
59    /// Changes the number of threads the forward pass uses. The results do not change with it.
60    pub fn set_threads(&mut self, threads: usize) {
61        self.threads = threads.max(1);
62    }
63
64    /// The checkpoint's configuration.
65    #[must_use]
66    pub fn spec(&self) -> &LayaSpec {
67        &self.spec
68    }
69
70    fn w(&self, i: usize) -> &[f32] {
71        &self.w[i]
72    }
73
74    /// `y = x wᵀ + b` for a bound weight.
75    fn linear(&self, x: &[f32], k: usize, w: usize, b: Option<usize>) -> Vec<f32> {
76        let m = x.len() / k;
77        let n = self.w[w].len() / k;
78        let mut y = vec![0f32; m * n];
79        linear(x, m, k, self.w(w), n, b.map(|b| self.w(b)), &mut y, self.threads);
80        y
81    }
82
83    fn affine(&self, x: &[f32], k: usize, a: Affine) -> Vec<f32> {
84        self.linear(x, k, a.w, Some(a.b))
85    }
86
87    /// Runs a batch. Sequences are packed end to end, so a batch costs what its tokens cost.
88    ///
89    /// # Panics
90    ///
91    /// If a token id is past the vocabulary, a marker is past its sequence, or a qtype is not 0,
92    /// 1 or 2.
93    #[must_use]
94    pub fn forward(&self, batch: &[Input<'_>]) -> Vec<Output> {
95        let e = &self.spec.encoder;
96        let g = &self.graph;
97        let d = e.d;
98        let heads = e.heads;
99        assert_eq!(d, heads * HEAD);
100        let mut cu = vec![0usize];
101        for x in batch {
102            cu.push(cu.last().unwrap() + x.ids.len());
103        }
104        let t = *cu.last().unwrap();
105        let longest = batch.iter().map(|x| x.ids.len()).max().unwrap_or(0);
106
107        // Embeddings, then the embedding norm.
108        let emb = self.w(g.tok_embeddings);
109        let mut h = Vec::with_capacity(t * d);
110        for x in batch {
111            for &id in x.ids {
112                let id = id as usize;
113                assert!(id < e.vocab, "token id {id} is past the vocabulary");
114                h.extend_from_slice(&emb[id * d..(id + 1) * d]);
115            }
116        }
117        let mut x = vec![0f32; t * d];
118        layer_norm(&h, d, self.w(g.embed_norm), None, e.norm_eps, &mut x);
119        std::mem::swap(&mut h, &mut x);
120
121        // The encoder.
122        let ropes: Vec<(f64, Rope)> = [e.rope_global, e.rope_local]
123            .iter()
124            .map(|&theta| (theta, Rope::new(theta, HEAD, longest)))
125            .collect();
126        let mut att = vec![0f32; t * d];
127        let mut act = vec![0f32; t * e.inter];
128        for layer in &g.layers {
129            let xin = match layer.attn_norm {
130                Some(n) => {
131                    layer_norm(&h, d, self.w(n), None, e.norm_eps, &mut x);
132                    &x
133                }
134                None => &h,
135            };
136            let mut qkv = self.linear(xin, d, layer.wqkv, None);
137            let rope =
138                &ropes.iter().find(|r| r.0.to_bits() == layer.rope_theta.to_bits()).unwrap().1;
139            for s in 0..batch.len() {
140                for (pos, i) in (cu[s]..cu[s + 1]).enumerate() {
141                    let row = &mut qkv[i * 3 * d..(i + 1) * 3 * d];
142                    for head in row[..2 * d].as_chunks_mut::<HEAD>().0 {
143                        rope.apply(head, pos);
144                    }
145                }
146            }
147            let window = (!layer.global).then_some(e.window / 2);
148            attention(&qkv, heads, &cu, window, &mut att, self.threads);
149            add(&mut h, &self.linear(&att, d, layer.wo, None));
150            layer_norm(&h, d, self.w(layer.mlp_norm), None, e.norm_eps, &mut x);
151            let u = self.linear(&x, d, layer.wi, None);
152            geglu(&u, e.inter, &mut act);
153            add(&mut h, &self.linear(&act, e.inter, layer.mlp_wo, None));
154        }
155        layer_norm(&h, d, self.w(g.final_norm), None, e.norm_eps, &mut x);
156        std::mem::swap(&mut h, &mut x);
157
158        // The question type, added to every position.
159        let types = self.w(g.type_emb);
160        for (s, input) in batch.iter().enumerate() {
161            assert!(input.qtype < 3, "qtype {} is not 0, 1 or 2", input.qtype);
162            let te = &types[input.qtype * d..(input.qtype + 1) * d];
163            for i in cu[s]..cu[s + 1] {
164                add(&mut h[i * d..(i + 1) * d], te);
165            }
166        }
167
168        // The decision head, PyTorch TransformerEncoderLayers with norm_first and ReLU.
169        for l in &g.head {
170            layer_norm(&h, d, self.w(l.norm1_w), Some(self.w(l.norm1_b)), TORCH_EPS, &mut x);
171            let qkv = self.linear(&x, d, l.in_proj_w, Some(l.in_proj_b));
172            attention(&qkv, heads, &cu, None, &mut att, self.threads);
173            add(&mut h, &self.linear(&att, d, l.out_proj_w, Some(l.out_proj_b)));
174            layer_norm(&h, d, self.w(l.norm2_w), Some(self.w(l.norm2_b)), TORCH_EPS, &mut x);
175            let mut f = self.linear(&x, d, l.linear1_w, Some(l.linear1_b));
176            f.iter_mut().for_each(|v| *v = v.max(0.0));
177            let ffn = f.len() / t.max(1);
178            add(&mut h, &self.linear(&f, ffn, l.linear2_w, Some(l.linear2_b)));
179        }
180
181        // The scorer, on every marker of every question at once.
182        let mut m = Vec::new();
183        for (s, input) in batch.iter().enumerate() {
184            for &p in input.markers {
185                let p = p as usize;
186                assert!(p < input.ids.len(), "marker {p} is past its sequence");
187                m.extend_from_slice(&h[(cu[s] + p) * d..(cu[s] + p + 1) * d]);
188            }
189        }
190        let mut mn = vec![0f32; m.len()];
191        let sn = g.scorer_norm;
192        layer_norm(&m, d, self.w(sn.w), Some(self.w(sn.b)), TORCH_EPS, &mut mn);
193        let mut z = self.affine(&mn, d, g.scorer_in);
194        z.iter_mut().for_each(|v| *v = gelu(*v));
195        let logits = self.affine(&z, d, g.scorer_out);
196
197        // The act head: the CLS row and four numbers about the option distribution.
198        let mut feats = Vec::with_capacity(batch.len() * (d + 4));
199        let mut at = 0;
200        let mut out = Vec::with_capacity(batch.len());
201        for (s, input) in batch.iter().enumerate() {
202            let k = input.markers.len();
203            let l = logits[at..at + k].to_vec();
204            at += k;
205            let first = cu[s] * d;
206            if cu[s + 1] > cu[s] {
207                feats.extend_from_slice(&h[first..first + d]);
208            } else {
209                feats.extend(std::iter::repeat_n(0.0, d));
210            }
211            feats.extend_from_slice(&act_features(&l));
212            out.push(Output { logits: l, act: [0.0; 2] });
213        }
214        let a = self.affine(&feats, d + 4, g.act_in);
215        let a: Vec<f32> = a.iter().map(|&v| gelu(v)).collect();
216        let a = self.affine(&a, a.len() / batch.len().max(1), g.act_out);
217        for (s, o) in out.iter_mut().enumerate() {
218            o.act = [a[2 * s], a[2 * s + 1]];
219        }
220        out
221    }
222}
223
224/// `[top1, top1 - top2, entropy / ln k, k / 255]` over the softmax of the logits, with `k` at
225/// least 2, as Laya computes them. A single option has a top2 of 0. No options at all is an error
226/// in Laya, and gives zeros here apart from the count.
227#[must_use]
228pub fn act_features(logits: &[f32]) -> [f32; 4] {
229    let kf = logits.len().max(2) as f32;
230    if logits.is_empty() {
231        return [0.0, 0.0, 0.0, kf / 255.0];
232    }
233    let mx = logits.iter().copied().fold(f32::NEG_INFINITY, f32::max);
234    let e: Vec<f32> = logits.iter().map(|&l| (l - mx).exp()).collect();
235    let sum: f32 = e.iter().sum();
236    let p: Vec<f32> = e.iter().map(|x| x / sum).collect();
237    let ent = -p.iter().map(|&q| q * q.max(1e-9).ln()).sum::<f32>() / kf.ln();
238    let mut sorted = p.clone();
239    sorted.sort_by(|a, b| b.total_cmp(a));
240    let top1 = sorted[0];
241    let top2 = sorted.get(1).copied().unwrap_or(0.0);
242    [top1, top1 - top2, ent, kf / 255.0]
243}