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
//! Independent, lane-only images of the physical draft rings.
//!
//! A full physical window is intentional even before wrap: restoring after a
//! prediction wrapped must also undo writes into the formerly unused slots.
//! Neither workspace views nor model tensors are retained by an image.

use super::*;
use crate::inference::models::qwen35::carry_memory::CarryOwners;
use mlx_native::DType;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Geometry {
    layers: usize,
    heads: usize,
    window: usize,
    dim: usize,
    identity: [u8; 32],
}

impl Geometry {
    fn new(config: &DFlash2Config, descriptor: &DFlash2CheckpointDescriptor) -> Result<Self> {
        ensure!(config.num_hidden_layers > 0 && config.num_key_value_heads > 0
            && config.sliding_window > 0 && config.head_dim > 0,
            "invalid DFlash2 checkpoint ring geometry");
        let mut hash = Sha256::new();
        hash.update(b"hf2q-dflash2-lane-image-v1");
        for text in [descriptor.id, config.draft_model_type.as_str()] {
            hash.update(text.len().to_le_bytes());
            hash.update(text.as_bytes());
        }
        for value in [config.hidden_size, config.intermediate_size, config.num_hidden_layers,
            config.num_attention_heads, config.num_key_value_heads, config.head_dim,
            config.vocab_size, config.num_target_layers, config.max_position_embeddings,
            config.sliding_window, config.block_size, config.conv_group_size,
            config.conv_kernel_size, config.selector_rank, config.selector_top_k,
            config.target_layer_ids.len(), config.layer_types.len()]
        {
            hash.update(value.to_le_bytes());
        }
        for value in &config.target_layer_ids {
            hash.update(value.to_le_bytes());
        }
        for value in &config.layer_types {
            hash.update([match value {
                super::super::config::DFlash2LayerType::FullAttention => 0,
                super::super::config::DFlash2LayerType::SlidingAttention => 1,
            }]);
        }
        hash.update(config.rms_norm_eps.to_bits().to_le_bytes());
        hash.update(config.rope_theta.to_bits().to_le_bytes());
        hash.update(config.mask_token_id.to_le_bytes());
        for value in [config.final_logit_softcapping, config.output_multiplier] {
            hash.update([u8::from(value.is_some())]);
            hash.update(value.unwrap_or_default().to_bits().to_le_bytes());
        }
        Ok(Self {
            layers: config.num_hidden_layers,
            heads: config.num_key_value_heads,
            window: config.sliding_window,
            dim: config.head_dim,
            identity: hash.finalize().into(),
        })
    }

    fn lane_elements(self) -> Result<usize> {
        self.heads.checked_mul(self.window).and_then(|n| n.checked_mul(self.dim))
            .context("DFlash2 checkpoint lane geometry overflow")
    }

    fn ring_count(self) -> Result<usize> {
        self.layers.checked_mul(2).context("DFlash2 checkpoint layer count overflow")
    }

    fn elements(self) -> Result<usize> {
        self.lane_elements()?.checked_mul(self.ring_count()?)
            .context("DFlash2 checkpoint image geometry overflow")
    }

    fn shape(self) -> Result<[usize; 4]> {
        Ok([self.ring_count()?, self.heads, self.window, self.dim])
    }

    fn owned_bytes(self, prefix_tokens: usize) -> Result<usize> {
        self.elements()?.checked_mul(DType::BF16.size_of())
            .and_then(|n| n.checked_add(std::mem::size_of::<DFlash2LaneCheckpoint>()))
            .and_then(|n| n.checked_add(4 * std::mem::size_of::<usize>()))
            .and_then(|n| prefix_tokens.checked_mul(std::mem::size_of::<u32>())
                .and_then(|prefix| n.checked_add(prefix)))
            .context("DFlash2 checkpoint owned-byte count overflow")
    }
}

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

/// Immutable, independently owned physical rings and exact logical token binding.
/// The native allocation is private: no mutable view or multi-lane root escapes.
/// Hash state binds arbitrarily long prefixes without retaining their history;
/// the optional rewind prefix is bounded by one window and right-sized.
pub(crate) struct DFlash2LaneCheckpoint {
    geometry: Geometry,
    rings: MlxBuffer,
    logical_tokens: usize,
    hasher: Sha256,
    rewind_tokens: Option<Box<[u32]>>,
    owned_bytes: usize,
}

impl DFlash2LaneCheckpoint {
    /// Requested owned payload: image value, buffer shape, one native ring
    /// allocation and bounded token prefix. External Arc headers are caller-owned;
    /// native allocator/driver overhead is not a requested tensor payload.
    pub(crate) fn owned_bytes(&self) -> usize {
        self.owned_bytes
    }

    pub(crate) fn logical_tokens(&self) -> usize {
        self.logical_tokens
    }

    pub(crate) fn matches_tokens(&self, tokens: &[u32]) -> bool {
        matches_binding(self.logical_tokens, &self.hasher, tokens)
    }

    pub(crate) fn include_carry_owners(&self, owners: &mut CarryOwners) {
        owners.include(&self.rings);
    }

    fn validate(&self, geometry: Geometry) -> Result<()> {
        ensure!(self.geometry == geometry, "incompatible DFlash2 checkpoint geometry or identity");
        ensure!(self.logical_tokens <= u32::MAX as usize,
            "DFlash2 checkpoint logical cursor exceeds native position range");
        let prefix_tokens = match &self.rewind_tokens {
            Some(prefix) => {
                ensure!(self.logical_tokens <= geometry.window
                    && self.matches_tokens(prefix), "corrupted DFlash2 checkpoint token binding");
                prefix.len()
            }
            None => {
                ensure!(self.logical_tokens > geometry.window,
                    "DFlash2 checkpoint is missing its bounded rewind binding");
                0
            }
        };
        let bytes = geometry.elements()?.checked_mul(DType::BF16.size_of())
            .context("DFlash2 checkpoint ring byte count overflow")?;
        ensure!(self.rings.dtype() == DType::BF16
            && self.rings.shape() == geometry.shape()?
            && self.rings.byte_offset() == 0
            && self.rings.byte_len() == bytes && self.rings.data_byte_len() == bytes,
            "corrupted DFlash2 checkpoint ring allocation");
        ensure!(self.owned_bytes == geometry.owned_bytes(prefix_tokens)?,
            "corrupted DFlash2 checkpoint owned-byte count");
        // This allocation is immutable and has never been a GPU output.
        self.rings.as_slice::<u16>().context("read DFlash2 checkpoint rings")?;
        Ok(())
    }
}

impl DFlash2Runtime {
    fn checkpoint_geometry(&self, lane: usize) -> Result<Geometry> {
        ensure!(lane < self.workspace.max_lanes && lane < self.lane_lengths.len()
            && lane < self.lane_bindings.len(), "DFlash2 checkpoint lane {lane} is out of range");
        let geometry = Geometry::new(&self.config, self.descriptor)?;
        ensure!(self.workspace.ring_keys.len() == geometry.layers
            && self.workspace.ring_values.len() == geometry.layers,
            "DFlash2 checkpoint workspace layer count mismatch");
        let shape = [self.workspace.max_lanes, geometry.heads, geometry.window, geometry.dim];
        let elements = geometry.lane_elements()?.checked_mul(self.workspace.max_lanes)
            .context("DFlash2 checkpoint workspace geometry overflow")?;
        let bytes = elements.checked_mul(DType::BF16.size_of())
            .context("DFlash2 checkpoint workspace byte count overflow")?;
        for ring in self.workspace.ring_keys.iter().chain(&self.workspace.ring_values) {
            ensure!(ring.dtype() == DType::BF16 && ring.shape() == shape
                && ring.data_byte_len() == bytes && ring.is_cpu_writable()
                && !ring.contents_ptr().is_null() && ring.byte_offset() % 2 == 0,
                "DFlash2 checkpoint workspace ring geometry mismatch");
        }
        Ok(geometry)
    }

    /// Pre-ingestion upper bound, independent of the lane's current cursor:
    /// cue folding asks before the prefix it will capture has been ingested.
    pub(crate) fn lane_checkpoint_owned_bytes(&self, lane: usize) -> Result<usize> {
        let geometry = self.checkpoint_geometry(lane)?;
        geometry.owned_bytes(geometry.window)
    }

    pub(crate) fn snapshot_lane_checkpoint(
        &mut self, device: &MlxDevice, lane: usize,
    ) -> Result<DFlash2LaneCheckpoint> {
        let geometry = self.checkpoint_geometry(lane)?;
        self.prepare_lane_checkpoint_change(lane)?;
        let binding = &self.lane_bindings[lane];
        ensure!(binding.tokens == self.lane_lengths[lane],
            "DFlash2 checkpoint lane {lane} ring cursor is not token-bound");
        ensure!(binding.tokens <= u32::MAX as usize,
            "DFlash2 checkpoint logical cursor exceeds native position range");
        let rewind_tokens = binding.rewind_tokens.as_deref().map(Box::<[u32]>::from);
        let prefix_tokens = rewind_tokens.as_deref().map_or(0, <[u32]>::len);
        let owned_bytes = geometry.owned_bytes(prefix_tokens)?;
        let elements = geometry.elements()?;
        let mut rings = device.alloc_buffer(elements * DType::BF16.size_of(),
            DType::BF16, geometry.shape()?.to_vec())
            .context("allocate independent DFlash2 lane checkpoint")?;
        let lane_elements = geometry.lane_elements()?;
        let start = lane * lane_elements;
        for (source, destination) in self.workspace.ring_keys.iter()
            .chain(&self.workspace.ring_values)
            .zip(rings.as_mut_slice::<u16>()?.chunks_exact_mut(lane_elements))
        {
            destination.copy_from_slice(&source.as_slice::<u16>()?[start..start + lane_elements]);
        }
        let image = DFlash2LaneCheckpoint {
            geometry, rings, logical_tokens: binding.tokens,
            hasher: binding.hasher.clone(), rewind_tokens, owned_bytes,
        };
        image.validate(geometry)?;
        Ok(image)
    }

    /// Immutable geometry/token preflight only: this does not establish producer
    /// quiescence. Use prepare_lane_checkpoint_restore before target mutation.
    /// No workspace views, command waits, cursor mutation or ring writes occur.
    pub(crate) fn validate_lane_checkpoint(
        &self, lane: usize, image: &DFlash2LaneCheckpoint, tokens: &[u32],
    ) -> Result<()> {
        image.validate(self.checkpoint_geometry(lane)?)?;
        ensure!(image.matches_tokens(tokens), "DFlash2 checkpoint token binding mismatch");
        Ok(())
    }

    /// Settled paired preflight, inside the supervised transaction and BEFORE
    /// either target or drafter restore writes. Reject invalid images before
    /// waiting, then settle current/next drafts and refuse externally unfinalized
    /// context transactions. Settlement cannot change the validated geometry or
    /// immutable image, so no repeated hash or image allocation is necessary.
    pub(crate) fn prepare_lane_checkpoint_restore(
        &mut self, lane: usize, image: &DFlash2LaneCheckpoint, tokens: &[u32],
    ) -> Result<()> {
        self.validate_lane_checkpoint(lane, image, tokens)?;
        self.prepare_lane_checkpoint_change(lane)
    }

    /// Quiesce a destination before a supervised checkpoint transaction, including
    /// an explicitly excluded target-only restore with no draft image. This does
    /// not clear or copy rings, allocate an image, or publish cursor/binding state.
    pub(crate) fn prepare_lane_checkpoint_change(&mut self, lane: usize) -> Result<()> {
        ensure!(lane < self.workspace.max_lanes && lane < self.lane_lengths.len()
            && lane < self.lane_bindings.len(), "DFlash2 checkpoint lane {lane} is out of range");
        self.settle_prefetch()?;
        self.require_context_finalized()
    }

    /// A successful preflight does not excuse transaction supervision: if the
    /// paired target restore already wrote and this settlement fails, invalidate
    /// both sides. All fallible native views are acquired before the first copy;
    /// once copies begin, ring writes and final cursor/binding publication cannot
    /// fail. Pending external context transactions must first be finalized.
    pub(crate) fn restore_lane_checkpoint(
        &mut self, _device: &MlxDevice, lane: usize, image: &DFlash2LaneCheckpoint,
    ) -> Result<()> {
        let geometry = self.checkpoint_geometry(lane)?;
        image.validate(geometry)?;
        self.prepare_lane_checkpoint_change(lane)?;
        let lane_elements = geometry.lane_elements()?;
        let start = lane * lane_elements;
        let source = image.rings.as_slice::<u16>()?;
        // Borrow every destination first: a failed view cannot leave half an image.
        let destinations = self.workspace.ring_keys.iter_mut()
            .chain(self.workspace.ring_values.iter_mut())
            .map(|ring| Ok(&mut ring.as_mut_slice::<u16>()?[start..start + lane_elements]))
            .collect::<Result<Vec<_>>>()?;
        let rewind_tokens = image.rewind_tokens.as_deref().map(|prefix| {
            let mut tokens = self.lane_bindings[lane].rewind_tokens.take()
                .unwrap_or_else(|| Vec::with_capacity(geometry.window));
            tokens.clear();
            tokens.extend_from_slice(prefix);
            tokens
        });
        let binding = DFlash2LaneBinding {
            hasher: image.hasher.clone(), tokens: image.logical_tokens, rewind_tokens,
        };
        for (destination, source) in destinations.into_iter().zip(source.chunks_exact(lane_elements)) {
            destination.copy_from_slice(source);
        }
        self.lane_lengths[lane] = image.logical_tokens;
        self.lane_bindings[lane] = binding;
        Ok(())
    }
}

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

/// Shared serving/runtime recovery fixtures. These write deterministic ring
/// bytes with real physical modulo addressing; they do not simulate model math.
#[cfg(test)]
impl DFlash2Runtime {
    /// Byte-only recovery fixture. Its small rings and 64-wide heads are not
    /// executable native attention geometry; use the prefill fixture for forwards.
    pub(crate) fn test_for_lane_checkpoints(
        device: &MlxDevice, lanes: usize, window: usize,
    ) -> Result<Self> {
        Self::test_checkpoint_runtime(device, lanes, DFlash2Config {
            hidden_size: 64,
            intermediate_size: 64,
            num_attention_heads: 1,
            num_key_value_heads: 1,
            head_dim: 64,
            conv_group_size: 4,
            sliding_window: window,
            ..super::context_commit_tests::config()
        })
    }

    /// Executable native-prefill fixture. The reviewed wrap cases choose windows
    /// of at least 256; this is a fixture bound, NOT a native attention minimum
    /// (the native window constraint is only window > rows). Never round inputs.
    pub(crate) fn test_for_prefill_checkpoints(
        device: &MlxDevice, lanes: usize, window: usize, target_hidden_size: usize,
    ) -> Result<Self> {
        ensure!(target_hidden_size > 0 && target_hidden_size % 128 == 0,
            "native prefill checkpoint fixture target width must be a positive multiple of 128");
        ensure!(window >= 256,
            "reviewed prefill checkpoint fixture requires window >= 256 (not a native minimum)");
        let config = DFlash2Config {
            hidden_size: target_hidden_size,
            intermediate_size: target_hidden_size,
            num_attention_heads: target_hidden_size / 128,
            num_key_value_heads: 1,
            head_dim: 128,
            // Sixteen convolution groups produce 64 AF4-aligned dynamic rows.
            conv_group_size: target_hidden_size / 16,
            sliding_window: window,
            ..super::context_commit_tests::config()
        };
        let packed_len = window.checked_add(config.block_size - 1)
            .context("native prefill checkpoint fixture packed length overflow")?;
        mlx_native::ops::dflash2_attention_pack::DFlash2AttentionPackParams {
            lanes: u32::try_from(lanes)?,
            q_heads: u32::try_from(config.num_attention_heads)?,
            kv_heads: u32::try_from(config.num_key_value_heads)?,
            head_dim: u32::try_from(config.head_dim)?,
            rows: u32::try_from(config.block_size)?,
            window: u32::try_from(window)?,
            packed_len: u32::try_from(packed_len)?,
            max_commit: u32::try_from(config.block_size)?,
        }.validate().context("validate native prefill checkpoint fixture geometry")?;
        Self::test_checkpoint_runtime(device, lanes, config)
    }

    fn test_checkpoint_runtime(
        device: &MlxDevice, lanes: usize, config: DFlash2Config,
    ) -> Result<Self> {
        let window = config.sliding_window;
        let workspace = DFlash2Workspace::new(device, &config, lanes, false)?;
        let tensors = DFlash2ModelTensors::synthetic_af4_g64(device, &config, 5);
        Ok(Self {
            descriptor: &super::super::schema::QWEN38_DFLASH2,
            config,
            tensors,
            workspace,
            lane_lengths: vec![0; lanes],
            lane_bindings: (0..lanes).map(|_| DFlash2LaneBinding::new(window)).collect(),
            verify_budget: DFlash2VerifyBudget::default(),
            gpu_target_tokens: false,
            proposal_repetition_enabled: false,
            submitted_draft: Mutex::new(None),
            prefetched: None,
            prefetch_counts: DraftPrefetchCounts::default(),
            budget_epoch: 0,
            context_positions: None,
        })
    }

    pub(crate) fn test_bind_lane_checkpoint_tokens(
        &mut self, lane: usize, tokens: &[u32],
    ) -> Result<()> {
        let geometry = self.checkpoint_geometry(lane)?;
        self.settle_prefetch()?;
        self.require_context_finalized()?;
        let lane_elements = geometry.lane_elements()?;
        let start = lane * lane_elements;
        for (ring_index, ring) in self.workspace.ring_keys.iter_mut()
            .chain(self.workspace.ring_values.iter_mut()).enumerate()
        {
            let values = &mut ring.as_mut_slice::<u16>()?[start..start + lane_elements];
            values.fill(0);
            for (position, token) in tokens.iter().enumerate().skip(tokens.len().saturating_sub(geometry.window)) {
                for head in 0..geometry.heads {
                    for dim in 0..geometry.dim {
                        let offset = (head * geometry.window + position % geometry.window) * geometry.dim + dim;
                        values[offset] = token.wrapping_mul(31)
                            .wrapping_add((position as u32).wrapping_mul(17))
                            .wrapping_add((ring_index * 13 + head * 7 + dim) as u32) as u16;
                    }
                }
            }
        }
        let mut binding = DFlash2LaneBinding::new(geometry.window);
        binding.append(tokens, geometry.window);
        self.lane_lengths[lane] = tokens.len();
        self.lane_bindings[lane] = binding;
        Ok(())
    }

    pub(crate) fn test_lane_checkpoint_bits(&mut self, lane: usize) -> Result<Vec<Vec<u16>>> {
        let geometry = self.checkpoint_geometry(lane)?;
        self.settle_prefetch()?;
        self.require_context_finalized()?;
        let lane_elements = geometry.lane_elements()?;
        let start = lane * lane_elements;
        self.workspace.ring_keys.iter().chain(&self.workspace.ring_values)
            .map(|ring| Ok(ring.as_slice::<u16>()?[start..start + lane_elements].to_vec()))
            .collect()
    }
}