1use 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
19pub fn executor(model: &Model, threads: usize) -> kime_tensor::Result<Executor<CpuBackend>> {
26 executor_from(&model.spec, &model.graph, &model.tensors, threads)
27}
28
29pub 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#[derive(Debug, Clone, Copy)]
52pub struct Input<'a> {
53 pub ids: &'a [u32],
55 pub markers: &'a [u32],
57 pub qtype: usize,
59}
60
61#[derive(Debug, Clone, PartialEq)]
63pub struct Output {
64 pub logits: Vec<f32>,
66 pub act: [f32; 2],
68}
69
70#[derive(Debug)]
72pub struct Compat {
73 spec: LayaSpec,
74 graph: LayaGraph,
75 w: Vec<Vec<f32>>,
76 threads: usize,
77}
78
79impl Compat {
80 #[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 #[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 pub fn set_threads(&mut self, threads: usize) {
96 self.threads = threads.max(1);
97 }
98
99 #[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 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 #[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 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 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 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 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 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 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#[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}