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
use super::*;
use super::super::context_commit_tests::{config, lane_rings, random, rings, runtime, LANES};
use crate::inference::spec_decode::dflash2::config::DFlash2TargetShape;
use crate::inference::spec_decode::dflash2::schema::QWEN38_DFLASH2;
use crate::serve::forward_mlx_shared::MlxQWeight;
use crate::serve::gpu::QuantWeightInfo;
use mlx_native::GgmlType;

fn tokens(length: usize, lane: usize) -> Vec<u32> {
    (0..length).map(|position| ((position * 7 + lane) % 63 + 1) as u32).collect()
}

#[test]
fn checkpoint_binding_survives_prediction_wrap_without_retaining_history() {
    for parent_length in [7, 8, 9, 14_000] {
        let parent = tokens(parent_length, 0);
        let mut live = DFlash2LaneBinding::new(8);
        live.append(&parent, 8);
        let saved_hash = live.hasher.clone();
        live.append(&[2; 16], 8);
        assert!(live.rewind_tokens.is_none());
        assert!(!live.rewind(&parent, 8));
        assert!(matches_binding(parent_length, &saved_hash, &parent));
        let mut changed = parent.clone();
        changed[parent_length - 1] ^= 1;
        assert!(!matches_binding(parent_length, &saved_hash, &changed));
        assert!(!matches_binding(parent_length, &saved_hash, &parent[..parent_length - 1]));
    }
}

#[test]
fn checkpoint_geometry_binds_semantics_and_checks_byte_overflow() {
    let original = config();
    let geometry = Geometry::new(&original, &QWEN38_DFLASH2).unwrap();
    assert_eq!(geometry.shape().unwrap(), [4, 4, 256, 128]);
    let payload = 4 * 4 * 256 * 128 * 2;
    assert_eq!(geometry.owned_bytes(17).unwrap(), payload
        + std::mem::size_of::<DFlash2LaneCheckpoint>()
        + 4 * std::mem::size_of::<usize>() + 17 * 4);
    for changed in [
        DFlash2Config { head_dim: 64, ..original.clone() },
        DFlash2Config { rope_theta: 10_000.0, ..original.clone() },
        DFlash2Config { target_layer_ids: vec![1], ..original.clone() },
    ] {
        assert_ne!(geometry, Geometry::new(&changed, &QWEN38_DFLASH2).unwrap());
    }
    assert!(Geometry { window: usize::MAX, ..geometry }.elements().is_err());
    assert!(Geometry { layers: usize::MAX, ..geometry }.ring_count().is_err());
    assert!(geometry.owned_bytes(usize::MAX).is_err());
    assert!(Geometry::new(&DFlash2Config { sliding_window: 0, ..original }, &QWEN38_DFLASH2).is_err());
}

// The existing tiny native context-commit fixture, plus a dense synthetic target
// of its shape. No model files, downloads or environment configuration are used.
struct Target {
    embedding: MlxQWeight,
    head: MlxQWeight,
}

impl Target {
    fn new(device: &MlxDevice, config: &DFlash2Config) -> Self {
        let dense = |mut seed: u64, scale: f32| {
            let (rows, cols) = (config.vocab_size, config.hidden_size);
            let mut buffer = device.alloc_buffer(rows * cols * 4, DType::F32, vec![rows, cols]).unwrap();
            for value in buffer.as_mut_slice::<f32>().unwrap() {
                *value = scale * random(&mut seed);
            }
            MlxQWeight {
                buffer,
                info: QuantWeightInfo { ggml_dtype: GgmlType::F32, rows, cols },
                affine: None,
                f16_shadow: None,
                decode_record_q6k_m1: std::sync::OnceLock::new(),
            }
        };
        Self { embedding: dense(101, 1.0), head: dense(103, 0.25) }
    }
}

impl DFlash2TargetFamily for Target {
    fn family_name(&self) -> &'static str { "synthetic" }
    fn target_shape(&self) -> DFlash2TargetShape<'_> {
        DFlash2TargetShape {
            architecture: "synthetic", hidden_size: self.embedding.info.cols,
            vocab_size: self.embedding.info.rows, num_hidden_layers: 1,
        }
    }
    fn embedding(&self) -> Result<&MlxQWeight> { Ok(&self.embedding) }
    fn vocabulary_head(&self) -> Result<&MlxQWeight> { Ok(&self.head) }
    fn embedding_scale(&self) -> f32 { 1.0 }
}

fn stage(runtime: &mut DFlash2Runtime, seed: &mut u64) {
    for value in runtime.workspace.captured_target_hidden.as_mut_slice::<f32>().unwrap() {
        *value = 2.0 * random(seed);
    }
    let positions: Vec<_> = runtime.lane_lengths.iter().map(|&length| length as u32).collect();
    prepare_decode_positions(&mut runtime.workspace, &runtime.config, &positions).unwrap();
}

fn bind_committed(runtime: &mut DFlash2Runtime, counts: &[u32; LANES]) {
    for (lane, &count) in counts.iter().enumerate() {
        let length = runtime.lane_lengths[lane];
        runtime.record_lane_tokens(lane, &tokens(length, lane)[length - count as usize..]).unwrap();
    }
}

fn append(
    runtime: &mut DFlash2Runtime, device: &MlxDevice, registry: &mut KernelRegistry,
    mut rows: usize, all_lanes: bool, seed: &mut u64,
) {
    while rows > 0 {
        let count = rows.min(runtime.config.block_size) as u32;
        let counts = if all_lanes { [count; LANES] } else { [count, 0, 0, 0] };
        stage(runtime, seed);
        runtime.commit_target_context(device, registry, &counts).unwrap();
        bind_committed(runtime, &counts);
        rows -= count as usize;
    }
}

fn draft_inputs(runtime: &DFlash2Runtime) -> Vec<u32> {
    runtime.lane_lengths.iter().map(|&length| length as u32).collect()
}

fn output_bits(runtime: &DFlash2Runtime) -> (Vec<u32>, Vec<u32>, Vec<u32>) {
    (
        runtime.proposals().unwrap().to_vec(),
        runtime.verify_rows().unwrap().to_vec(),
        runtime.workspace.logits.as_slice::<f32>().unwrap().iter().map(|value| value.to_bits()).collect(),
    )
}

#[test]
fn lane_checkpoint_restores_wrapped_prediction_and_native_continuation_twins() {
    let _gpu = crate::inference::hf2q_gpu_test_lock();
    let Ok(device) = MlxDevice::new() else { return };
    let mut registry = KernelRegistry::new();
    for staged in [false, true] {
        for parent_length in [248, 280] {
            let mut live = runtime(&device, staged);
            let mut twin = runtime(&device, staged);
            let target = Target::new(&device, &live.config);
            // The pre-ingestion estimate must cover a boundary not yet ingested.
            let estimate = live.lane_checkpoint_owned_bytes(0).unwrap();
            append(&mut live, &device, &mut registry, parent_length, true, &mut 31);
            append(&mut twin, &device, &mut registry, parent_length, true, &mut 31);
            let parent = tokens(parent_length, 0);
            let positions = draft_inputs(&live);
            live.prefetch_draft(&device, &mut registry, &target, &[1; LANES], &positions,
                &[0.0; LANES], 0, &[8; LANES], &[0, 1, 2, 3], &[0.5; LANES * 7], true, None).unwrap();
            let image = live.snapshot_lane_checkpoint(&device, 0).unwrap();
            assert!(!live.prefetch_outstanding());
            assert_eq!(live.prefetch_counts().discarded, 1);
            assert_eq!(image.logical_tokens(), parent_length);
            assert!(image.matches_tokens(&parent));
            assert!(image.owned_bytes() <= estimate);
            assert_eq!(image.rewind_tokens.is_some(), parent_length <= live.config.sliding_window);
            assert_eq!(image.owned_bytes(), image.geometry.owned_bytes(
                if parent_length <= live.config.sliding_window { parent_length } else { 0 }).unwrap());
            let mut owners = CarryOwners::default();
            image.include_carry_owners(&mut owners);
            image.include_carry_owners(&mut owners);
            assert_eq!(owners.bytes(), image.rings.byte_len() as u64);

            append(&mut live, &device, &mut registry, 32, false, &mut 43);
            assert!(!live.align_lane_prefix(0, &parent));
            assert_ne!(lane_rings(&live, 0), lane_rings(&twin, 0));
            let other_lanes: Vec<_> = (1..LANES).map(|lane| lane_rings(&live, lane)).collect();
            // Restore must settle an asynchronous current draft as well as prefetch.
            let positions = draft_inputs(&live);
            live.run_draft_for_gpu_target(&device, &mut registry, &target, &[1; LANES], &positions,
                &[0.0; LANES], 0, &[8; LANES], &[0, 1, 2, 3], &[0.5; LANES * 7], None).unwrap();
            live.validate_lane_checkpoint(0, &image, &parent).unwrap();
            live.prepare_lane_checkpoint_restore(0, &image, &parent).unwrap();
            live.restore_lane_checkpoint(&device, 0, &image).unwrap();
            assert_eq!(live.lane_lengths, twin.lane_lengths);
            assert_eq!(rings(&live), rings(&twin));
            for (lane, expected) in (1..LANES).zip(other_lanes) {
                assert_eq!(lane_rings(&live, lane), expected);
            }
            assert!(live.lane_bindings[0].matches(&parent));

            append(&mut live, &device, &mut registry, 13, false, &mut 73);
            append(&mut twin, &device, &mut registry, 13, false, &mut 73);
            assert_eq!(rings(&live), rings(&twin));
            for runtime in [&mut live, &mut twin] {
                let positions = draft_inputs(runtime);
                runtime.run_draft(&device, &mut registry, &target, &[1; LANES], &positions,
                    &[0.0; LANES], 0, &[8; LANES], &[0.5; LANES * 7], None).unwrap();
            }
            assert_eq!(output_bits(&live), output_bits(&twin),
                "staged={staged} parent={parent_length}: native continuation differs");
        }
    }
}

#[test]
fn lane_checkpoint_preflight_rejects_binding_geometry_and_lane_without_writes() {
    let _gpu = crate::inference::hf2q_gpu_test_lock();
    let Ok(device) = MlxDevice::new() else { return };
    let mut registry = KernelRegistry::new();
    let mut live = runtime(&device, false);
    append(&mut live, &device, &mut registry, 17, true, &mut 89);
    let mut image = live.snapshot_lane_checkpoint(&device, 0).unwrap();
    append(&mut live, &device, &mut registry, 8, false, &mut 97);
    let before = rings(&live);
    let lengths = live.lane_lengths.clone();
    assert!(live.validate_lane_checkpoint(0, &image, &tokens(17, 1)).is_err());
    assert!(live.validate_lane_checkpoint(LANES, &image, &tokens(17, 0)).is_err());
    assert!(live.prepare_lane_checkpoint_restore(0, &image, &tokens(17, 1)).is_err());
    assert!(live.prepare_lane_checkpoint_restore(LANES, &image, &tokens(17, 0)).is_err());
    assert!(live.prepare_lane_checkpoint_change(LANES).is_err());
    assert!(live.restore_lane_checkpoint(&device, LANES, &image).is_err());
    assert!(live.lane_checkpoint_owned_bytes(LANES).is_err());
    image.geometry.window += 1;
    assert!(live.restore_lane_checkpoint(&device, 0, &image).is_err());
    image.geometry.window -= 1;
    image.logical_tokens += 1;
    assert!(live.restore_lane_checkpoint(&device, 0, &image).is_err());
    image.logical_tokens -= 1;
    image.owned_bytes += 1;
    assert!(live.restore_lane_checkpoint(&device, 0, &image).is_err());
    image.owned_bytes -= 1;
    image.rings = image.rings.clone().with_shape(vec![image.geometry.elements().unwrap()]).unwrap();
    assert!(live.restore_lane_checkpoint(&device, 0, &image).is_err());
    assert_eq!(rings(&live), before);
    assert_eq!(live.lane_lengths, lengths);
    assert!(live.lane_bindings[0].matches(&tokens(lengths[0], 0)));
    // A capture between the ring commit and record_lane_tokens cannot publish.
    live.lane_lengths[0] += 1;
    assert!(live.snapshot_lane_checkpoint(&device, 0).is_err());
}

#[test]
fn lane_checkpoint_waits_but_cannot_finalize_external_context_transactions() {
    let _gpu = crate::inference::hf2q_gpu_test_lock();
    let Ok(device) = MlxDevice::new() else { return };
    let mut registry = KernelRegistry::new();
    for detached in [false, true] {
        let mut live = runtime(&device, false);
        append(&mut live, &device, &mut registry, 8, true, &mut 107);
        let image = live.snapshot_lane_checkpoint(&device, 0).unwrap();
        stage(&mut live, &mut 109);
        let counts = [8, 0, 0, 0];
        let submitted = if detached {
            live.submit_target_context_detached(&device, &mut registry, &counts)
        } else {
            live.submit_target_context(&device, &mut registry, &counts)
        }.unwrap();
        assert!(live.snapshot_lane_checkpoint(&device, 0).is_err());
        let after_submission = rings(&live);
        let lengths = live.lane_lengths.clone();
        assert!(live.prepare_lane_checkpoint_restore(0, &image, &tokens(8, 0)).is_err());
        assert!(live.prepare_lane_checkpoint_change(0).is_err());
        assert!(live.restore_lane_checkpoint(&device, 0, &image).is_err());
        assert_eq!(rings(&live), after_submission);
        assert_eq!(live.lane_lengths, lengths);
        // The refusal did not consume the scheduler's completion ownership.
        live.finish_target_context(submitted, &counts, !detached).unwrap();
        bind_committed(&mut live, &counts);
        live.prepare_lane_checkpoint_restore(0, &image, &tokens(8, 0)).unwrap();
        live.prepare_lane_checkpoint_change(0).unwrap();
        let settled = live.snapshot_lane_checkpoint(&device, 0).unwrap();
        assert!(settled.matches_tokens(&tokens(16, 0)));
        live.restore_lane_checkpoint(&device, 0, &image).unwrap();
        assert!(live.lane_bindings[0].matches(&tokens(8, 0)));
    }
}