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
//! The cue fold's scheduler wiring on the synthetic model (default-run; no
//! model file): `Qwen35PrefillState::advance` with
//! `HF2Q_QWEN_PREFILL_FOLD_CUE` on runs the content chunk and the cue as
//! one transaction that returns `Ready` with the stable-boundary
//! checkpoint, and leaves what the two transactions leave; the conditions
//! under which `cue_fold_prefix_rows` keeps the two forwards; and a second
//! request that restores the folded checkpoint and diverges behind it.
//!
//! The switches come from a thread-local test override, not the process
//! environment. The paired-ring cases use a tiny native synthetic drafter
//! and the same folded/ordinary/joint capture paths as served requests.

use std::collections::BTreeMap;
use std::sync::atomic::Ordering;

use mlx_native::MlxDevice;

use super::{
    anchor_store, HybridPromptCache, Qwen35LoadedModel, Qwen35PrefillAdvance, Qwen35PrefillState,
};
use crate::inference::glp::bind::BoundGlp;
use crate::inference::glp::reader::{GlpHookPoint, GlpMode, GlpVector};
use crate::inference::models::qwen35::kv_cache::{HybridKvCache, HybridKvSlotAnchor};
use crate::inference::models::qwen35::model::Qwen35Model;
use crate::inference::models::qwen35::prefill_prepared::{PrefillSwitches, SwitchesForTest};
use crate::inference::models::qwen35::prefill_prepared_tests::{
    observable_synthetic_model, observable_synthetic_model_with_context_length,
};
use crate::serve::api::engine::SamplingParams;
use crate::serve::api::engine_supervisor::EngineSupervisor;
use crate::serve::multi_seq_kv::SlotId;
use crate::serve::scheduler::Scheduler;

const SLOTS: u32 = 2;
const CAPACITY: u32 = 256;
/// Larger than any prompt here: a chunk ends at the stable boundary or at
/// the prompt's end.
const CHUNK: usize = 720;
const SLOT: SlotId = SlotId(1);

fn token(stream: u32, position: usize) -> u32 {
    (stream * 131 + position as u32 * 37 + 11) % 512
}

fn tokens(stream: u32, range: std::ops::Range<usize>) -> Vec<u32> {
    range.map(|position| token(stream, position)).collect()
}

fn bits(values: &[f32]) -> Vec<u32> {
    values.iter().map(|value| value.to_bits()).collect()
}

fn switches(fold_cue: bool) -> SwitchesForTest {
    SwitchesForTest::set(PrefillSwitches {
        prepared: true,
        fold_cue,
        joint: false,
        wait_layers: 1,
        keep_fresh: false,
    })
}

/// A loaded model around the observable synthetic model, boxed so that the
/// address the GPU cache is primed for does not move.
pub(in crate::serve::api) fn loaded(device: &MlxDevice) -> Box<Qwen35LoadedModel> {
    loaded_from_model(observable_synthetic_model(device), CAPACITY)
}

pub(in crate::serve::api) fn loaded_paired(device: &MlxDevice) -> Box<Qwen35LoadedModel> {
    loaded_from_model(
        observable_synthetic_model_with_context_length(device, 512), PAIRED_CAPACITY)
}

fn loaded_from_model(model: Qwen35Model, capacity: u32) -> Box<Qwen35LoadedModel> {
    let (hidden_size, vocab_size) = (
        model.cfg.hidden_size as usize,
        model.cfg.vocab_size as usize,
    );
    let qwen = Box::new(Qwen35LoadedModel {
        #[cfg(test)]
        c2_model_witness: std::sync::Arc::new(()),
        model,
        tokenizer: tokenizers::Tokenizer::new(tokenizers::models::bpe::BPE::default()),
        chat_template: "{{ messages }}".to_string(),
        model_id: "prefill-fold-scheduler-test".to_string(),
        model_path: std::path::PathBuf::from("/tmp/prefill-fold-scheduler-test.gguf"),
        eos_token_ids: vec![151_645],
        hidden_size,
        vocab_size,
        context_length: Some(capacity as usize),
        quant_type: Some("Q4_K".to_string()),
        load_duration: std::time::Duration::from_millis(1),
        provenance: crate::core::provenance::Provenance::External,
        expected_projector_sha256: None,
        vision_projector_profile: None,
        vision_deepstack_output_count: None,
        vision_special_tokens_present: false,
        prompt_cache: HybridPromptCache::new(),
        lcp_registry: crate::serve::kv_persist::lcp_registry::LcpRegistry::new(1),
        kv_metrics_sink: None,
        disk_persistor: None,
        lcp_hydrated_for_cfg: std::collections::HashSet::new(),
        tq_kv_active: true,
        persistent_kv_cache: None,
        dflash2: None,
        dflash2_plan: None,
        routes: crate::inference::spec_decode::dflash2::route_profile::current(),
        speculation: crate::serve::api::qwen35_speculation::QwenSpeculationController::new(
            crate::serve::api::qwen35_speculation::QwenSpeculationPolicy::Off,
        ),
        slot_spill_budget_bytes: 0,
    });
    qwen.model
        .ensure_gpu_cache_primed()
        .expect("prime the GPU cache at the model's final address");
    qwen
}

fn new_cache(qwen: &Qwen35LoadedModel) -> HybridKvCache {
    qwen.model
        .with_gpu_cache_mut(|device, _registry| {
            HybridKvCache::new_with_options(&qwen.model.cfg, device, CAPACITY, SLOTS, true)
        })
        .expect("allocate TQ cache")
}

fn begin(
    qwen: &Qwen35LoadedModel,
    kv: &mut HybridKvCache,
    prompt: &[u32],
    stable_prefix: Option<usize>,
    cached_tokens: usize,
) -> Qwen35PrefillState {
    let params = SamplingParams {
        max_tokens: 1,
        stable_prompt_prefix_tokens: stable_prefix,
        ..SamplingParams::default()
    };
    Qwen35PrefillState::begin(
        prompt.to_vec(),
        params,
        None,
        kv,
        SLOT,
        cached_tokens,
        None,
        None,
        None,
        qwen.hidden_size,
        None,
    )
    .unwrap_or_else(|error| panic!("prefill admission: {error:#}"))
}

/// What one request's bounded prefill hands the scheduler.
struct Served {
    /// `advance` calls until `Ready`.
    transactions: usize,
    /// `(transaction index, prompt rows, checkpoint)` of every checkpoint.
    checkpoints: Vec<(usize, Vec<u32>, Vec<u32>, HybridKvSlotAnchor)>,
    /// Whether the `Ready` transaction carried a checkpoint.
    ready_with_checkpoint: bool,
    prefill_logits: Vec<u32>,
}

fn serve(
    qwen: &mut Qwen35LoadedModel,
    kv: &mut HybridKvCache,
    prompt: &[u32],
    stable_prefix: Option<usize>,
    cached_tokens: usize,
    supervisor: &EngineSupervisor,
) -> Served {
    let mut pending = Some(begin(qwen, kv, prompt, stable_prefix, cached_tokens));
    let mut checkpoints = Vec::new();
    let mut transactions = 0;
    loop {
        let advance = pending
            .take()
            .expect("a pending prefill")
            .advance(qwen, None, kv, CHUNK, supervisor, None)
            .unwrap_or_else(|error| panic!("bounded prefill: {error:#}"));
        let (checkpoint, ready) = match advance {
            Qwen35PrefillAdvance::Pending {
                state, checkpoint, ..
            } => {
                pending = Some(state);
                (checkpoint, None)
            }
            Qwen35PrefillAdvance::Ready {
                prefill_logits,
                checkpoint,
                ..
            } => (checkpoint, Some(prefill_logits)),
        };
        let carried = checkpoint.is_some();
        if let Some(checkpoint) = checkpoint {
            checkpoints.push((
                transactions,
                checkpoint.prompt_tokens,
                bits(&checkpoint.prefill_logits),
                checkpoint.kv,
            ));
        }
        transactions += 1;
        if let Some(prefill_logits) = ready {
            return Served {
                transactions,
                checkpoints,
                ready_with_checkpoint: carried,
                prefill_logits: bits(&prefill_logits),
            };
        }
    }
}

/// A first request whose prompt has a stable boundary, then a second request
/// that restores the boundary checkpoint and diverges behind it.
struct Conversation {
    first: Served,
    /// The checkpoint's cursors and DeltaNet words.
    checkpoint_words: (Vec<u32>, Vec<u32>),
    second_logits: Vec<u32>,
    /// Cursors and DeltaNet words after the second request's prefill.
    second_state: (Vec<u32>, Vec<u32>),
}

/// One conversation on a fresh cache of `qwen`. Both arms of a comparison
/// run on the one loaded model: the thread's buffer pool belongs to its
/// device.
fn converse(
    qwen: &mut Qwen35LoadedModel,
    supervisor: &EngineSupervisor,
    fold_cue: bool,
    prefix: usize,
    cue: usize,
) -> Conversation {
    const SUFFIX: usize = 11;
    let _switches = switches(fold_cue);
    let mut kv = new_cache(qwen);
    let prompt = tokens(1, 0..prefix + cue);
    let first = serve(qwen, &mut kv, &prompt, Some(prefix), 0, supervisor);
    let (_, _, _, anchor) = first.checkpoints.last().expect("a boundary checkpoint");
    let words = anchor.test_words();
    let plan = kv
        .plan_slot_anchor_restore(SLOT, anchor)
        .expect("restore plan");
    kv.apply_slot_anchor_restore(plan).expect("restore");
    let mut diverging = prompt[..prefix].to_vec();
    diverging.extend(tokens(9, prefix..prefix + SUFFIX));
    let second = serve(qwen, &mut kv, &diverging, None, prefix, supervisor);
    let after = kv
        .snapshot_slot_anchor(SLOT, prefix + SUFFIX)
        .expect("slot state after the second request")
        .test_words();
    Conversation {
        first,
        checkpoint_words: (words.3, words.5),
        second_logits: second.prefill_logits,
        second_state: (after.3, after.5),
    }
}

#[test]
fn a_folded_transaction_is_ready_with_the_checkpoint_the_two_transactions_take() {
    let _gpu = crate::inference::hf2q_gpu_test_lock();
    let Ok(device) = MlxDevice::new() else {
        return;
    };
    let mut qwen = loaded(&device);
    let supervisor = EngineSupervisor::new();
    for (prefix, cue) in [(40, 5), (97, 8)] {
        let snapshots = || {
            anchor_store::ANCHOR_TELEMETRY
                .snapshot_count
                .load(Ordering::Relaxed)
        };
        let before = snapshots();
        let two = converse(&mut qwen, &supervisor, false, prefix, cue);
        let between = snapshots();
        let folded = converse(&mut qwen, &supervisor, true, prefix, cue);
        let after = snapshots();

        // Two transactions: the content chunk hands over the checkpoint,
        // the cue chunk is ready without one.
        assert_eq!(two.first.transactions, 2, "{prefix}+{cue}");
        assert!(!two.first.ready_with_checkpoint);
        assert_eq!(two.first.checkpoints.len(), 1);
        assert_eq!(two.first.checkpoints[0].0, 0);
        // One folded transaction: ready, with the checkpoint.
        assert_eq!(folded.first.transactions, 1, "{prefix}+{cue}");
        assert!(folded.first.ready_with_checkpoint);
        assert_eq!(folded.first.checkpoints.len(), 1);

        let (two_checkpoint, folded_checkpoint) =
            (&two.first.checkpoints[0], &folded.first.checkpoints[0]);
        assert_eq!(two_checkpoint.1, tokens(1, 0..prefix));
        assert_eq!(folded_checkpoint.1, two_checkpoint.1, "checkpoint prompt");
        assert!(
            folded_checkpoint.2 == two_checkpoint.2,
            "{prefix}+{cue}: boundary logits differ"
        );
        assert!(
            folded.checkpoint_words == two.checkpoint_words,
            "{prefix}+{cue}: the boundary checkpoint differs"
        );
        assert!(
            folded.first.prefill_logits == two.first.prefill_logits,
            "{prefix}+{cue}: the prompt's last-row logits differ"
        );
        // The request that restored the checkpoint and diverged.
        assert!(
            folded.second_logits == two.second_logits,
            "{prefix}+{cue}: logits behind the restored folded checkpoint differ"
        );
        assert!(
            folded.second_state == two.second_state,
            "{prefix}+{cue}: slot state behind the restored folded checkpoint differs"
        );
        // Each arm took one checkpoint and counted it (other tests of this
        // process may count too, so at least one each).
        assert!(between > before && after > between, "snapshot metric");
    }
}

#[test]
fn the_scheduler_keeps_two_forwards_where_the_fold_does_not_apply() {
    let _gpu = crate::inference::hf2q_gpu_test_lock();
    let Ok(device) = MlxDevice::new() else {
        return;
    };
    let mut qwen = loaded(&device);
    let mut kv = new_cache(&qwen);
    /// The content rows the scheduler would fold, if it folds.
    fn folds(
        qwen: &Qwen35LoadedModel,
        kv: &mut HybridKvCache,
        prefix: usize,
        cue: usize,
        mtp_prefill: bool,
        headroom: Option<usize>,
    ) -> Option<usize> {
        let prompt = tokens(1, 0..prefix + cue);
        let state = begin(qwen, kv, &prompt, Some(prefix), 0);
        state
            .cue_fold_prefix_rows(qwen, kv, prefix, false, mtp_prefill, headroom)
            .expect("fold decision")
            .map(|(rows, _image)| rows)
    }
    {
        let _switches = switches(true);
        assert_eq!(folds(&qwen, &mut kv, 40, 5, false, None), Some(40));
        assert_eq!(folds(&qwen, &mut kv, 40, 32, false, None), Some(40));
        // A short content chunk the cue would carry past 32 rows.
        assert_eq!(folds(&qwen, &mut kv, 31, 5, false, None), None);
        assert_eq!(folds(&qwen, &mut kv, 20, 5, false, None), Some(20));
        // One-row segments and a cue longer than 32 rows.
        assert_eq!(folds(&qwen, &mut kv, 40, 1, false, None), None);
        assert_eq!(folds(&qwen, &mut kv, 1, 5, false, None), None);
        assert_eq!(folds(&qwen, &mut kv, 40, 33, false, None), None);
        // The MTP catch-up prefill, and a checkpoint over its quota.
        assert_eq!(folds(&qwen, &mut kv, 40, 5, true, None), None);
        assert_eq!(crate::serve::api::engine::qwen35_slot_prefill_chunk_tokens(4), 2_048);
        // MTP cannot take the extra folded cue: its N4 parent ceiling is the
        // content quantum, not 2080 rows per slot.
        assert_eq!(folds(&qwen, &mut kv, 40, 5, false, Some(0)), None);
        assert_eq!(
            folds(&qwen, &mut kv, 40, 5, false, Some(usize::MAX)),
            Some(40)
        );
        // A bound GLP vector (`hf2q serve --glp`): two forwards, no error.
        let width = qwen.hidden_size;
        qwen.model.glp = Some(BoundGlp {
            vector: GlpVector {
                mode: GlpMode::Add,
                hook_point: GlpHookPoint::ResidualStreamPostLayer,
                derived_at: None,
                alpha_default: 1.0,
                rank: 1,
                layers: BTreeMap::from([(3_u32, vec![0.25_f32; width])]),
                width,
                content_sha256: None,
                method: None,
                base_model_name: None,
            },
            alpha: 1.0,
            device_directions: BTreeMap::new(),
        });
        assert_eq!(folds(&qwen, &mut kv, 40, 5, false, None), None);
        qwen.model.glp = None;
        assert_eq!(folds(&qwen, &mut kv, 40, 5, false, None), Some(40));
    }
    {
        // The switch off, and the fold without the prepared kernels.
        let _switches = switches(false);
        assert_eq!(folds(&qwen, &mut kv, 40, 5, false, None), None);
    }
    let _switches = SwitchesForTest::set(PrefillSwitches {
        prepared: false,
        fold_cue: true,
        joint: false,
        wait_layers: 1,
        keep_fresh: false,
    });
    assert_eq!(folds(&qwen, &mut kv, 40, 5, false, None), None);
}

#[test]
fn active_prefill_and_retained_prefix_keep_two_distinct_parents_not_two_rows() {
    use crate::inference::models::qwen35::carry_memory::CarryOwners;
    use mlx_native::DType;
    let _gpu = crate::inference::hf2q_gpu_test_lock();
    let Ok(device) = MlxDevice::new() else { return };
    let qwen = loaded(&device);
    let mut kv = new_cache(&qwen);
    let prompt = tokens(1, 0..20);
    let mut state = begin(&qwen, &mut kv, &prompt, None, 0);
    let h = qwen.hidden_size;
    let old = device.alloc_buffer(8 * h * 4, DType::F32, vec![8, h]).unwrap();
    let next = device.alloc_buffer(3 * h * 4, DType::F32, vec![3, h]).unwrap();
    let old_bytes = old.byte_len() as u64;
    let new_bytes = next.byte_len() as u64;
    let prefix = super::Qwen35SpecPrefixBoundary {
        token_count: 8, pending_target_hidden: old.slice_view((7 * h * 4) as u64, h),
    };
    state.mtp_pending_hidden = Some(old.slice_view((7 * h * 4) as u64, h));
    drop(old);
    let mut owners = CarryOwners::default();
    state.include_carry_owners(&mut owners);
    owners.include(&prefix.pending_target_hidden);
    assert_eq!(owners.bytes(), old_bytes, "active/prefix aliases share a backing");
    state.mtp_pending_hidden = Some(next.slice_view((2 * h * 4) as u64, h));
    state.include_carry_owners(&mut owners);
    assert_eq!(owners.bytes(), old_bytes + new_bytes, "replacement overlaps the retained old parent");
    drop(owners);
    let mut remaining = CarryOwners::default();
    state.include_carry_owners(&mut remaining);
    remaining.include(&prefix.pending_target_hidden);
    assert_eq!(remaining.bytes(), old_bytes + new_bytes);
    drop(prefix);
    drop(remaining);
    let mut active = CarryOwners::default();
    state.include_carry_owners(&mut active);
    assert_eq!(active.bytes(), new_bytes);
}

const PAIRED_WINDOW: usize = 256;
const PAIRED_CAPACITY: u32 = 512;

fn paired_cache(qwen: &Qwen35LoadedModel) -> HybridKvCache {
    qwen.model
        .with_gpu_cache_mut(|device, _| {
            HybridKvCache::new_with_options(
                &qwen.model.cfg, device, PAIRED_CAPACITY, SLOTS, true)
        })
        .expect("allocate native paired-prefill cache")
}

fn paired_prefill(
    qwen: &mut Qwen35LoadedModel,
    kv: &mut HybridKvCache,
    prompt: &[u32],
    boundary: usize,
    cached: usize,
    discard_only: bool,
) -> super::Qwen35StablePromptCheckpoint {
    let mut state = begin(qwen, kv, prompt, Some(boundary), cached);
    state.set_discard_only_checkpoint(discard_only);
    let supervisor = EngineSupervisor::new();
    let mut saved = None;
    loop {
        match state.advance(qwen, None, kv, CHUNK, &supervisor, None).unwrap() {
            Qwen35PrefillAdvance::Pending { state: pending, checkpoint, .. } => {
                if checkpoint.is_some() { saved = checkpoint; }
                state = pending;
            }
            Qwen35PrefillAdvance::Ready { checkpoint, .. } => {
                return checkpoint.or(saved).expect("stable boundary checkpoint");
            }
        }
    }
}

#[test]
fn folded_drafter_checkpoint_precedes_cue_ingestion_on_both_sides_of_wrap() {
    use crate::inference::spec_decode::dflash2::runtime::DFlash2Runtime;
    let _gpu = crate::inference::hf2q_gpu_test_lock();
    let Ok(device) = MlxDevice::new() else { return };
    let mut qwen = loaded_paired(&device);
    for boundary in [248, 280] {
        let prompt = tokens(1, 0..boundary + 16);
        let mut results = Vec::new();
        for fold in [false, true] {
            let _switches = switches(fold);
            qwen.dflash2 = Some(DFlash2Runtime::test_for_prefill_checkpoints(
                &device, SLOTS as usize, PAIRED_WINDOW, qwen.hidden_size).unwrap());
            let mut kv = paired_cache(&qwen);
            let checkpoint = paired_prefill(&mut qwen, &mut kv, &prompt, boundary, 0, false);
            let image = checkpoint.draft.as_ref().expect("publishable target has a draft image");
            assert_eq!(image.logical_tokens(), boundary);
            assert!(image.matches_tokens(&prompt[..boundary]));
            let runtime = qwen.dflash2.as_mut().unwrap();
            assert_eq!(runtime.lane_lengths()[SLOT.0 as usize], prompt.len());
            let live = runtime.test_lane_checkpoint_bits(SLOT.0 as usize).unwrap();
            runtime.restore_lane_checkpoint(&device, 0, image).unwrap();
            let parent = runtime.test_lane_checkpoint_bits(0).unwrap();
            assert_ne!(parent, live, "the cue must not contaminate the parent ring image");
            results.push((parent, live, bits(&checkpoint.prefill_logits)));
        }
        assert_eq!(results[0], results[1],
            "folded and separate prefix/cue forwards must leave the same paired boundary");
    }
}

#[test]
fn a_draft_image_that_exceeds_quota_never_leaves_a_target_only_checkpoint() {
    use crate::inference::spec_decode::dflash2::runtime::DFlash2Runtime;
    let _gpu = crate::inference::hf2q_gpu_test_lock();
    let Ok(device) = MlxDevice::new() else { return };
    let _switches = switches(true);
    let mut qwen = loaded_paired(&device);
    qwen.dflash2 = Some(DFlash2Runtime::test_for_prefill_checkpoints(
        &device, SLOTS as usize, PAIRED_WINDOW, qwen.hidden_size).unwrap());
    let mut kv = paired_cache(&qwen);
    let prompt = tokens(1, 0..264);
    let state = begin(&qwen, &mut kv, &prompt, Some(248), 0);
    let target_only = kv.slot_anchor_image_bytes().unwrap()
        + anchor_store::anchor_non_payload_bytes(248, qwen.vocab_size, 0).unwrap();
    assert!(state.cue_fold_prefix_rows(&qwen, &kv, 248, true, false,
        Some(target_only)).unwrap().is_none());
    let advance = state.advance(&mut qwen, None, &mut kv, CHUNK,
        &EngineSupervisor::new(), Some(target_only)).unwrap();
    let Qwen35PrefillAdvance::Pending { checkpoint, .. } = advance else {
        panic!("quota refusal keeps the separate prefix and cue forwards");
    };
    assert!(checkpoint.is_none(), "quota refusal cannot publish target without draft");
    assert!(qwen.dflash2.as_mut().unwrap().align_lane_prefix(SLOT.0 as usize, &prompt[..248]),
        "quota refusal must not abandon the current working ring");
}

#[test]
fn a_live_append_discards_its_target_child_without_copying_or_replacing_the_draft_parent() {
    use crate::inference::spec_decode::dflash2::runtime::DFlash2Runtime;
    let _gpu = crate::inference::hf2q_gpu_test_lock();
    let Ok(device) = MlxDevice::new() else { return };
    let _switches = switches(true);
    let mut qwen = loaded_paired(&device);
    qwen.dflash2 = Some(DFlash2Runtime::test_for_prefill_checkpoints(
        &device, SLOTS as usize, PAIRED_WINDOW, qwen.hidden_size).unwrap());
    let mut kv = paired_cache(&qwen);
    let first = tokens(1, 0..264);
    let parent = paired_prefill(&mut qwen, &mut kv, &first, 248, 0, false);
    let parent_image = parent.draft.clone().unwrap();
    let mut store = anchor_store::Qwen35AnchorStore::new(1).unwrap();
    let id = store.stage(1, anchor_store::Qwen35Anchor {
        id: 0, request: 1, prompt_tokens: parent.prompt_tokens, kv: parent.kv,
        prefill_logits: parent.prefill_logits, vision_fingerprint: None,
        spec: parent.spec, draft: parent.draft, discard_only: false,
        draft_prefix: parent.draft_prefix,
    }).unwrap();
    store.commit(1, false).unwrap();
    let next = tokens(1, 0..288);
    let child = paired_prefill(&mut qwen, &mut kv, &next, 280, first.len(), true);
    assert!(child.discard_only && child.draft.is_none());
    assert!(qwen.dflash2.as_mut().unwrap().align_lane_prefix(SLOT.0 as usize, &next));
    store.stage(2, anchor_store::Qwen35Anchor {
        id: 0, request: 2, prompt_tokens: child.prompt_tokens, kv: child.kv,
        prefill_logits: child.prefill_logits, vision_fingerprint: None,
        spec: child.spec, draft: child.draft, discard_only: true,
        draft_prefix: child.draft_prefix,
    }).unwrap();
    assert!(store.commit(2, false).is_err(), "discard-only targets cannot be published");
    assert!(!store.commit(2, true).unwrap());
    assert_eq!(store.deepest().unwrap().id, id);
    assert!(std::sync::Arc::ptr_eq(store.deepest().unwrap().draft.as_ref().unwrap(), &parent_image));
    assert!(store.pending().is_none());
}

#[test]
fn joint_folded_prefill_pairs_each_lanes_prefix_before_its_own_cue_wrap() {
    use crate::inference::spec_decode::dflash2::runtime::DFlash2Runtime;
    use super::{Qwen35JointPrefillAdvance, Qwen35PrefillCohort, Qwen35PrefillLane};
    let _gpu = crate::inference::hf2q_gpu_test_lock();
    let Ok(device) = MlxDevice::new() else { return };
    let _switches = switches(true);
    let mut qwen = loaded_paired(&device);
    qwen.dflash2 = Some(DFlash2Runtime::test_for_prefill_checkpoints(
        &device, SLOTS as usize, PAIRED_WINDOW, qwen.hidden_size).unwrap());
    let mut kv = paired_cache(&qwen);
    let mut lanes = Vec::new();
    for slot in 0..SLOTS {
        let boundary = 248 + 32 * slot as usize;
        let prompt = tokens(slot + 1, 0..boundary + 16);
        let state = Qwen35PrefillState::begin(prompt,
            SamplingParams { max_tokens: 1, stable_prompt_prefix_tokens: Some(boundary),
                ..SamplingParams::default() },
            None, &mut kv, SlotId(slot), 0, None, None, None, qwen.hidden_size, None).unwrap();
        let mut chunk = state.plan_joint_chunk(&mut qwen, &kv, CHUNK, None).unwrap().unwrap();
        assert!(chunk.folds_cue());
        let fold_image = state.cue_fold_image(&kv, &mut chunk);
        lanes.push(Qwen35PrefillLane { state, chunk, fold_image, anchor_quota_headroom: None });
    }
    let cohort = Qwen35PrefillCohort {
        lanes: SLOTS as usize, shared_rows: 0, sharing: vec![false; SLOTS as usize],
        rows: lanes.iter().map(|lane| lane.chunk.rows()).sum(),
    };
    let Qwen35JointPrefillAdvance::Lanes(outcomes) = super::run_qwen35_joint_prefill(
        lanes, &cohort, &mut qwen, None, &mut kv, &EngineSupervisor::new()) else {
        panic!("joint folded prefill failed");
    };
    let mut images = Vec::new();
    for (slot, outcome) in outcomes.into_iter().enumerate() {
        let Qwen35PrefillAdvance::Ready { checkpoint: Some(checkpoint), .. } = outcome.unwrap() else {
            panic!("joint lane lost its folded boundary");
        };
        let image = checkpoint.draft.unwrap();
        let boundary = 248 + 32 * slot;
        assert_eq!(image.logical_tokens(), boundary);
        assert!(image.matches_tokens(&tokens(slot as u32 + 1, 0..boundary)));
        assert!(!image.matches_tokens(&tokens((1 - slot) as u32 + 1, 0..boundary)));
        images.push(image);
    }
    let runtime = qwen.dflash2.as_mut().unwrap();
    let live: Vec<_> = (0..SLOTS as usize).map(|slot|
        runtime.test_lane_checkpoint_bits(slot).unwrap()).collect();
    for slot in 0..SLOTS as usize {
        runtime.restore_lane_checkpoint(&device, slot, &images[slot]).unwrap();
        assert_ne!(runtime.test_lane_checkpoint_bits(slot).unwrap(), live[slot]);
        assert!(runtime.align_lane_prefix(slot, &tokens(slot as u32 + 1, 0..248 + 32 * slot)));
    }
    assert_ne!(runtime.test_lane_checkpoint_bits(0).unwrap(), runtime.test_lane_checkpoint_bits(1).unwrap());
}

#[test]
fn sampled_logprob_requests_keep_paired_native_cached_continuation_and_canonical_settings() {
    use crate::inference::spec_decode::dflash2::runtime::DFlash2Runtime;
    use super::{Qwen35DecodeState, Qwen35DraftPrefix, Qwen35StablePromptCheckpoint};
    fn ready(
        qwen: &mut Qwen35LoadedModel, kv: &mut HybridKvCache, prompt: &[u32],
        params: &SamplingParams, cached: usize, supervisor: &EngineSupervisor,
    ) -> (Qwen35DecodeState, Vec<u32>, Option<Qwen35StablePromptCheckpoint>) {
        let mut state = Qwen35PrefillState::begin(prompt.to_vec(), params.clone(), None,
            kv, SLOT, cached, None, None, None, qwen.hidden_size, None).unwrap();
        state.set_draft_prefix(Qwen35DraftPrefix::Maintained);
        let mut saved = None;
        loop {
            match state.advance(qwen, None, kv, CHUNK, supervisor, None).unwrap() {
                Qwen35PrefillAdvance::Pending { state: pending, checkpoint, .. } => {
                    if checkpoint.is_some() { saved = checkpoint; }
                    state = pending;
                }
                Qwen35PrefillAdvance::Ready { state, prefill_logits, checkpoint, .. } => {
                    return (state, bits(&prefill_logits), checkpoint.or(saved));
                }
            }
        }
    }
    let _gpu = crate::inference::hf2q_gpu_test_lock();
    let Ok(device) = MlxDevice::new() else { return };
    let _switches = switches(true);
    let mut qwen = loaded_paired(&device);
    let supervisor = EngineSupervisor::new();
    let prompt = tokens(1, 0..296);
    for (temperature, seed) in [(0.0, None), (0.7, Some(7))] {
        qwen.dflash2 = Some(DFlash2Runtime::test_for_prefill_checkpoints(
            &device, SLOTS as usize, PAIRED_WINDOW, qwen.hidden_size).unwrap());
        let mut kv = paired_cache(&qwen);
        let params = SamplingParams { max_tokens: 4, temperature, seed,
            logprobs: true, top_logprobs: 3, stable_prompt_prefix_tokens: Some(280),
            ..SamplingParams::default() };
        let (original, original_logits, checkpoint) =
            ready(&mut qwen, &mut kv, &prompt, &params, 0, &supervisor);
        let checkpoint = checkpoint.unwrap();
        assert!(original.draft_prefix().maintained());
        assert!(original.dflash2_readiness(&kv).is_ok(),
            "full-logit canonical sampling must not be gated by MTP-only greedy restrictions");
        let original_tokens = original.generated_tokens.clone();
        let original_probs: Vec<_> = original.logprobs_vec.as_ref().unwrap().iter()
            .map(|record| (record.token_id, record.logprob.to_bits(), record.top.len())).collect();
        assert_eq!(original_probs[0].2, 3);
        qwen.dflash2.as_mut().unwrap()
            .prepare_lane_checkpoint_change(SLOT.0 as usize).unwrap();
        let original_ring = qwen.dflash2.as_mut().unwrap()
            .test_lane_checkpoint_bits(SLOT.0 as usize).unwrap();
        let original_probe = qwen.model.forward_gpu_last_logits(
            &[original.next_token], &[prompt.len() as i32; 4], &mut kv, SLOT).unwrap();
        let mut store = anchor_store::Qwen35AnchorStore::new(1).unwrap();
        let id = store.stage(1, anchor_store::Qwen35Anchor {
            id: 0, request: 1, prompt_tokens: checkpoint.prompt_tokens, kv: checkpoint.kv,
            prefill_logits: checkpoint.prefill_logits, vision_fingerprint: None,
            spec: checkpoint.spec, draft: checkpoint.draft, discard_only: false,
            draft_prefix: checkpoint.draft_prefix,
        }).unwrap();
        store.commit(1, false).unwrap();
        qwen.model.with_gpu_cache_mut(|device, _| anchor_store::restore_committed_anchor(
            &mut kv, SLOT, &mut store, id, &supervisor,
            Some((device, qwen.dflash2.as_mut().unwrap())))).unwrap();
        let (resumed, resumed_logits, _) =
            ready(&mut qwen, &mut kv, &prompt, &params, 280, &supervisor);
        assert_eq!(resumed.cached_prefix_tokens(), 280);
        assert_eq!(resumed_logits, original_logits);
        assert_eq!(resumed.generated_tokens, original_tokens);
        let resumed_probs: Vec<_> = resumed.logprobs_vec.as_ref().unwrap().iter()
            .map(|record| (record.token_id, record.logprob.to_bits(), record.top.len())).collect();
        assert_eq!(resumed_probs, original_probs);
        qwen.dflash2.as_mut().unwrap()
            .prepare_lane_checkpoint_change(SLOT.0 as usize).unwrap();
        assert!(resumed.draft_prefix().maintained() && resumed.dflash2_readiness(&kv).is_ok());
        assert_eq!(qwen.dflash2.as_mut().unwrap()
            .test_lane_checkpoint_bits(SLOT.0 as usize).unwrap(), original_ring);
        let resumed_probe = qwen.model.forward_gpu_last_logits(
            &[resumed.next_token], &[prompt.len() as i32; 4], &mut kv, SLOT).unwrap();
        assert_eq!(bits(&resumed_probe), bits(&original_probe),
            "the next native target continuation must match after paired cached restore");
    }
}

#[test]
fn post_forward_pending_and_ready_cancellation_each_emit_one_actual_request_summary() {
    use crate::serve::api::engine::{
        Qwen35KvGuard, Qwen35RetainedPrefix, PromptCache, SlotReply,
        settle_qwen35_prefill_advance,
    };
    use crate::serve::scheduler::{AdmitRequest, InflightBatchedScheduler};
    use std::io::Write;
    use std::sync::{Arc, Mutex};
    struct LogWriter(Arc<Mutex<Vec<u8>>>);
    impl Write for LogWriter {
        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
            self.0.lock().unwrap().extend_from_slice(bytes);
            Ok(bytes.len())
        }
        fn flush(&mut self) -> std::io::Result<()> { Ok(()) }
    }
    let _gpu = crate::inference::hf2q_gpu_test_lock();
    let Ok(device) = MlxDevice::new() else { return };
    let _switches = switches(true);
    for ready in [false, true] {
        let mut qwen = loaded(&device);
        qwen.persistent_kv_cache = Some(new_cache(&qwen));
        let mut guard = Qwen35KvGuard::take(&mut qwen).unwrap();
        let mut scheduler = InflightBatchedScheduler::new(SLOTS, 1);
        let handle = scheduler.admit(AdmitRequest {
            prompt_tokens: 48, max_tokens: 1, kv_bytes_needed: 0, prompt_kv_bytes: 0,
            preferred_slot: None,
        }).unwrap().handle.unwrap();
        let prompt = tokens(1, 0..48);
        let state = Qwen35PrefillState::begin(prompt, SamplingParams {
            max_tokens: 1, stable_prompt_prefix_tokens: Some(40), ..SamplingParams::default()
        }, None, guard.kv.as_mut().unwrap(), handle.slot_id, 0, None, None, None,
            guard.model.hidden_size, None).unwrap();
        let supervisor = EngineSupervisor::new();
        let advance = state.advance(guard.model, None, guard.kv.as_mut().unwrap(),
            if ready { CHUNK } else { 16 }, &supervisor, None).unwrap();
        assert_eq!(matches!(&advance, Qwen35PrefillAdvance::Ready { .. }), ready);
        assert_eq!(guard.kv.as_ref().unwrap().sequence_len_for_slot(handle.slot_id).unwrap(),
            if ready { 48 } else { 16 }, "disconnect must occur after the actual checked native advance");
        let (send, receive) = tokio::sync::oneshot::channel();
        drop(receive);
        let mut slots = vec![None, None];
        let mut retained = vec![Qwen35RetainedPrefix::default(); SLOTS as usize];
        let mut caches: Vec<_> = (0..SLOTS).map(|_| PromptCache::new()).collect();
        let mut anchors: Vec<_> = (0..SLOTS)
            .map(|_| anchor_store::Qwen35AnchorStore::new(1).unwrap()).collect();
        let log = Arc::new(Mutex::new(Vec::new()));
        let sink = Arc::clone(&log);
        let subscriber = tracing_subscriber::fmt().without_time().with_ansi(false)
            .with_max_level(tracing::Level::INFO)
            .with_writer(move || LogWriter(Arc::clone(&sink))).finish();
        let fatal = tracing::subscriber::with_default(subscriber, || {
            settle_qwen35_prefill_advance(&mut guard, &mut scheduler, &mut slots,
                &mut retained, &mut caches, &mut anchors, None, handle, Ok(advance),
                SlotReply::Unary(send), 0, &supervisor)
        });
        if let Some(fatal) = fatal { panic!("post-forward cancellation failed: {:#}", fatal.error); }
        let text = String::from_utf8(log.lock().unwrap().clone()).unwrap();
        let summaries: Vec<_> = text.lines()
            .filter(|line| line.contains("hf2q.request-decoder-work.v1")).collect();
        assert_eq!(summaries.len(), 1, "{text}");
        let summary = summaries[0];
        assert!(summary.contains(&format!("prefill_seed_tokens={}", usize::from(ready))), "{summary}");
        assert!(summary.contains(&format!("completion_tokens={}", usize::from(ready))), "{summary}");
        assert!(summary.contains("cached_tokens=0") && summary.contains("target_rounds=0")
            && summary.contains("dflash2_rounds=0"), "{summary}");
        assert!(slots.iter().all(Option::is_none));
        assert!(retained[handle.slot_id.0 as usize].is_empty());
        assert_eq!(guard.kv.as_ref().unwrap().sequence_len_for_slot(handle.slot_id).unwrap(), 0);
        assert_eq!(scheduler.stats().in_flight_slots, 0);
        assert!(supervisor.is_healthy());
    }
}