hf2q 0.1.33

Pure Rust CLI for converting HuggingFace models to hardware-optimized formats and serving them over an OpenAI-compatible API on Apple Silicon
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
//! Layer-major joint decode over independent Qwen3.5/3.6/3.8 slots.
//!
//! One transaction advances `B` slots of the shared [`HybridKvCache`] by one
//! token each, every slot at its own position. Row-parallel work runs once
//! over the packed rows: embedding gather, RMS norms, the DeltaNet and
//! full-attention projections (per [`JointProductRoute`]), the fused
//! residual norm, the dense FFN (per [`JointDenseFfnRoute`]) and the output
//! head. Work that touches a slot's cache (DeltaNet conv + recurrence, KV
//! write + SDPA) runs per row against that slot's cursor and ping-pong
//! parity; see
//! [`super::super::joint_decode_core`]. MoE FFNs with native router and
//! shared-expert storage (`HF2Q_QWEN_MOE_BATCHED=1`) run one batched layer
//! over the packed rows ([`super::super::moe_batched`]), whose kernels are
//! row-exact, so serial decode runs the same route at one row. Otherwise
//! they run per row through the serial helper: the BF16 router and shared
//! expert are float projections whose packed route differs from `m = 1`.
//!
//! Admission ([`super::super::joint_decode_routes`]) runs before the first
//! write. Cursors and parities advance at encode time exactly as in the
//! serial graph, so a failed step leaves every row of the step needing the
//! caller's per-slot recovery; rows outside the step are never touched.
//!
//! This module is a child of `forward_gpu` so it shares the thread-local GPU
//! weight cache without widening that cache's visibility.

use anyhow::{anyhow, bail, ensure, Context, Result};
use mlx_native::ops::argmax::dispatch_argmax_f32;
use mlx_native::ops::copy::dispatch_copy_f32;
use mlx_native::ops::fused_norm_add::dispatch_fused_residual_norm_f32;
use mlx_native::ops::rms_norm;
use mlx_native::{CommandEncoder, DType, KernelRegistry, MlxBuffer, MlxDevice};

use super::{
    default_chain_n, dump_layer_n, embed_token_ids_gpu_into, embed_tokens_gpu_into,
    gpu_cache_matches_model, FfnWeightsGpu, ForwardGpuCache, LayerWeightsGpu, OutputHeadGpu,
    GPU_CACHE,
};
use crate::inference::models::qwen35::decode_pool;
use crate::inference::models::qwen35::dump_bisect;
use crate::inference::models::qwen35::ffn::MoeFfnShape;
use crate::inference::models::qwen35::gpu_ffn::{
    build_dense_ffn_layer_gpu_q_into_with_gate_up, build_moe_ffn_layer_gpu_q_into,
    DenseGateUpDispatch,
};
use crate::inference::models::qwen35::gpu_full_attn::apply_linear_projection_f32_into_with_ggml_type;
use crate::inference::models::qwen35::joint_decode_core::{
    encode_joint_delta_net_layer, encode_joint_full_attn_layer, row_view, DeltaNetReplay,
    DeltaNetRoutes, FullAttnRoutes, JointRows, JointWindow,
};
use crate::inference::models::qwen35::joint_decode_routes::{
    check_dense_ffn_route, check_mode_policy, dense_ffn_route, joint_decode_env_unavailable_reason,
    joint_mode_max_rows, joint_padded_width, projection_route, select_joint_route_mode,
    JointDenseFfnRoute, JointProductRoute, JointRouteMode, JointRoutingPolicy,
    DFLASH2_VERIFY_WIDTH, MAX_JOINT_DECODE_ROWS,
};
use crate::inference::models::qwen35::joint_projection::{
    JointProjectionKernel, JointProjectionScope,
};
use crate::inference::models::qwen35::joint_step_options::JointStepOptions;
use crate::inference::models::qwen35::kv_cache::HybridKvCache;
use crate::inference::models::qwen35::model::{Qwen35FfnWeights, Qwen35Model};
use crate::inference::models::qwen35::moe_batched::{
    build_moe_ffn_layer_gpu_batched_into, DFlash2MoeRouteMask,
};
use crate::inference::models::qwen35::prepared_projection;
use crate::inference::models::qwen35::spec_decode::nth_hidden_row;
use crate::inference::models::qwen35::verify_attn_tile::VerifyTileScratch;
use crate::inference::models::qwen35::Qwen35Config;
use crate::inference::spec_decode::dflash2::adapters::DFlash2TargetCapture;
use crate::serve::multi_seq_kv::SlotId;

/// What the caller needs back for one joint row.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum Qwen35JointOutput {
    /// GPU argmax over the row's logits (the serial greedy head's kernel).
    GreedyToken,
    /// Full logits for host sampling.
    Logits,
    /// Full logits plus the post-output-norm hidden row MTP consumes.
    LogitsAndHidden,
    /// GPU argmax plus the post-output-norm hidden row (a greedy MTP lane).
    GreedyTokenAndHidden,
    /// The post-output-norm hidden row only. A DFlash2 verify row whose
    /// decision comes from [`crate::inference::models::qwen35::verify_decision`] returns this.
    Hidden,
}

impl Qwen35JointOutput {
    fn wants_argmax(self) -> bool {
        matches!(self, Self::GreedyToken | Self::GreedyTokenAndHidden)
    }

    fn wants_logits(self) -> bool {
        matches!(self, Self::Logits | Self::LogitsAndHidden)
    }

    fn wants_hidden(self) -> bool {
        matches!(
            self,
            Self::LogitsAndHidden | Self::GreedyTokenAndHidden | Self::Hidden
        )
    }
}

/// One slot's input to a joint step.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Qwen35JointRow {
    pub slot_id: SlotId,
    pub token: u32,
    /// Text-axis position; all four MRoPE axes use it, as in serial decode.
    pub position: i32,
    pub output: Qwen35JointOutput,
}

/// One slot's result of a joint step.
pub(crate) struct Qwen35JointRowOutput {
    pub greedy_token: Option<u32>,
    pub logits: Option<Vec<f32>>,
    /// `[1, hidden]` view of a durable buffer; outlives the decode pool.
    pub nextn_hidden: Option<MlxBuffer>,
    /// Candidates of the row's greedy decision, when the step was asked for
    /// them ([`crate::inference::models::qwen35::verify_decision`]).
    pub decision: Option<crate::inference::models::qwen35::verify_decision::JointRowDecision>,
}

pub(super) type JointOutputHeadTail<'a> =
    dyn FnMut(&mut CommandEncoder, &mut KernelRegistry, &MlxDevice, &MlxBuffer) -> Result<()> + 'a;

enum LayerRoutes {
    Full(FullAttnRoutes),
    Linear(DeltaNetRoutes),
}

/// Admitted product routes of every layer and the output head.
pub(super) struct JointPlan {
    layers: Vec<LayerRoutes>,
    head: JointProductRoute,
}

/// The packed rows of one joint forward.
pub(super) struct JointPacking<'a> {
    /// Real rows in packed order.
    pub rows: &'a [Qwen35JointRow],
    /// Lane windows over `rows` (single rows for a decode step).
    pub windows: &'a [JointWindow],
    /// Packed width, at least `rows.len()`; padding rows copy row 0.
    pub width: usize,
    /// DFlash2 verify with the tiled TQ full attention requested.
    pub attention_tile: bool,
    /// A DFlash2 target verify step: its rows are a route of their own, not
    /// held to the serial one-token forward's bits, so the prepared routes
    /// may serve it at every width (`HF2Q_REPACKED_GGUF_ANY_WIDTH=1`). Plain
    /// joint decode and joint MTP verify steps are not.
    pub dflash2_verify: bool,
    /// DFlash2 verify with the fused mixer stage requested.
    pub mixer_fused: bool,
}

fn plan_joint_routes(
    mode: JointRouteMode,
    cfg: &Qwen35Config,
    layer_weights: &[LayerWeightsGpu],
    output_head: &OutputHeadGpu,
) -> Result<JointPlan, String> {
    let mut layers = Vec::with_capacity(layer_weights.len());
    for (layer, weights) in layer_weights.iter().enumerate() {
        let (routes, ffn) = match weights {
            LayerWeightsGpu::FullAttn { attn, ffn } => {
                (LayerRoutes::Full(FullAttnRoutes::plan(layer, attn)?), ffn)
            }
            LayerWeightsGpu::LinearAttn { attn, ffn } => {
                (LayerRoutes::Linear(DeltaNetRoutes::plan(layer, attn)?), ffn)
            }
        };
        match ffn {
            FfnWeightsGpu::DenseQ(weights) => {
                dense_ffn_route(layer, weights.ggml_type_gate_up, weights.ggml_type_down)?
            }
            FfnWeightsGpu::MoeQ(_) if mode == JointRouteMode::Exact && cfg.moe.is_some() => {}
            FfnWeightsGpu::MoeQ(_) => {
                return Err(format!(
                    "layer {layer} MoE FFN is admitted only in exact mode with a MoE config"
                ))
            }
            FfnWeightsGpu::Dense(_) | FfnWeightsGpu::Moe(_) => {
                return Err(format!(
                    "layer {layer} uses expanded float FFN storage, which has no joint graph"
                ))
            }
        }
        layers.push(routes);
    }
    let head = projection_route(
        "output",
        output_head.lm_head.dtype(),
        output_head.lm_head_ggml_type,
    )?;
    Ok(JointPlan { layers, head })
}

/// Same chain grouping knobs the serial greedy graph honours.
fn joint_chain_n(cfg: &Qwen35Config, layer_weights: &[LayerWeightsGpu]) -> usize {
    if std::env::var_os("HF2Q_PARTIAL_CHAIN_LEGACY").is_some_and(|value| value == "1") {
        return 1;
    }
    std::env::var("HF2Q_PARTIAL_CHAIN_N")
        .ok()
        .and_then(|value| value.parse::<usize>().ok())
        .filter(|&n| n >= 1)
        .unwrap_or_else(|| default_chain_n(cfg, layer_weights))
}

/// Whether the joint layer chain closes (commits) after `layer_idx`.
fn closes_chain(layer_idx: usize, chain_n: usize, n_layers: usize) -> bool {
    (layer_idx + 1) % chain_n == 0 || layer_idx + 1 == n_layers
}

/// The observed native commands of one joint forward, in commit order: the
/// embedding gather (an observed command only on the native embedding route),
/// one command per closed layer chain, an open-chain flush (never, while every
/// chain closes at `n_layers`) and the output head.
fn joint_command_plan(n_layers: usize, chain_n: usize, native_embedding: bool) -> Vec<String> {
    let mut commands = Vec::new();
    if native_embedding {
        commands.push("embed".to_string());
    }
    let mut start = 0;
    for layer in 0..n_layers {
        if closes_chain(layer, chain_n, n_layers) {
            commands.push(format!("layers[{start},{})", layer + 1));
            start = layer + 1;
        }
    }
    if start < n_layers {
        commands.push(format!("layers.flush[{start},{n_layers})"));
    }
    commands.push("output_head".into());
    commands
}

fn host_buffer<T: bytemuck::Pod>(
    device: &MlxDevice,
    dtype: DType,
    values: &[T],
    label: &str,
) -> Result<MlxBuffer> {
    let mut buffer = device
        .alloc_buffer(std::mem::size_of_val(values), dtype, vec![values.len()])
        .map_err(|e| anyhow!("allocate Qwen joint {label}: {e}"))?;
    buffer
        .as_mut_slice::<T>()
        .map_err(|e| anyhow!("map Qwen joint {label}: {e}"))?
        .copy_from_slice(values);
    Ok(buffer)
}

impl Qwen35Model {
    /// Decode route of this model's MoE FFN layers, from the loaded weights:
    /// `batched_native` (every MoE layer has native router/shared storage,
    /// `HF2Q_QWEN_MOE_BATCHED=1`), `per_row_bf16`, `mixed`, or `none` for a
    /// dense artifact.
    pub(crate) fn moe_ffn_decode_route(&self) -> &'static str {
        let (mut moe, mut native) = (0_usize, 0_usize);
        for layer in &self.layers {
            match layer.ffn() {
                Qwen35FfnWeights::MoeQ(weights) => {
                    moe += 1;
                    native += usize::from(weights.native_dense.is_some());
                }
                Qwen35FfnWeights::Moe(_) => moe += 1,
                Qwen35FfnWeights::Dense(_) | Qwen35FfnWeights::DenseQ(_) => {}
            }
        }
        match (moe, native) {
            (0, _) => "none",
            (moe, native) if native == moe => "batched_native",
            (_, 0) => "per_row_bf16",
            _ => "mixed",
        }
    }

    /// Expert route of the batched MoE layers, as the process switches
    /// resolved it at model load: `matvec`, `staged_m8` or `live_tiles`, and
    /// `none` when the layers do not run the batched route.
    pub(crate) fn moe_expert_decode_route(&self) -> &'static str {
        if self.moe_ffn_decode_route() != "batched_native" {
            return "none";
        }
        crate::inference::models::qwen35::moe_batched::qwen_moe_expert_route()
            .map_or("invalid", |route| route.label())
    }

    /// Joint route mode for this artifact and its routing policy, or why decode must
    /// stay serial. Primes the GPU weight cache so storage types are known.
    pub(crate) fn joint_decode_mode(&self) -> Result<JointRouteMode, String> {
        if let Some(reason) = joint_decode_env_unavailable_reason() {
            return Err(reason);
        }
        if dump_bisect::is_enabled() || dump_layer_n().is_some() {
            return Err("layer-dump diagnostics require the serial graph".into());
        }
        if self.glp.is_some() {
            return Err("GLP steering requires the serial graph".into());
        }
        let policy = JointRoutingPolicy::from_ggml(&self.ggml_routing_policy);
        let mode = select_joint_route_mode(policy, self.cfg.moe.is_some())?;
        check_mode_policy(mode, policy)?;
        self.ensure_gpu_cache_primed()
            .map_err(|error| format!("GPU cache priming failed: {error:#}"))?;
        GPU_CACHE.with(|cell| -> Result<JointRouteMode, String> {
            let cache = cell.borrow();
            let cache = cache
                .as_ref()
                .ok_or_else(|| "GPU cache is not primed".to_string())?;
            if !gpu_cache_matches_model(cache, self) {
                return Err("GPU cache belongs to a different Qwen model".to_string());
            }
            plan_joint_routes(mode, &self.cfg, &cache.layer_weights, &cache.output_head)
                .map(|_| mode)
        })
    }

    /// [`Self::forward_gpu_decode_joint_with_options`] with the default
    /// step options (every switch off).
    #[cfg(test)]
    pub(crate) fn forward_gpu_decode_joint(
        &self,
        rows: &[Qwen35JointRow],
        kv_cache: &mut HybridKvCache,
        mode: JointRouteMode,
        dense_ffn: JointDenseFfnRoute,
    ) -> Result<Vec<Qwen35JointRowOutput>> {
        let options = JointStepOptions::default();
        self.forward_gpu_decode_joint_with_options(rows, kv_cache, mode, dense_ffn, options)
    }

    /// Advance `rows.len()` distinct slots by one token each in one
    /// layer-major transaction. Under [`JointRouteMode::Exact`] every row's
    /// logits, hidden, KV codes, recurrent state, cursor and parity are
    /// bitwise those of its serial one-token forward, whatever the
    /// prepared-route switches say: they change DFlash2 target verify steps
    /// only (`JointPacking::dflash2_verify`). `dense_ffn` must be
    /// admitted for `mode` ([`check_dense_ffn_route`]). `options` are
    /// resolved by the caller (the serving worker reads their switches once
    /// at start; the Q1 trace runs several in one process); the
    /// column-invariant MMA kernel is admitted only in the padded mode.
    /// Refusal (admission, shape, slot range) happens before any cache write.
    pub(crate) fn forward_gpu_decode_joint_with_options(
        &self,
        rows: &[Qwen35JointRow],
        kv_cache: &mut HybridKvCache,
        mode: JointRouteMode,
        dense_ffn: JointDenseFfnRoute,
        options: JointStepOptions,
    ) -> Result<Vec<Qwen35JointRowOutput>> {
        let max_rows = joint_mode_max_rows(mode, MAX_JOINT_DECODE_ROWS);
        ensure!(
            (1..=max_rows).contains(&rows.len()),
            "Qwen {} joint decode requires 1..={max_rows} rows, got {}",
            mode.label(),
            rows.len()
        );
        for (index, row) in rows.iter().enumerate() {
            ensure!(
                row.slot_id.0 < kv_cache.n_seqs,
                "Qwen joint slot {} outside n_seqs={}",
                row.slot_id.0,
                kv_cache.n_seqs
            );
            ensure!(
                rows[..index]
                    .iter()
                    .all(|earlier| earlier.slot_id != row.slot_id),
                "Qwen joint decode slot {} appears twice",
                row.slot_id.0
            );
            ensure!(
                row.position >= 0,
                "Qwen joint position must be non-negative"
            );
        }
        self.check_joint_step_admission(kv_cache, mode, dense_ffn, options)?;
        let slots = rows.iter().map(|row| row.slot_id).collect::<Vec<_>>();
        let windows = JointWindow::per_row(&slots);
        let packing = JointPacking {
            rows,
            windows: &windows,
            width: joint_padded_width(mode, rows.len()),
            attention_tile: false,
            dflash2_verify: false,
            mixer_fused: false,
        };
        self.with_joint_forward(
            mode,
            |device, registry, layer_weights, output_head, plan| {
                self.encode_joint_decode(
                    device,
                    registry,
                    layer_weights,
                    output_head,
                    plan,
                    &packing,
                    kv_cache,
                    dense_ffn,
                    options,
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                )
                .map(|(outputs, _normed)| outputs)
            },
        )
    }

    /// Admission shared by every joint forward, before any cache write: no
    /// DeltaNet capture, no serial-only diagnostics or steering, the mode
    /// and dense FFN route admitted by the model's routing policy, and the
    /// MMA projections only in the padded mode.
    pub(super) fn check_joint_step_admission(
        &self,
        kv_cache: &HybridKvCache,
        mode: JointRouteMode,
        dense_ffn: JointDenseFfnRoute,
        options: JointStepOptions,
    ) -> Result<()> {
        ensure!(
            !kv_cache.la_capture_active(),
            "Qwen joint decode cannot run while a DeltaNet capture is active"
        );
        if let Some(reason) = joint_decode_env_unavailable_reason() {
            bail!("Qwen joint decode unavailable: {reason}");
        }
        ensure!(
            !dump_bisect::is_enabled() && dump_layer_n().is_none(),
            "Qwen joint decode unavailable: layer-dump diagnostics require the serial graph"
        );
        ensure!(
            self.glp.is_none(),
            "Qwen joint decode unavailable: GLP steering requires the serial graph"
        );
        check_mode_policy(
            mode,
            JointRoutingPolicy::from_ggml(&self.ggml_routing_policy),
        )
        .map_err(|reason| anyhow!("Qwen joint decode unavailable: {reason}"))?;
        check_dense_ffn_route(mode, dense_ffn)
            .map_err(|reason| anyhow!("Qwen joint decode unavailable: {reason}"))?;
        ensure!(
            options.projection == JointProjectionKernel::Canonical
                || mode == JointRouteMode::PaddedMvExt,
            "Qwen joint decode unavailable: the column-invariant MMA projections are \
             admitted only in the padded mode"
        );
        Ok(())
    }

    /// Run `encode` inside one joint forward: the primed GPU cache of this
    /// model, its admitted route plan and a freshly reset decode pool.
    pub(super) fn with_joint_forward<R>(
        &self,
        mode: JointRouteMode,
        encode: impl FnOnce(
            &MlxDevice,
            &mut KernelRegistry,
            &[LayerWeightsGpu],
            &OutputHeadGpu,
            &JointPlan,
        ) -> Result<R>,
    ) -> Result<R> {
        // Check the enclosing scope before temporarily replacing its owner list.
        #[cfg(test)]
        super::super::encoder_stage::settle_submitted()
            .context("original parent commands before nested joint target scope")?;
        #[cfg(test)]
        let _submitted = super::super::encoder_stage::SubmittedCommands::open(true);
        self.ensure_gpu_cache_primed()?;
        let pool_operation = decode_pool::profile::Operation::enter(self as *const _ as usize)?;
        let result = GPU_CACHE.with(|cell| -> Result<R> {
            let mut guard = cell.borrow_mut();
            let cache = guard
                .as_mut()
                .context("Qwen joint decode: GPU cache not primed")?;
            ensure!(
                gpu_cache_matches_model(cache, self),
                "Qwen joint decode: GPU cache belongs to a different Qwen model"
            );
            let _prepared_scratch = cache.prepared_scratch.enter(&cache.device)?;
            let ForwardGpuCache {
                device,
                registry,
                layer_weights,
                output_head,
                ..
            } = cache;
            let plan = plan_joint_routes(mode, &self.cfg, layer_weights, output_head)
                .map_err(|reason| anyhow!("Qwen joint decode unavailable: {reason}"))?;
            decode_pool::checked_reset_decode_pool()
                .map_err(|e| anyhow!("Qwen joint decode pool reset: {e}"))?;
            mlx_native::command_timeline::mark("joint.pool_reset");
            encode(device, registry, layer_weights, output_head, &plan)
        });
        #[cfg(test)]
        let result = match (
            result,
            super::super::encoder_stage::settle_submitted()
                .context("original joint target commands before test-state observation"),
        ) {
            (result, Ok(())) => result,
            (Ok(_), Err(gpu)) => Err(gpu),
            (Err(host), Err(gpu)) => Err(gpu.context(format!(
                "the joint target had already failed on the host: {host:#}"
            ))),
        };
        pool_operation.complete()?;
        result
    }

    /// Encode and run one joint forward over `packing`. `replay` (MTP
    /// verify only) retains the multi-row windows' DeltaNet inputs. Returns
    /// the real rows' outputs and the packed `[width, hidden]`
    /// post-output-norm rows (a durable allocation).
    #[allow(clippy::too_many_arguments)]
    pub(super) fn encode_joint_decode(
        &self,
        device: &MlxDevice,
        registry: &mut KernelRegistry,
        layer_weights: &[LayerWeightsGpu],
        output_head: &OutputHeadGpu,
        plan: &JointPlan,
        packing: &JointPacking<'_>,
        kv_cache: &mut HybridKvCache,
        dense_ffn: JointDenseFfnRoute,
        options: JointStepOptions,
        gpu_token_ids: Option<&MlxBuffer>,
        mut replay: Option<&mut DeltaNetReplay>,
        capture: Option<DFlash2TargetCapture<'_>>,
        mut output_tail: Option<&mut JointOutputHeadTail<'_>>,
        held_outputs: Option<&mut Vec<MlxBuffer>>,
        decision_histories: Option<&[Option<&[u32]>]>,
        host_work: Option<&mut dyn FnMut()>,
    ) -> Result<(Vec<Qwen35JointRowOutput>, MlxBuffer)> {
        #[cfg(test)]
        let c2_native = crate::serve::api::engine_qwen35::anchor_exactness_tests::trace::acquire::native_begin()?;
        let arena_setup = crate::inference::stage_profile::CpuSpan::begin("per_row_arena_setup");
        let cfg = &self.cfg;
        let hidden_size = cfg.hidden_size;
        let h = hidden_size as usize;
        let eps = cfg.rms_norm_eps;
        let vocab = cfg.vocab_size as usize;
        let rows = packing.rows;
        let width = packing.width;
        ensure!(
            (1..=width).contains(&rows.len()) && width <= DFLASH2_VERIFY_WIDTH,
            "Qwen joint forward packs {} rows at width {width}",
            rows.len()
        );
        kv_cache.bind_fa_producer(device)?;
        let required_backing = packing.windows.iter().try_fold(0usize, |required, window| {
            Ok::<_, anyhow::Error>(required.max(kv_cache.fa_append_requirement(
                window.slot, window.rows, false,
            )?))
        })?;
        kv_cache.ensure_fa_backing(required_backing)?;
        #[cfg(test)]
        {
            use crate::serve::api::engine_qwen35::anchor_exactness_tests::{
                trace::acquire, registration::NativeHead, native_inputs::InputBinding};
            if acquire::enabled() {
                let heads = rows.iter().enumerate().map(|(row, input)| {
                    let window = packing.windows.iter()
                        .find(|window| row >= window.start && row < window.start + window.rows)
                        .context("required native row has no immutable packing window")?;
                    let start = usize::try_from(rows[window.start].position)?;
                    ensure!(usize::try_from(input.position)? == start + row - window.start,
                        "required native packing window has noncontiguous physical positions");
                    let count = row - window.start + 1;
                    let source = match gpu_token_ids {
                        Some(buffer) => InputBinding::gpu(buffer, window.start, count)?,
                        None => InputBinding::host_rows(count, rows[window.start..=row].iter().map(|input| input.token))?,
                    };
                    Ok(NativeHead { slot: input.slot_id, start, input_rows: row - window.start + 1,
                        projected_rows: 1, vocab, hidden_width: h, gpu_argmax: input.output.wants_argmax(), input: source })
                }).collect::<Result<Vec<_>>>()?;
                acquire::native_contract(heads)?;
            }
        }
        if let Some(capture) = capture {
            ensure!(
                capture.lane_indices.len() == packing.windows.len()
                    && capture
                        .lane_indices
                        .iter()
                        .enumerate()
                        .all(|(index, lane)| {
                            *lane < capture.lanes && !capture.lane_indices[..index].contains(lane)
                        })
                    && capture.rows_per_lane == 8
                    && !capture.layer_ids.is_empty()
                    && capture.feature_width == h * capture.layer_ids.len()
                    && capture.output.dtype() == DType::F32
                    && capture.output.element_count()
                        == capture.lanes * capture.rows_per_lane * capture.feature_width
                    && capture.layer_ids.windows(2).all(|pair| pair[0] < pair[1])
                    && capture
                        .layer_ids
                        .iter()
                        .all(|layer| *layer < layer_weights.len())
                    && packing
                        .windows
                        .iter()
                        .all(|window| window.rows <= capture.rows_per_lane),
                "invalid Qwen DFlash2 target capture geometry"
            );
        }
        let width_u32 = width as u32;
        let slots = rows.iter().map(|row| row.slot_id).collect::<Vec<_>>();
        let tile_scratch = VerifyTileScratch::default();
        let joint_rows = JointRows {
            slots: &slots,
            windows: packing.windows,
            width,
            attention_tile: packing.attention_tile.then_some(&tile_scratch),
            mixer_fused: packing.mixer_fused,
        };
        // Padding rows replay row 0's token and position; their outputs are
        // discarded and they never reach a cache.
        let packed = |index: usize| rows[if index < rows.len() { index } else { 0 }];
        let tokens = (0..width)
            .map(|index| packed(index).token)
            .collect::<Vec<_>>();
        let mut positions = vec![0_i32; 4 * width];
        for axis in 0..4 {
            for index in 0..width {
                positions[axis * width + index] = packed(index).position;
            }
        }
        #[cfg(test)]
        let c23_layers = if super::super::c23_layer_capture::selected() {
            let cohort = rows.iter().map(|row| (row.slot_id,row.position,row.token)).collect::<Vec<_>>();
            let scope = super::super::c23_layer_capture::begin(device, cfg, &cohort,
                &positions, width, || serde_json::json!({
                    "route":"joint-existing-output-head","packed_width":width,
                    "windows":packing.windows.iter().map(|window| serde_json::json!({
                        "slot":window.slot.0,"start":window.start,"rows":window.rows})).collect::<Vec<_>>(),
                    "attention_tile":packing.attention_tile,"mixer_fused":packing.mixer_fused,
                    "dflash2_verify":packing.dflash2_verify,"dense_ffn":format!("{:?}",dense_ffn),
                    "projection":format!("{:?}",options.projection),
                    "pooled_outputs":options.pooled_outputs}))?;
            if scope.is_some() {
                ensure!(gpu_token_ids.is_none() && replay.is_none() && capture.is_none()
                    && !packing.dflash2_verify && self.token_embd_native.is_some()
                    && layer_weights.iter().all(|layer| matches!(layer,
                        LayerWeightsGpu::FullAttn {ffn:FfnWeightsGpu::DenseQ(_),..}
                        | LayerWeightsGpu::LinearAttn {ffn:FfnWeightsGpu::DenseQ(_),..})),
                    "unsupported selected localization joint graph; never fallback");
            }
            scope
        } else { None };
        let positions = host_buffer(device, DType::I32, positions.as_slice(), "positions")?;
        // The decode forward's actual input manifest (trace on only): one
        // row per packed slot in matrix order, padding rows owner-less. Its
        // drop at return closes the forward before the caller's per-lane
        // settle work. A verify window has no joint trace role yet.
        let _native_input = replay.is_none().then(|| {
            crate::inference::native_observation::joint_decode_input(
                rows.iter().map(|row| (row.slot_id.0, row.position)),
                width,
            )
        });
        let mut embedded = device
            .alloc_buffer(width * h * 4, DType::F32, vec![width, h])
            .map_err(|e| anyhow!("allocate Qwen joint embeddings: {e}"))?;
        if let Some(token_ids) = gpu_token_ids {
            ensure!(
                token_ids.dtype() == DType::U32 && token_ids.element_count() >= width,
                "Qwen GPU target token tile has {:?} with {} rows, expected at least {width} U32 rows",
                token_ids.dtype(),
                token_ids.element_count()
            );
            let narrowed;
            let token_ids = if token_ids.element_count() == width {
                token_ids
            } else {
                narrowed = token_ids.slice_view(0, width);
                &narrowed
            };
            embed_token_ids_gpu_into(
                token_ids,
                self.token_embd_native.as_ref(),
                hidden_size,
                device,
                registry,
                &mut embedded,
            )
            .context("Qwen joint GPU-token embedding gather")?;
        } else {
            embed_tokens_gpu_into(
                &tokens,
                &self.token_embd,
                self.token_embd_native.as_ref(),
                cfg.vocab_size,
                hidden_size,
                device,
                registry,
                &mut embedded,
                #[cfg(test)]
                None,
            )
            .context("Qwen joint embedding gather")?;
        }
        mlx_native::command_timeline::mark("joint.embedding_committed");

        drop(arena_setup);
        let chain_n = joint_chain_n(cfg, layer_weights);
        let n_layers = layer_weights.len();
        ensure!(
            plan.layers.len() == n_layers,
            "Qwen joint plan covers {} of {n_layers} layers",
            plan.layers.len()
        );
        crate::inference::native_observation::joint_chain_plan(|| {
            let kinds: Vec<_> = layer_weights
                .iter()
                .map(|weights| match weights {
                    LayerWeightsGpu::FullAttn { .. } => "full",
                    LayerWeightsGpu::LinearAttn { .. } => "linear",
                })
                .collect();
            let native_embedding = self.token_embd_native.is_some();
            serde_json::json!({"model":"qwen35","n_layers":n_layers,"chain_n":chain_n,
                "native_embedding":native_embedding,"layer_kinds":kinds,
                "commands":joint_command_plan(n_layers, chain_n, native_embedding)})
        });
        let mut hidden = embedded;
        let mut retained = Vec::with_capacity(n_layers);
        let mut chain: Option<CommandEncoder> = None;
        // Keep the selected projection through the head as cohort widths vary.
        // Only layer intermediates use the step's pooled-output scope.
        let projection_scope =
            JointProjectionScope::enter_step(options.projection, width_u32, packing.dflash2_verify);
        let pooled_scope = decode_pool::StepPooledOutputs::enter(options.pooled_outputs);
        for (layer_idx, (weights, routes)) in layer_weights.iter().zip(&plan.layers).enumerate() {
            if let Some(enc) = chain.as_mut() {
                // Cross-layer RAW: this layer reads the previous FFN output.
                enc.memory_barrier();
            } else {
                chain = Some(
                    device
                        .command_encoder()
                        .map(crate::inference::native_observation::encoder)
                        .with_context(|| format!("Qwen joint encoder layer {layer_idx}"))?,
                );
            }
            let enc = chain.as_mut().expect("joint layer encoder opened above");
            #[cfg(test)]
            let c23_before = if c23_layers.is_some() {
                Some(rows.iter().map(|row| super::q1_layer_metadata::state(kv_cache,layer_idx,row.slot_id))
                    .collect::<Result<Vec<_>>>()?)
            } else { None };
            let (attention, post_norm, ffn) = match (weights, routes) {
                (LayerWeightsGpu::FullAttn { attn, ffn }, LayerRoutes::Full(routes)) => (
                    encode_joint_full_attn_layer(
                        enc,
                        device,
                        registry,
                        &hidden,
                        &positions,
                        attn,
                        routes,
                        kv_cache,
                        layer_idx,
                        &joint_rows,
                        cfg,
                    )
                    .with_context(|| format!("Qwen joint full attention layer {layer_idx}"))?,
                    &attn.post_attn_norm,
                    ffn,
                ),
                (LayerWeightsGpu::LinearAttn { attn, ffn }, LayerRoutes::Linear(routes)) => (
                    encode_joint_delta_net_layer(
                        enc,
                        device,
                        registry,
                        &hidden,
                        attn,
                        routes,
                        kv_cache,
                        layer_idx,
                        &joint_rows,
                        cfg,
                        replay.as_deref_mut(),
                    )
                    .with_context(|| format!("Qwen joint DeltaNet layer {layer_idx}"))?,
                    &attn.post_attn_norm,
                    ffn,
                ),
                _ => bail!("Qwen joint plan disagrees with layer {layer_idx} kind"),
            };
            enc.memory_barrier();
            let ffn_input =
                decode_pool::pooled_alloc_buffer(device, width * h * 4, DType::F32, vec![width, h])
                    .map_err(|e| anyhow!("allocate Qwen joint FFN input: {e}"))?;
            let ffn_residual =
                decode_pool::pooled_alloc_buffer(device, width * h * 4, DType::F32, vec![width, h])
                    .map_err(|e| anyhow!("allocate Qwen joint FFN residual: {e}"))?;
            dispatch_fused_residual_norm_f32(
                enc,
                registry,
                device.metal_device(),
                &hidden,
                &attention,
                post_norm,
                &ffn_input,
                Some(&ffn_residual),
                width_u32,
                hidden_size,
                eps,
            )
            .with_context(|| format!("Qwen joint fused residual norm layer {layer_idx}"))?;
            #[cfg(test)]
            if let Some(before) = c23_before.as_ref() {
                let loaded = super::q1_layer_metadata::layer(weights,kv_cache,layer_idx,rows[0].slot_id,
                    width_u32,cfg,&self.ggml_routing_policy,registry.ggml_routing_policy(),&before[0])?;
                super::super::c23_layer_capture::snapshot(enc, &ffn_residual, layer_idx,
                    crate::adr063_invariance::receipt::Stage::Residual,
                    || serde_json::json!({"boundary":"actual joint fused attention residual sum",
                        "loaded_projections_and_host_state":loaded,"all_real_rows_before":before,
                        "actual_width":width,"mixer_fused":packing.mixer_fused,
                        "attention_tile":packing.attention_tile,
                        "projection":format!("{:?}",options.projection)}))?;
            }
            enc.memory_barrier();
            let output = match ffn {
                FfnWeightsGpu::DenseQ(weights) => build_dense_ffn_layer_gpu_q_into_with_gate_up(
                    enc,
                    device,
                    registry,
                    &ffn_input,
                    weights,
                    Some(&ffn_residual),
                    match dense_ffn {
                        JointDenseFfnRoute::SerialBuilder => DenseGateUpDispatch::PreferFused,
                        JointDenseFfnRoute::SharedWeights => DenseGateUpDispatch::Separate,
                    },
                )
                .with_context(|| format!("Qwen joint dense FFN layer {layer_idx}"))?,
                FfnWeightsGpu::MoeQ(weights) => {
                    let moe = cfg
                        .moe
                        .as_ref()
                        .with_context(|| format!("Qwen joint MoE config (layer {layer_idx})"))?;
                    let shape = MoeFfnShape {
                        hidden_size,
                        num_experts: moe.num_experts,
                        num_experts_per_tok: moe.num_experts_per_tok,
                        moe_intermediate_size: moe.moe_intermediate_size,
                        shared_intermediate_size: moe.shared_expert_intermediate_size,
                    };
                    if weights.dense_storage.is_native() {
                        let mut output = decode_pool::pooled_alloc_buffer(
                            device,
                            width * h * 4,
                            DType::F32,
                            vec![width, h],
                        )
                        .map_err(|e| anyhow!("allocate Qwen joint MoE output: {e}"))?;
                        let moe_rows = if capture.is_some() {
                            rows.len() as u32
                        } else {
                            width_u32
                        };
                        let route_mask = if gpu_token_ids.is_some() {
                            let capture = capture.context(
                                "Qwen GPU-target MoE verification requires DFlash2 capture",
                            )?;
                            let mut physical_lane = [0_u32; 4];
                            for (logical, &physical) in capture.lane_indices.iter().enumerate() {
                                physical_lane[logical] = u32::try_from(physical)
                                    .context("Qwen DFlash2 physical lane overflow")?;
                            }
                            Some(DFlash2MoeRouteMask {
                                verify_rows: capture.verify_rows,
                                params: mlx_native::ops::dflash2_attention_pack::DFlash2MoeRouteMaskParams {
                                    physical_lane,
                                    lanes: capture.lane_indices.len() as u32,
                                    rows_per_lane: capture.rows_per_lane as u32,
                                    top_k: shape.num_experts_per_tok,
                                    n_experts: shape.num_experts,
                                    width: moe_rows,
                                },
                            })
                        } else {
                            None
                        };
                        build_moe_ffn_layer_gpu_batched_into(
                            enc,
                            device,
                            registry,
                            &ffn_input,
                            weights,
                            shape,
                            Some(&ffn_residual),
                            &mut output,
                            moe_rows,
                            layer_idx,
                            route_mask,
                        )
                        .with_context(|| format!("Qwen joint batched MoE FFN layer {layer_idx}"))?;
                        output
                    } else {
                        let mut per_row = Vec::with_capacity(rows.len());
                        for row in 0..rows.len() {
                            if row > 0 {
                                enc.memory_barrier();
                            }
                            per_row.push(
                                build_moe_ffn_layer_gpu_q_into(
                                    enc,
                                    device,
                                    registry,
                                    &row_view(&ffn_input, row, vec![1, h])?,
                                    weights,
                                    shape,
                                    Some(&row_view(&ffn_residual, row, vec![1, h])?),
                                    layer_idx,
                                )
                                .with_context(|| {
                                    format!("Qwen joint MoE FFN layer {layer_idx} row {row}")
                                })?,
                            );
                        }
                        enc.memory_barrier();
                        let packed_output = device
                            .alloc_buffer(width * h * 4, DType::F32, vec![width, h])
                            .map_err(|e| anyhow!("allocate Qwen joint MoE output: {e}"))?;
                        for index in 0..width {
                            let source = &per_row[if index < rows.len() { index } else { 0 }];
                            dispatch_copy_f32(
                                enc,
                                registry,
                                device.metal_device(),
                                source,
                                &packed_output,
                                0,
                                index * h,
                                h,
                            )
                            .map_err(|e| anyhow!("gather Qwen joint MoE row {index}: {e}"))?;
                        }
                        packed_output
                    }
                }
                FfnWeightsGpu::Dense(_) | FfnWeightsGpu::Moe(_) => {
                    bail!("Qwen joint layer {layer_idx} has no admitted FFN arm")
                }
            };
            #[cfg(test)]
            super::super::c23_layer_capture::snapshot(enc, &output, layer_idx,
                crate::adr063_invariance::receipt::Stage::LayerOutput,
                || serde_json::json!({"boundary":"actual joint FFN projection fused residual sum",
                    "standalone_ffn_output":"nonexistent on selected fused path",
                    "dense_ffn":format!("{:?}",dense_ffn),"actual_width":width,
                    "chain_n":chain_n,"closes_chain":closes_chain(layer_idx,chain_n,n_layers),
                    "head_route":format!("{:?}",plan.head),
                    "projection":format!("{:?}",options.projection),
                    "weights":match ffn {FfnWeightsGpu::DenseQ(w)=>super::q1_layer_metadata::ffn(w),_=>serde_json::Value::Null}}))?;
            if let Some(capture) = capture {
                if let Some(capture_index) = capture
                    .layer_ids
                    .iter()
                    .position(|captured| *captured == layer_idx)
                {
                    enc.memory_barrier();
                    for (&lane, window) in capture.lane_indices.iter().zip(packing.windows) {
                        let source =
                            output.slice_view((window.start * h * 4) as u64, window.rows * h);
                        let destination = capture.output.slice_view(
                            (lane * capture.rows_per_lane * capture.feature_width * 4) as u64,
                            window.rows * capture.feature_width,
                        );
                        mlx_native::ops::feature_concat::dispatch_feature_concat_f32(
                            enc,
                            registry,
                            device.metal_device(),
                            &source,
                            &destination,
                            window.rows as u32,
                            hidden_size,
                            (capture_index * h) as u32,
                            capture.feature_width as u32,
                        )
                        .with_context(|| {
                            format!("capture Qwen DFlash2 layer {layer_idx} lane {lane}")
                        })?;
                    }
                }
            }
            crate::inference::stage_profile::boundary(enc, "adr065.ffn_moe")
                .with_context(|| format!("profile Qwen joint FFN layer {layer_idx}"))?;
            if closes_chain(layer_idx, chain_n, n_layers) {
                let mut submitted = chain
                    .take()
                    .expect("joint layer encoder opened above");
                submitted.commit_labeled("qwen35.joint_decode.layers");
                #[cfg(test)]
                super::super::encoder_stage::retain_submitted(submitted, "qwen35.joint_decode.layers");
            }
            retained.push(std::mem::replace(&mut hidden, output));
        }
        if let Some(mut enc) = chain.take() {
            enc.commit_labeled("qwen35.joint_decode.layers.flush");
            #[cfg(test)]
            super::super::encoder_stage::retain_submitted(enc, "qwen35.joint_decode.layers.flush");
        }
        mlx_native::command_timeline::mark("joint.layers_committed");
        drop(pooled_scope);

        // ---- Output head: final norm, lm_head, per-row argmax ----
        let mut enc = device
            .command_encoder()
            .map(crate::inference::native_observation::encoder)
            .context("Qwen joint output-head encoder")?;
        let normed = device
            .alloc_buffer(width * h * 4, DType::F32, vec![width, h])
            .map_err(|e| anyhow!("allocate Qwen joint output norm: {e}"))?;
        let norm_params = host_buffer(
            device,
            DType::F32,
            &[eps, hidden_size as f32],
            "norm params",
        )?;
        rms_norm::dispatch_rms_norm(
            &mut enc,
            registry,
            device.metal_device(),
            &hidden,
            &output_head.norm_w,
            &normed,
            &norm_params,
            width_u32,
            hidden_size,
        )
        .context("Qwen joint output norm")?;
        enc.memory_barrier();
        // The width rule is the prepared route's own: 32 rows, or every
        // width of a DFlash2 target verify step with
        // `HF2Q_REPACKED_GGUF_ANY_WIDTH=1`.
        let prepared_head = plan.head == JointProductRoute::Batched
            && prepared_projection::admits_head(
                width_u32,
                &output_head.lm_head,
                output_head.lm_head_ggml_type,
                hidden_size,
                cfg.vocab_size,
                packing.dflash2_verify,
            );
        // Pooled: the head writes every row and every result leaves this
        // function as an owned copy before the next forward resets the pool,
        // so a step pays no fresh `[width, vocab]` allocation and CPU zeroing.
        #[cfg(test)]
        crate::serve::api::engine_qwen35::anchor_exactness_tests::trace::acquire::plan_native()?;
        let logits = if prepared_head {
            let normed_bf16 = prepared_projection::bf16_input(
                &mut enc,
                registry,
                device,
                &normed,
                width_u32,
                hidden_size,
            )?;
            enc.memory_barrier();
            match self
                .shared_prepared_output_head(registry, device)
                .context("Qwen joint shared prepared lm_head")?
            {
                // The planes the staged draft reads too.
                Some(shared) => prepared_projection::project_prepared(
                    &mut enc,
                    registry,
                    device,
                    &normed_bf16,
                    shared,
                    output_head.lm_head_ggml_type,
                    width_u32,
                    hidden_size,
                    cfg.vocab_size,
                ),
                None => prepared_projection::project(
                    &mut enc,
                    registry,
                    device,
                    &normed_bf16,
                    &output_head.lm_head,
                    output_head.lm_head_ggml_type,
                    &output_head.prepared_m32,
                    width_u32,
                    hidden_size,
                    cfg.vocab_size,
                ),
            }
            .context("Qwen joint prepared lm_head")?
        } else {
            let mut logits = decode_pool::pooled_alloc_buffer(
                device,
                width * vocab * 4,
                DType::F32,
                vec![width, vocab],
            )
            .map_err(|e| anyhow!("allocate Qwen joint logits: {e}"))?;
            match plan.head {
                JointProductRoute::Batched => apply_linear_projection_f32_into_with_ggml_type(
                    &mut enc,
                    registry,
                    device,
                    &normed,
                    &output_head.lm_head,
                    output_head.lm_head_ggml_type,
                    &mut logits,
                    width_u32,
                    hidden_size,
                    cfg.vocab_size,
                )
                .context("Qwen joint lm_head")?,
                JointProductRoute::PerRow => {
                    for row in 0..rows.len() {
                        let mut destination = row_view(&logits, row, vec![1, vocab])?;
                        apply_linear_projection_f32_into_with_ggml_type(
                            &mut enc,
                            registry,
                            device,
                            &row_view(&normed, row, vec![1, h])?,
                            &output_head.lm_head,
                            output_head.lm_head_ggml_type,
                            &mut destination,
                            1,
                            hidden_size,
                            cfg.vocab_size,
                        )
                        .with_context(|| format!("Qwen joint lm_head row {row}"))?;
                    }
                }
            }
            logits
        };
        drop(projection_scope);
        enc.memory_barrier();
        // Decision candidates of host-sampled verify rows: per window with a
        // base history, the history tokens' logits and the argmax outside
        // them. They mask those rows' history tokens in `logits`; the
        // readback below undoes it in every copy it hands out.
        let decisions = match decision_histories {
            Some(histories) => {
                let host_tokens;
                let row_tokens = match gpu_token_ids {
                    Some(token_ids) => token_ids,
                    None => {
                        let mut pooled = decode_pool::pooled_alloc_buffer(
                            device,
                            tokens.len() * DType::U32.size_of(),
                            DType::U32,
                            vec![tokens.len()],
                        )
                        .map_err(|e| anyhow!("allocate Qwen joint decision tokens: {e}"))?;
                        pooled
                            .as_mut_slice::<u32>()
                            .map_err(|e| anyhow!("map Qwen joint decision tokens: {e}"))?
                            .copy_from_slice(&tokens);
                        host_tokens = pooled;
                        &host_tokens
                    }
                };
                let encoded = crate::inference::models::qwen35::verify_decision::encode(
                    &mut enc,
                    registry,
                    device,
                    &logits,
                    packing.windows,
                    histories,
                    row_tokens,
                    rows.len(),
                    vocab,
                )
                .context("Qwen joint verify decisions")?;
                enc.memory_barrier();
                Some(encoded)
            }
            None => None,
        };
        let argmax = if rows.iter().any(|row| row.output.wants_argmax()) {
            let params = host_buffer(device, DType::U32, &[cfg.vocab_size], "argmax params")?;
            let indices = decode_pool::pooled_alloc_buffer(
                device,
                rows.len() * DType::U32.size_of(),
                DType::U32,
                vec![rows.len()],
            )
            .map_err(|e| anyhow!("allocate Qwen joint argmax indices: {e}"))?;
            let values = decode_pool::pooled_alloc_buffer(
                device,
                rows.len() * DType::F32.size_of(),
                DType::F32,
                vec![rows.len()],
            )
            .map_err(|e| anyhow!("allocate Qwen joint argmax values: {e}"))?;
            for (row, input) in rows.iter().enumerate() {
                if !input.output.wants_argmax() {
                    continue;
                }
                dispatch_argmax_f32(
                    &mut enc,
                    registry,
                    device.metal_device(),
                    &row_view(&logits, row, vec![1, vocab])?,
                    &indices.slice_view((row * DType::U32.size_of()) as u64, 1),
                    &values.slice_view((row * DType::F32.size_of()) as u64, 1),
                    &params,
                    cfg.vocab_size,
                )
                .with_context(|| format!("Qwen joint argmax row {row}"))?;
            }
            Some((indices, values, params))
        } else {
            None
        };
        #[cfg(test)]
        let c2_selector = if output_tail.is_some()
            && crate::serve::api::engine_qwen35::anchor_exactness_tests::trace::enabled()
        {
            let (indices, _, _) = argmax.as_ref().context("C2 GPU selector requires actual argmax")?;
            let coordinates = rows.iter().map(|row|
                Ok((row.slot_id, usize::try_from(row.position)?))).collect::<Result<Vec<_>>>()?;
            crate::serve::api::engine_qwen35::anchor_exactness_tests::trace::gpu_selector(
                &mut enc, registry, device, indices, &coordinates)?
        } else { None };
        if let Some(tail) = output_tail.as_mut() {
            ensure!(
                rows.iter().all(|row| row.output.wants_argmax()),
                "Qwen joint output-head tail requires greedy output for every row"
            );
            let (indices, _values, _params) =
                argmax.as_ref().context("Qwen joint output-head argmax")?;
            #[cfg(test)]
            let indices = c2_selector.as_ref().map_or(indices, |owners| &owners.selected);
            enc.memory_barrier();
            tail(&mut enc, registry, device, indices).context("Qwen joint output-head tail")?;
        }
        let head_label = if crate::inference::stage_profile::enabled() {
            "adr065.head"
        } else {
            "qwen35.joint_decode.output_head"
        };
        if let Some(host_work) = host_work {
            if mlx_native::kernel_profile::is_enabled()
                || mlx_native::kernel_profile::is_dispatch_enabled()
            {
                // The native async labeled commit cannot preserve dispatch-only
                // samples or return profile-resolution errors. Keep the checked
                // synchronous profiling path, explicitly without overlap.
                enc.commit_and_wait_labeled(head_label)
                    .map_err(|e| anyhow!("Qwen joint decode command buffer: {e}"))?;
                mlx_native::command_timeline::mark("joint.head_profile_sync_no_overlap");
                mlx_native::command_timeline::mark("joint.host_work_begin");
                host_work();
                mlx_native::command_timeline::mark("joint.host_work_end");
            } else {
                enc.commit_labeled(head_label);
                #[cfg(test)]
                super::super::encoder_stage::retain_submitted(enc, head_label);
                mlx_native::command_timeline::mark("joint.head_submitted");
                mlx_native::command_timeline::mark("joint.host_work_begin");
                host_work();
                mlx_native::command_timeline::mark("joint.host_work_end");
                #[cfg(not(test))]
                enc.wait_until_completed()
                    .map_err(|e| anyhow!("Qwen joint decode command buffer: {e}"))?;
            }
        } else {
            enc.commit_and_wait_labeled(head_label)
                .map_err(|e| anyhow!("Qwen joint decode command buffer: {e}"))?;
        }
        #[cfg(test)]
        super::super::encoder_stage::settle_submitted()
            .context("original joint target commands before output readback")?;
        mlx_native::command_timeline::mark("joint.head_completed");
        #[cfg(test)]
        if let Some(snapshots) = c23_layers {
            snapshots.finish_after_checked_output_head()?;
        }
        match held_outputs {
            // The caller releases them when its commit settles.
            Some(held) => held.append(&mut retained),
            None => drop(retained),
        }

        let readback = crate::inference::stage_profile::CpuSpan::begin("logit_readback");
        let all_logits = logits
            .as_slice::<f32>()
            .map_err(|e| anyhow!("read Qwen joint logits: {e}"))?;
        let argmax_indices = argmax
            .as_ref()
            .map(|(indices, _values, _params)| indices.as_slice::<u32>())
            .transpose()
            .map_err(|e| anyhow!("read Qwen joint argmax indices: {e}"))?;
        let outputs = rows
            .iter()
            .enumerate()
            .map(|(row, input)| -> Result<Qwen35JointRowOutput> {
                let greedy_token = if input.output.wants_argmax() {
                    Some(argmax_indices.context("missing Qwen joint argmax indices")?[row])
                } else {
                    None
                };
                let decision = match decisions.as_ref() {
                    Some(decisions) => {
                        decisions.read(row, row_view(&logits, row, vec![1, vocab])?)?
                    }
                    None => None,
                };
                #[cfg(test)]
                if crate::serve::api::engine_qwen35::anchor_exactness_tests::trace::enabled() {
                    let window = packing.windows.iter().find(|window| row >= window.start && row < window.start + window.rows)
                        .context("C2 row has no complete verifier-window provenance")?;
                    let actual_tokens = gpu_token_ids.map(|tokens| tokens.as_logical_slice::<u32>()).transpose()?;
                    let consumed = (window.start..=row).map(|index|
                        actual_tokens.map_or(rows[index].token, |tokens| tokens[index])).collect::<Vec<_>>();
                    if let Some(indices) = argmax_indices.filter(|_| input.output.wants_argmax()) {
                        // Keep the actual GPU result distinct from both the raw
                        // target row and the frozen selector's acceptance input.
                        crate::serve::api::engine_qwen35::anchor_exactness_tests::trace::gpu_argmax(
                            input.slot_id, usize::try_from(input.position)?, indices[row])?;
                    }
                    let projected = &all_logits[row * vocab..(row + 1) * vocab];
                    let restored = decision.as_ref().map(|decision| {
                        let mut raw = projected.to_vec();
                        decision.restore(&mut raw);
                        raw
                    });
                    // Restore only this diagnostic copy. Production logits remain
                    // the decision kernel's masked scratch until their usual readback.
                    crate::serve::api::engine_qwen35::anchor_exactness_tests::trace::forward(
                        input.slot_id, usize::try_from(rows[window.start].position)?, &consumed,
                        "joint-existing-output-head", restored.as_deref().unwrap_or(projected), vocab,
                        Some(&normed.as_logical_slice::<f32>()?[row * h..(row + 1) * h]), h,
                    )?;
                }
                let logits = input.output.wants_logits().then(|| {
                    let mut logits = all_logits[row * vocab..(row + 1) * vocab].to_vec();
                    if let Some(decision) = decision.as_ref() {
                        decision.restore(&mut logits);
                    }
                    logits
                });
                let nextn_hidden = input
                    .output
                    .wants_hidden()
                    .then(|| nth_hidden_row(&normed, hidden_size, row as u64))
                    .transpose()?;
                Ok(Qwen35JointRowOutput {
                    greedy_token,
                    logits,
                    nextn_hidden,
                    decision,
                })
            })
            .collect::<Result<Vec<_>>>();
        drop(readback);
        mlx_native::command_timeline::mark("joint.readback_end");
        let outputs = outputs?;
        #[cfg(test)]
        c2_native.finish()?;
        Ok((outputs, normed))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::inference::models::qwen35::gpu_delta_net::apply_proj_with_ggml_type;
    use crate::inference::models::qwen35::gpu_ffn::{
        build_dense_ffn_layer_gpu_q_into, DenseFfnWeightsGpuQ,
    };
    use crate::inference::models::qwen35::gpu_full_attn::{
        apply_linear_projection_f32_pooled_with_ggml_type, upload_f32,
    };
    use crate::inference::models::qwen35::joint_decode_core::project_rows;
    use crate::inference::models::qwen35::joint_decode_test_support::{
        bits, random_f32, synthetic_blocks,
    };
    use mlx_native::ops::quantized_matmul_ggml::GgmlType;

    /// A registry frozen to the operator policy with `mul_mv_ext` off, so the
    /// exact-policy proofs below run whatever the process environment says.
    fn exact_policy_registry() -> KernelRegistry {
        let mut policy = mlx_native::ggml_routing_policy_from_environment();
        policy.dense_decode_mv_ext = false;
        let mut registry = KernelRegistry::new();
        registry
            .freeze_ggml_routing_policy(policy)
            .expect("freeze exact routing policy");
        registry
    }

    /// Admitted block storage: one packed dispatch at `m = 2..=4` must equal
    /// the serial `m = 1` dispatch of every row, bit for bit, on the default
    /// (exact) routing policy. A failing type must leave
    /// `joint_decode_routes::packed_block_type`.
    #[test]
    fn packed_block_projections_match_per_row_dispatch_bitwise() {
        let _gpu = crate::inference::hf2q_gpu_test_lock();
        let device = match MlxDevice::new() {
            Ok(device) => device,
            Err(_) => return,
        };
        let mut registry = exact_policy_registry();
        let (k, n) = (512_u32, 256_u32);
        let mut seed = 0x51A7_0001_u32;
        for ggml_type in [
            GgmlType::Q4_0,
            GgmlType::Q8_0,
            GgmlType::Q4_K,
            GgmlType::Q5_K,
            GgmlType::Q6_K,
        ] {
            let weight = synthetic_blocks(&device, ggml_type, n, k, &mut seed);
            for m in 2..=4_usize {
                let input = upload_f32(&random_f32(&mut seed, m * k as usize), &device)
                    .expect("upload input");
                let mut enc = device.command_encoder().expect("encoder");
                let run = |enc: &mut CommandEncoder,
                           registry: &mut KernelRegistry,
                           route: JointProductRoute| {
                    project_rows(
                        enc,
                        registry,
                        &device,
                        route,
                        &input,
                        m,
                        k as usize,
                        |enc, registry, input, seq| {
                            apply_proj_with_ggml_type(
                                enc, registry, &device, input, &weight, ggml_type, seq, k, n,
                            )
                            .map(|output| vec![output])
                        },
                    )
                    .expect("joint projection")
                    .remove(0)
                };
                let packed = run(&mut enc, &mut registry, JointProductRoute::Batched);
                let per_row = run(&mut enc, &mut registry, JointProductRoute::PerRow);
                enc.commit_and_wait_labeled("test.qwen.joint.projection")
                    .expect("complete joint projection");
                assert_eq!(
                    bits(&packed, m * n as usize),
                    bits(&per_row, m * n as usize),
                    "{ggml_type:?} packed m={m} differs from per-row m=1"
                );
            }
        }
    }

    /// The packed dense FFN (fused gate/up/SiLU, down, residual fold) must
    /// equal one serial `m = 1` FFN per row for every admitted type pair.
    #[test]
    fn packed_dense_ffn_matches_per_row_ffn_bitwise() {
        let _gpu = crate::inference::hf2q_gpu_test_lock();
        let device = match MlxDevice::new() {
            Ok(device) => device,
            Err(_) => return,
        };
        let mut registry = exact_policy_registry();
        let (hidden, intermediate) = (256_u32, 512_u32);
        let h = hidden as usize;
        let mut seed = 0x51A7_0002_u32;
        for (gate_up, down) in [
            (GgmlType::Q4_K, GgmlType::Q6_K),
            (GgmlType::Q5_K, GgmlType::Q6_K),
            (GgmlType::Q8_0, GgmlType::Q8_0),
            (GgmlType::Q6_K, GgmlType::Q4_K),
        ] {
            let weights = DenseFfnWeightsGpuQ {
                gate_q: synthetic_blocks(&device, gate_up, intermediate, hidden, &mut seed),
                up_q: synthetic_blocks(&device, gate_up, intermediate, hidden, &mut seed),
                down_q: synthetic_blocks(&device, down, hidden, intermediate, &mut seed),
                ggml_type_gate_up: gate_up,
                ggml_type_down: down,
                intermediate_size: intermediate,
                hidden_size: hidden,
                repacked_m32: Default::default(),
            };
            for m in 2..=4_usize {
                let x = upload_f32(&random_f32(&mut seed, m * h), &device)
                    .expect("upload x")
                    .with_shape(vec![m, h])
                    .expect("shape x");
                let residual = upload_f32(&random_f32(&mut seed, m * h), &device)
                    .expect("upload residual")
                    .with_shape(vec![m, h])
                    .expect("shape residual");
                let mut enc = device.command_encoder().expect("encoder");
                let packed = build_dense_ffn_layer_gpu_q_into(
                    &mut enc,
                    &device,
                    &mut registry,
                    &x,
                    &weights,
                    Some(&residual),
                )
                .expect("packed dense FFN");
                let mut per_row = Vec::with_capacity(m);
                for row in 0..m {
                    enc.memory_barrier();
                    per_row.push(
                        build_dense_ffn_layer_gpu_q_into(
                            &mut enc,
                            &device,
                            &mut registry,
                            &row_view(&x, row, vec![1, h]).expect("x row"),
                            &weights,
                            Some(&row_view(&residual, row, vec![1, h]).expect("residual row")),
                        )
                        .expect("per-row dense FFN"),
                    );
                }
                enc.commit_and_wait_labeled("test.qwen.joint.dense_ffn")
                    .expect("complete dense FFN");
                let packed = bits(&packed, m * h);
                for (row, output) in per_row.iter().enumerate() {
                    assert_eq!(
                        &packed[row * h..(row + 1) * h],
                        bits(output, h).as_slice(),
                        "{gate_up:?}/{down:?} packed m={m} row {row} differs from m=1"
                    );
                }
            }
        }
    }

    /// Packed width-4 products inside an MMA [`JointProjectionScope`]: each
    /// row is bitwise the MMA kernel's own result, equals the same row in a
    /// padded 1-real-row step (row copies in the other slots) and the
    /// width-1 dispatch, and repeats bitwise. Qwen3.8 K values included.
    #[test]
    fn mma_scope_rows_are_cohort_invariant_and_deterministic() {
        let _gpu = crate::inference::hf2q_gpu_test_lock();
        let device = match MlxDevice::new() {
            Ok(device) => device,
            Err(_) => return,
        };
        let mut registry = KernelRegistry::new();
        let width = 4_usize;
        let mut seed = 0x51A7_0003_u32;
        for (ggml_type, n, k) in [
            (GgmlType::Q4_K, 256_u32, 5120_u32),
            (GgmlType::Q6_K, 256, 5120),
            (GgmlType::Q4_K, 128, 17408),
            (GgmlType::Q6_K, 128, 17408),
            (GgmlType::Q4_K, 48, 6144),
        ] {
            let (nn, kk) = (n as usize, k as usize);
            let weight = synthetic_blocks(&device, ggml_type, n, k, &mut seed);
            let rows = random_f32(&mut seed, width * kk);
            let packed_input = upload_f32(&rows, &device).expect("upload rows");
            // Padded step for row r: row r first, copies of it after.
            let padded_inputs: Vec<MlxBuffer> = (0..width)
                .map(|r| {
                    let row = &rows[r * kk..(r + 1) * kk];
                    upload_f32(&row.repeat(width), &device).expect("upload padded")
                })
                .collect();
            let mut enc = device.command_encoder().expect("encoder");
            let project = |enc: &mut CommandEncoder,
                           registry: &mut KernelRegistry,
                           input: &MlxBuffer,
                           seq: u32| {
                apply_proj_with_ggml_type(
                    enc, registry, &device, input, &weight, ggml_type, seq, k, n,
                )
                .expect("scoped projection")
            };
            let (packed, repeat, padded, singles) = {
                let _scope =
                    JointProjectionScope::enter(JointProjectionKernel::ColumnInvariantMma, 4);
                let packed = project(&mut enc, &mut registry, &packed_input, 4);
                let repeat = project(&mut enc, &mut registry, &packed_input, 4);
                let padded: Vec<MlxBuffer> = padded_inputs
                    .iter()
                    .map(|input| project(&mut enc, &mut registry, input, 4))
                    .collect();
                let _single_scope =
                    JointProjectionScope::enter(JointProjectionKernel::ColumnInvariantMma, 1);
                let singles: Vec<MlxBuffer> = (0..width)
                    .map(|r| {
                        let input = row_view(&packed_input, r, vec![1, kk]).expect("row view");
                        project(&mut enc, &mut registry, &input, 1)
                    })
                    .collect();
                (packed, repeat, padded, singles)
            };
            let direct = device
                .alloc_buffer(width * nn * 4, DType::F32, vec![width, nn])
                .expect("direct output");
            mlx_native::quantized_matmul_ggml_column_invariant_mma(
                &mut enc,
                &mut registry,
                &device,
                &packed_input,
                &weight,
                &direct,
                &mlx_native::ops::quantized_matmul_ggml::GgmlQuantizedMatmulParams {
                    m: 4,
                    n,
                    k,
                    ggml_type,
                },
            )
            .expect("direct MMA");
            enc.commit_and_wait_labeled("test.qwen.joint.mma_scope")
                .expect("complete scoped projections");
            let label = format!("{ggml_type:?} {n}x{k}");
            let packed = bits(&packed, width * nn);
            assert_eq!(
                packed,
                bits(&direct, width * nn),
                "{label}: scope did not route to MMA"
            );
            assert_eq!(packed, bits(&repeat, width * nn), "{label}: repeat differs");
            for r in 0..width {
                let row = &packed[r * nn..(r + 1) * nn];
                assert_eq!(
                    row,
                    &bits(&padded[r], nn)[..],
                    "{label}: row {r} differs when padded"
                );
                assert_eq!(
                    row,
                    &bits(&singles[r], nn)[..],
                    "{label}: row {r} differs from m=1"
                );
            }
        }
    }

    /// The shared-weights dense FFN inside an MMA scope: every packed row is
    /// bitwise the 1-row FFN of that row (joint ≡ per-slot by construction).
    #[test]
    fn mma_scope_shared_dense_ffn_matches_per_row_bitwise() {
        let _gpu = crate::inference::hf2q_gpu_test_lock();
        let device = match MlxDevice::new() {
            Ok(device) => device,
            Err(_) => return,
        };
        let mut registry = KernelRegistry::new();
        let (hidden, intermediate) = (512_u32, 1024_u32);
        let h = hidden as usize;
        let m = 4_usize;
        let mut seed = 0x51A7_0004_u32;
        for down in [GgmlType::Q4_K, GgmlType::Q6_K] {
            let weights = DenseFfnWeightsGpuQ {
                gate_q: synthetic_blocks(&device, GgmlType::Q4_K, intermediate, hidden, &mut seed),
                up_q: synthetic_blocks(&device, GgmlType::Q4_K, intermediate, hidden, &mut seed),
                down_q: synthetic_blocks(&device, down, hidden, intermediate, &mut seed),
                ggml_type_gate_up: GgmlType::Q4_K,
                ggml_type_down: down,
                intermediate_size: intermediate,
                hidden_size: hidden,
                repacked_m32: Default::default(),
            };
            let x = upload_f32(&random_f32(&mut seed, m * h), &device)
                .expect("upload x")
                .with_shape(vec![m, h])
                .expect("shape x");
            let residual = upload_f32(&random_f32(&mut seed, m * h), &device)
                .expect("upload residual")
                .with_shape(vec![m, h])
                .expect("shape residual");
            let mut enc = device.command_encoder().expect("encoder");
            let packed = {
                let _scope =
                    JointProjectionScope::enter(JointProjectionKernel::ColumnInvariantMma, 4);
                build_dense_ffn_layer_gpu_q_into_with_gate_up(
                    &mut enc,
                    &device,
                    &mut registry,
                    &x,
                    &weights,
                    Some(&residual),
                    DenseGateUpDispatch::Separate,
                )
                .expect("packed dense FFN")
            };
            let per_row: Vec<MlxBuffer> = {
                let _scope =
                    JointProjectionScope::enter(JointProjectionKernel::ColumnInvariantMma, 1);
                (0..m)
                    .map(|row| {
                        enc.memory_barrier();
                        build_dense_ffn_layer_gpu_q_into_with_gate_up(
                            &mut enc,
                            &device,
                            &mut registry,
                            &row_view(&x, row, vec![1, h]).expect("x row"),
                            &weights,
                            Some(&row_view(&residual, row, vec![1, h]).expect("residual row")),
                            DenseGateUpDispatch::Separate,
                        )
                        .expect("per-row dense FFN")
                    })
                    .collect()
            };
            enc.commit_and_wait_labeled("test.qwen.joint.mma_dense_ffn")
                .expect("complete dense FFN");
            let packed = bits(&packed, m * h);
            for (row, output) in per_row.iter().enumerate() {
                assert_eq!(
                    &packed[row * h..(row + 1) * h],
                    bits(output, h).as_slice(),
                    "Q4_K/{down:?} MMA packed row {row} differs from m=1"
                );
            }
        }
    }

    /// Pooled step outputs (Class A): the packed shared-weights dense FFN
    /// and an attention-style projection give the same bytes with and
    /// without [`decode_pool::StepPooledOutputs`].
    #[test]
    fn step_pooled_outputs_keep_packed_ffn_and_projection_bitwise() {
        let _gpu = crate::inference::hf2q_gpu_test_lock();
        let device = match MlxDevice::new() {
            Ok(device) => device,
            Err(_) => return,
        };
        let mut registry = KernelRegistry::new();
        let (hidden, intermediate) = (512_u32, 1024_u32);
        let h = hidden as usize;
        let m = 4_usize;
        let mut seed = 0x51A7_0005_u32;
        let weights = DenseFfnWeightsGpuQ {
            gate_q: synthetic_blocks(&device, GgmlType::Q4_K, intermediate, hidden, &mut seed),
            up_q: synthetic_blocks(&device, GgmlType::Q4_K, intermediate, hidden, &mut seed),
            down_q: synthetic_blocks(&device, GgmlType::Q6_K, hidden, intermediate, &mut seed),
            ggml_type_gate_up: GgmlType::Q4_K,
            ggml_type_down: GgmlType::Q6_K,
            intermediate_size: intermediate,
            hidden_size: hidden,
            repacked_m32: Default::default(),
        };
        let projection = synthetic_blocks(&device, GgmlType::Q4_K, 256, hidden, &mut seed);
        let x = upload_f32(&random_f32(&mut seed, m * h), &device)
            .expect("upload x")
            .with_shape(vec![m, h])
            .expect("shape x");
        let residual = upload_f32(&random_f32(&mut seed, m * h), &device)
            .expect("upload residual")
            .with_shape(vec![m, h])
            .expect("shape residual");
        decode_pool::checked_reset_decode_pool().expect("reset pool");
        let mut enc = device.command_encoder().expect("encoder");
        let mut run = |enc: &mut CommandEncoder, pooled: bool| {
            let _scope = decode_pool::StepPooledOutputs::enter(pooled);
            let ffn = build_dense_ffn_layer_gpu_q_into_with_gate_up(
                enc,
                &device,
                &mut registry,
                &x,
                &weights,
                Some(&residual),
                DenseGateUpDispatch::Separate,
            )
            .expect("dense FFN");
            let proj = apply_linear_projection_f32_pooled_with_ggml_type(
                enc,
                &mut registry,
                &device,
                &x,
                &projection,
                GgmlType::Q4_K,
                m as u32,
                hidden,
                256,
            )
            .expect("projection");
            (ffn, proj)
        };
        let (fresh_ffn, fresh_proj) = run(&mut enc, false);
        let (pooled_ffn, pooled_proj) = run(&mut enc, true);
        enc.commit_and_wait_labeled("test.qwen.joint.pooled_outputs")
            .expect("complete pooled outputs");
        assert_eq!(bits(&fresh_ffn, m * h), bits(&pooled_ffn, m * h));
        assert_eq!(bits(&fresh_proj, m * 256), bits(&pooled_proj, m * 256));
        decode_pool::checked_reset_decode_pool().expect("reset pool");
    }

    #[test]
    fn joint_command_plan_follows_the_commit_points() {
        let plan = joint_command_plan(64, 4, true);
        assert_eq!(plan.len(), 18);
        assert_eq!(plan[0], "embed");
        assert_eq!(plan[1], "layers[0,4)");
        assert_eq!(plan[16], "layers[60,64)");
        assert_eq!(plan[17], "output_head");
        // A remainder group closes at the last layer; no open-chain flush.
        assert_eq!(
            joint_command_plan(10, 4, true),
            [
                "embed",
                "layers[0,4)",
                "layers[4,8)",
                "layers[8,10)",
                "output_head"
            ]
        );
        assert_eq!(joint_command_plan(3, 1, true).len(), 5);
        // Host embedding (no native table): no observed embed command.
        assert_eq!(
            joint_command_plan(8, 4, false),
            ["layers[0,4)", "layers[4,8)", "output_head"]
        );
        let closes = (0..10).filter(|&layer| closes_chain(layer, 4, 10)).count();
        assert_eq!(closes, 3);
    }
}