Repository navigation
Expand file tree
/
Copy pathengine.zig
More file actions
2239 lines (2117 loc) · 108 KB
/
Copy pathengine.zig
File metadata and controls
2239 lines (2117 loc) · 108 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// engine.zig — the transformer decode loop.
//
// Work split:
// ANE : every linear projection (qkv, attention output, gate/up, down, lm head)
// as 1x1 conv kernels with weights baked in at compile time.
// CPU : RMSNorm, RoPE, attention (with the KV cache), SwiGLU activation,
// residual adds and sampling.
//
// That split is forced by the ANE's MIL dialect: `rsqrt`, `reduce_mean`,
// `concat` and `gelu` are rejected by ANECCompile, and SDPA causal masks are
// silently ignored, so normalisation and attention cannot be expressed portably
// yet. The projections are >95% of the FLOPs, so the ANE still does the heavy
// work — and the SiLU is fused into the ANE program, which does support
// sigmoid/mul.
//
// Ownership: an Engine borrows all weights from the ModelWeights passed to
// init(); that struct must outlive the engine.
const std = @import("std");
const sys = @import("sys.zig");
const cpu = @import("cpu.zig");
const gguf = @import("gguf.zig");
const model = @import("model.zig");
const ane = @import("ane/runtime.zig");
const mil = @import("ane/mil.zig");
const weights = @import("ane/weights.zig");
pub const Options = struct {
max_seq: u32 = 2048,
/// Build kernels for only the first N layers. 0 means all of them.
///
/// The ANE program pool is machine-wide and a large model needs tens of kernels, so a degraded
/// pool stalls at the first layer and there is no way to ask a smaller question. This builds a
/// prefix, which is enough to check a new architecture's kernel shapes on a machine that
/// cannot hold the whole model at once.
max_layers: u32 = 0,
verbose: bool = true,
/// Activation width every kernel is compiled for. The ANE reads the weights
/// once per evaluation regardless of width (measured: width 128 costs 5%
/// more than width 1), so one token and a whole prompt chunk cost the same.
/// Must be a multiple of 32 for the planar layout to stay contiguous.
/// 128 measured ~50% faster prefill than 64 with no decode regression
/// (the weights are read once per eval either way); 256 is no better and
/// costs more activation memory.
chunk: u32 = 128,
/// Fuse gate/up/SiLU/down into one ANE program (3 BLOBFILEs, one kernel
/// instead of two). Keeps the intermediate activation on the ANE instead of
/// round-tripping it through the CPU, and measured ~45% faster decode.
/// Falls back to the split path if the fused program fails to compile.
fuse_ffn: bool = true,
};
const LayerKernels = struct {
qkv: ane.Kernel,
/// Rows the qkv kernel produces: `q + 2*kv` for a normal layer, `q` alone for one that
/// borrows another layer's K/V (Gemma 4's shared tail), whose checkpoint has no K/V weights.
qkv_rows: u32,
/// `blk.N.layer_output_scale`: Gemma 4 ends every layer with `h *= scale`.
/// 1.0 when the file has no such tensor, which is every other model here.
out_scale: f32 = 1.0,
o: ane.Kernel,
/// Fused: [hidden] -> [hidden]. Split: [hidden] -> [2*inter] (gate || up).
/// For a sparse MoE layer this kernel computes the SHARED expert, which every
/// token uses.
ffn: ane.Kernel,
ffn_split: bool,
down: ?ane.Kernel = null,
/// PLE (Gemma 4). `ple_gate` is `[ple_dim][hidden]`, `ple_proj` is `[hidden][ple_dim]` and
/// `ple_post_norm` is `[hidden]`. Moved in from the layer's Matrices like the experts are,
/// and null for every model without per-layer embeddings.
ple_gate: ?[]f16 = null,
ple_proj: ?[]f16 = null,
ple_post_norm: ?[]f32 = null,
/// Routed experts of a MoE layer, run on the CPU. The ANE cannot hold a kernel
/// per expert (see research/moe-design.md), and only k of them are used per
/// token, so they are read and multiplied here instead.
moe: ?model.MoeWeights = null,
};
/// Which ANE node a measurement belongs to.
pub const Node = enum(usize) { qkv = 0, o = 1, ffn = 2, head = 3 };
pub const Stats = struct {
ane_eval_ns: u64 = 0,
ane_evals: u64 = 0,
/// ANE time split by node type, so the next optimisation is measured
/// rather than guessed.
node_ns: [4]u64 = .{ 0, 0, 0, 0 },
node_evals: [4]u64 = .{ 0, 0, 0, 0 },
/// For the qkv node: how much is IOSurface staging vs the evaluation.
qkv_write_ns: u64 = 0,
qkv_read_ns: u64 = 0,
/// Prefill CPU phases, to find where the non-ANE time goes.
pf_convert_ns: u64 = 0,
pf_rope_ns: u64 = 0,
/// Time spent on the CPU running routed MoE experts.
moe_ns: u64 = 0,
/// Snapshots of the ANE counters taken when prefill ends, so a caller can report
/// decode-only "per token" figures. Without them `node_ns` mixes the prompt's
/// chunk-passes with decode's single-column passes: on a 14-token prompt with 1
/// generated token, dividing the sum by the decode count inflates every number
/// ~30x, which is exactly what the per-token split used to do.
prefill_done_tokens: u64 = 0,
prefill_done_node_ns: [4]u64 = @splat(0),
prefill_done_evals: [4]u64 = @splat(0),
prefill_done_moe_ns: u64 = 0,
prefill_done_ane_ns: u64 = 0,
/// ANE node time of the FIRST decode step only, and its pass count. It differs
/// sharply from the remaining steps and not in a fixed direction (13x slower on
/// Qwen1.5-MoE, slightly faster on SmolLM2), so it is reported separately rather
/// than averaged in — which overstated the MoE figure 3.6x on a 6-token run.
first_token_node_ns: [4]u64 = @splat(0),
first_token_passes: u64 = 0,
pf_attn_ns: u64 = 0,
pf_norm_ns: u64 = 0,
pf_stage_ns: u64 = 0,
total_ns: u64 = 0,
tokens: u64 = 0,
pub fn nodeMs(self: Stats, n: Node) f64 {
return @as(f64, @floatFromInt(self.node_ns[@backingInt(n)])) / 1e6;
}
pub fn aneMs(self: Stats) f64 {
return @as(f64, @floatFromInt(self.ane_eval_ns)) / 1e6;
}
pub fn tokPerSec(self: Stats) f64 {
if (self.tokens == 0) return 0;
return @as(f64, @floatFromInt(self.tokens)) / (@as(f64, @floatFromInt(self.total_ns)) / 1e9);
}
};
pub const Engine = struct {
allocator: std.mem.Allocator,
config: model.Config,
opts: Options,
/// Owned: embedding, final norm, per-layer norms and biases.
rt: model.Runtime,
embed: []const f16,
final_norm: []const f32,
head: []const f16,
norms: []const model.Norm,
kernels: []LayerKernels,
head_kernel: ane.Kernel,
/// The head is split into this many vocabulary rows per kernel, so its weight blob
/// stays bounded. One kernel for a 256000-row vocabulary is a 1.18 GB blob, which
/// the ANE accepts and then computes wrongly (gemma-2-2b: relative error 0.95
/// against a CPU matmul, i.e. unrelated to the right answer).
head_chunk: u32 = 0,
/// When set, `runHead` leaves the final logit soft-cap off. `verify` needs the
/// pre-cap values: tanh saturates, so comparing capped logits cannot distinguish a
/// real disagreement from compression — gemma-2-2b reported MISMATCH while producing
/// exactly the right text.
pre_softcap: bool = false,
/// Number of chunk kernels the head was split into (1 = not split).
head_kernels: u32 = 1,
/// The remaining chunk kernels (the first lives in `head_kernel`).
head_extra: []ane.Kernel = &.{},
/// How many entries of `head_extra` are initialised, for errdefer-safe cleanup.
head_extra_built: u32 = 0,
/// Vocabulary rows each extra chunk kernel covers (the last may be short).
head_extra_rows: []u32 = &.{},
/// fp16 KV cache: halves both the resident memory and the attention
/// traffic, at the cost of ~5e-4 relative error per stored value (the same
/// trade llama.cpp makes with -ctk f16 -ctv f16, its default).
k_cache: [][]f16,
v_cache: [][]f16,
max_seq: u32,
/// All activation buffers are `[channel * chunk + column]`.
chunk: usize,
x: []f32,
h: []f32,
qkv: []f32,
attn: []f32,
proj: []f32,
gu: []f32,
act: []f32,
logits: []f32,
scores: []f32,
in16: []f16,
out16: []f16,
/// Single-column staging for the decode path (the padded columns stay zero
/// in the IOSurfaces, so only column 0 is written and read).
dec_in: []f16,
dec_out: []f16,
/// Width-1 staging for the lm-head kernel.
head_in: []f16,
/// Scratch for Gemma 2's sandwich norms. Always allocated: it is used on dense
/// models, where `moe_hidden` (MoE-only, empty) would be an empty slice.
sandwich: []f32 = &.{},
/// The head kernel's output: [vocab], read back once per prefill and per token.
/// Separate from `out16` because that is sized `stage * chunk` for activations and
/// multiplying the vocabulary into it wasted 78 MB.
head_out: []f16 = &.{},
/// PLE (Gemma 4), all empty for every other model. `ple_emb` holds the token's scaled
/// embedding, `ple_row` the dequantised table row, `ple_proj_out` the model projection of
/// `ple_emb`, and `ple_in` the combined per-layer vectors `pleBlock` consumes.
ple_emb: []f32 = &.{},
ple_row: []f32 = &.{},
ple_proj_out: []f32 = &.{},
ple_in: []f32 = &.{},
ple_scr: []f32 = &.{},
ple_tmp: []f32 = &.{},
/// Borrowed from `Runtime`: the model projection, its norm, and the table's bytes and type.
ple_proj: []f16 = &.{},
ple_norm: []f32 = &.{},
ple_table: []const u8 = &.{},
ple_type: u32 = 0,
/// Contiguous scratch for one column's q/k/v/attention vectors.
sq: []f32,
sk: []f32,
sv: []f32,
sa: []f32,
stats: Stats = .{},
/// Number of layers actually executed (all of them; see stopAfterLayer).
active_layers: u32 = 0,
/// Called between prefill chunks so the server can answer cheap requests
/// while a long prompt is still being prefilled. A 971-token prompt is ~8
/// chunks and took 6.4 s, during which /health was unanswerable.
prefill_tick: ?*const fn (?*anyopaque) void = null,
prefill_tick_ctx: ?*anyopaque = null,
/// MoE scratch, sized once from the config. Empty for a dense model.
moe_logits: []f32 = &.{},
moe_probs: []f32 = &.{},
moe_idx: []u32 = &.{},
moe_out: []f32 = &.{},
/// f32 copy of the layer's normalised input, for the CPU router and experts
/// (the ANE staging buffer is fp16).
moe_hidden: []f32 = &.{},
/// Chunk-level MoE batching scratch. See prefillExpertBatched.
moe_chunk_idx: []u32 = &.{},
/// f32 expert scratch for the batched prefill path, kept separate from the decode
/// path's so the two cannot interleave into each other's buffers.
moe_expert_scratch_f32_alt: []f32 = &.{},
moe_chunk_probs: []f32 = &.{},
moe_expert_cols: []u32 = &.{},
moe_col_out: []f32 = &.{},
moe_gate_scratch: []f32 = &.{},
moe_upd_scratch: []f32 = &.{},
/// Optional routing recorder: counts how often each expert of each layer is
/// chosen. A resident-expert cache is only worth building if the counts are
/// concentrated, so this is how that gets decided rather than assumed.
/// Layout: [layer][num_experts]; null when not recording.
route_counts: ?[]u32 = null,
route_tokens: u32 = 0,
pub fn deinit(self: *Engine) void {
for (self.kernels) |*k| {
k.qkv.deinit();
k.o.deinit();
k.ffn.deinit();
if (k.down) |*d| d.deinit();
// Routed experts were moved in from the layer's Matrices.
if (k.moe) |*m| m.deinit(self.allocator);
if (k.ple_gate) |g| self.allocator.free(g);
if (k.ple_proj) |g| self.allocator.free(g);
if (k.ple_post_norm) |g| self.allocator.free(g);
}
if (self.ple_emb.len > 0) self.allocator.free(self.ple_emb);
if (self.ple_row.len > 0) self.allocator.free(self.ple_row);
if (self.ple_proj_out.len > 0) self.allocator.free(self.ple_proj_out);
if (self.ple_in.len > 0) self.allocator.free(self.ple_in);
if (self.ple_scr.len > 0) self.allocator.free(self.ple_scr);
if (self.ple_tmp.len > 0) self.allocator.free(self.ple_tmp);
self.head_kernel.deinit();
for (self.head_extra[0..self.head_extra_built]) |*k| k.deinit();
if (self.head_extra.len > 0) self.allocator.free(self.head_extra);
if (self.head_extra_rows.len > 0) self.allocator.free(self.head_extra_rows);
self.allocator.free(self.kernels);
self.rt.deinit();
for (self.k_cache) |c| self.allocator.free(c);
for (self.v_cache) |c| self.allocator.free(c);
self.allocator.free(self.k_cache);
self.allocator.free(self.v_cache);
if (self.moe_logits.len > 0) self.allocator.free(self.moe_logits);
if (self.moe_probs.len > 0) self.allocator.free(self.moe_probs);
if (self.moe_idx.len > 0) self.allocator.free(self.moe_idx);
if (self.moe_out.len > 0) self.allocator.free(self.moe_out);
if (self.moe_hidden.len > 0) self.allocator.free(self.moe_hidden);
if (self.sandwich.len > 0) self.allocator.free(self.sandwich);
if (self.moe_chunk_idx.len > 0) self.allocator.free(self.moe_chunk_idx);
if (self.moe_expert_scratch_f32_alt.len > 0) self.allocator.free(self.moe_expert_scratch_f32_alt);
if (self.moe_chunk_probs.len > 0) self.allocator.free(self.moe_chunk_probs);
if (self.moe_expert_cols.len > 0) self.allocator.free(self.moe_expert_cols);
if (self.moe_col_out.len > 0) self.allocator.free(self.moe_col_out);
if (self.moe_gate_scratch.len > 0) self.allocator.free(self.moe_gate_scratch);
if (self.moe_upd_scratch.len > 0) self.allocator.free(self.moe_upd_scratch);
self.allocator.free(self.x);
self.allocator.free(self.h);
self.allocator.free(self.qkv);
self.allocator.free(self.attn);
self.allocator.free(self.proj);
self.allocator.free(self.gu);
self.allocator.free(self.act);
self.allocator.free(self.logits);
self.allocator.free(self.scores);
self.allocator.free(self.in16);
self.allocator.free(self.out16);
self.allocator.free(self.dec_in);
self.allocator.free(self.dec_out);
self.allocator.free(self.head_in);
if (self.head_out.len > 0) self.allocator.free(self.head_out);
self.allocator.free(self.sq);
self.allocator.free(self.sk);
self.allocator.free(self.sv);
self.allocator.free(self.sa);
self.* = undefined;
}
/// Build every ANE kernel.
///
/// `rt` is taken by value and owned by the engine. Layer matrices are pulled
/// from `layers` one at a time and freed as soon as that layer's kernels
/// exist, so peak memory stays near one layer instead of the whole model.
pub fn init(
allocator: std.mem.Allocator,
rt: model.Runtime,
layers: model.LayerSource,
head: model.HeadSource,
opts: Options,
) !Engine {
const cfg = rt.config;
try cfg.validate();
var self: Engine = undefined;
// A field with a default value is NOT covered by `undefined`: it holds
// 0xaaaa. Two things read those garbage bits: `prefill_tick`, which is
// called as a function pointer between prefill chunks (jumping to
// 0xaaaaaaaa is a real bus error, not a hypothetical), and the MoE scratch
// below, whose `.len` decides what `deinit` frees.
self.prefill_tick = null;
self.prefill_tick_ctx = null;
self.moe_logits = &.{};
self.moe_probs = &.{};
self.moe_idx = &.{};
self.moe_out = &.{};
self.moe_hidden = &.{};
self.sandwich = &.{};
self.moe_chunk_idx = &.{};
self.moe_expert_scratch_f32_alt = &.{};
self.head_extra = &.{};
self.head_extra_rows = &.{};
self.head_extra_built = 0;
self.moe_chunk_probs = &.{};
self.moe_expert_cols = &.{};
self.moe_col_out = &.{};
self.moe_gate_scratch = &.{};
self.moe_upd_scratch = &.{};
self.route_counts = null;
self.route_tokens = 0;
self.allocator = allocator;
self.config = cfg;
self.opts = opts;
self.rt = rt;
self.embed = rt.embed;
self.final_norm = rt.final_norm;
// Borrowed, not owned, like `embed` and `norms` above: `Runtime.deinit` frees these.
// The table likewise aliases the mapping, so the `Gguf` must outlive the engine.
self.ple_proj = rt.ple_proj;
self.ple_norm = rt.ple_norm;
self.ple_table = rt.ple_table;
self.ple_type = rt.ple_table_type;
self.head = &.{};
self.norms = rt.norms;
self.max_seq = opts.max_seq;
self.chunk = opts.chunk;
self.stats = .{};
const L: usize = cfg.layers;
self.kernels = try allocator.alloc(LayerKernels, L);
var built: usize = 0;
errdefer {
for (self.kernels[0..built]) |*k| {
k.qkv.deinit();
k.o.deinit();
k.ffn.deinit();
if (k.down) |*d| d.deinit();
}
allocator.free(self.kernels);
}
// A prefix, when asked for. Everything below shrinks to `built` so deinit and the
// forward loops see only what was actually compiled.
const build_layers: usize = if (opts.max_layers > 0) @min(L, opts.max_layers) else L;
for (0..build_layers) |i| {
if (opts.verbose) sys.print(" layer {d}/{d}: loading weights + compiling ANE kernels\n", .{ i + 1, build_layers });
var m = try layers.load(allocator, @intCast(i));
defer m.deinit(allocator); // matrices are baked into the kernels now
self.kernels[i] = try buildLayerKernels(allocator, cfg, &m, @intCast(i), opts, opts.chunk);
// The routed experts were moved into the kernels; do not let the deferred
// deinit free them.
m.moe = null;
m.ple_gate = null;
m.ple_proj = null;
m.ple_post_norm = null;
built += 1;
}
if (built < L) {
// Shrink so `deinit` and both loops only see compiled layers.
self.kernels = self.kernels[0..built];
self.norms = self.norms[0..built];
self.active_layers = @intCast(built);
sys.eprint("note: built {d} of {d} layers (--max-layers); the head still runs.\n", .{ built, L });
}
if (opts.verbose) sys.print(" lm head: loading weights + compiling ANE kernel ({d} -> {d})\n", .{ cfg.hidden, cfg.vocab });
const hw = try head.load(allocator);
defer if (hw.owned) allocator.free(hw.data);
self.head = hw.data;
// The head stays width 1: a [vocab][chunk] output surface would be tens of MB.
//
// Large vocabularies are split: one kernel for 256000 rows is a 1.18 GB weight
// blob, which the ANE compiles, runs, and gets wrong. Splitting also lowers peak
// memory, which matters on an 8 GB machine.
self.head_chunk = headChunkFor(cfg.hidden, cfg.vocab);
self.head_kernels = (cfg.vocab + self.head_chunk - 1) / self.head_chunk;
self.head_extra = try allocator.alloc(ane.Kernel, self.head_kernels - 1);
self.head_extra_rows = try allocator.alloc(u32, self.head_kernels - 1);
self.head_extra_built = 0;
for (0..self.head_kernels - 1) |i| {
const first_row = (i + 1) * self.head_chunk;
const off = @as(usize, first_row) * cfg.hidden;
// The final chunk is short when the vocabulary does not divide evenly.
const rows = @min(self.head_chunk, cfg.vocab - @as(u32, @intCast(first_row)));
self.head_extra[i] = makeConvKernel(allocator, cfg.hidden, rows, hw.data[off..], "lm_head", 1) catch |e| {
sys.eprint("lm head chunk {d}/{d} ({d} rows) failed: {s}: {s}\n", .{
i + 1, self.head_kernels - 1, rows, @errorName(e), ane.lastError(),
});
return e;
};
// The chunk's row count is needed again at eval time.
self.head_extra_rows[i] = rows;
self.head_extra_built += 1;
}
self.head_kernel = makeConvKernel(allocator, cfg.hidden, self.head_chunk, hw.data, "lm_head", 1) catch |e| {
// Say why: a bare AneCompileFailed gives no clue whether the blob is too
// large, the program pool is full, or the MIL is malformed.
sys.eprint("lm head kernel ({d} -> {d}, chunk {d}) failed: {s}: {s}\n", .{
cfg.hidden, cfg.vocab, self.head_chunk, @errorName(e), ane.lastError(),
});
return e;
};
self.k_cache = try allocator.alloc([]f16, L);
self.v_cache = try allocator.alloc([]f16, L);
for (0..L) |i| {
// Per layer: Gemma 4's sliding layers carry a narrower K/V than its global ones,
// so one uniform row width would either overrun the narrow layers or waste the
// wide ones.
const kv_dim: usize = cfg.layerKvDim(@intCast(i));
self.k_cache[i] = try allocator.alloc(f16, @as(usize, opts.max_seq) * kv_dim);
self.v_cache[i] = try allocator.alloc(f16, @as(usize, opts.max_seq) * kv_dim);
@memset(self.k_cache[i], 0);
@memset(self.v_cache[i], 0);
}
const ch: usize = self.chunk;
if (cfg.num_experts > 0) {
self.moe_logits = try allocator.alloc(f32, cfg.num_experts);
self.moe_probs = try allocator.alloc(f32, @max(cfg.experts_per_tok, 1));
self.moe_idx = try allocator.alloc(u32, @max(cfg.experts_per_tok, 1));
self.moe_out = try allocator.alloc(f32, cfg.hidden * ch);
// Chunk-level batching: every column's top-k picks, flattened.
self.moe_chunk_idx = try allocator.alloc(u32, ch * cfg.experts_per_tok);
self.moe_expert_scratch_f32_alt = try allocator.alloc(f32, cfg.moe_inter * cfg.hidden);
self.moe_chunk_probs = try allocator.alloc(f32, ch * cfg.experts_per_tok);
// Columns grouped by expert, so one expert read serves them all.
self.moe_expert_cols = try allocator.alloc(u32, ch);
// Per-column expert output, accumulated across that column's experts.
self.moe_col_out = try allocator.alloc(f32, cfg.hidden * ch);
self.moe_hidden = try allocator.alloc(f32, cfg.hidden);
self.moe_gate_scratch = try allocator.alloc(f32, cfg.moe_inter);
self.moe_upd_scratch = try allocator.alloc(f32, cfg.moe_inter);
}
self.x = try allocator.alloc(f32, @as(usize, cfg.hidden) * ch);
self.h = try allocator.alloc(f32, @as(usize, cfg.hidden) * ch);
self.qkv = try allocator.alloc(f32, @as(usize, cfg.qkvDim()) * ch);
self.attn = try allocator.alloc(f32, @as(usize, cfg.maxQDim()) * ch);
self.proj = try allocator.alloc(f32, @as(usize, cfg.hidden) * ch);
self.gu = try allocator.alloc(f32, @as(usize, 2 * cfg.inter) * ch);
self.act = try allocator.alloc(f32, @as(usize, cfg.inter) * ch);
self.logits = try allocator.alloc(f32, cfg.vocab);
self.scores = try allocator.alloc(f32, opts.max_seq);
// `stage` sizes the per-layer staging buffers, which hold activations.
//
// Prefill ends by reading the whole vocabulary out of the head kernel, which a
// vocab-sized `stage` would cover — but `stage` is multiplied by `chunk`, so
// folding `vocab` into it allocated 39 MB for `in16` and 39 MB for `out16` on a
// 151936-token vocabulary (78 MB, and it showed up as swap). The head read gets
// its own `vocab`-sized buffer instead; that is the only place the vocabulary
// needs to fit.
const stage = @max(@max(cfg.hidden, cfg.qkvDim()), @max(cfg.qDim(), @max(2 * cfg.inter, cfg.inter)));
self.in16 = try allocator.alloc(f16, @as(usize, stage) * ch);
self.out16 = try allocator.alloc(f16, @as(usize, stage) * ch);
self.dec_in = try allocator.alloc(f16, stage);
self.dec_out = try allocator.alloc(f16, stage);
self.head_in = try allocator.alloc(f16, cfg.hidden);
self.sandwich = try allocator.alloc(f32, cfg.hidden);
// PLE (Gemma 4). All empty for every other model.
if (cfg.ple_dim > 0) {
const rows: usize = @as(usize, cfg.layers) * cfg.ple_dim;
self.ple_emb = try allocator.alloc(f32, cfg.hidden);
self.ple_row = try allocator.alloc(f32, rows);
self.ple_proj_out = try allocator.alloc(f32, rows);
// Per column: prefill prepares a whole chunk's worth before the layer loop, since
// every layer walks all the columns.
self.ple_in = try allocator.alloc(f32, rows * ch);
self.ple_scr = try allocator.alloc(f32, cfg.ple_dim);
self.ple_tmp = try allocator.alloc(f32, cfg.hidden);
}
self.head_out = try allocator.alloc(f16, cfg.vocab);
const vec = @max(cfg.maxQDim(), @max(cfg.maxKvDim(), cfg.inter));
self.sq = try allocator.alloc(f32, vec);
self.sk = try allocator.alloc(f32, vec);
self.sv = try allocator.alloc(f32, vec);
self.sa = try allocator.alloc(f32, vec);
return self;
}
fn f32ToF16Into(dst: []f16, src: []const f32) void {
for (dst, src) |*d, s| d.* = @floatCast(s);
}
fn f16ToF32Into(dst: []f32, src: []const f16) void {
for (dst, src) |*d, s| d.* = @floatCast(s);
}
/// Gather channel `col` of a `[channel * ch + col]` buffer into `dst`.
fn gatherColumn(dst: []f32, src: []const f32, ch: usize, col: usize) void {
for (dst, 0..) |*d, c| d.* = src[c * ch + col];
}
/// Scatter `src` into channel `col` of a `[channel * ch + col]` buffer.
fn scatterColumn(dst: []f32, src: []const f32, ch: usize, col: usize) void {
for (src, 0..) |v, c| dst[c * ch + col] = v;
}
/// One decode step for `token` at position `pos`. Returns the logits slice
/// (owned by the engine, valid until the next call).
///
/// Kernels are compiled for `chunk` columns, but a decode step only fills
/// column 0: the padded columns stay zero, so the ANE's extra output columns
/// are harmless — and measurably free, because the weights are read once per
/// evaluation regardless of width.
pub fn forward(self: *Engine, token: u32, pos: u32) ![]f32 {
// Same bound as `prefill`: `pos` indexes a row of the KV cache.
if (pos >= self.max_seq) return error.ContextOverflow;
const cfg = self.config;
const ch = self.chunk;
const hidden: usize = cfg.hidden;
// q/kv widths are per layer: Gemma 4 sizes sliding layers differently from global
// ones, so both are computed inside the layer loop below.
const inter: usize = cfg.inter;
const t_start = sys.nowNs();
// Apply the architecture's embedding scale (Gemma: sqrt(hidden)). The prefill
// path does this, and leaving it out here made decode start from a differently
// scaled activation than prefill — the model then emitted "." for every step.
for (0..hidden) |c| {
const e: f32 = @floatCast(self.embed[@as(usize, token) * hidden + c]);
self.x[c * ch] = e * cfg.embed_scale;
}
// PLE is computed once per token, before any layer, because every layer needs its slice
// of the same result. Empty for every model without per-layer embeddings.
if (cfg.ple_dim > 0) self.preparePle(token, 0);
for (self.kernels, 0..) |*k, li| {
const l_hd: u32 = cfg.layerHeadDim(@intCast(li));
const kv_dim: usize = cfg.layerKvDim(@intCast(li));
const q_dim: usize = cfg.layerQDim(@intCast(li));
const norm = &self.norms[li];
// ---- attention: qkv projection on ANE (column 0) ----
rmsnormColumn(self.dec_in[0..hidden], self.x, norm.attn, cfg.eps, ch);
const tw = sys.nowNs();
try k.qkv.writeInputColumnF16(0, 0, self.dec_in[0..hidden]);
self.stats.qkv_write_ns += sys.nowNs() - tw;
var t0 = sys.nowNs();
try k.qkv.eval();
const dt_qkv = sys.nowNs() - t0;
self.stats.ane_eval_ns += dt_qkv;
self.stats.ane_evals += 1;
self.stats.node_ns[@backingInt(Node.qkv)] += dt_qkv;
self.stats.node_evals[@backingInt(Node.qkv)] += 1;
const tr = sys.nowNs();
try k.qkv.readOutputColumnF16(0, 0, self.dec_out[0..k.qkv_rows]);
self.stats.qkv_read_ns += sys.nowNs() - tr;
for (0..k.qkv_rows) |c| self.qkv[c * ch] = @floatCast(self.dec_out[c]);
if (norm.qkv_bias) |b| {
for (b, 0..) |v, c| self.qkv[c * ch] += v;
}
gatherColumn(self.sq[0..q_dim], self.qkv[0..], ch, 0);
if (cfg.isKvShared(@intCast(li))) {
self.ropeQueryOnly(li, pos, cfg, l_hd);
} else {
gatherColumn(self.sk[0..kv_dim], self.qkv[q_dim * ch ..], ch, 0);
gatherColumn(self.sv[0..kv_dim], self.qkv[(q_dim + kv_dim) * ch ..], ch, 0);
self.ropeAndCache(li, pos, cfg, kv_dim, l_hd);
}
// A shared layer attends with its own queries against the donor's keys and values.
const donor: usize = cfg.kvDonor(@intCast(li));
cpu.attentionDecode(self.sa[0..q_dim], self.sq[0..q_dim], self.k_cache[donor], self.v_cache[donor], pos + 1, cfg.heads, cfg.kv_heads, l_hd, self.scores, .{
.logit_softcap = cfg.attn_logit_softcap,
.scale = cfg.attn_scale,
.window = if (cfg.layerIsSliding(@intCast(li))) cfg.sliding_window else 0,
});
scatterColumn(self.attn[0..], self.sa[0..q_dim], ch, 0);
// ---- attention output projection on ANE ----
for (0..q_dim) |c| self.dec_in[c] = @floatCast(self.attn[c * ch]);
try k.o.writeInputColumnF16(0, 0, self.dec_in[0..q_dim]);
t0 = sys.nowNs();
try k.o.eval();
const dt_o = sys.nowNs() - t0;
self.stats.ane_eval_ns += dt_o;
self.stats.ane_evals += 1;
self.stats.node_ns[@backingInt(Node.o)] += dt_o;
self.stats.node_evals[@backingInt(Node.o)] += 1;
try k.o.readOutputColumnF16(0, 0, self.dec_out[0..hidden]);
for (0..hidden) |c| {
var v = @as(f32, @floatCast(self.dec_out[c]));
if (norm.o_bias) |b| v += b[c];
self.sandwich[c] = v;
}
// Gemma 2 normalises the attention output before it joins the residual.
if (norm.post_attn.len == hidden) {
rmsnormFlat(self.sandwich[0..hidden], norm.post_attn, cfg.eps);
}
for (0..hidden) |c| self.x[c * ch] += self.sandwich[c];
// ---- feed-forward on ANE ----
rmsnormColumn(self.dec_in[0..hidden], self.x, norm.ffn, cfg.eps, ch);
try k.ffn.writeInputColumnF16(0, 0, self.dec_in[0..hidden]);
t0 = sys.nowNs();
try k.ffn.eval();
const dt_ffn = sys.nowNs() - t0;
self.stats.ane_eval_ns += dt_ffn;
self.stats.ane_evals += 1;
self.stats.node_ns[@backingInt(Node.ffn)] += dt_ffn;
self.stats.node_evals[@backingInt(Node.ffn)] += 1;
if (k.ffn_split) {
try k.ffn.readOutputColumnF16(0, 0, self.dec_out[0 .. 2 * inter]);
const gate = self.sq[0..inter];
const up = self.sk[0..inter];
for (0..inter) |c| {
gate[c] = @floatCast(self.dec_out[c]);
up[c] = @floatCast(self.dec_out[inter + c]);
}
cpu.gateMul(self.sa[0..inter], gate, up, cfg.use_gelu);
for (0..inter) |c| self.dec_in[c] = @floatCast(self.sa[c]);
const dk = &k.down.?;
try dk.writeInputColumnF16(0, 0, self.dec_in[0..inter]);
t0 = sys.nowNs();
try dk.eval();
const dt_down = sys.nowNs() - t0;
self.stats.ane_eval_ns += dt_down;
self.stats.ane_evals += 1;
// Attribute the down projection to `ffn` as well. Without this the split
// path reports only the gate/up kernel against the fused path's full
// three-conv byte count, which inflated `ffn` to 67.6 GB/s against a real
// 46 GB/s and made the fused form look worse than it is.
self.stats.node_ns[@backingInt(Node.ffn)] += dt_down;
self.stats.node_evals[@backingInt(Node.ffn)] += 1;
try dk.readOutputColumnF16(0, 0, self.dec_out[0..hidden]);
} else {
try k.ffn.readOutputColumnF16(0, 0, self.dec_out[0..hidden]);
}
// The shared expert's output is scaled by sigmoid(gate . h) before it joins
// the residual. The ANE kernel cannot express that (it is a 1-wide
// projection plus a sigmoid), so it is applied here. Omitting it produces
// plausible-looking but wrong text.
if (k.moe) |*moe2| {
if (moe2.shared_gate_lin.len == hidden) {
var g: f32 = 0;
for (moe2.shared_gate_lin, self.moe_hidden[0..hidden]) |w, xv| {
g += @as(f32, @floatCast(w)) * xv;
}
const scale = cpu.sigmoid(g);
for (0..hidden) |c| {
const v: f32 = @floatCast(self.dec_out[c]);
self.x[c * ch] += scale * v;
}
} else {
for (0..hidden) |c| {
const v: f32 = @floatCast(self.dec_out[c]);
self.x[c * ch] += v;
}
}
} else {
for (0..hidden) |c| {
const v: f32 = @floatCast(self.dec_out[c]);
self.sandwich[c] = v;
}
// Gemma 2 normalises the MLP output before it joins the residual.
if (norm.post_ffw.len == hidden) {
rmsnormFlat(self.sandwich[0..hidden], norm.post_ffw, cfg.eps);
}
for (0..hidden) |c| self.x[c * ch] += self.sandwich[c];
}
// ---- routed experts (MoE), on the CPU ----
// The shared expert above came from the ANE. These are the k experts the
// router picked, and they are computed here because the ANE cannot hold a
// kernel per expert. See research/moe-design.md.
if (k.moe) |*moe| {
const t_moe = sys.nowNs();
// `dec_in` is fp16 (it feeds the ANE); the CPU wants f32.
for (0..hidden) |c| self.moe_hidden[c] = @floatCast(self.dec_in[c]);
const hh = self.moe_hidden[0..hidden];
// The router reads the same normalised input the shared expert did.
cpu.matmulF16(self.moe_logits[0..moe.num_experts], moe.router, hh, moe.num_experts, hidden);
cpu.moeRoute(
self.moe_logits[0..moe.num_experts],
cfg.experts_per_tok,
cfg.norm_topk_prob,
self.moe_probs[0..cfg.experts_per_tok],
self.moe_idx[0..cfg.experts_per_tok],
);
// Accumulate the routed experts into a scratch, then add once, so the
// residual is touched a single time.
@memset(self.moe_out[0..hidden], 0);
if (self.route_counts) |counts| {
self.route_tokens += 1;
for (self.moe_idx[0..cfg.experts_per_tok]) |e| {
counts[@as(usize, li) * cfg.num_experts + e] += 1;
}
}
for (self.moe_idx[0..cfg.experts_per_tok], self.moe_probs[0..cfg.experts_per_tok]) |e, p| {
// A streaming layer reads the expert from the mapping as f32; an
// eager one already has it as fp16 in memory. Both branches exist
// because the two representations need different matmuls, and the
// scratch differs too — using the fp16 accessor on a streaming
// layer reads an empty buffer and silently multiplies by zeros.
if (moe.streaming()) {
if (moe.expert_scratch_f32_alt.len < moe.expert_slot * 3) {
sys.eprint("[moe] BUG: f32 scratch {d} < needed {d}\n", .{ moe.expert_scratch_f32_alt.len, moe.expert_slot * 3 });
}
const g_w = moe.loadExpertF32(e, 0, moe.expert_scratch_f32_alt);
const u_w = moe.loadExpertF32(e, 1, moe.expert_scratch_f32_alt);
const d_w = moe.loadExpertF32(e, 2, moe.expert_scratch_f32_alt);
cpu.moeExpertAccumF32(
self.moe_out[0..hidden],
self.moe_gate_scratch[0..moe.inter],
self.moe_upd_scratch[0..moe.inter],
hh,
g_w,
u_w,
d_w,
moe.inter,
hidden,
p,
cfg.use_gelu,
);
} else {
const g_w = moe.loadExpert(e, 0, moe.expert_scratch);
const u_w = moe.loadExpert(e, 1, moe.expert_scratch);
const d_w = moe.loadExpert(e, 2, moe.expert_scratch);
cpu.moeExpertAccum(
self.moe_out[0..hidden],
self.moe_gate_scratch[0..moe.inter],
self.moe_upd_scratch[0..moe.inter],
hh,
g_w,
u_w,
d_w,
moe.inter,
hidden,
p,
cfg.use_gelu,
);
}
}
for (0..hidden) |c| self.x[c * ch] += self.moe_out[c];
self.stats.moe_ns += sys.nowNs() - t_moe;
}
// PLE: Gemma 4 gates, projects and norms a per-layer vector back onto the residual
// before the layer's output scale. `x` is strided, so the column is gathered into
// `h` for the contiguous arithmetic and scattered back.
if (k.ple_gate) |g| {
const off: usize = @as(usize, li) * cfg.ple_dim;
for (0..hidden) |c| self.h[c] = self.x[c * ch];
cpu.pleBlock(
self.h[0..hidden],
self.ple_in[off..][0..cfg.ple_dim],
g,
k.ple_proj.?,
k.ple_post_norm.?,
self.ple_scr,
self.ple_tmp,
cfg.eps,
);
for (0..hidden) |c| self.x[c * ch] = self.h[c];
}
// Gemma 4 scales the whole output of the layer; 1.0 for every other model.
if (k.out_scale != 1.0) {
for (0..hidden) |c| self.x[c * ch] *= k.out_scale;
}
}
// ---- final norm + lm head ----
rmsnormColumn(self.head_in[0..hidden], self.x, self.final_norm, cfg.eps, ch);
try self.runHead();
self.stats.total_ns += sys.nowNs() - t_start;
self.stats.tokens += 1;
// Snapshot the first decode step on its own, so the steady state can be
// reported without the cold-start ramp folded in.
if (self.stats.first_token_passes == 0 and self.stats.prefill_done_tokens > 0) {
const pd_ns = self.stats.prefill_done_node_ns;
for (0..4) |i| self.stats.first_token_node_ns[i] = self.stats.node_ns[i] -| pd_ns[i];
self.stats.first_token_passes = self.stats.tokens -| self.stats.prefill_done_tokens;
}
return self.logits;
}
/// The routing weight a column gave to `expert`, or 0 when it did not choose it.
///
/// A column can list the same expert at most once (moeRoute picks distinct experts),
/// so the first match is the only match.
fn expertWeightFor(idx: []const u32, probs: []const f32, topk: u32, col: usize, expert: u32) f32 {
for (0..topk) |s| {
if (idx[col * topk + s] == expert) return probs[col * topk + s];
}
return 0;
}
/// Vocabulary rows per head kernel. 64k rows keeps the fp16 blob at 64k * hidden * 2
/// bytes: 300 MB for a 2304-wide model, 128 MB for a 1024-wide one.
fn headChunkFor(hidden: u32, vocab: u32) u32 {
// Overridable so the multi-chunk path can be exercised on a model whose head fits in one
// chunk. Every model that passes `verify` has had a single-chunk head, and the two that do
// not pass — gemma-2-2b and gemma-4-E2B — both need several, which is worth testing
// directly rather than inferring from a correlation.
const target: u64 = if (std.c.getenv("ANEDVD_HEAD_CHUNK_MB")) |v| blk: {
const mb = std.fmt.parseInt(u64, std.mem.span(v), 10) catch 0;
break :blk if (mb > 0) mb * 1024 * 1024 else 512 * 1024 * 1024;
} else 512 * 1024 * 1024;
const per_row: u64 = @as(u64, hidden) * 2;
const rows: u64 = @max(1, target / per_row);
return @intCast(@min(rows, vocab));
}
/// RMSNorm over a flat f32 vector, in place. Used for Gemma 2's sandwich norms, where
/// the value to normalise is a plain activation column rather than a strided chunk.
fn rmsnormFlat(v: []f32, weight: []const f32, eps: f32) void {
const n = weight.len;
std.debug.assert(v.len >= n);
var acc: f32 = 0;
for (v[0..n]) |x| acc += x * x;
const inv = 1.0 / @sqrt(acc / @as(f32, @floatFromInt(n)) + eps);
for (v[0..n], weight) |*x, w| x.* = x.* * inv * w;
}
/// Run the lm head over the whole vocabulary, split across chunks as needed, and
/// write the (optionally soft-capped) logits into `self.logits`.
///
/// Chunking exists because a single kernel for a 256000-row vocabulary is a 1.18 GB
/// weight blob, which the ANE accepts and then computes wrongly: gemma-2-2b's
/// lm_head came back with a relative error of 0.95 against a CPU matmul.
fn runHead(self: *Engine) !void {
const cfg = self.config;
const hidden: usize = cfg.hidden;
const chunk: usize = self.head_chunk;
try self.head_kernel.writeInputF16(0, self.head_in[0..hidden]);
const t0 = sys.nowNs();
try self.head_kernel.eval();
// The FIRST kernel's row count, not the whole vocabulary: `head_out` is
// vocab-sized, and readOutputF16 requires exactly the kernel's elemCount.
// Reading `[0..vocab]` here is what produced "got 256000, kernel expects 116508".
const first_rows: usize = @min(chunk, cfg.vocab);
try self.head_kernel.readOutputF16(0, self.head_out[0..first_rows]);
for (0..self.head_extra_built) |i| {
const k = &self.head_extra[i];
const off = (i + 1) * chunk;
const rows: usize = @min(chunk, cfg.vocab - off);
try k.writeInputF16(0, self.head_in[0..hidden]);
try k.eval();
try k.readOutputF16(0, self.head_out[off..][0..rows]);
}
const dt = sys.nowNs() - t0;
self.stats.ane_eval_ns += dt;
self.stats.ane_evals += 1 + self.head_extra_built;
self.stats.node_ns[@backingInt(Node.head)] += dt;
self.stats.node_evals[@backingInt(Node.head)] += 1 + self.head_extra_built;
for (self.logits, 0..) |*l, i| {
const v: f32 = @floatCast(self.head_out[i]);
// Gemma 2 caps the final logits too.
l.* = if (cfg.final_logit_softcap > 0 and !self.pre_softcap)
cfg.final_logit_softcap * std.math.tanh(v / cfg.final_logit_softcap)
else
v;
}
}
/// RMSNorm applied per attention head (Qwen3's q_norm/k_norm), before RoPE.
fn applyHeadNorm(vec: []f32, heads: u32, head_dim: u32, weight: []const f32, eps: f32) void {
const hd: usize = head_dim;
for (0..heads) |h| {
const v = vec[h * hd ..][0..hd];
cpu.rmsnorm(v, v, weight, eps);
}
}
/// Q norm and rotary only, for a layer that borrows another layer's K/V. Its own keys
/// do not exist: no weights were loaded for them, so there is nothing to normalise, rotate
/// or store.
/// Compute every layer's per-layer input vector for one token, into `ple_in`.
///
/// The table row is dequantised straight out of the aliased mapping: the table is 23.5e9
/// parameters on E2B and one row is used per token, so it is never materialised. The row and
/// the model projection of the token's own embedding are combined by `cpu.plePrepare`, which
/// also owns the reference's three constants.
fn preparePle(self: *Engine, token: u32, col: usize) void {
const cfg = self.config;
const hidden: usize = cfg.hidden;
const rows: usize = @as(usize, cfg.layers) * cfg.ple_dim;
// The projection consumes the same scaled embedding the model runs on, not the raw one.
for (0..hidden) |c| {
const e: f32 = @floatCast(self.embed[@as(usize, token) * hidden + c]);
self.ple_emb[c] = e * cfg.embed_scale;
}
const ttype: gguf.GgmlType = @fromBackingInt(@intCast(self.ple_type));
if (gguf.dequantizeRange(ttype, self.ple_table, @as(u64, token) * rows, self.ple_row[0..rows])) |_| {} else |_| {
// A malformed table is the only way here: `loadRuntime` refuses a model that declares
// PLE without the tensor. Zero rather than stale, so the failure is deterministic.
@memset(self.ple_row[0..rows], 0);
}
cpu.matmulF16(self.ple_proj_out[0..rows], self.ple_proj, self.ple_emb[0..hidden], @intCast(rows), @intCast(hidden));
const out = self.ple_in[col * rows ..][0..rows];
cpu.plePrepare(out, self.ple_row[0..rows], self.ple_proj_out[0..rows], self.ple_norm, cfg.layers, cfg.ple_dim, cfg.hidden, cfg.eps, self.ple_scr);
}
fn ropeQueryOnly(self: *Engine, li: usize, pos: u32, cfg: model.Config, hd: u32) void {
const norm = &self.norms[li];
// Per layer: Gemma 4 rotates its sliding layers at a different base from its global ones.
const theta = cfg.layerRopeTheta(@intCast(li));
if (norm.q_norm) |w| applyHeadNorm(self.sq, cfg.heads, hd, w, cfg.eps);
if (cfg.rope_adjacent) {
cpu.ropeAdjacent(self.sq, cfg.heads, hd, pos, theta);
} else {
cpu.rope(self.sq, cfg.heads, hd, pos, theta);
}
}
fn ropeAndCache(self: *Engine, li: usize, pos: u32, cfg: model.Config, kv_dim: usize, hd: u32) void {
const norm = &self.norms[li];
const theta = cfg.layerRopeTheta(@intCast(li));
if (norm.q_norm) |w| applyHeadNorm(self.sq, cfg.heads, hd, w, cfg.eps);
if (norm.k_norm) |w| applyHeadNorm(self.sk[0..kv_dim], cfg.kv_heads, hd, w, cfg.eps);
if (cfg.rope_adjacent) {
cpu.ropeAdjacent(self.sq, cfg.heads, hd, pos, theta);
cpu.ropeAdjacent(self.sk[0..kv_dim], cfg.kv_heads, hd, pos, theta);
} else {
cpu.rope(self.sq, cfg.heads, hd, pos, theta);
cpu.rope(self.sk[0..kv_dim], cfg.kv_heads, hd, pos, theta);
}
const krow = self.k_cache[li][@as(usize, pos) * kv_dim ..][0..kv_dim];
const vrow = self.v_cache[li][@as(usize, pos) * kv_dim ..][0..kv_dim];
for (0..kv_dim) |i| {
krow[i] = @floatCast(self.sk[i]);
vrow[i] = @floatCast(self.sv[i]);
}
}
/// Process up to `chunk` prompt tokens in one pass and return the logits for
/// the last one. This is where the weight-bandwidth-bound behaviour of the
/// ANE pays off: a whole chunk costs the same as a single token.
pub fn prefill(self: *Engine, ids: []const u32, start_pos: u32) ![]f32 {
// The KV cache holds exactly `max_seq` rows per layer. Writing past them is a heap
// overflow, and it does not fail loudly: `anedvd verify` with a 1121-token prompt on
// a 1024-token context returned all-zero logits and a rel of 1.0 rather than
// crashing. `generate` truncates its input so it never gets here, but `verify`,
// `layers` and `check` call this directly.
if (@as(usize, start_pos) + ids.len > self.max_seq) return error.ContextOverflow;
const cfg = self.config;
const ch = self.chunk;
const hidden: usize = cfg.hidden;
// Per layer, as in `forward`: a sliding layer may use a different head dimension.
// Both are bound inside the layer loop below.
const inter: usize = cfg.inter;
var done: usize = 0;
while (done < ids.len) {
// The tick is fired per layer inside the loop below, which also covers the
// start of every chunk; firing it here as well would just duplicate the first
// call of each iteration.
const n = @min(ch, ids.len - done);
const base_pos: u32 = start_pos + @as(u32, @intCast(done));
for (0..n) |j| {
const row = self.embed[@as(usize, ids[done + j]) * hidden ..][0..hidden];
for (0..hidden) |c| {
const e: f32 = @floatCast(row[c]);