hf2q 0.1.31

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
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
//! Verified checkpoint ownership and bounded DFlash2 cycle execution.

use std::{path::Path, sync::Mutex};

use sha2::{Digest, Sha256};

use super::{
    adapters::{dispatch_dflash2_input, target_vocabulary_head, DFlash2TargetFamily},
    config::DFlash2Config,
    forward::{
        dispatch_dflash2_context_commit, dispatch_dflash2_context_commit_at,
        dispatch_dflash2_forward, dispatch_dflash2_lane_ingest, prepare_decode_positions,
    },
    route_profile,
    proposal_repetition::{self, DraftRepetitionPrior},
    schema::{DFlash2CheckpointDescriptor, DFlash2FamilyAdapter},
    selector::dispatch_dflash2_selection,
    staged::{reads_prepared_head, resolve_staged_draft, DFLASH2_DRAFT_STAGED_ENV},
    tensors::DFlash2ModelTensors,
    verify_budget::{DFlash2VerifyBudget, VerifyBudgetLane},
    weights::DFlash2WeightsFile,
    workspace::DFlash2Workspace,
};
use crate::inference::spec_decode::dflash::hidden_capture::DFlashCaptureSession;
use anyhow::{bail, ensure, Context, Result};
use mlx_native::{
    ops::copy::{dispatch_strided_copy_f32, StridedCopyParams},
    ops::dflash2_selector::{
        dispatch_dflash2_accept_greedy, DFlash2GreedyAcceptanceParams, DFLASH2_MAX_LANES,
    },
    CommandEncoder, KernelRegistry, MlxBuffer, MlxDevice,
};

const GPU_TARGET_TOKENS_ENV: &str = "HF2Q_DFLASH2_GPU_TARGET_TOKENS";
const PROPOSAL_REPETITION_ENV: &str = "HF2Q_DFLASH2_PROPOSAL_REPETITION";

fn resolve_gpu_target_tokens(
    descriptor: &DFlash2CheckpointDescriptor,
    raw: Option<&str>,
) -> Result<bool> {
    let supported = matches!(
        descriptor.family_adapter,
        DFlash2FamilyAdapter::QwenDense | DFlash2FamilyAdapter::QwenMoe
    );
    match raw {
        None => Ok(false),
        Some("0" | "off" | "false") => Ok(false),
        Some("1" | "on" | "true") if supported => Ok(true),
        Some("1" | "on" | "true") => bail!(
            "{GPU_TARGET_TOKENS_ENV}=1 is not qualified for DFlash2 adapter {:?}",
            descriptor.family_adapter
        ),
        Some(value) => {
            bail!("{GPU_TARGET_TOKENS_ENV} must be one of 0/off/false/1/on/true, got {value:?}")
        }
    }
}

struct DFlash2LaneBinding {
    hasher: Sha256,
    tokens: usize,
    rewind_tokens: Option<Vec<u32>>,
}

impl DFlash2LaneBinding {
    fn new(rewind_limit: usize) -> Self {
        let mut hasher = Sha256::new();
        hasher.update(b"hf2q-dflash2-lane-v1");
        Self {
            hasher,
            tokens: 0,
            rewind_tokens: Some(Vec::with_capacity(rewind_limit)),
        }
    }

    fn append(&mut self, tokens: &[u32], rewind_limit: usize) {
        for token in tokens {
            self.hasher.update(token.to_le_bytes());
        }
        self.tokens += tokens.len();
        if let Some(prefix) = self.rewind_tokens.as_mut() {
            if self.tokens <= rewind_limit {
                prefix.extend_from_slice(tokens);
            } else {
                self.rewind_tokens = None;
            }
        }
    }

    fn matches(&self, tokens: &[u32]) -> bool {
        if self.tokens != tokens.len() {
            return false;
        }
        let mut hasher = Sha256::new();
        hasher.update(b"hf2q-dflash2-lane-v1");
        for token in tokens {
            hasher.update(token.to_le_bytes());
        }
        self.hasher.clone().finalize() == hasher.finalize()
    }

    fn rewind(&mut self, tokens: &[u32], rewind_limit: usize) -> bool {
        if self.matches(tokens) {
            return true;
        }
        let Some(prefix) = self.rewind_tokens.as_ref() else {
            return false;
        };
        if tokens.len() >= self.tokens || prefix.get(..tokens.len()) != Some(tokens) {
            return false;
        }
        *self = Self::new(rewind_limit);
        self.append(tokens, rewind_limit);
        true
    }
}

/// A draft-context commit the GPU is executing
/// ([`DFlash2Runtime::submit_target_context`]).
pub(crate) struct SubmittedContextCommit {
    encoder: CommandEncoder,
}

/// Every input of one draft command. Two drafts with equal inputs, issued
/// over the same rings and verify-budget state, are the same command. Built
/// only when a prefetched command is stored.
#[derive(Clone, Debug)]
struct DraftInputs {
    anchors: Vec<u32>,
    logical_positions: Vec<u32>,
    temperature_bits: Vec<u32>,
    sampling_mask: u32,
    maximum_verify_rows: Vec<u32>,
    target_lane_order: Vec<u32>,
    uniform_bits: Vec<u32>,
    /// The caller reads the proposals on the host (the draft is waited for)
    /// rather than leaving the target tokens on the queue.
    wait: bool,
    /// [`DFlash2Runtime::budget_epoch`] when the command was encoded: the
    /// GPU row selection of an adaptive target reads the verify budget.
    budget_epoch: u64,
    repetition: Option<DraftRepetitionPrior>,
}

impl DraftInputs {
    /// Whether a draft call with these borrowed inputs is the command this
    /// snapshot describes. Floats compare by bits. Allocates nothing.
    #[allow(clippy::too_many_arguments)]
    fn matches(
        &self,
        anchors: &[u32],
        logical_positions: &[u32],
        temperatures: &[f32],
        sampling_mask: u32,
        maximum_verify_rows: &[u32],
        target_lane_order: &[u32],
        uniforms: &[f32],
        wait: bool,
        budget_epoch: u64,
        repetition: Option<&DraftRepetitionPrior>,
    ) -> bool {
        let same_bits = |bits: &[u32], values: &[f32]| {
            bits.len() == values.len()
                && bits
                    .iter()
                    .zip(values)
                    .all(|(bits, value)| *bits == value.to_bits())
        };
        self.wait == wait
            && self.sampling_mask == sampling_mask
            && self.budget_epoch == budget_epoch
            && self.repetition.as_ref() == repetition
            && self.anchors == anchors
            && self.logical_positions == logical_positions
            && self.maximum_verify_rows == maximum_verify_rows
            && self.target_lane_order == target_lane_order
            && same_bits(&self.temperature_bits, temperatures)
            && same_bits(&self.uniform_bits, uniforms)
    }
}

/// A draft command committed ahead of the step that will use it
/// ([`DFlash2Runtime::prefetch_draft`]).
struct PrefetchedDraft {
    inputs: DraftInputs,
    encoder: CommandEncoder,
}

/// What became of the draft commands a runtime prefetched.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(crate) struct DraftPrefetchCounts {
    /// Committed ahead of their step.
    pub prefetched: u64,
    /// Taken by the next draft call because its inputs were the same.
    pub adopted: u64,
    /// Waited for and dropped: the next draft call had other inputs, or the
    /// rings were about to change under it.
    pub discarded: u64,
}

/// GPU-resident DFlash2 checkpoint and persistent per-slot draft rings.
pub struct DFlash2Runtime {
    pub descriptor: &'static DFlash2CheckpointDescriptor,
    pub config: DFlash2Config,
    pub tensors: DFlash2ModelTensors,
    pub workspace: DFlash2Workspace,
    lane_lengths: Vec<usize>,
    lane_bindings: Vec<DFlash2LaneBinding>,
    verify_budget: DFlash2VerifyBudget,
    gpu_target_tokens: bool,
    proposal_repetition_enabled: bool,
    /// The current asynchronous draft producer, including an adopted prefetch.
    /// CPU views check this exact command before reading its workspace outputs.
    submitted_draft: Mutex<Option<CommandEncoder>>,
    /// The next step's draft, when the previous step committed it
    /// ([`Self::prefetch_draft`]). While it is `Some` the command may be
    /// executing: it reads the rings and writes the draft outputs of the
    /// workspace, so nothing may touch either before [`Self::settle_prefetch`].
    prefetched: Option<PrefetchedDraft>,
    prefetch_counts: DraftPrefetchCounts,
    /// Counts verify-budget observations ([`DraftInputs::budget_epoch`]).
    budget_epoch: u64,
    /// Copies of the workspace's row positions and ring slots that a
    /// context commit submitted ahead of the next draft reads
    /// ([`Self::submit_target_context_detached`]); allocated on first use.
    context_positions: Option<ContextPositions>,
}

/// `rope_positions` and `write_positions` of one context commit.
struct ContextPositions {
    rope: MlxBuffer,
    write: MlxBuffer,
}

impl DFlash2Runtime {
    /// Constructor-backed host payload geometry without constructing a runtime.
    pub(super) fn metadata_memory(
        config: &DFlash2Config,
        lanes: usize,
    ) -> std::result::Result<
        super::runtime_memory::DFlash2RuntimeMetadataMemory,
        super::runtime_memory::DFlash2RuntimeMemoryError,
    > {
        use super::runtime_memory::{add, mul, DFlash2RuntimeMemoryError, DFlash2RuntimeMetadataMemory};
        let word = std::mem::size_of::<u32>();
        let config_heap_bytes = add(
            config.draft_model_type.len(),
            add(
                mul(config.target_layer_ids.len(), std::mem::size_of::<usize>())?,
                mul(config.layer_types.len(), std::mem::size_of::<super::config::DFlash2LayerType>())?,
            )?,
        )?;
        let lane_state_bytes = mul(lanes, add(
            std::mem::size_of::<usize>(), std::mem::size_of::<DFlash2LaneBinding>(),
        )?)?;
        let lane_rebind_temporary_bytes = mul(config.sliding_window, word)?;
        let lane_rewind_bytes = mul(lanes, lane_rebind_temporary_bytes)?;
        let verify_budget_label_bytes = DFlash2VerifyBudget::label_payload_bytes()
            .ok_or(DFlash2RuntimeMemoryError::Invalid("verify-budget label payload overflows"))?;
        let weight_layer_array_bytes = mul(
            config.num_hidden_layers, std::mem::size_of::<super::tensors::DFlash2LayerTensors>(),
        )?;
        let workspace_ring_array_bytes = mul(
            mul(2, config.num_hidden_layers)?, std::mem::size_of::<MlxBuffer>(),
        )?;
        let runtime_inline_bytes = std::mem::size_of::<Self>();
        let retained_bytes = add(
            add(runtime_inline_bytes, config_heap_bytes)?,
            add(
                add(add(lane_state_bytes, lane_rewind_bytes)?, verify_budget_label_bytes)?,
                add(weight_layer_array_bytes, workspace_ring_array_bytes)?,
            )?,
        )?;
        // Five lane-width u32 snapshots and one lane*proposal uniform snapshot.
        let prefetch_snapshot_bytes = mul(
            add(mul(5, lanes)?, mul(lanes, config.proposal_tokens())?)?, word,
        )?;
        Ok(DFlash2RuntimeMetadataMemory {
            runtime_inline_bytes,
            config_heap_bytes,
            lane_state_bytes,
            lane_rewind_bytes,
            verify_budget_label_bytes,
            weight_layer_array_bytes,
            workspace_ring_array_bytes,
            retained_bytes,
            prefetch_snapshot_bytes,
            prefetch_host_lane_order_temporary_bytes: mul(lanes, word)?,
            lane_rebind_temporary_bytes,
        })
    }

    /// Verify the immutable checkpoint identity before uploading any tensor.
    pub fn load_verified<T: DFlash2TargetFamily>(
        device: &MlxDevice,
        descriptor: &'static DFlash2CheckpointDescriptor,
        config_path: impl AsRef<Path>,
        weights_path: impl AsRef<Path>,
        target: &T,
        lanes: usize,
    ) -> Result<Self> {
        crate::inference::route_host::require_explicit(device)?;
        const PRIOR: route_profile::Switch = route_profile::switch(PROPOSAL_REPETITION_ENV);
        let proposal_repetition_enabled = route_profile::with_value(PRIOR, |raw| {
            crate::inference::models::qwen35::joint_step_options::parse_switch(
                PROPOSAL_REPETITION_ENV,
                raw,
            )
        })
        .map_err(anyhow::Error::msg)?;
        ensure!(
            !proposal_repetition_enabled
                || descriptor.family_adapter == DFlash2FamilyAdapter::QwenDense,
            "{PROPOSAL_REPETITION_ENV} is not supported for adapter {:?}",
            descriptor.family_adapter
        );
        let config_bytes = std::fs::read(config_path.as_ref())
            .with_context(|| format!("read DFlash2 config {}", config_path.as_ref().display()))?;
        let config = descriptor
            .parse_config(&config_bytes)
            .context("validate DFlash2 config identity")?;
        target
            .validate(&config)
            .context("bind DFlash2 checkpoint to target")?;
        let weights_file = DFlash2WeightsFile::open_verified(weights_path.as_ref(), descriptor)
            .with_context(|| {
                format!("verify DFlash2 weights {}", weights_path.as_ref().display())
            })?;
        let weights = weights_file
            .load_verified(&config, descriptor)
            .context("validate DFlash2 tensor manifest")?;
        let tensors = DFlash2ModelTensors::upload(device, &config, &weights)
            .context("upload DFlash2 tensors")?;
        const STAGED: route_profile::Switch = route_profile::switch(DFLASH2_DRAFT_STAGED_ENV);
        const GPU_TARGET_TOKENS: route_profile::Switch =
            route_profile::switch(GPU_TARGET_TOKENS_ENV);
        let staged = route_profile::with_value(STAGED, |raw| {
            resolve_staged_draft(raw, &config, &tensors, lanes)
        })?;
        let workspace = DFlash2Workspace::new(device, &config, lanes, staged)
            .context("allocate DFlash2 workspace")?;
        let gpu_target_tokens = route_profile::with_value(GPU_TARGET_TOKENS, |raw| {
            resolve_gpu_target_tokens(descriptor, raw)
        })?;
        tracing::info!(
            checkpoint = descriptor.id,
            gpu_target_tokens,
            proposal_repetition_enabled,
            staged_draft = staged,
            "DFlash2 transaction policy resolved"
        );
        let rewind_limit = config.sliding_window;
        Ok(Self {
            descriptor,
            config,
            tensors,
            workspace,
            lane_lengths: vec![0; lanes],
            lane_bindings: (0..lanes)
                .map(|_| DFlash2LaneBinding::new(rewind_limit))
                .collect(),
            verify_budget: DFlash2VerifyBudget::default(),
            gpu_target_tokens,
            proposal_repetition_enabled,
            submitted_draft: Mutex::new(None),
            prefetched: None,
            prefetch_counts: DraftPrefetchCounts::default(),
            budget_epoch: 0,
            context_positions: None,
        })
    }

    pub(crate) fn gpu_target_tokens(&self) -> bool {
        self.gpu_target_tokens
    }

    pub(crate) fn proposal_repetition_enabled(&self) -> bool {
        self.proposal_repetition_enabled
    }

    /// Execute one physical anchor-plus-seven-proposal graph for every slot
    /// and wait until host proposal readback is safe.
    #[allow(clippy::too_many_arguments)]
    pub fn run_draft<T: DFlash2TargetFamily>(
        &mut self,
        device: &MlxDevice,
        registry: &mut KernelRegistry,
        target: &T,
        anchors: &[u32],
        logical_positions: &[u32],
        temperatures: &[f32],
        sampling_mask: u32,
        maximum_verify_rows: &[u32],
        uniforms: &[f32],
        repetition: Option<&DraftRepetitionPrior>,
    ) -> Result<()> {
        let target_lane_order = (0..self.workspace.max_lanes as u32).collect::<Vec<_>>();
        self.run_draft_inner(
            device,
            registry,
            target,
            anchors,
            logical_positions,
            temperatures,
            sampling_mask,
            maximum_verify_rows,
            &target_lane_order,
            uniforms,
            true,
            false,
            repetition,
        )
    }

    /// Submit the draft graph without a host wait. The graph also composes
    /// `workspace.target_tokens`; a same-queue target embedding may consume it
    /// immediately. CPU proposal access checks the retained producer's completion,
    /// independently of the target command's eventual completion.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn run_draft_for_gpu_target<T: DFlash2TargetFamily>(
        &mut self,
        device: &MlxDevice,
        registry: &mut KernelRegistry,
        target: &T,
        anchors: &[u32],
        logical_positions: &[u32],
        temperatures: &[f32],
        sampling_mask: u32,
        maximum_verify_rows: &[u32],
        target_lane_order: &[u32],
        uniforms: &[f32],
        repetition: Option<&DraftRepetitionPrior>,
    ) -> Result<()> {
        self.run_draft_inner(
            device,
            registry,
            target,
            anchors,
            logical_positions,
            temperatures,
            sampling_mask,
            maximum_verify_rows,
            target_lane_order,
            uniforms,
            false,
            false,
            repetition,
        )
    }

    #[allow(clippy::too_many_arguments)]
    fn run_draft_inner<T: DFlash2TargetFamily>(
        &mut self,
        device: &MlxDevice,
        registry: &mut KernelRegistry,
        target: &T,
        anchors: &[u32],
        logical_positions: &[u32],
        temperatures: &[f32],
        sampling_mask: u32,
        maximum_verify_rows: &[u32],
        target_lane_order: &[u32],
        uniforms: &[f32],
        wait: bool,
        prefetch: bool,
        repetition: Option<&DraftRepetitionPrior>,
    ) -> Result<()> {
        let repetition = if self.proposal_repetition_enabled {
            repetition
        } else {
            None
        };
        let lanes = self.workspace.max_lanes;
        let proposals = self.config.proposal_tokens();
        ensure!(
            uniforms.len() == lanes * proposals,
            "DFlash2 uniform count {} != lanes {lanes} * proposals {proposals}",
            uniforms.len()
        );
        ensure!(
            logical_positions
                .iter()
                .zip(&self.lane_lengths)
                .all(|(position, length)| usize::try_from(*position) == Ok(*length)),
            "DFlash2 draft positions {logical_positions:?} do not match lane contexts {:?}",
            self.lane_lengths
        );
        self.finish_submitted_draft()?;
        // A draft that does not involve a prefetch (the stock route, and a
        // step with nothing outstanding) allocates nothing here: the
        // outstanding snapshot is compared with the borrowed inputs, and a
        // snapshot is built only when a prefetched command is stored.
        if let Some(prefetched) = self.prefetched.take() {
            if !prefetch
                && prefetched.inputs.matches(
                    anchors,
                    logical_positions,
                    temperatures,
                    sampling_mask,
                    maximum_verify_rows,
                    target_lane_order,
                    uniforms,
                    wait,
                    self.budget_epoch,
                    repetition,
                )
            {
                // The command this call would encode is already on the
                // queue, issued over the rings and budget this call sees.
                self.prefetch_counts.adopted += 1;
                mlx_native::command_timeline::mark("draft.prefetch_adopted");
                if wait {
                    prefetched
                        .encoder
                        .wait_until_completed()
                        .context("execute prefetched DFlash2 draft cycle")?;
                } else {
                    *self.submitted_draft.get_mut().map_err(|_| {
                        anyhow::anyhow!("DFlash2 draft producer ownership mutex poisoned")
                    })? = Some(prefetched.encoder);
                }
                return Ok(());
            }
            self.discard_prefetched(prefetched)?;
        }
        self.workspace
            .uniforms
            .as_mut_slice::<f32>()?
            .copy_from_slice(uniforms);
        prepare_decode_positions(&mut self.workspace, &self.config, logical_positions)?;
        let mut encoder = device
            .command_encoder()
            .context("create DFlash2 draft encoder")?;
        dispatch_dflash2_input(
            &self.tensors,
            &mut encoder,
            registry,
            device,
            &self.config,
            target,
            anchors,
            &mut self.workspace,
        )?;
        let vocabulary_head = target_vocabulary_head(
            target,
            registry,
            device,
            reads_prepared_head(&self.workspace, &self.config),
        )?;
        dispatch_dflash2_forward(
            &mut encoder,
            registry,
            device,
            &self.config,
            &self.tensors,
            vocabulary_head,
            &mut self.workspace,
        )?;
        if let Some(prior) = repetition {
            proposal_repetition::encode(
                &mut encoder,
                registry,
                device,
                &self.workspace.logits,
                lanes,
                self.config.block_size,
                self.config.vocab_size,
                prior,
            )?;
        }
        let verify_model = if !wait && target.adaptive_verify_budget() {
            Some(self.verify_budget.model(target_lane_order.len())?)
        } else {
            None
        };
        dispatch_dflash2_selection(
            &mut encoder,
            registry,
            device,
            &self.config,
            &self.tensors,
            &self.workspace,
            anchors,
            temperatures,
            sampling_mask,
            maximum_verify_rows,
            target_lane_order,
            verify_model,
        )?;
        if wait && !prefetch {
            encoder
                .commit_and_wait_labeled("adr067.dflash2_draft")
                .context("execute DFlash2 draft cycle")?;
        } else {
            encoder.commit_labeled("adr067.dflash2_draft");
        }
        if let Some(staged) = self.workspace.staged.as_mut() {
            staged.command_committed();
        }
        if prefetch {
            self.prefetch_counts.prefetched += 1;
            let inputs = DraftInputs {
                anchors: anchors.to_vec(),
                logical_positions: logical_positions.to_vec(),
                temperature_bits: temperatures.iter().map(|value| value.to_bits()).collect(),
                sampling_mask,
                maximum_verify_rows: maximum_verify_rows.to_vec(),
                target_lane_order: target_lane_order.to_vec(),
                uniform_bits: uniforms.iter().map(|value| value.to_bits()).collect(),
                wait,
                budget_epoch: self.budget_epoch,
                repetition: repetition.copied(),
            };
            self.prefetched = Some(PrefetchedDraft { inputs, encoder });
        } else if !wait {
            *self.submitted_draft.get_mut().map_err(|_| {
                anyhow::anyhow!("DFlash2 draft producer ownership mutex poisoned")
            })? = Some(encoder);
        }
        Ok(())
    }

    /// Commit the draft command of the step that follows the one being
    /// settled, without waiting for it. `host_tokens` says how that step
    /// will call for its draft: [`Self::run_draft`] (`true`) or
    /// [`Self::run_draft_for_gpu_target`] with `target_lane_order`.
    ///
    /// The next draft call adopts the command when its inputs are exactly
    /// these and neither the rings nor the verify budget changed in between
    /// (any ring write goes through [`Self::settle_prefetch`], and a budget
    /// observation changes the inputs' epoch); otherwise it waits for the
    /// command, drops its outputs and drafts again. A draft command writes
    /// only this workspace's draft outputs and scratch, never the rings, so
    /// a discarded one leaves no trace.
    ///
    /// The caller has finished with the current step's draft outputs
    /// (proposals, verify rows, confidences): the command overwrites them.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn prefetch_draft<T: DFlash2TargetFamily>(
        &mut self,
        device: &MlxDevice,
        registry: &mut KernelRegistry,
        target: &T,
        anchors: &[u32],
        logical_positions: &[u32],
        temperatures: &[f32],
        sampling_mask: u32,
        maximum_verify_rows: &[u32],
        target_lane_order: &[u32],
        uniforms: &[f32],
        host_tokens: bool,
        repetition: Option<&DraftRepetitionPrior>,
    ) -> Result<()> {
        let every_lane;
        let target_lane_order = if host_tokens {
            every_lane = (0..self.workspace.max_lanes as u32).collect::<Vec<_>>();
            &every_lane
        } else {
            target_lane_order
        };
        self.run_draft_inner(
            device,
            registry,
            target,
            anchors,
            logical_positions,
            temperatures,
            sampling_mask,
            maximum_verify_rows,
            target_lane_order,
            uniforms,
            host_tokens,
            true,
            repetition,
        )
    }

    /// Check the actual producer before a host view or another workspace writer.
    /// Keep a failed producer owned; a successful check releases it immediately.
    fn finish_submitted_draft(&self) -> Result<()> {
        let mut submitted = self.submitted_draft.lock().map_err(|_| {
            anyhow::anyhow!("DFlash2 draft producer ownership mutex poisoned")
        })?;
        if let Some(encoder) = submitted.as_ref() {
            encoder
                .wait_until_completed()
                .context("complete current DFlash2 draft producer")?;
            *submitted = None;
        }
        Ok(())
    }

    /// Check the current producer, then wait for and drop any next-step prefetch.
    /// Called before anything writes the rings or encodes another command over
    /// this workspace; does no GPU work when neither submission is outstanding.
    pub(crate) fn settle_prefetch(&mut self) -> Result<()> {
        self.finish_submitted_draft()?;
        match self.prefetched.take() {
            Some(prefetched) => self.discard_prefetched(prefetched),
            None => Ok(()),
        }
    }

    fn discard_prefetched(&mut self, prefetched: PrefetchedDraft) -> Result<()> {
        self.prefetch_counts.discarded += 1;
        mlx_native::command_timeline::mark("draft.prefetch_discarded");
        prefetched
            .encoder
            .wait_until_completed()
            .context("wait for a discarded DFlash2 draft prefetch")
    }

    /// Whether a prefetched draft command is on the queue, possibly executing.
    pub(crate) fn prefetch_outstanding(&self) -> bool {
        self.prefetched.is_some()
    }

    pub(crate) fn prefetch_counts(&self) -> DraftPrefetchCounts {
        self.prefetch_counts
    }

    /// The current step's proposals, after checked producer completion.
    /// A prefetched next draft makes these unreadable until its adoption.
    pub fn proposals(&self) -> Result<&[u32]> {
        self.ensure_draft_outputs_current()?;
        Ok(self.workspace.proposed_tokens.as_slice::<u32>()?)
    }

    pub fn verify_rows(&self) -> Result<&[u32]> {
        self.ensure_draft_outputs_current()?;
        Ok(self.workspace.verify_rows.as_slice::<u32>()?)
    }

    fn ensure_draft_outputs_current(&self) -> Result<()> {
        ensure!(
            self.prefetched.is_none(),
            "DFlash2 draft outputs read after the next draft was prefetched"
        );
        self.finish_submitted_draft()?;
        Ok(())
    }

    pub(crate) fn select_verify_rows(
        &mut self,
        lane_indices: &[usize],
        maximum_rows: &[u32],
    ) -> Result<()> {
        self.ensure_draft_outputs_current()?;
        let rows = self
            .verify_budget
            .select_rows(&self.workspace, lane_indices, maximum_rows)?;
        let selected = self.workspace.verify_rows.as_mut_slice::<u32>()?;
        for (&lane, rows) in lane_indices.iter().zip(rows) {
            selected[lane] = u32::try_from(rows)?;
        }
        Ok(())
    }

    /// Reads the current step's draft confidences from the workspace: call
    /// it before [`Self::prefetch_draft`] overwrites them.
    pub(crate) fn observe_verify_budget(
        &mut self,
        lanes: &[VerifyBudgetLane],
        milliseconds: f64,
    ) -> Result<()> {
        ensure!(
            self.prefetched.is_none(),
            "DFlash2 verify-budget observation after the next draft was prefetched"
        );
        self.budget_epoch = self.budget_epoch.wrapping_add(1);
        self.verify_budget
            .observe(&self.workspace, lanes, milliseconds)
    }
    pub fn lane_lengths(&self) -> &[usize] {
        &self.lane_lengths
    }

    /// Align a resident draft ring with the exact target token prefix restored
    /// into this slot. Rewind is safe only before the first ring wrap; after
    /// that, overwritten older rows make an earlier prefix unrecoverable.
    pub fn align_lane_prefix(&mut self, lane: usize, tokens: &[u32]) -> bool {
        let Some(length) = self.lane_lengths.get_mut(lane) else {
            return false;
        };
        let Some(binding) = self.lane_bindings.get_mut(lane) else {
            return false;
        };
        if binding.tokens != *length || !binding.rewind(tokens, self.config.sliding_window) {
            return false;
        }
        *length = tokens.len();
        true
    }

    /// Bind a successfully committed hidden-state suffix to its exact target
    /// token IDs. The ring and token identity must advance in lockstep.
    pub fn record_lane_tokens(&mut self, lane: usize, tokens: &[u32]) -> Result<()> {
        let lane_length = *self
            .lane_lengths
            .get(lane)
            .context("DFlash2 token-binding lane is out of range")?;
        let binding = self
            .lane_bindings
            .get_mut(lane)
            .context("DFlash2 token-binding lane is out of range")?;
        let bound_length = binding
            .tokens
            .checked_add(tokens.len())
            .context("DFlash2 token-binding length overflow")?;
        ensure!(
            bound_length == lane_length,
            "DFlash2 lane {lane} token binding {} + {} != ring length {lane_length}",
            binding.tokens,
            tokens.len()
        );
        binding.append(tokens, self.config.sliding_window);
        Ok(())
    }

    /// Append a target prefill capture to one physical draft-ring lane.
    ///
    /// The capture's single shared layer-major backing is GPU-gathered into
    /// the existing caller-owned row tile and appended in lane passes, one
    /// command buffer for the chunk
    /// ([`ingest_capture_lane_passes`]); the ring bytes are those of the
    /// block commits made after target verification.
    pub fn ingest_target_capture(
        &mut self,
        device: &MlxDevice,
        registry: &mut KernelRegistry,
        capture: &DFlashCaptureSession,
        lane: usize,
        logical_start: usize,
    ) -> Result<()> {
        self.ingest_target_capture_rows(
            device,
            registry,
            capture,
            lane,
            logical_start,
            0..capture.seq_len,
        )
    }

    /// [`Self::ingest_target_capture`] for the capture rows `rows` only,
    /// appended at `logical_start`. A prefill forward that crossed a prompt
    /// boundary appends the rows before it and the rows after it as two
    /// calls, as the two forwards would have.
    pub fn ingest_target_capture_rows(
        &mut self,
        device: &MlxDevice,
        registry: &mut KernelRegistry,
        capture: &DFlashCaptureSession,
        lane: usize,
        logical_start: usize,
        rows: std::ops::Range<usize>,
    ) -> Result<()> {
        self.ingest_target_capture_runs(device, registry, capture, lane, logical_start, &[rows])
    }

    /// [`Self::ingest_target_capture_rows`] for rows that are not contiguous
    /// in the capture: the runs `rows`, appended in order as one chunk. A
    /// joint prefill forward holds a lane's shared prefix rows and its own
    /// rows apart; the lane appends them exactly as its own forward's
    /// capture, which holds them side by side.
    pub fn ingest_target_capture_runs(
        &mut self,
        device: &MlxDevice,
        registry: &mut KernelRegistry,
        capture: &DFlashCaptureSession,
        lane: usize,
        logical_start: usize,
        rows: &[std::ops::Range<usize>],
    ) -> Result<()> {
        ensure!(
            lane < self.workspace.max_lanes,
            "DFlash2 capture lane {lane} is out of range"
        );
        self.settle_prefetch()?;
        ensure!(
            logical_start == self.lane_lengths[lane],
            "DFlash2 capture starts at {logical_start}, lane {lane} is at {}",
            self.lane_lengths[lane]
        );
        let appended = rows.iter().try_fold(0usize, |total, run| {
            ensure!(run.start <= run.end, "invalid DFlash2 capture run {run:?}");
            total.checked_add(run.end - run.start).context("DFlash2 capture row count overflow")
        })?;
        ingest_capture_lane_passes(
            device,
            registry,
            &self.config,
            &self.tensors,
            &self.workspace,
            capture,
            lane,
            logical_start,
            rows,
        )?;
        self.lane_lengths[lane] = logical_start
            .checked_add(appended)
            .context("DFlash2 lane length overflow")?;
        Ok(())
    }

    /// Project retained target hidden rows and append only those rows to each
    /// physical slot's draft rings.
    pub fn commit_target_context(
        &mut self,
        device: &MlxDevice,
        registry: &mut KernelRegistry,
        retained_counts: &[u32],
    ) -> Result<()> {
        let mut encoder = self.encode_target_context(device, registry, retained_counts)?;
        encoder
            .commit_and_wait()
            .context("commit DFlash2 target context")?;
        self.advance_lane_lengths(retained_counts)
    }

    /// Encode the context commit of [`Self::commit_target_context`] and hand
    /// it to the GPU without waiting. The rings are being written until
    /// [`Self::finish_target_context`] returns: until then nothing may read
    /// or write them on the host, and the lane lengths are unchanged.
    ///
    /// Committing another command afterwards does not order it behind this
    /// one: with a concurrent compute encoder per command, a later command
    /// of the same queue was measured starting before this one ended in
    /// most cycles. A later command may therefore share no resource with
    /// the context commit (which reads the captured target rows, the
    /// retained counts and the ring positions and writes the draft rings),
    /// and only [`Self::finish_target_context`] says the rings are settled.
    pub(crate) fn submit_target_context(
        &mut self,
        device: &MlxDevice,
        registry: &mut KernelRegistry,
        retained_counts: &[u32],
    ) -> Result<SubmittedContextCommit> {
        let mut encoder = self.encode_target_context(device, registry, retained_counts)?;
        encoder.commit();
        Ok(SubmittedContextCommit { encoder })
    }

    /// [`Self::submit_target_context`] for a step that commits the next
    /// draft behind it: the commit reads copies of the workspace's row
    /// positions and ring slots, so the next draft's positions can be
    /// written while it executes, and every lane's length moves past the
    /// rows it retains at once (the next draft is issued from those
    /// lengths). The rings are settled only when
    /// [`Self::finish_target_context`] (with `advance` false) returns.
    ///
    /// What orders the draft committed behind this command after it is not
    /// the queue as such (commands of one queue that share no resource
    /// overlap; the replay beside this commit does): it is Metal's
    /// dependency ordering of tracked resources. mlx-native allocates
    /// buffers with `newBufferWithLength` and shared storage, whose hazard
    /// tracking is the default tracked mode, and the draft rings (and the
    /// workspace scratch) are bound directly to both commands, so on an
    /// `MTLCommandQueue` the draft's reads of the rings are synchronized
    /// behind this command's writes. A ring moved to an untracked heap or
    /// reached through anything but a direct binding would lose that
    /// ordering.
    ///
    /// If the step fails after this call, clear its lanes
    /// ([`Self::settle_submitted_step`]): their lengths have moved.
    pub(crate) fn submit_target_context_detached(
        &mut self,
        device: &MlxDevice,
        registry: &mut KernelRegistry,
        retained_counts: &[u32],
    ) -> Result<SubmittedContextCommit> {
        self.settle_prefetch()?;
        self.stage_retained_counts(retained_counts)?;
        if self.context_positions.is_none() {
            let copy = |source: &MlxBuffer| {
                device.alloc_buffer(
                    source.element_count() * std::mem::size_of::<u32>(),
                    mlx_native::DType::U32,
                    vec![source.element_count()],
                )
            };
            self.context_positions = Some(ContextPositions {
                rope: copy(&self.workspace.rope_positions)?,
                write: copy(&self.workspace.write_positions)?,
            });
        }
        let positions = self.context_positions.as_mut().expect("allocated above");
        positions
            .rope
            .as_mut_slice::<u32>()?
            .copy_from_slice(self.workspace.rope_positions.as_slice::<u32>()?);
        positions
            .write
            .as_mut_slice::<u32>()?
            .copy_from_slice(self.workspace.write_positions.as_slice::<u32>()?);
        let mut encoder = device
            .command_encoder()
            .context("create DFlash2 context encoder")?;
        dispatch_dflash2_context_commit_at(
            &mut encoder,
            registry,
            device,
            &self.config,
            &self.tensors,
            &self.workspace.retained_counts,
            &self.workspace,
            &positions.rope,
            &positions.write,
        )?;
        encoder.commit();
        self.advance_lane_lengths(retained_counts)?;
        Ok(SubmittedContextCommit { encoder })
    }

    /// Wait for a submitted context commit itself (a wait on a later
    /// command of the queue does not stand in for it). `advance` moves each
    /// lane's length past the rows it retained; pass `false` when the step
    /// the rows belong to failed after the submission, and then clear those
    /// lanes: a ring that has wrapped lost its oldest rows to the commit.
    pub(crate) fn finish_target_context(
        &mut self,
        submitted: SubmittedContextCommit,
        retained_counts: &[u32],
        advance: bool,
    ) -> Result<()> {
        submitted
            .encoder
            .wait_until_completed()
            .context("commit DFlash2 target context")?;
        if advance {
            self.advance_lane_lengths(retained_counts)?;
        }
        Ok(())
    }

    /// The context-first order of a step that settles acceptance on the
    /// host, from the submission on: run `replay` (the target's verify
    /// commit, which encodes, commits and waits for its own replay command)
    /// while the submitted context commit executes, then wait for the
    /// context command.
    ///
    /// The two commands overlap on the GPU in most cycles and either may
    /// finish first; nothing orders them. That is correct because they share
    /// no resource (the replay reads the verify step's replay storage and
    /// writes the target's DeltaNet state; the context commit reads the
    /// captured target rows and writes the draft rings) and because this
    /// function waits for the context command before it returns, whatever
    /// `replay` returned. That wait must not be removed: the replay's own
    /// wait does not cover the context command.
    ///
    /// Returns `replay`'s result and the context's. A failed submission is
    /// reported in the context's after `replay` ran, as in the stock order.
    /// When `replay` fails, the lane lengths do not advance and the lanes of
    /// `step_lanes` are cleared, because their rings hold rows of a step
    /// that did not commit: every lane is attempted, and a clear that fails
    /// is reported in the context's result (the first failure; later ones
    /// are logged) so the caller can stop instead of serving from a ring it
    /// could not reset.
    pub(crate) fn settle_context_first(
        &mut self,
        submitted: Result<SubmittedContextCommit>,
        retained_counts: &[u32],
        step_lanes: &[usize],
        replay: impl FnOnce() -> Result<()>,
    ) -> (Result<()>, Result<()>) {
        let committed = replay();
        let mut context = submitted.and_then(|submitted| {
            self.finish_target_context(submitted, retained_counts, committed.is_ok())
        });
        if committed.is_err() {
            for &lane in step_lanes {
                let cleared = self
                    .clear_lane(lane)
                    .with_context(|| format!("clear DFlash2 lane {lane} after a failed step"));
                match (cleared, context.is_ok()) {
                    (Ok(()), _) => {}
                    (Err(error), true) => context = Err(error),
                    (Err(error), false) => {
                        tracing::error!(error = %format!("{error:#}"), "DFlash2 lane cleanup failed");
                    }
                }
            }
        }
        (committed, context)
    }

    /// Close a step whose context commit
    /// ([`Self::submit_target_context_detached`]) and replay have both been
    /// waited for: `context` is the context command's result, `committed`
    /// whether the target's commit succeeded. A step with either failed
    /// must not leave anything of itself behind: a draft prefetched for the
    /// next step is waited for and dropped, and the lanes of `step_lanes`
    /// are cleared as in [`Self::settle_context_first`] (their lengths
    /// moved at the submission). Returns the context's result, or the
    /// first cleanup failure.
    pub(crate) fn settle_submitted_step(
        &mut self,
        committed: bool,
        mut context: Result<()>,
        step_lanes: &[usize],
    ) -> Result<()> {
        if committed && context.is_ok() {
            return context;
        }
        for &lane in step_lanes {
            let cleared = self
                .clear_lane(lane)
                .with_context(|| format!("clear DFlash2 lane {lane} after a failed step"));
            match (cleared, context.is_ok()) {
                (Ok(()), _) => {}
                (Err(error), true) => context = Err(error),
                (Err(error), false) => {
                    tracing::error!(error = %format!("{error:#}"), "DFlash2 lane cleanup failed");
                }
            }
        }
        context
    }

    fn encode_target_context(
        &mut self,
        device: &MlxDevice,
        registry: &mut KernelRegistry,
        retained_counts: &[u32],
    ) -> Result<CommandEncoder> {
        // A context commit shares the workspace's scratch and position
        // buffers with a draft command and writes the rings it reads.
        self.settle_prefetch()?;
        self.stage_retained_counts(retained_counts)?;
        let mut encoder = device
            .command_encoder()
            .context("create DFlash2 context encoder")?;
        dispatch_dflash2_context_commit(
            &mut encoder,
            registry,
            device,
            &self.config,
            &self.tensors,
            &self.workspace.retained_counts,
            &self.workspace,
        )?;
        Ok(encoder)
    }

    fn stage_retained_counts(&mut self, retained_counts: &[u32]) -> Result<()> {
        ensure!(
            retained_counts.len() == self.workspace.max_lanes,
            "DFlash2 retained-count length {} != workspace lanes {}",
            retained_counts.len(),
            self.workspace.max_lanes
        );
        ensure!(
            retained_counts
                .iter()
                .all(|count| (*count as usize) <= self.config.block_size),
            "DFlash2 retained counts {retained_counts:?} exceed block size {}",
            self.config.block_size
        );
        self.workspace
            .retained_counts
            .as_mut_slice::<u32>()?
            .copy_from_slice(retained_counts);
        Ok(())
    }

    fn advance_lane_lengths(&mut self, retained_counts: &[u32]) -> Result<()> {
        for (length, retained) in self.lane_lengths.iter_mut().zip(retained_counts) {
            *length = length
                .checked_add(*retained as usize)
                .context("DFlash2 lane length overflow")?;
        }
        Ok(())
    }

    /// Append greedy acceptance and draft-context settlement to the target
    /// output-head command. The caller owns the command's completion boundary
    /// and must validate the GPU counts before committing host state.
    pub(crate) fn encode_gpu_acceptance_and_context(
        &self,
        encoder: &mut CommandEncoder,
        registry: &mut KernelRegistry,
        device: &MlxDevice,
        target_tokens: &MlxBuffer,
        target_lane_order: &[u32],
        maximum_rows: &[u32],
        eos_tokens: &[u32],
    ) -> Result<()> {
        ensure!(
            !target_lane_order.is_empty()
                && target_lane_order.len() <= DFLASH2_MAX_LANES
                && maximum_rows.len() == self.workspace.max_lanes,
            "invalid DFlash2 GPU acceptance lane geometry"
        );
        ensure!(
            !eos_tokens.is_empty() && eos_tokens.len() <= 8,
            "DFlash2 GPU acceptance requires 1..=8 EOS tokens"
        );
        let mut physical_lane = [0_u32; DFLASH2_MAX_LANES];
        let mut maximum = [0_u32; DFLASH2_MAX_LANES];
        for (logical, &physical) in target_lane_order.iter().enumerate() {
            let physical_index = physical as usize;
            ensure!(
                physical_index < self.workspace.max_lanes
                    && !physical_lane[..logical].contains(&physical),
                "invalid DFlash2 GPU acceptance physical lane {physical}"
            );
            physical_lane[logical] = physical;
            maximum[logical] = maximum_rows[physical_index];
        }
        let mut eos_token = [0_u32; 8];
        eos_token[..eos_tokens.len()].copy_from_slice(eos_tokens);
        dispatch_dflash2_accept_greedy(
            encoder,
            registry,
            device,
            &self.workspace.proposed_tokens,
            target_tokens,
            &self.workspace.verify_rows,
            &self.workspace.retained_counts,
            &self.workspace.accepted_counts,
            DFlash2GreedyAcceptanceParams {
                physical_lane,
                maximum,
                eos_token,
                physical_lanes: self.workspace.max_lanes as u32,
                lanes: target_lane_order.len() as u32,
                rows_per_lane: self.config.block_size as u32,
                width: target_tokens.element_count() as u32,
                eos_count: eos_tokens.len() as u32,
            },
        )
        .context("encode DFlash2 greedy GPU acceptance")?;
        encoder.memory_barrier();
        dispatch_dflash2_context_commit(
            encoder,
            registry,
            device,
            &self.config,
            &self.tensors,
            &self.workspace.retained_counts,
            &self.workspace,
        )
        .context("encode DFlash2 GPU-resident target context commit")
    }

    pub(crate) fn gpu_acceptance_counts(&self) -> Result<(&[u32], &[u32])> {
        Ok((
            self.workspace.retained_counts.as_slice::<u32>()?,
            self.workspace.accepted_counts.as_slice::<u32>()?,
        ))
    }

    pub(crate) fn settle_gpu_context_lengths(&mut self, retained_counts: &[u32]) -> Result<()> {
        ensure!(
            retained_counts.len() == self.workspace.max_lanes
                && retained_counts
                    .iter()
                    .all(|count| (*count as usize) <= self.config.block_size),
            "invalid DFlash2 GPU retained counts {retained_counts:?}"
        );
        for (length, retained) in self.lane_lengths.iter_mut().zip(retained_counts) {
            *length = length
                .checked_add(*retained as usize)
                .context("DFlash2 lane length overflow")?;
        }
        Ok(())
    }

    /// Reset one scheduler slot before reassignment or incompatible prefix
    /// restore. Other slots remain byte-identical.
    pub fn clear_lane(&mut self, lane: usize) -> Result<()> {
        ensure!(
            lane < self.workspace.max_lanes,
            "DFlash2 lane {lane} is out of range"
        );
        self.settle_prefetch()?;
        let heads = self.config.num_key_value_heads;
        let width = self.config.sliding_window;
        let dim = self.config.head_dim;
        let lane_elements = heads * width * dim;
        for ring in self
            .workspace
            .ring_keys
            .iter_mut()
            .chain(self.workspace.ring_values.iter_mut())
        {
            let values = ring.as_mut_slice::<u16>()?;
            values[lane * lane_elements..(lane + 1) * lane_elements].fill(0);
        }
        self.lane_lengths[lane] = 0;
        self.lane_bindings[lane] = DFlash2LaneBinding::new(self.config.sliding_window);
        Ok(())
    }
}

/// Append the capture rows of the runs `rows`, in order, to `lane`'s rings
/// at `logical_start`.
///
/// A decode commit carries `block_size` rows of every lane, so appending a
/// prefill capture through it projects `block_size` rows per pass over the
/// draft's context weights. Here each pass carries the workspace's whole row
/// capacity (`max_lanes * block_size` rows) of the one lane
/// ([`dispatch_dflash2_lane_ingest`]), and the passes of a chunk share one
/// command buffer: GPU gathers reuse the workspace capture tile after its
/// last reader, without host uploads or waits between passes.
/// The projections, norms and RoPE retain the same row count as a decode
/// commit, and the ring bytes are those of
/// `block_size`-row commits (`lane_passes_write_the_rings_of_block_commits`).
#[allow(clippy::too_many_arguments)]
pub(super) fn ingest_capture_lane_passes(
    device: &MlxDevice,
    registry: &mut KernelRegistry,
    config: &DFlash2Config,
    tensors: &DFlash2ModelTensors,
    workspace: &DFlash2Workspace,
    capture: &DFlashCaptureSession,
    lane: usize,
    logical_start: usize,
    rows: &[std::ops::Range<usize>],
) -> Result<()> {
    ensure!(
        capture.target_layer_ids == config.target_layer_ids,
        "DFlash2 capture layers {:?} != checkpoint layers {:?}",
        capture.target_layer_ids,
        config.target_layer_ids
    );
    let layers = capture.target_layer_ids.len();
    let hidden = capture.hidden_size;
    let feature_width = layers.checked_mul(hidden).context("capture feature width overflow")?;
    let capture_elements = feature_width.checked_mul(capture.seq_len)
        .context("capture element count overflow")?;
    ensure!(
        rows.iter()
            .all(|run| run.start <= run.end && run.end <= capture.seq_len)
            && feature_width == config.fc_input_dim()
            && capture.hidden_output.len() == capture_elements,
        "DFlash2 capture rows {rows:?} of a {}-row, {layers}-layer, {hidden}-wide capture \
         do not fit the checkpoint's {feature_width}-wide context",
        capture.seq_len
    );
    ensure!(lane < workspace.max_lanes, "DFlash2 capture lane {lane} is out of range");
    let appended = rows.iter().try_fold(0usize, |total, run| {
        total.checked_add(run.len()).context("DFlash2 capture row count overflow")
    })?;
    if appended == 0 {
        return Ok(());
    }
    let block = config.block_size;
    let groups = workspace.max_lanes;
    let pass_rows = groups.checked_mul(block).filter(|rows| *rows > 0)
        .context("invalid DFlash2 capture pass rows")?;
    let passes = appended.div_ceil(pass_rows);
    let staged_rows = passes.checked_mul(pass_rows).context("capture padded rows overflow")?;
    ensure!(
        logical_start.checked_add(staged_rows).and_then(|end| u32::try_from(end).ok()).is_some(),
        "DFlash2 context position exceeds u32"
    );
    let source = capture.hidden_output.shared_buffer()?;
    let captured = &workspace.captured_target_hidden;
    let tile_elements = pass_rows.checked_mul(feature_width).context("capture tile overflow")?;
    let source_bytes = capture_elements.checked_mul(4).context("capture source bytes overflow")?;
    let tile_bytes = tile_elements.checked_mul(4).context("capture tile bytes overflow")?;
    ensure!(
        source.dtype() == mlx_native::DType::F32
            && source.shape() == [layers, capture.seq_len, hidden]
            && source.byte_offset() == 0 && source.data_byte_len() == source_bytes
            && captured.dtype() == mlx_native::DType::F32
            && captured.shape() == [pass_rows, feature_width]
            && captured.data_byte_len() == tile_bytes,
        "invalid DFlash2 shared capture or caller-owned transpose tile"
    );
    let copy = StridedCopyParams {
        rows: u32::try_from(layers)?,
        cols: u32::try_from(hidden)?,
        stride_row: u32::try_from(capture.seq_len.checked_mul(hidden)
            .context("capture layer stride overflow")?)?,
        stride_col: 1,
    };
    // Native shader offsets are u32 as well as the dimensions/strides.
    u32::try_from(capture_elements)?;
    u32::try_from(tile_elements)?;
    let words = |values: &[u32]| -> Result<MlxBuffer> {
        let mut buffer = device.alloc_buffer(
            std::mem::size_of_val(values),
            mlx_native::DType::U32,
            vec![values.len()],
        )?;
        buffer.as_mut_slice::<u32>()?.copy_from_slice(values);
        Ok(buffer)
    };
    let positions = words(
        &(0..staged_rows)
            .map(|index| (logical_start + index) as u32)
            .collect::<Vec<_>>(),
    )?;
    // Group `g` of pass `p` holds rows `first..first + block`.
    let group_firsts = (0..passes * groups).map(|group| group * block);
    let write_positions = words(
        &group_firsts
            .clone()
            .map(|first| ((logical_start + first) % config.sliding_window) as u32)
            .collect::<Vec<_>>(),
    )?;
    let commit_counts = words(
        &group_firsts
            .map(|first| appended.saturating_sub(first).min(block) as u32)
            .collect::<Vec<_>>(),
    )?;
    // An immutable scalar supplies exact +0 padding on the GPU. The tile
    // itself is already retained/charged by the workspace, not allocated here.
    let zero = if appended % pass_rows == 0 {
        None
    } else {
        let mut zero = device.alloc_buffer(4, mlx_native::DType::F32, vec![1])?;
        zero.as_mut_slice::<f32>()?[0] = 0.0;
        Some(zero)
    };

    let mut encoder = device
        .command_encoder()
        .context("create DFlash2 capture ingest encoder")?;
    let word = std::mem::size_of::<u32>();
    let mut selected = rows.iter().flat_map(|run| run.clone());
    for pass in 0..passes {
        // The previous pass's context projection (and its ring writes) must
        // finish before this shared workspace tile or its scratch is reused.
        encoder.memory_barrier();
        let count = (appended - pass * pass_rows).min(pass_rows);
        for index in 0..count {
            let row = selected.next().context("missing selected capture row")?;
            let offset = row * hidden;
            dispatch_strided_copy_f32(
                &mut encoder, registry, device.metal_device(),
                &source.slice_view((offset * 4) as u64, capture_elements - offset),
                &captured.slice_view((index * feature_width * 4) as u64, feature_width),
                &copy,
            ).with_context(|| format!("gather DFlash2 capture pass {pass}, row {index}"))?;
        }
        if count < pass_rows {
            dispatch_strided_copy_f32(
                &mut encoder, registry, device.metal_device(),
                zero.as_ref().context("missing capture padding scalar")?,
                &captured.slice_view((count * feature_width * 4) as u64,
                    (pass_rows - count) * feature_width),
                &StridedCopyParams {
                    rows: 1,
                    cols: u32::try_from((pass_rows - count) * feature_width)?,
                    stride_row: 0,
                    stride_col: 0,
                },
            ).context("zero DFlash2 capture pass padding")?;
        }
        encoder.memory_barrier();
        dispatch_dflash2_lane_ingest(
            &mut encoder,
            registry,
            device,
            config,
            tensors,
            workspace,
            lane,
            captured,
            &positions.slice_view((pass * pass_rows * word) as u64, pass_rows),
            &write_positions.slice_view((pass * groups * word) as u64, groups),
            &commit_counts.slice_view((pass * groups * word) as u64, groups),
        )
        .with_context(|| format!("encode DFlash2 capture pass {pass}"))?;
    }
    encoder
        .commit_and_wait()
        .context("commit DFlash2 capture ingest")?;
    Ok(())
}

#[cfg(test)]
#[path = "context_commit_tests.rs"]
mod context_commit_tests;

#[cfg(test)]
#[path = "draft_prefetch_tests.rs"]
mod draft_prefetch_tests;

#[cfg(test)]
#[path = "joint_capture_tests.rs"]
mod joint_capture_tests;

#[cfg(test)]
#[path = "shared_capture_ingest_tests.rs"]
mod shared_capture_ingest_tests;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::inference::models::qwen35::model::Qwen35Model;
    use crate::inference::spec_decode::dflash2::adapters::QwenDFlash2Adapter;
    use crate::inference::spec_decode::dflash2::schema::{QWEN36_DFLASH2, QWEN38_DFLASH2};
    use crate::serve::header::LoadProgress;
    use half::bf16;
    use safetensors::{tensor::TensorView, Dtype, SafeTensors};
    use std::path::PathBuf;

    #[test]
    fn lane_binding_rewinds_exact_unwrapped_prefix_only() {
        let mut binding = DFlash2LaneBinding::new(8);
        assert!(binding.matches(&[]));
        binding.append(&[7, 11, 13], 8);
        assert!(binding.matches(&[7, 11, 13]));
        assert!(!binding.matches(&[7, 11, 17]));
        assert!(binding.rewind(&[7, 11], 8));
        assert!(binding.matches(&[7, 11]));

        binding.append(&[13, 17], 3);
        assert!(!binding.rewind(&[7, 11, 13], 3));
    }

    #[test]
    fn gpu_target_token_policy_respects_kill_switch_and_refuses_invalid_values() {
        assert!(!resolve_gpu_target_tokens(&QWEN38_DFLASH2, None).unwrap());
        assert!(!resolve_gpu_target_tokens(&QWEN36_DFLASH2, None).unwrap());
        assert!(!resolve_gpu_target_tokens(&QWEN38_DFLASH2, Some("0")).unwrap());
        assert!(resolve_gpu_target_tokens(&QWEN36_DFLASH2, Some("1")).unwrap());
        assert!(resolve_gpu_target_tokens(&QWEN38_DFLASH2, Some("invalid")).is_err());
    }

    fn float_values(view: TensorView<'_>) -> Vec<f32> {
        match view.dtype() {
            Dtype::BF16 => view
                .data()
                .chunks_exact(2)
                .map(|bytes| bf16::from_bits(u16::from_le_bytes([bytes[0], bytes[1]])).to_f32())
                .collect(),
            Dtype::F32 => f32_values(view),
            dtype => panic!("unsupported fixture floating-point dtype {dtype:?}"),
        }
    }

    fn f32_values(view: TensorView<'_>) -> Vec<f32> {
        view.data()
            .chunks_exact(4)
            .map(|bytes| f32::from_le_bytes(bytes.try_into().unwrap()))
            .collect()
    }

    fn i64_values(view: TensorView<'_>) -> Vec<i64> {
        view.data()
            .chunks_exact(8)
            .map(|bytes| i64::from_le_bytes(bytes.try_into().unwrap()))
            .collect()
    }

    fn max_abs(actual: &[f32], expected: &[f32]) -> f32 {
        assert_eq!(actual.len(), expected.len());
        actual
            .iter()
            .zip(expected)
            .map(|(actual, expected)| (actual - expected).abs())
            .fold(0.0, f32::max)
    }

    #[test]
    #[ignore = "requires HF2Q_QWEN36_GGUF, HF2Q_QWEN36_DFLASH2_CONFIG, HF2Q_QWEN36_DFLASH2_WEIGHTS and Apple Metal"]
    fn qwen36_verified_checkpoint_runs_one_real_draft_cycle() {
        let _gpu = crate::inference::hf2q_gpu_test_lock();
        let gguf_path =
            PathBuf::from(std::env::var_os("HF2Q_QWEN36_GGUF").expect("HF2Q_QWEN36_GGUF"));
        let config_path = PathBuf::from(
            std::env::var_os("HF2Q_QWEN36_DFLASH2_CONFIG").expect("HF2Q_QWEN36_DFLASH2_CONFIG"),
        );
        let weights_path = PathBuf::from(
            std::env::var_os("HF2Q_QWEN36_DFLASH2_WEIGHTS").expect("HF2Q_QWEN36_DFLASH2_WEIGHTS"),
        );
        let gguf = mlx_native::gguf::GgufFile::open(&gguf_path).expect("open Qwen3.6 GGUF");
        let mut progress = LoadProgress::new(false, 1, 0);
        let model = Qwen35Model::load_from_gguf(&gguf, &mut progress)
            .expect("load Qwen3.6")
            .finalize_canonical_experts()
            .expect("finalize experts before the real draft cycle");
        model
            .ensure_gpu_cache_primed()
            .expect("prime Qwen3.6 GPU cache");
        model
            .with_gpu_cache_mut(|device, registry| {
                let config_bytes = std::fs::read(&config_path)?;
                let config = QWEN36_DFLASH2.parse_config(&config_bytes)?;
                let adapter = QwenDFlash2Adapter::new(&model, &config)?;
                let mut runtime = DFlash2Runtime::load_verified(
                    device,
                    &QWEN36_DFLASH2,
                    &config_path,
                    &weights_path,
                    &adapter,
                    1,
                )?;
                runtime
                    .workspace
                    .captured_target_hidden
                    .as_mut_slice::<f32>()?
                    .fill(0.0);
                runtime.run_draft(
                    device,
                    registry,
                    &adapter,
                    &[1],
                    &[0],
                    &[0.0],
                    0,
                    &[8],
                    &[0.5; 7],
                    None,
                )?;
                ensure!(
                    runtime
                        .proposals()?
                        .iter()
                        .all(|token| (*token as usize) < runtime.config.vocab_size),
                    "real DFlash2 proposal exceeds target vocabulary"
                );
                ensure!(
                    runtime.verify_rows()? == [8],
                    "real DFlash2 did not verify all rows"
                );
                let mut expected_target_tokens = vec![1_u32];
                expected_target_tokens.extend_from_slice(runtime.proposals()?);
                ensure!(
                    runtime.workspace.target_tokens.as_slice::<u32>()?
                        [..expected_target_tokens.len()]
                        == expected_target_tokens,
                    "real DFlash2 GPU target tile did not contain anchor plus proposals"
                );
                Ok(())
            })
            .expect("run real Qwen3.6 DFlash2 cycle");
    }

    /// The capture ingest the lane passes replaced: one decode-shaped commit
    /// of `block_size` rows on the lane's own row group, one command buffer
    /// each. Kept as the reference of the gate below.
    fn ingest_block_commits(
        runtime: &mut DFlash2Runtime,
        device: &MlxDevice,
        registry: &mut KernelRegistry,
        capture: &DFlashCaptureSession,
        lane: usize,
    ) -> Result<()> {
        use crate::inference::spec_decode::dflash::hidden_capture::extract_drafter_concat;
        let concatenated = extract_drafter_concat(
            &capture.hidden_output,
            &capture.target_layer_ids,
            &runtime.config.target_layer_ids,
            capture.seq_len,
            capture.hidden_size,
        )?;
        let width = runtime.config.fc_input_dim();
        let block = runtime.config.block_size;
        for chunk in concatenated.chunks(block * width) {
            let lane_start = lane * block * width;
            let destination = runtime
                .workspace
                .captured_target_hidden
                .as_mut_slice::<f32>()?;
            destination[lane_start..lane_start + block * width].fill(0.0);
            destination[lane_start..lane_start + chunk.len()].copy_from_slice(chunk);
            let positions: Vec<u32> = runtime
                .lane_lengths
                .iter()
                .map(|length| *length as u32)
                .collect();
            prepare_decode_positions(&mut runtime.workspace, &runtime.config, &positions)?;
            let mut retained = vec![0_u32; runtime.workspace.max_lanes];
            retained[lane] = (chunk.len() / width) as u32;
            runtime.commit_target_context(device, registry, &retained)?;
        }
        Ok(())
    }

    /// Real-checkpoint gate for the lane-pass capture ingest, run explicitly
    /// with the served draft switches on one model:
    /// `HF2Q_QWEN38_GGUF=… HF2Q_DFLASH2_CONFIG=… HF2Q_DFLASH2_WEIGHTS=… HF2Q_DFLASH2_DRAFT_AF4_G64=1
    /// HF2Q_DFLASH2_DRAFT_STAGED=1 <test binary> capture_ingest_matches_block_commits_on_the_real_checkpoint
    /// --ignored --nocapture --test-threads=1` (or `HF2Q_QWEN36_GGUF=…`).
    ///
    /// At one to four lanes, every lane receives prefill chunks of 5, 31,
    /// 157 and 720 rows (so chunks start off a block boundary and end in a
    /// partial block) and then enough rows to wrap its ring, once through
    /// the block commits and once through the lane passes. After every chunk
    /// the rings of all lanes and the lane cursors must agree bit for bit,
    /// and so must the logits, proposals and verify rows of a draft cycle
    /// run on the context each route left.
    #[test]
    #[ignore = "requires HF2Q_QWEN38_GGUF or HF2Q_QWEN36_GGUF, HF2Q_DFLASH2_CONFIG, HF2Q_DFLASH2_WEIGHTS and Apple Metal; run alone"]
    fn capture_ingest_matches_block_commits_on_the_real_checkpoint() {
        let _gpu = crate::inference::hf2q_gpu_test_lock();
        let (gguf_path, descriptor) = match (
            std::env::var_os("HF2Q_QWEN38_GGUF"),
            std::env::var_os("HF2Q_QWEN36_GGUF"),
        ) {
            (Some(path), None) => (PathBuf::from(path), &QWEN38_DFLASH2),
            (None, Some(path)) => (PathBuf::from(path), &QWEN36_DFLASH2),
            _ => panic!("set exactly one of HF2Q_QWEN38_GGUF and HF2Q_QWEN36_GGUF"),
        };
        let config_path =
            PathBuf::from(std::env::var_os("HF2Q_DFLASH2_CONFIG").expect("HF2Q_DFLASH2_CONFIG"));
        let weights_path =
            PathBuf::from(std::env::var_os("HF2Q_DFLASH2_WEIGHTS").expect("HF2Q_DFLASH2_WEIGHTS"));
        let gguf = mlx_native::gguf::GgufFile::open(&gguf_path).expect("open target GGUF");
        let mut progress = LoadProgress::new(false, 1, 0);
        let model = Qwen35Model::load_from_gguf(&gguf, &mut progress)
            .expect("load target")
            .finalize_canonical_experts()
            .expect("finalize experts before shared capture caches");
        model.ensure_gpu_cache_primed().expect("prime GPU cache");

        const CHUNKS: [usize; 4] = [5, 31, 157, 720];
        fn random(state: &mut u64) -> f32 {
            *state = state
                .wrapping_mul(6_364_136_223_846_793_005)
                .wrapping_add(1_442_695_040_888_963_407);
            (*state >> 40) as f32 / (1_u64 << 24) as f32 - 0.5
        }
        fn rings(runtime: &DFlash2Runtime) -> Vec<u16> {
            runtime
                .workspace
                .ring_keys
                .iter()
                .chain(&runtime.workspace.ring_values)
                .flat_map(|ring| ring.as_slice::<u16>().expect("ring bits").to_vec())
                .collect()
        }

        model
            .with_gpu_cache_mut(|device, registry| {
                let config_bytes = std::fs::read(&config_path)?;
                let config = descriptor.parse_config(&config_bytes)?;
                let adapter = QwenDFlash2Adapter::new(&model, &config)?;
                let layers = config.target_layer_ids.len();
                let hidden = config.fc_input_dim() / layers;
                // The last chunk carries every lane past one ring wrap.
                let prefix: usize = CHUNKS.iter().sum();
                let mut chunks = CHUNKS.to_vec();
                chunks.push(config.sliding_window + 13 - prefix.min(config.sliding_window));
                for lanes in 1..=4_usize {
                    let mut runtime = DFlash2Runtime::load_verified(
                        device,
                        descriptor,
                        &config_path,
                        &weights_path,
                        &adapter,
                        lanes,
                    )?;
                    let proposals = runtime.config.proposal_tokens();
                    // One route's whole run: the rings and cursors after
                    // every chunk, then a draft cycle's outputs.
                    let run = |runtime: &mut DFlash2Runtime,
                                   registry: &mut KernelRegistry,
                                   lane_passes: bool|
                     -> Result<(Vec<Vec<u16>>, Vec<usize>, Vec<u32>, Vec<u32>, Vec<u32>)> {
                        for lane in 0..lanes {
                            runtime.clear_lane(lane)?;
                        }
                        let mut after_chunks = Vec::new();
                        let mut state = 0x5EED_u64;
                        for &rows in &chunks {
                            for lane in 0..lanes {
                                let mut capture = DFlashCaptureSession::new_shared(
                                    device,
                                    runtime.config.target_layer_ids.clone(),
                                    rows,
                                    hidden,
                                    false,
                                )?;
                                for value in capture.hidden_output.iter_mut() {
                                    *value = 4.0 * random(&mut state);
                                }
                                let start = runtime.lane_lengths()[lane];
                                if lane_passes {
                                    runtime.ingest_target_capture(
                                        device, registry, &capture, lane, start,
                                    )?;
                                } else {
                                    ingest_block_commits(
                                        runtime, device, registry, &capture, lane,
                                    )?;
                                }
                                ensure!(
                                    runtime.lane_lengths()[lane] == start + rows,
                                    "lane {lane} cursor after a {rows}-row chunk"
                                );
                            }
                            after_chunks.push(rings(runtime));
                        }
                        let lengths = runtime.lane_lengths().to_vec();
                        let positions: Vec<u32> =
                            lengths.iter().map(|length| *length as u32).collect();
                        runtime.run_draft(device,
                        registry,
                        &adapter,
                        &vec![1; lanes],
                        &positions,
                        &vec![0.0; lanes],
                        0,
                        &vec![8; lanes],
                        &vec![0.5; lanes * proposals], None)?;
                        Ok((
                            after_chunks,
                            lengths,
                            runtime.proposals()?.to_vec(),
                            runtime.verify_rows()?.to_vec(),
                            runtime
                                .workspace
                                .logits
                                .as_slice::<u32>()?
                                .to_vec(),
                        ))
                    };
                    let started = std::time::Instant::now();
                    let blocks = run(&mut runtime, registry, false)?;
                    let blocks_ms = started.elapsed().as_secs_f64() * 1e3;
                    let started = std::time::Instant::now();
                    let passes = run(&mut runtime, registry, true)?;
                    let passes_ms = started.elapsed().as_secs_f64() * 1e3;
                    eprintln!(
                        "[DFLASH2_INGEST] {} lanes={lanes}: {} rows per lane and one draft cycle: block commits {blocks_ms:.1} ms, lane passes {passes_ms:.1} ms",
                        descriptor.id,
                        chunks.iter().sum::<usize>()
                    );
                    for (index, (block, pass)) in blocks.0.iter().zip(&passes.0).enumerate() {
                        ensure!(block.iter().any(|&bits| bits != 0), "nothing was appended");
                        let differing = block.iter().zip(pass).filter(|(a, b)| a != b).count();
                        ensure!(
                            differing == 0,
                            "{lanes} lanes, after the {}-row chunk: {differing} of {} ring values differ",
                            chunks[index],
                            block.len()
                        );
                    }
                    ensure!(blocks.1 == passes.1, "{lanes} lanes: lane cursors differ");
                    ensure!(blocks.2 == passes.2, "{lanes} lanes: draft proposals differ");
                    ensure!(blocks.3 == passes.3, "{lanes} lanes: verify rows differ");
                    ensure!(blocks.4 == passes.4, "{lanes} lanes: draft logits differ");
                    eprintln!(
                        "[DFLASH2_INGEST] {} lanes={lanes} chunks={chunks:?} staged={} rings, cursors and draft outputs identical",
                        descriptor.id,
                        runtime.workspace.staged.is_some()
                    );
                }
                Ok(())
            })
            .expect("lane-pass ingest against block commits");
    }

    fn capture_lane(
        device: &MlxDevice,
        values: &[f32],
        lane: usize,
        rows: usize,
        hidden: usize,
        layer_ids: &[usize],
    ) -> DFlashCaptureSession {
        let layers = layer_ids.len();
        let mut capture = DFlashCaptureSession::new_shared(
            device, layer_ids.to_vec(), rows, hidden, false,
        ).expect("shared fixture capture");
        for row in 0..rows {
            for layer in 0..layers {
                let source = ((lane * rows + row) * layers + layer) * hidden;
                let destination = (layer * rows + row) * hidden;
                capture.hidden_output[destination..destination + hidden]
                    .copy_from_slice(&values[source..source + hidden]);
            }
        }
        capture
    }

    include!("reference_oracle_tests.rs");
    include!("reference_fixture_tests.rs");
    include!("native_af4_manifest_tests.rs");
    include!("native_af4_source_tests.rs");
    include!("native_af4_weight_tests.rs");
    include!("native_af4_state_tests.rs");
    include!("native_af4_restore_tests.rs");
    include!("native_af4_fixture_tests.rs");
}