1use std::cell::UnsafeCell;
17use std::sync::Arc;
18use std::time::Instant;
19
20use kime_tensor::plan::{Epilogue, Graph, Op, Rows, Val, layout};
21use kime_tensor::{Backend, Batch, Bucket, Caps, Error, HostTensor, Outputs, Result};
22
23use crate::attention::{self, HEAD, QB};
24use crate::gemm::{self, Gemm};
25use crate::ops::{Rope, geglu, layer_norm};
26use crate::par::{self, Shared};
27use crate::pool::Pool;
28use crate::qgemm::{self, QGemm, QMatrix};
29
30#[derive(Debug)]
32pub struct Tensor {
33 pub shape: Vec<usize>,
35 pub data: Vec<f32>,
37 pub packed: Vec<f32>,
40 pub quant: Option<QMatrix>,
42}
43
44#[derive(Debug, Clone)]
46pub struct Weights(Arc<[Tensor]>);
47
48#[derive(Debug)]
50pub struct CpuBackend {
51 pool: Pool,
52 int8: bool,
53}
54
55impl CpuBackend {
56 #[must_use]
58 pub fn new(threads: usize) -> Self {
59 Self { pool: Pool::new(threads.max(1)), int8: false }
60 }
61
62 #[must_use]
66 pub fn with_int8(mut self, on: bool) -> Self {
67 self.int8 = on;
68 self
69 }
70
71 #[must_use]
73 pub fn int8(&self) -> bool {
74 self.int8
75 }
76
77 fn int8_rows(&self, rows: Rows) -> bool {
79 self.int8 && rows == Rows::Tokens
80 }
81
82 #[must_use]
84 pub fn threads(&self) -> usize {
85 self.pool.threads()
86 }
87}
88
89#[derive(Debug, Clone, Copy)]
91struct Loc {
92 off: usize,
93 rows: Rows,
94 width: usize,
95}
96
97#[derive(Debug, Clone, Copy)]
98enum Step {
99 Embed { table: usize, out: Loc },
100 LayerNorm { x: Loc, w: usize, b: Option<usize>, eps: f64, out: Loc },
101 Gemm { a: Loc, w: usize, b: Option<usize>, ep: Epilogue, out: Loc },
102 Gemm8 { a: Loc, w: usize, b: Option<usize>, ep: Epilogue, out: Loc },
103 Rope { qkv: Loc, rope: usize },
104 Attention { qkv: Loc, window: Option<usize>, out: Loc },
105 GeGlu { x: Loc, out: Loc },
106 AddType { h: Loc, table: usize },
107 Gather { h: Loc, out: Loc },
108 ActFeatures { h: Loc, logits: Loc, out: Loc },
109}
110
111impl Step {
112 fn name(&self) -> &'static str {
113 match self {
114 Step::Embed { .. } => "embed",
115 Step::LayerNorm { .. } => "layer norm",
116 Step::Gemm { .. } => "gemm",
117 Step::Gemm8 { .. } => "gemm int8",
118 Step::Rope { .. } => "rope",
119 Step::Attention { .. } => "attention",
120 Step::GeGlu { .. } => "geglu",
121 Step::AddType { .. } => "type embedding",
122 Step::Gather { .. } => "gather markers",
123 Step::ActFeatures { .. } => "act features",
124 }
125 }
126}
127
128struct PerWorker<T>(Vec<UnsafeCell<T>>);
130
131unsafe impl<T: Send> Sync for PerWorker<T> {}
134
135impl<T> PerWorker<T> {
136 #[allow(clippy::mut_from_ref)]
140 unsafe fn get(&self, worker: usize) -> &mut T {
141 unsafe { &mut *self.0[worker].get() }
143 }
144}
145
146pub struct CpuPlan {
148 w: Weights,
149 bucket: Bucket,
150 steps: Vec<Step>,
151 arena: Vec<f32>,
152 ropes: Vec<Rope>,
153 logits: Loc,
154 act: Loc,
155 cu: Vec<usize>,
158 mcu: Vec<usize>,
159 row_seq: Vec<u32>,
160 blocks: Vec<(u32, u32)>,
161 scratch: PerWorker<Vec<f32>>,
162 profile: Option<Vec<u64>>,
164}
165
166impl std::fmt::Debug for CpuPlan {
167 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
168 f.debug_struct("CpuPlan")
169 .field("bucket", &self.bucket)
170 .field("steps", &self.steps.len())
171 .field("arena", &self.arena.len())
172 .finish_non_exhaustive()
173 }
174}
175
176impl CpuPlan {
177 #[must_use]
179 pub fn bucket(&self) -> Bucket {
180 self.bucket
181 }
182
183 #[must_use]
185 pub fn arena_bytes(&self) -> usize {
186 self.arena.len() * 4
187 }
188
189 pub fn profile(&mut self) {
191 self.profile = Some(vec![0; self.steps.len()]);
192 }
193
194 #[must_use]
196 pub fn timings(&self) -> Vec<(&'static str, u64)> {
197 let mut by: Vec<(&'static str, u64)> = Vec::new();
198 for (s, &ns) in self.steps.iter().zip(self.profile.iter().flatten()) {
199 match by.iter_mut().find(|b| b.0 == s.name()) {
200 Some(b) => b.1 += ns,
201 None => by.push((s.name(), ns)),
202 }
203 }
204 by.sort_by_key(|b| std::cmp::Reverse(b.1));
205 by
206 }
207}
208
209#[derive(Clone, Copy)]
211struct Arena(*mut f32);
212
213unsafe impl Send for Arena {}
216unsafe impl Sync for Arena {}
218
219impl Arena {
220 unsafe fn slice<'a>(self, off: usize, len: usize) -> &'a [f32] {
224 unsafe { std::slice::from_raw_parts(self.0.add(off), len) }
226 }
227
228 #[allow(clippy::mut_from_ref)]
232 unsafe fn slice_mut<'a>(self, off: usize, len: usize) -> &'a mut [f32] {
233 unsafe { std::slice::from_raw_parts_mut(self.0.add(off), len) }
235 }
236}
237
238const ROWS: usize = 16;
240
241impl Backend for CpuBackend {
242 type Weights = Weights;
243 type Plan = CpuPlan;
244
245 fn caps(&self) -> Caps {
246 Caps { name: "cpu", threads: self.threads(), graphs: false, unified_memory: true }
247 }
248
249 fn upload(&self, tensors: &[HostTensor<'_>], graph: &Graph) -> Result<Weights> {
250 let (mut gemm, mut other) = (vec![false; tensors.len()], vec![false; tensors.len()]);
253 let mut gemm8 = vec![false; tensors.len()];
254 let mark = |flags: &mut Vec<bool>, w: Option<usize>| {
255 if let Some(f) = w.and_then(|w| flags.get_mut(w)) {
256 *f = true;
257 }
258 };
259 for op in &graph.ops {
260 match *op {
261 Op::Gemm { a, w, b, .. } => {
262 match self.int8_rows(graph.shape(a).rows) {
263 true => mark(&mut gemm8, Some(w)),
264 false => mark(&mut gemm, Some(w)),
265 }
266 mark(&mut other, b);
267 }
268 Op::Embed { table, .. } | Op::AddType { table, .. } => {
269 mark(&mut other, Some(table))
270 }
271 Op::LayerNorm { w, b, .. } => {
272 mark(&mut other, Some(w));
273 mark(&mut other, b);
274 }
275 Op::Rope { .. }
276 | Op::Attention { .. }
277 | Op::GeGlu { .. }
278 | Op::GatherMarkers { .. }
279 | Op::ActFeatures { .. } => {}
280 }
281 }
282 let t = par::map(tensors.len(), self.threads(), |i| {
283 let h = &tensors[i];
284 let n = h.bytes.len() / h.dtype.size();
285 if n != h.shape.iter().product::<usize>() {
286 return Err(Error::Unsupported(format!(
287 "tensor {i} has {n} values for {:?}",
288 h.shape
289 )));
290 }
291 let data: Vec<f32> = (0..n).map(|j| h.dtype.read_f32(h.bytes, j)).collect();
292 let packed = match (gemm[i], h.shape) {
293 (true, &[rows, cols]) => gemm::pack(&data, rows, cols),
294 _ => Vec::new(),
295 };
296 let quant = match (gemm8[i], h.shape) {
297 (true, &[rows, cols]) => Some(QMatrix::quantize(&data, rows, cols)),
298 _ => None,
299 };
300 let copied = (!gemm[i] || !packed.is_empty()) && (!gemm8[i] || quant.is_some());
302 let data = if (gemm[i] || gemm8[i]) && !other[i] && copied { Vec::new() } else { data };
303 Ok(Tensor { shape: h.shape.to_vec(), data, packed, quant })
304 });
305 Ok(Weights(t.into_iter().collect::<Result<Vec<_>>>()?.into()))
306 }
307
308 fn lower(&self, w: &Weights, graph: &Graph, bucket: Bucket) -> Result<CpuPlan> {
309 let lay = layout(graph, |r| bucket.rows(r));
310 let loc = |v: Val| {
311 let s = graph.shape(v);
312 Loc { off: lay.offsets[v.0 as usize], rows: s.rows, width: s.width }
313 };
314 let bad = |m: String| Err(Error::Unsupported(m));
315 let shape = |i: usize| -> Result<&[usize]> {
316 match w.0.get(i) {
317 Some(t) => Ok(&t.shape),
318 None => Err(Error::Unsupported(format!("weight {i} is not in the checkpoint"))),
319 }
320 };
321 let mut ropes: Vec<(u64, Rope)> = Vec::new();
322 let mut scratch = bucket.tokens;
323 let mut steps = Vec::with_capacity(graph.ops.len());
324 for (i, op) in graph.ops.iter().enumerate() {
325 let step = match *op {
326 Op::Embed { table, out } => {
327 let out = loc(out);
328 if shape(table)?.get(1) != Some(&out.width) || out.rows != Rows::Tokens {
329 return bad(format!("op {i}: embedding table does not match its output"));
330 }
331 Step::Embed { table, out }
332 }
333 Op::LayerNorm { x, w: nw, b, eps, out } => {
334 let (x, out) = (loc(x), loc(out));
335 let ok = shape(nw)? == [x.width]
336 && b.map_or(Ok(true), |b| shape(b).map(|s| s == [x.width]))?
337 && x.width == out.width
338 && x.rows == out.rows;
339 if !ok {
340 return bad(format!("op {i}: layer norm shapes do not match"));
341 }
342 Step::LayerNorm { x, w: nw, b, eps, out }
343 }
344 Op::Gemm { a, w: gw, b, epilogue, out } => {
345 let (a, out) = (loc(a), loc(out));
346 let ok = shape(gw)? == [out.width, a.width]
347 && b.map_or(Ok(true), |b| shape(b).map(|s| s == [out.width]))?
348 && a.rows == out.rows;
349 if !ok {
350 return bad(format!("op {i}: gemm shapes do not match"));
351 }
352 if self.int8_rows(a.rows) {
353 if w.0[gw].quant.is_none() {
354 return bad(format!("op {i}: gemm weight {gw} was not rounded"));
355 }
356 scratch = scratch.max(qgemm::scratch_len(a.width));
357 Step::Gemm8 { a, w: gw, b, ep: epilogue, out }
358 } else {
359 if w.0[gw].packed.is_empty() && a.width * out.width > 0 {
360 return bad(format!("op {i}: gemm weight {gw} was not packed"));
361 }
362 scratch = scratch.max(gemm::scratch_len(a.width, out.width));
363 Step::Gemm { a, w: gw, b, ep: epilogue, out }
364 }
365 }
366 Op::Rope { qkv, theta } => {
367 let qkv = loc(qkv);
368 if !qkv.width.is_multiple_of(3 * HEAD) || qkv.rows != Rows::Tokens {
369 return bad(format!("op {i}: rope needs token rows of 3 heads 64"));
370 }
371 let at = match ropes.iter().position(|r| r.0 == theta.to_bits()) {
372 Some(at) => at,
373 None => {
374 ropes.push((theta.to_bits(), Rope::new(theta, HEAD, bucket.tokens)));
375 ropes.len() - 1
376 }
377 };
378 Step::Rope { qkv, rope: at }
379 }
380 Op::Attention { qkv, window, out } => {
381 let (qkv, out) = (loc(qkv), loc(out));
382 let ok = qkv.width.is_multiple_of(3 * HEAD)
383 && out.width * 3 == qkv.width
384 && qkv.rows == Rows::Tokens
385 && out.rows == Rows::Tokens;
386 if !ok {
387 return bad(format!("op {i}: attention shapes do not match"));
388 }
389 Step::Attention { qkv, window, out }
390 }
391 Op::GeGlu { x, out } => {
392 let (x, out) = (loc(x), loc(out));
393 if x.width != 2 * out.width || x.rows != out.rows {
394 return bad(format!("op {i}: geglu input is not twice its output"));
395 }
396 Step::GeGlu { x, out }
397 }
398 Op::AddType { h, table } => {
399 let h = loc(h);
400 if shape(table)?.get(1) != Some(&h.width) || h.rows != Rows::Tokens {
401 return bad(format!("op {i}: type table does not match"));
402 }
403 Step::AddType { h, table }
404 }
405 Op::GatherMarkers { h, out } => {
406 let (h, out) = (loc(h), loc(out));
407 if h.width != out.width || h.rows != Rows::Tokens || out.rows != Rows::Markers {
408 return bad(format!("op {i}: gather shapes do not match"));
409 }
410 Step::Gather { h, out }
411 }
412 Op::ActFeatures { h, logits, out } => {
413 let (h, logits, out) = (loc(h), loc(logits), loc(out));
414 let ok = out.width == h.width + 4
415 && logits.width == 1
416 && logits.rows == Rows::Markers
417 && out.rows == Rows::Seqs;
418 if !ok {
419 return bad(format!("op {i}: act feature shapes do not match"));
420 }
421 Step::ActFeatures { h, logits, out }
422 }
423 };
424 steps.push(step);
425 }
426 let (Some(logits), Some(act)) = (graph.logits, graph.act) else {
427 return bad("the graph has no logits or act output".into());
428 };
429 let (logits, act) = (loc(logits), loc(act));
430 if logits.width != 1
431 || logits.rows != Rows::Markers
432 || act.width != 2
433 || act.rows != Rows::Seqs
434 {
435 return bad(
436 "outputs must be one logit per marker and two act logits per sequence".into()
437 );
438 }
439 let threads = self.threads();
440 Ok(CpuPlan {
441 w: w.clone(),
442 bucket,
443 steps,
444 arena: vec![0.0; lay.len],
445 ropes: ropes.into_iter().map(|r| r.1).collect(),
446 logits,
447 act,
448 cu: Vec::with_capacity(bucket.seqs + 1),
449 mcu: Vec::with_capacity(bucket.seqs + 1),
450 row_seq: Vec::with_capacity(bucket.tokens),
451 blocks: Vec::with_capacity(bucket.tokens.div_ceil(QB) + bucket.seqs),
452 scratch: PerWorker(
453 (0..threads).map(|_| UnsafeCell::new(Vec::with_capacity(scratch))).collect(),
454 ),
455 profile: None,
456 })
457 }
458
459 fn run(&self, plan: &mut CpuPlan, batch: &Batch<'_>, out: &mut Outputs) -> Result<()> {
460 let (t, s, m) = (batch.ids.len(), batch.seqs(), batch.markers.len());
461 if !plan.bucket.holds(t, s, m) {
462 return Err(Error::Batch(format!("batch does not fit bucket {}", plan.bucket)));
463 }
464 plan.cu.clear();
465 plan.cu.extend(batch.cu.iter().map(|&c| c as usize));
466 plan.mcu.clear();
467 plan.mcu.extend(batch.mcu.iter().map(|&c| c as usize));
468 plan.row_seq.clear();
469 plan.blocks.clear();
470 for q in 0..s {
471 let (lo, hi) = (plan.cu[q], plan.cu[q + 1]);
472 plan.row_seq.extend(std::iter::repeat_n(q as u32, hi - lo));
473 plan.blocks.extend((lo..hi).step_by(QB).map(|q0| (q as u32, q0 as u32)));
474 }
475 let ctx = Ctx {
476 pool: &self.pool,
477 w: &plan.w.0,
478 arena: Arena(plan.arena.as_mut_ptr()),
479 ropes: &plan.ropes,
480 batch,
481 cu: &plan.cu,
482 mcu: &plan.mcu,
483 row_seq: &plan.row_seq,
484 blocks: &plan.blocks,
485 scratch: &plan.scratch,
486 counts: [t, s, m],
487 };
488 for (i, step) in plan.steps.iter().enumerate() {
489 match plan.profile.as_mut() {
490 None => ctx.step(step),
491 Some(p) => {
492 let at = Instant::now();
493 ctx.step(step);
494 p[i] += u64::try_from(at.elapsed().as_nanos()).unwrap_or(u64::MAX);
495 }
496 }
497 }
498 let logits = unsafe { ctx.arena.slice(plan.logits.off, m) };
500 let act = unsafe { ctx.arena.slice(plan.act.off, 2 * s) };
502 out.logits.clear();
503 out.logits.extend_from_slice(logits);
504 out.act.clear();
505 out.act.extend_from_slice(act.as_chunks::<2>().0);
506 Ok(())
507 }
508}
509
510struct Ctx<'a> {
512 pool: &'a Pool,
513 w: &'a [Tensor],
514 arena: Arena,
515 ropes: &'a [Rope],
516 batch: &'a Batch<'a>,
517 cu: &'a [usize],
518 mcu: &'a [usize],
519 row_seq: &'a [u32],
520 blocks: &'a [(u32, u32)],
521 scratch: &'a PerWorker<Vec<f32>>,
522 counts: [usize; 3],
523}
524
525impl Ctx<'_> {
526 fn rows(&self, r: Rows) -> usize {
527 self.counts[r as usize]
528 }
529
530 fn w(&self, i: usize) -> &[f32] {
531 &self.w[i].data
532 }
533
534 unsafe fn get(&self, l: Loc) -> &[f32] {
540 unsafe { self.arena.slice(l.off, self.rows(l.rows) * l.width) }
542 }
543
544 unsafe fn rows_of(&self, out: Loc, f: &(dyn Fn(usize, &mut [f32]) + Sync)) {
550 let n = self.rows(out.rows);
551 let arena = self.arena;
552 self.pool.run(n.div_ceil(ROWS), &|task, _| {
553 let r0 = task * ROWS;
554 let r1 = (r0 + ROWS).min(n);
555 let rows = unsafe { arena.slice_mut(out.off + r0 * out.width, (r1 - r0) * out.width) };
557 f(r0, rows);
558 });
559 }
560
561 fn step(&self, step: &Step) {
562 match *step {
566 Step::Embed { table, out } => {
567 let (tab, ids, d) = (self.w(table), self.batch.ids, out.width);
568 unsafe {
570 self.rows_of(out, &|r0, rows| {
571 for (i, row) in rows.chunks_exact_mut(d).enumerate() {
572 let id = ids[r0 + i] as usize;
573 row.copy_from_slice(&tab[id * d..(id + 1) * d]);
574 }
575 });
576 }
577 }
578 Step::LayerNorm { x, w, b, eps, out } => {
579 let x = unsafe { self.get(x) };
581 let (nw, nb, d) = (self.w(w), b.map(|b| self.w(b)), out.width);
582 unsafe {
584 self.rows_of(out, &|r0, rows| {
585 layer_norm(&x[r0 * d..r0 * d + rows.len()], d, nw, nb, eps, rows);
586 });
587 }
588 }
589 Step::Gemm { a, w, b, ep, out } => {
590 let rows = self.rows(a.rows);
591 let x = unsafe { self.get(a) };
593 let y = unsafe { self.arena.slice_mut(out.off, rows * out.width) };
595 let g = Gemm {
596 x,
597 m: rows,
598 k: a.width,
599 w: &self.w[w].packed,
600 n: out.width,
601 b: b.map(|b| self.w(b)),
602 ep,
603 };
604 let scratch = self.scratch;
605 g.run(y, self.pool.threads(), |n, f| {
606 self.pool.run(n, &|i, worker| {
607 let s = unsafe { scratch.get(worker) };
610 s.resize(gemm::scratch_len(g.k, g.n), 0.0);
611 f(i, s);
612 });
613 });
614 }
615 Step::Gemm8 { a, w, b, ep, out } => {
616 let rows = self.rows(a.rows);
617 let x = unsafe { self.get(a) };
619 let y = unsafe { self.arena.slice_mut(out.off, rows * out.width) };
621 let q = self.w[w]
622 .quant
623 .as_ref()
624 .unwrap_or_else(|| unreachable!("checked when lowered"));
625 let g = QGemm { x, m: rows, w: q, b: b.map(|b| self.w(b)), ep };
626 let scratch = self.scratch;
627 g.run(y, self.pool.threads(), |n, f| {
628 self.pool.run(n, &|i, worker| {
629 let s = unsafe { scratch.get(worker) };
632 s.resize(qgemm::scratch_len(q.k), 0.0);
633 f(i, s);
634 });
635 });
636 }
637 Step::Rope { qkv, rope } => {
638 let (rope, d, cu, seq) = (&self.ropes[rope], qkv.width / 3, self.cu, self.row_seq);
639 unsafe {
641 self.rows_of(qkv, &|r0, rows| {
642 for (i, row) in rows.chunks_exact_mut(qkv.width).enumerate() {
643 let r = r0 + i;
644 let pos = r - cu[seq[r] as usize];
645 for head in row[..2 * d].as_chunks_mut::<HEAD>().0 {
646 rope.apply(head, pos);
647 }
648 }
649 });
650 }
651 }
652 Step::Attention { qkv, window, out } => {
653 let heads = out.width / HEAD;
654 let x = unsafe { self.get(qkv) };
656 let y = unsafe { self.arena.slice_mut(out.off, self.rows(out.rows) * out.width) };
658 let shared = Shared::new(y);
659 let (blocks, cu, scratch) = (self.blocks, self.cu, self.scratch);
660 self.pool.run(blocks.len() * heads, &|task, worker| {
661 let (s, q0) = blocks[task / heads];
662 let (s, q0, h) = (s as usize, q0 as usize, task % heads);
663 unsafe {
666 let p = scratch.get(worker);
667 attention::block(x, heads, (cu[s], cu[s + 1]), q0, h, window, p, &shared);
668 }
669 });
670 }
671 Step::GeGlu { x, out } => {
672 let (x, d) = (unsafe { self.get(x) }, out.width);
674 unsafe {
676 self.rows_of(out, &|r0, rows| {
677 geglu(&x[2 * r0 * d..2 * (r0 * d + rows.len())], d, rows);
678 });
679 }
680 }
681 Step::AddType { h, table } => {
682 let (tab, d, seq, qt) = (self.w(table), h.width, self.row_seq, self.batch.qtype);
683 unsafe {
685 self.rows_of(h, &|r0, rows| {
686 for (i, row) in rows.chunks_exact_mut(d).enumerate() {
687 let q = usize::from(qt[seq[r0 + i] as usize]);
688 row.iter_mut().zip(&tab[q * d..(q + 1) * d]).for_each(|(a, b)| *a += b);
689 }
690 });
691 }
692 }
693 Step::Gather { h, out } => {
694 let (x, d) = (unsafe { self.get(h) }, h.width);
696 let y = unsafe { self.arena.slice_mut(out.off, self.rows(out.rows) * d) };
698 let mut at = 0;
699 for s in 0..self.cu.len() - 1 {
700 for &p in &self.batch.markers[self.mcu[s]..self.mcu[s + 1]] {
701 let r = self.cu[s] + p as usize;
702 y[at * d..(at + 1) * d].copy_from_slice(&x[r * d..(r + 1) * d]);
703 at += 1;
704 }
705 }
706 }
707 Step::ActFeatures { h, logits, out } => {
708 let (x, d) = (unsafe { self.get(h) }, h.width);
710 let l = unsafe { self.get(logits) };
712 let y = unsafe { self.arena.slice_mut(out.off, self.rows(out.rows) * out.width) };
714 for (s, row) in y.chunks_exact_mut(out.width).enumerate() {
715 let (lo, hi) = (self.cu[s], self.cu[s + 1]);
716 if hi > lo {
717 row[..d].copy_from_slice(&x[lo * d..(lo + 1) * d]);
718 } else {
719 row[..d].fill(0.0);
720 }
721 row[d..].copy_from_slice(&act_features(&l[self.mcu[s]..self.mcu[s + 1]]));
722 }
723 }
724 }
725 }
726}
727
728fn act_features(logits: &[f32]) -> [f32; 4] {
731 let kf = logits.len().max(2) as f32;
732 if logits.is_empty() {
733 return [0.0, 0.0, 0.0, kf / 255.0];
734 }
735 let mx = logits.iter().copied().fold(f32::NEG_INFINITY, f32::max);
736 let sum: f32 = logits.iter().map(|&l| (l - mx).exp()).sum();
737 let (mut top1, mut top2, mut ent) = (f32::NEG_INFINITY, 0f32, 0f32);
738 let mut first = true;
739 for &l in logits {
740 let q = (l - mx).exp() / sum;
741 ent += q * q.max(1e-9).ln();
742 if q > top1 || first {
743 if !first {
744 top2 = top1;
745 }
746 top1 = q;
747 first = false;
748 } else if q > top2 {
749 top2 = q;
750 }
751 }
752 let ent = -ent / kf.ln();
753 [top1, top1 - top2, ent, kf / 255.0]
754}
755
756#[cfg(test)]
757mod tests {
758 use super::*;
759
760 #[test]
761 fn act_features_match_the_reference() {
762 let cases: [&[f32]; 6] =
763 [&[], &[0.3], &[1.0, 1.0], &[2.0, -1.0, 2.0], &[5.0, 0.1, -3.0, 4.9], &[-1e3, 0.0]];
764 for l in cases {
765 assert_eq!(
766 act_features(l).map(f32::to_bits),
767 crate::compat::act_features(l).map(f32::to_bits),
768 "{l:?}"
769 );
770 }
771 }
772}