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