1use 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
17const TORCH_EPS: f64 = 1e-5;
19
20#[derive(Debug, Clone, Copy)]
22pub struct Input<'a> {
23 pub ids: &'a [u32],
25 pub markers: &'a [u32],
27 pub qtype: usize,
29}
30
31#[derive(Debug, Clone, PartialEq)]
33pub struct Output {
34 pub logits: Vec<f32>,
36 pub act: [f32; 2],
38}
39
40#[derive(Debug)]
42pub struct Compat {
43 spec: LayaSpec,
44 graph: LayaGraph,
45 w: Vec<Vec<f32>>,
46 threads: usize,
47}
48
49impl Compat {
50 #[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 pub fn set_threads(&mut self, threads: usize) {
61 self.threads = threads.max(1);
62 }
63
64 #[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 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 #[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 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 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 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 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 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 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#[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}