memra-engine 0.98.0

From-scratch CUDA LLM inference engine for NVIDIA RTX 50-series (sm_120a) and Hopper (sm_90a) - custom kernels, no frameworks
Documentation
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
//! dsv4-gpu-gate: DeepSeek-V4-Flash GPU output-sample gate (lane 4, gate (a) + the
//! expert-dequant sub-gate + the VRAM placement table of gate (c)).
//!
//! Replays the lane-2 fixture inputs through the 2-card GPU forward
//! (memra_engine::dsv4_gpu) and compares every TRUNK banked array (mtp_logits_last is
//! SKIPPED — the MTP GPU path is optional for this lane and a skip is never a PASS).
//! ONE fixture variant per invocation, read from the JSON.
//!
//! Usage: dsv4-gpu-gate <model-dir> <fixtures.json> [dev0,dev1]      exit 0 PASS
//!
//! ── Threshold doctrine (bf16-vs-f32, derived in RECEIPTS.md "Lane 4", not guessed;
//!    corrected after run 1 — the correction is banked in RECEIPTS.md too) ──
//! Weights are EXACT in bf16 (rung proofs at load are refusals). f32 islands run f32/f64.
//! The only rounding vs the CPU oracle is the bf16 cast of activation inputs at the
//! non-island GEMMs: unit roundoff u = 2⁻⁸. Each residual sub-block injects ~2 rounded
//! GEMM hops; hc comb is doubly-stochastic and rmsnorm re-anchors scale, so per-element
//! errors random-walk with σ ≈ u·√d·scale. The gate bounds the MAX-ABS over an
//! n-element array, so the extreme-value factor of n zero-mean draws applies:
//!     thr(array) = u · √d · √(2·ln n) · absmax(fixture)
//! (run-1 correction: the banked formula used an ad-hoc 2× where √(2 ln n) belongs —
//! 4.85 at n=129280; measured drift at every banked depth sits at 0.3-0.7× this bound).
//! Depths: layerN_out d=2(N+1); layerN_attn_out d=2N+1; compressor/indexer arrays d=2N
//! (their input's depth; the mechanisms themselves are f32 islands); final logits d=86.
//! Quantizer-grid arrays (run-1 correction #2): indexer_kv is on the e2m1 grid — bf16
//! upstream skew flips codes at boundaries (~u/grid-step ≈ 1/64 of elements expected).
//! A one-step flip from 0 to ±0.5·s has |diff| == max(|got|,|ref|), so the adjacency
//! bound is |diff| ≤ 1.0 × max(|got|,|ref|) (run 1 used 0.5 and rejected legitimate
//! 0↔0.5 flips), budget 5% of elements. index_score consumes the flipped kv/q: one
//! flipped element perturbs a head dot by ≤ 2·s_kv·6·s_q = 12·s_q·s_kv against a
//! 128-term dot — a few percent of the score scale; exceeders are budgeted 5% of
//! elements, each ≤ 0.05·absmax (run 1 modeled the score as continuous — wrong for the
//! FP4 path). Selection is unaffected at gate lengths (all completed blocks selected;
//! −inf causality mask compared EXACTLY). Under the clamp-only contract act_quant is an
//! IDENTITY (448·pow2ceil(amax/448) ≥ amax — the clamp never bites) — compressor_kv
//! gets NO flip budget.
//! Mandatory id gates on logits rows: top-1 exact, top-5 set-exact, and (run-3
//! correction, fully derived — no fixed overlap floor) top-20 set changes confined to
//! the drift-noise band of the rank-20 boundary: every symmetric-difference id must
//! satisfy |ref_logit(id) − ref_logit(rank 20)| ≤ 3·√2·u·√d·|ref rank-20 logit|.
//! An id outside that band dropping out or climbing in is a REAL bug. Raw overlap and
//! the 20/21 boundary gaps are always printed; the greedy-continuation gate remains the
//! end-to-end semantic instrument.

use memra_engine::dsv4_gpu::{Dsv4Gpu, GpuCapture};
use memra_gguf::dsv4_forward::{
    FixtureSpec, drift_coeff, expert_arm_native, quant_depth_of, read_npz,
};
use std::collections::BTreeSet;
use std::path::Path;

const U_BF16: f64 = 1.0 / 256.0; // 2^-8

/// Lane 7: per-array drift coefficient of the active numeric class. bf16 arm:
/// C = u_b·√d_b (the lane-4 doctrine unchanged). Native arm: C = √(d_b·u_b² + d_q·u_q²)
/// with d_q = 2 quantized hops per upstream MoE sub-block (RECEIPTS.md "Lane 7" table).
fn class_coeff(name: &str, d_b: f64) -> f64 {
    let d_q = if expert_arm_native() {
        quant_depth_of(name)
    } else {
        0.0
    };
    drift_coeff(d_b, d_q)
}

struct ArrayCheck {
    name: String,
    shape: Vec<usize>,
    max_abs: f64,
    max_rel: f64,
    threshold: f64,
    n_over: usize,
    verdict: &'static str,
    note: String,
}

enum Policy {
    BitExact,
    Derived {
        coeff: f64,
        flip_budget_frac: f64,
        /// per-element adjacency bound: |diff| ≤ flip_rel · max(|got|,|ref|) (0 = none)
        flip_rel: f32,
        /// alternative flip bound: |diff| ≤ flip_abs_of_amax · absmax_ref (0 = none)
        flip_abs_of_amax: f32,
    },
    Logits {
        coeff: f64,
        top_ids: Vec<u32>,
        /// native class: top-1/top-5 governed by the band rule (a flip must be in-band)
        /// instead of the bf16 class's strict top-1-exact + top-5-set-exact
        native: bool,
    },
}

fn depth_of(name: &str) -> u32 {
    // layer index parsed from the name; depths per the doctrine above
    let core = name.strip_prefix("c160_").unwrap_or(name);
    let n: u32 = core
        .strip_prefix("layer")
        .and_then(|r| r.split('_').next())
        .and_then(|x| x.parse().ok())
        .unwrap_or(0);
    if core.contains("_out") && !core.contains("attn_out") {
        2 * (n + 1)
    } else if core.contains("attn_out") {
        2 * n + 1
    } else {
        2 * n
    }
}

fn policy_for(name: &str, spec: &FixtureSpec) -> Option<Policy> {
    let native = expert_arm_native();
    match name {
        "embed_out" => Some(Policy::BitExact),
        "final_logits_last" => Some(Policy::Logits {
            coeff: class_coeff(name, 86.0),
            top_ids: spec.top20_ids.clone(),
            native,
        }),
        // MTP head: 2 more sub-blocks past the trunk's 86 (+ the e/h_proj casts).
        // mtp_top20 is absent on 0731-lineage trunk-only fixture sets; this policy is
        // only reachable when the set banks mtp_logits_last, so a missing json entry
        // there is fixture corruption — refuse loudly.
        "mtp_logits_last" => Some(Policy::Logits {
            coeff: class_coeff(name, 88.0),
            top_ids: spec
                .mtp_top20_ids
                .clone()
                .expect("fixture banks mtp_logits_last but json has no mtp_top20"),
            native,
        }),
        // native budgets re-derived for the class (RECEIPTS.md "Lane 7"): upstream rel
        // drift ≈ √(4u_b²+4u_q²) ≈ 0.125 vs e2m1 min one-step gap ≈ 0.25 ⇒ expected
        // one-step flip fraction ≈ 0.5 (budget 0.75); index_score flip noise on a
        // 128-dot ≈ 0.1-0.2 of scale (bound 0.25·absmax, budget 0.5)
        n if n.contains("indexer_kv") => Some(Policy::Derived {
            coeff: class_coeff(n, depth_of(n) as f64),
            flip_budget_frac: if native { 0.75 } else { 0.05 },
            flip_rel: 1.0, // one e2m1 step from 0 has |diff| == max(|got|,|ref|)
            flip_abs_of_amax: 0.0,
        }),
        n if n.contains("index_score") => Some(Policy::Derived {
            coeff: class_coeff(n, depth_of(n) as f64),
            flip_budget_frac: if native { 0.5 } else { 0.05 },
            flip_rel: 0.0,
            // one-flip propagation estimate (bf16) / native flip-noise bound (doc header)
            flip_abs_of_amax: if native { 0.25 } else { 0.05 },
        }),
        n => Some(Policy::Derived {
            coeff: class_coeff(n, depth_of(n) as f64),
            flip_budget_frac: 0.0,
            flip_rel: 0.0,
            flip_abs_of_amax: 0.0,
        }),
    }
}

fn top_ids(v: &[f32], k: usize) -> Vec<u32> {
    let mut order: Vec<usize> = (0..v.len()).collect();
    order.sort_by(|&a, &b| {
        v[b].partial_cmp(&v[a])
            .unwrap_or(std::cmp::Ordering::Equal)
            .then(a.cmp(&b))
    });
    order.into_iter().take(k).map(|x| x as u32).collect()
}

#[allow(clippy::too_many_arguments)]
fn check_array(
    name: &str,
    got: &[f32],
    got_shape: &[usize],
    ref_shape: &[usize],
    ref_vals: &[f32],
    policy: &Policy,
) -> ArrayCheck {
    let mut c = ArrayCheck {
        name: name.to_string(),
        shape: got_shape.to_vec(),
        max_abs: 0.0,
        max_rel: 0.0,
        threshold: 0.0,
        n_over: 0,
        verdict: "PASS",
        note: String::new(),
    };
    if got_shape != ref_shape {
        c.verdict = "FAIL";
        c.note = format!("shape mismatch: got {got_shape:?}, fixture {ref_shape:?}");
        return c;
    }
    if got.iter().any(|x| x.is_nan()) {
        c.verdict = "FAIL";
        c.note = "NaN in computed array".into();
        return c;
    }
    let mut inf_mismatch = 0usize;
    let mut absmax_ref = 0f32;
    for (&g, &r) in got.iter().zip(ref_vals) {
        if g.is_infinite() != r.is_infinite() || (g.is_infinite() && g != r) {
            inf_mismatch += 1;
        }
        if r.is_finite() {
            absmax_ref = absmax_ref.max(r.abs());
        }
    }
    if inf_mismatch > 0 {
        c.verdict = "FAIL";
        c.note = format!("{inf_mismatch} ±inf-mask position mismatches (causality)");
        return c;
    }
    let mut diffs: Vec<(usize, f64)> = Vec::new();
    for (i, (&g, &r)) in got.iter().zip(ref_vals).enumerate() {
        if !r.is_finite() {
            continue;
        }
        let d = (g as f64 - r as f64).abs();
        if d > c.max_abs {
            c.max_abs = d;
        }
        let rel = d / (r.abs() as f64).max(1e-6);
        if rel > c.max_rel {
            c.max_rel = rel;
        }
        if d > 0.0 {
            diffs.push((i, d));
        }
    }
    match policy {
        Policy::BitExact => {
            if c.max_abs > 0.0 {
                c.verdict = "FAIL";
                c.note = format!(
                    "{} non-identical elements (bit-exact required)",
                    diffs.len()
                );
            }
        }
        Policy::Derived {
            coeff,
            flip_budget_frac,
            flip_rel,
            flip_abs_of_amax,
        } => {
            let ev = (2.0 * (got.len().max(2) as f64).ln()).sqrt(); // extreme-value factor
            c.threshold = coeff.max(U_BF16) * ev * absmax_ref as f64;
            let over: Vec<&(usize, f64)> = diffs.iter().filter(|(_, d)| *d > c.threshold).collect();
            c.n_over = over.len();
            if !over.is_empty() {
                let budget = (*flip_budget_frac * got.len() as f64).floor() as usize;
                let bound_ok = |i: usize, d: f64| -> bool {
                    if *flip_abs_of_amax > 0.0 {
                        d <= *flip_abs_of_amax as f64 * absmax_ref as f64
                    } else if *flip_rel > 0.0 {
                        d <= *flip_rel as f64 * (got[i].abs() as f64).max(ref_vals[i].abs() as f64)
                    } else {
                        false
                    }
                };
                if over.len() <= budget && over.iter().all(|(i, d)| bound_ok(*i, *d)) {
                    c.note = format!(
                        "{} quantizer-flip exceeder(s) within the documented bound (budget {})",
                        over.len(),
                        budget
                    );
                } else {
                    c.verdict = "FAIL";
                    c.note = format!(
                        "{} elements over threshold (first at flat index {})",
                        over.len(),
                        over.first().map(|(i, _)| *i).unwrap_or(0)
                    );
                }
            }
        }
        Policy::Logits {
            coeff,
            top_ids: want,
            native,
        } => {
            let ev = (2.0 * (got.len().max(2) as f64).ln()).sqrt();
            c.threshold = coeff * ev * absmax_ref as f64;
            let got_top = top_ids(got, 21);
            let ref_top = top_ids(ref_vals, 21);
            if want[..5] != ref_top[..5] {
                c.verdict = "FAIL";
                c.note = format!(
                    "fixture self-inconsistency: json top5 {:?} vs npz {:?}",
                    &want[..5],
                    &ref_top[..5]
                );
                return c;
            }
            let top1_ok = got_top[0] == ref_top[0];
            let s5g: BTreeSet<u32> = got_top[..5].iter().cloned().collect();
            let s5r: BTreeSet<u32> = ref_top[..5].iter().cloned().collect();
            let s20g: BTreeSet<u32> = got_top[..20].iter().cloned().collect();
            let s20r: BTreeSet<u32> = ref_top[..20].iter().cloned().collect();
            let overlap20 = s20g.intersection(&s20r).count();
            // boundary diagnostics: rank-20/21 logit gap on both sides
            let ref20 = ref_vals[ref_top[19] as usize];
            let gap_ref = ref20 - ref_vals[ref_top[20] as usize];
            let gap_got = got[got_top[19] as usize] - got[got_top[20] as usize];
            // top-20 id rule (DERIVED, run-3 correction): every id in the symmetric
            // difference of the two top-20 SETS must sit inside the drift-noise band of
            // the rank-20 boundary. Per-logit drift σ(x) = u·√d·|x|; a rank swap
            // compares two logits (√2), band = 3·√2·σ(ref rank-20 logit). An id more
            // than `band` above the reference boundary must never drop out, and an id
            // more than `band` below it must never climb in — either is a REAL bug, not
            // noise. No fixed overlap floor: the rule scales with the measured cluster
            // structure (trunk run 1: 2 misses in a 0.27-gap boundary; MTP: 4 misses in
            // a 0.026/0.037/0.065 near-tie cluster — both are in-band physics).
            let band = 3.0 * std::f64::consts::SQRT_2 * coeff * (ref20.abs() as f64);
            let mut out_of_band: Vec<(u32, f32)> = Vec::new();
            for id in s20r.symmetric_difference(&s20g) {
                let dist = (ref_vals[*id as usize] - ref20).abs() as f64;
                if dist > band {
                    out_of_band.push((*id, ref_vals[*id as usize]));
                }
            }
            c.note = format!(
                "top1 {}=={} | top5 set {} | top20 overlap {}/20 | 20/21 gap ref {:.4} gpu {:.4} | boundary band ±{:.3}: {} set-diff id(s), {} out-of-band",
                got_top[0],
                ref_top[0],
                if s5g == s5r { "EXACT" } else { "MISMATCH" },
                overlap20,
                gap_ref,
                gap_got,
                band,
                s20r.symmetric_difference(&s20g).count(),
                out_of_band.len()
            );
            if !out_of_band.is_empty() {
                c.note.push_str(&format!(" | OUT-OF-BAND: {out_of_band:?}"));
            }
            // native class (lane 7): a top-1 flip must be an in-band near-tie on the
            // REF row; top-5 set changes confined to the rank-5 boundary band (the
            // bf16 class keeps lane-4's strict top-1-exact + top-5-set-exact).
            let top1_band_ok = top1_ok || {
                let m = (ref_vals[ref_top[0] as usize] as f64
                    - ref_vals[got_top[0] as usize] as f64)
                    .abs();
                m <= 3.0
                    * std::f64::consts::SQRT_2
                    * coeff
                    * (ref_vals[ref_top[0] as usize].abs() as f64)
            };
            let ref5_boundary = ref_vals[ref_top[4] as usize];
            let band5 = 3.0 * std::f64::consts::SQRT_2 * coeff * (ref5_boundary.abs() as f64);
            let top5_band_ok = s5r
                .symmetric_difference(&s5g)
                .all(|id| (ref_vals[*id as usize] - ref5_boundary).abs() as f64 <= band5);
            if !top1_band_ok {
                c.note.push_str(" | top1 OUT-OF-BAND");
            }
            if *native && s5g != s5r && !top5_band_ok {
                c.note.push_str(" | top5 OUT-OF-BAND");
            }
            let strict_ok = if *native {
                top1_band_ok && top5_band_ok
            } else {
                top1_ok && s5g == s5r
            };
            if !strict_ok || !out_of_band.is_empty() || c.max_abs > c.threshold {
                c.verdict = "FAIL";
            }
        }
    }
    c
}

fn vram_table(gpu: &Dsv4Gpu, tag: &str) {
    match gpu.vram_report() {
        Ok(rows) => {
            for (dev, free, total, resident) in rows {
                println!(
                    "[vram {tag}] dev{dev}: used {:.2} GiB / {:.2} GiB (free {:.2}), loader-resident {:.2} GiB",
                    (total - free) as f64 / 2f64.powi(30),
                    total as f64 / 2f64.powi(30),
                    free as f64 / 2f64.powi(30),
                    resident as f64 / 2f64.powi(30),
                );
            }
        }
        Err(err) => println!("[vram {tag}] report failed: {err}"),
    }
}

/// Expert-dequant sub-gate: GPU NVFP4/MXFP4 kernel output must be BIT-EXACT vs the
/// lane-1 host decoders (exactness proofs make any mismatch a kernel bug). `prefix` is
/// "layers.N" (trunk NVFP4) or "mtp.0" (MXFP4 — dispatched by the layer's detected kind).
fn expert_dequant_subgate(gpu: &Dsv4Gpu, samples: &[(&str, usize, &str)]) -> bool {
    use cudarc::driver::DevicePtr;
    use memra_engine::dsv4_gpu::ExpertKind;
    let mut ok = true;
    for &(prefix, ex, proj) in samples {
        let name = format!("{prefix}.ffn.experts.{ex}.{proj}");
        let (shape, host) = gpu.model.tensor_f32(&name);
        let (rows, cols) = (shape[0], shape[1]);
        let (stage, layer) = if prefix == "mtp.0" {
            let m = gpu.mtp.as_ref().expect("mtp loaded");
            (&gpu.stages[gpu.stages.len() - 1], &m.layer)
        } else {
            let il: u32 = prefix.strip_prefix("layers.").unwrap().parse().unwrap();
            let stage = &gpu.stages[gpu.layer_stage[il as usize]];
            (
                stage,
                stage.layers.iter().find(|l| l.il == il).expect("layer"),
            )
        };
        let pi = match proj {
            "w1" => 0usize,
            "w2" => 1,
            _ => 2,
        };
        stage.gpu.ctx.bind_to_thread().expect("bind ctx");
        let stream = stage.gpu.stream();
        let wbytes = rows * cols / 2;
        let sbytes = match layer.expert_kind {
            ExpertKind::Nvfp4 => rows * cols / 16,
            ExpertKind::Mxfp4 => rows * cols / 32,
        };
        let wp = (layer.experts_w.device_ptr(&stream).0 as usize + (ex * 3 + pi) * wbytes)
            as *const std::os::raw::c_void;
        let scp = (layer.experts_sc.device_ptr(&stream).0 as usize + (ex * 3 + pi) * sbytes)
            as *const std::os::raw::c_void;
        let dst = stage.deq[pi].device_ptr(&stream).0 as *mut std::os::raw::c_void;
        let sv = stream.cu_stream() as *mut std::os::raw::c_void;
        let rc = unsafe {
            match layer.expert_kind {
                ExpertKind::Nvfp4 => memra_engine::dsv4_ffi::memra_dsv4_nvfp4_deq_bf16(
                    wp,
                    scp,
                    layer.experts_s2[ex * 3 + pi],
                    rows as i32,
                    cols as i32,
                    dst,
                    sv,
                ),
                ExpertKind::Mxfp4 => memra_engine::dsv4_ffi::memra_dsv4_mxfp4_deq_bf16(
                    wp,
                    scp,
                    rows as i32,
                    cols as i32,
                    dst,
                    sv,
                ),
            }
        };
        assert_eq!(rc, 0, "dequant kernel rc {rc}");
        let mut raw = vec![0u8; rows * cols * 2];
        stream
            .memcpy_dtoh(&stage.deq[pi].slice(0..rows * cols * 2), &mut raw[..])
            .expect("dtoh");
        stream.synchronize().expect("sync");
        let mut mismatches = 0usize;
        for i in 0..rows * cols {
            let b = u16::from_le_bytes([raw[2 * i], raw[2 * i + 1]]);
            let g = f32::from_bits((b as u32) << 16);
            if g.to_bits() != host[i].to_bits() {
                if mismatches == 0 {
                    println!("  [FAIL] {name}[{i}]: gpu {g} vs host {}", host[i]);
                }
                mismatches += 1;
            }
        }
        let verdict = if mismatches == 0 { "PASS" } else { "FAIL" };
        println!(
            "  [{verdict}] expert-dequant {name} [{rows}x{cols}]: {mismatches} mismatches (bit-exact required)"
        );
        ok &= mismatches == 0;
    }
    ok
}

fn main() {
    let args: Vec<String> = std::env::args().collect();
    if args.len() < 3 {
        eprintln!("usage: dsv4-gpu-gate <model-dir> <fixtures.json> [dev0,dev1]");
        std::process::exit(2);
    }
    let t0 = std::time::Instant::now();
    let dir = Path::new(&args[1]);
    let spec = FixtureSpec::load(Path::new(&args[2]));
    let devices: Vec<usize> = args
        .get(3)
        .map(|s| {
            s.split(',')
                .map(|x| x.parse().expect("device ordinal"))
                .collect()
        })
        .unwrap_or_else(|| vec![0, 1]);
    println!(
        "dsv4-gpu-gate | model {} | fixtures {} | variant {} ({:?}) | devices {devices:?}",
        dir.display(),
        args[2],
        spec.variant_tag,
        spec.variant
    );

    // fixture integrity (sha256 per array, lane-3 rule)
    let npz = read_npz(&spec.npz_path);
    let mut failures: Vec<String> = Vec::new();
    for (name, (shape, sha)) in &spec.arrays {
        match npz.get(name) {
            None => failures.push(format!("fixture npz missing array {name}")),
            Some((nshape, _, nsha)) => {
                if nshape != shape || nsha != sha {
                    failures.push(format!("fixture integrity mismatch on {name}"));
                }
            }
        }
    }
    if !failures.is_empty() {
        for f in &failures {
            println!("  FAIL: {f}");
        }
        std::process::exit(1);
    }
    println!(
        "fixture integrity: {} arrays, payload sha256 all match",
        npz.len()
    );

    let max_seq = 4096.min(
        spec.tokens_160
            .as_ref()
            .map(|t| t.len())
            .unwrap_or(0)
            .max(512),
    );
    let gpu = Dsv4Gpu::load(dir, &devices, spec.variant, max_seq).expect("load");
    println!(
        "loaded: split at layer {} (stage0 {} layers, stage1 {} layers), t={:.0}s",
        gpu.split_at,
        gpu.stages[0].layers.len(),
        gpu.stages[1].layers.len(),
        t0.elapsed().as_secs_f64()
    );
    vram_table(&gpu, "post-load");

    // ---- expert-dequant sub-gate (bit-exact, both quadrant layers + the lane-1 pins,
    //      both recipes: trunk NVFP4 and MTP MXFP4)
    let n_trunk = gpu.model.mc.n_layer - gpu.model.mc.nextn_predict_layers;
    let stage1_prefix = format!("layers.{}", gpu.split_at);
    let last_prefix = format!("layers.{}", n_trunk - 1);
    let mut samples: Vec<(&str, usize, &str)> = vec![
        ("layers.0", 0, "w1"),
        ("layers.2", 100, "w3"),
        ("layers.20", 7, "w1"), // lane-1 NVFP4 oracle pin tensor
        (&stage1_prefix, 31, "w2"),
        (&last_prefix, 255, "w2"),
    ];
    // MXFP4 samples only when a NextN block is resident (0731: mtp.* is the DSpark
    // drafter, not loaded on GPU — its dequant gate belongs to the drafter lane).
    if gpu.mtp.is_some() {
        samples.push(("mtp.0", 7, "w1")); // lane-1 MXFP4 oracle pin tensor
        samples.push(("mtp.0", 200, "w2"));
    } else {
        println!(
            "  (MXFP4 mtp.* samples skipped: no NextN block resident — DSpark drafter lane owns that gate)"
        );
    }
    println!("\n== expert-dequant sub-gate (GPU kernels vs lane-1 host decoders) ==");
    let deq_ok = expert_dequant_subgate(&gpu, &samples);

    // capture layers derived from fixture names
    let mut cap32: BTreeSet<u32> = BTreeSet::new();
    let mut cap160: BTreeSet<u32> = BTreeSet::new();
    for name in spec.arrays.keys() {
        if let Some(rest) = name.strip_prefix("c160_layer") {
            if let Ok(n) = rest.split('_').next().unwrap_or("").parse::<u32>() {
                cap160.insert(n);
            }
        } else if let Some(rest) = name.strip_prefix("layer") {
            if let Ok(n) = rest.split('_').next().unwrap_or("").parse::<u32>() {
                cap32.insert(n);
            }
        }
    }

    let hc = gpu.model.cfg().hc_mult as usize;
    let hidden = gpu.model.mc.n_embd as usize;
    let mut table: Vec<ArrayCheck> = Vec::new();
    let mut checked: BTreeSet<String> = BTreeSet::new();
    let mut skipped: Vec<String> = Vec::new();
    let mut check = |name: &str, got: &[f32], got_shape: &[usize], table: &mut Vec<ArrayCheck>| {
        let Some((ref_shape, ref_vals, _)) = npz.get(name) else {
            return;
        };
        let Some(policy) = policy_for(name, &spec) else {
            return;
        };
        let c = check_array(name, got, got_shape, ref_shape, ref_vals, &policy);
        println!(
            "  [{}] {} {:?}: max-abs {:.3e} max-rel {:.3e} thr {:.3e} over {}{}",
            c.verdict,
            c.name,
            c.shape,
            c.max_abs,
            c.max_rel,
            c.threshold,
            c.n_over,
            if c.note.is_empty() {
                String::new()
            } else {
                format!(" | {}", c.note)
            }
        );
        checked.insert(name.to_string());
        table.push(c);
    };

    // ================= 32-token run =================
    let ids = &spec.tokens_32;
    let s = ids.len();
    let mut cap = GpuCapture {
        want: cap32.clone(),
        ..Default::default()
    };
    let fwd = gpu
        .forward(ids, Some(&mut cap), None)
        .expect("forward 32")
        .expect("logits expected");
    let logits = fwd.logits;
    println!("32-token forward done t={:.0}s", t0.elapsed().as_secs_f64());
    vram_table(&gpu, "post-warmup");

    if let Some(e0) = &cap.embed_out {
        check("embed_out", e0, &[1, s, hidden], &mut table);
    }
    for lid in &cap32 {
        if let Some(h) = cap.layer_out.get(lid) {
            check(
                &format!("layer{lid}_out"),
                h,
                &[1, s, hc, hidden],
                &mut table,
            );
        }
        if let Some(a) = cap.attn_out.get(lid) {
            check(
                &format!("layer{lid}_attn_out"),
                a,
                &[1, s, hidden],
                &mut table,
            );
        }
        if let Some((kv, nb)) = cap.compressor_kv.get(lid) {
            check(
                &format!("layer{lid}_compressor_kv"),
                kv,
                &[1, *nb, kv.len() / nb],
                &mut table,
            );
        }
        if let Some((kv, nb)) = cap.indexer_kv.get(lid) {
            check(
                &format!("layer{lid}_indexer_kv"),
                kv,
                &[1, *nb, kv.len() / nb],
                &mut table,
            );
        }
        if let Some((sc, nb)) = cap.index_score.get(lid) {
            check(
                &format!("layer{lid}_index_score"),
                sc,
                &[1, s, *nb],
                &mut table,
            );
        }
    }
    check("final_logits_last", &logits, &[logits.len()], &mut table);
    if spec.arrays.contains_key("mtp_logits_last") {
        if gpu.mtp.is_some() {
            let ml = gpu.mtp_logits_last(&fwd.h_last, ids).expect("mtp forward");
            check("mtp_logits_last", &ml, &[ml.len()], &mut table);
            println!("mtp forward done t={:.0}s", t0.elapsed().as_secs_f64());
        } else {
            skipped.push(
                "mtp_logits_last (MTP block absent from artifact — SKIPPED, not PASS)".into(),
            );
        }
    }

    // ================= 160-token run (early exit after the deepest capture layer) ====
    if let (Some(ids160), Some(&max_l)) = (&spec.tokens_160, cap160.iter().max()) {
        let s2 = ids160.len();
        let mut cap2 = GpuCapture {
            want: cap160.clone(),
            ..Default::default()
        };
        let r = gpu
            .forward(ids160, Some(&mut cap2), Some(max_l))
            .expect("forward 160");
        assert!(r.is_none(), "early exit expected");
        println!(
            "160-token partial forward done t={:.0}s",
            t0.elapsed().as_secs_f64()
        );
        for lid in &cap160 {
            if let Some(h) = cap2.layer_out.get(lid) {
                check(
                    &format!("c160_layer{lid}_out_last"),
                    &h[(s2 - 1) * hc * hidden..],
                    &[1, hc, hidden],
                    &mut table,
                );
            }
            if let Some(a) = cap2.attn_out.get(lid) {
                check(
                    &format!("c160_layer{lid}_attn_out_last"),
                    &a[(s2 - 1) * hidden..],
                    &[1, hidden],
                    &mut table,
                );
            }
            if let Some((kv, nb)) = cap2.compressor_kv.get(lid) {
                check(
                    &format!("c160_layer{lid}_compressor_kv"),
                    kv,
                    &[1, *nb, kv.len() / nb],
                    &mut table,
                );
            }
        }
    }
    vram_table(&gpu, "post-gate");

    // coverage: every banked TRUNK array must have been checked
    for name in spec.arrays.keys() {
        if !checked.contains(name) && name != "mtp_logits_last" {
            failures.push(format!(
                "banked array {name} was never computed by the gate"
            ));
        }
    }
    if !deq_ok {
        failures.push("expert-dequant sub-gate failed".into());
    }
    for c in &table {
        if c.verdict == "FAIL" {
            failures.push(format!("{}: {}", c.name, c.note));
        }
    }

    println!(
        "\n== GPU gate table (variant {}, {} class) ==",
        spec.variant_tag,
        if expert_arm_native() {
            "NATIVE expert arm: C = sqrt(d_b*u_b^2 + d_q*u_q^2), u_q = 2^-4"
        } else {
            "bf16-dequant arm: u = 2^-8 doctrine"
        }
    );
    println!("| array | shape | max-abs | max-rel | threshold | verdict |");
    println!("|---|---|---|---|---|---|");
    for c in &table {
        println!(
            "| {} | {:?} | {:.3e} | {:.3e} | {:.3e} | {}{} |",
            c.name,
            c.shape,
            c.max_abs,
            c.max_rel,
            c.threshold,
            c.verdict,
            if c.note.is_empty() {
                String::new()
            } else {
                format!(" ({})", c.note)
            }
        );
    }
    for skip in &skipped {
        println!("| SKIPPED: {skip} |");
    }
    println!(
        "\nelapsed: {:.1}s (informational, single-run, not a perf claim)",
        t0.elapsed().as_secs_f64()
    );
    if failures.is_empty() {
        println!(
            "GPU OUTPUT-SAMPLE GATE [{}]: PASS ({} arrays compared, {} skipped, 0 failures)",
            spec.variant_tag,
            table.len(),
            skipped.len()
        );
    } else {
        println!(
            "GPU OUTPUT-SAMPLE GATE [{}]: FAIL ({} failures)",
            spec.variant_tag,
            failures.len()
        );
        for f in &failures {
            println!("  FAIL: {f}");
        }
        std::process::exit(1);
    }
}