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
//! Explicit target-family adapters for DFlash2 embedding and vocabulary heads.

use super::{
    config::{DFlash2Config, DFlash2TargetShape},
    forward::DFlash2VocabularyHead,
    tensors::DFlash2ModelTensors,
    workspace::DFlash2Workspace,
};
use crate::{
    inference::models::{gemma4::model::MlxModelWeights, qwen35::model::Qwen35Model},
    serve::forward_mlx_shared::MlxQWeight,
};
use anyhow::{anyhow, ensure, Context, Result};
use mlx_native::ops::dflash2_attention_pack::{
    dispatch_dflash2_mask_rows_f32, DFlash2MaskRowsParams,
};
use mlx_native::ops::repacked_gguf_mm::PreparedGgufWeightPlanes;
use mlx_native::ops::ActivationPrecision;
use mlx_native::{CommandEncoder, GgmlType, KernelRegistry, MlxBuffer, MlxDevice};

/// Family-neutral target hidden-capture destination for one packed verify.
#[derive(Clone, Copy)]
pub struct DFlash2TargetCapture<'a> {
    pub layer_ids: &'a [usize],
    pub output: &'a MlxBuffer,
    /// Physical draft-ring lane for each packed target window.
    pub lane_indices: &'a [usize],
    /// GPU-selected live prefix length for every physical draft-ring lane.
    pub verify_rows: &'a MlxBuffer,
    pub lanes: usize,
    pub rows_per_lane: usize,
    pub feature_width: usize,
}

pub trait DFlash2TargetFamily {
    fn family_name(&self) -> &'static str;
    fn target_shape(&self) -> DFlash2TargetShape<'_>;
    fn embedding(&self) -> Result<&MlxQWeight>;
    fn vocabulary_head(&self) -> Result<&MlxQWeight>;
    /// Prepared planes of the vocabulary head that the target owns and shares
    /// with its own head, when the family offers them. The default prepares
    /// nothing: the staged draft then prepares a head of its own.
    fn shared_prepared_vocabulary_head(
        &self,
        _registry: &mut KernelRegistry,
        _device: &MlxDevice,
    ) -> Result<Option<&PreparedGgufWeightPlanes>> {
        Ok(None)
    }
    fn embedding_scale(&self) -> f32;
    /// Whether target verification should budget rows from selector confidence.
    ///
    /// Dense targets keep every row because reducing their packed width did
    /// not qualify. MoE targets benefit because fewer rows avoid expert work.
    fn adaptive_verify_budget(&self) -> bool {
        false
    }

    fn target_capture<'a>(
        &self,
        config: &'a DFlash2Config,
        workspace: &'a DFlash2Workspace,
        lane_indices: &'a [usize],
    ) -> Result<DFlash2TargetCapture<'a>> {
        ensure!(
            workspace.rows_per_lane == config.block_size
                && workspace.max_lanes <= 4
                && config.fc_input_dim()
                    == config.target_layer_ids.len() * self.target_shape().hidden_size,
            "DFlash2 {} target capture geometry does not match its workspace",
            self.family_name()
        );
        Ok(DFlash2TargetCapture {
            layer_ids: &config.target_layer_ids,
            output: &workspace.captured_target_hidden,
            lane_indices,
            verify_rows: &workspace.verify_rows,
            lanes: workspace.max_lanes,
            rows_per_lane: workspace.rows_per_lane,
            feature_width: config.fc_input_dim(),
        })
    }

    fn validate(&self, config: &DFlash2Config) -> Result<()> {
        config
            .validate_target(self.target_shape())
            .map_err(anyhow::Error::from)
    }
}

pub struct QwenDFlash2Adapter<'a> {
    model: &'a Qwen35Model,
}

impl<'a> QwenDFlash2Adapter<'a> {
    pub fn new(model: &'a Qwen35Model, config: &DFlash2Config) -> Result<Self> {
        let adapter = Self { model };
        adapter.validate(config)?;
        adapter.embedding()?;
        adapter.vocabulary_head()?;
        Ok(adapter)
    }
}

impl DFlash2TargetFamily for QwenDFlash2Adapter<'_> {
    fn family_name(&self) -> &'static str {
        "qwen35"
    }

    fn target_shape(&self) -> DFlash2TargetShape<'_> {
        DFlash2TargetShape {
            architecture: self.family_name(),
            hidden_size: self.model.cfg.hidden_size as usize,
            vocab_size: self.model.cfg.vocab_size as usize,
            num_hidden_layers: self.model.cfg.num_hidden_layers as usize,
        }
    }

    fn embedding(&self) -> Result<&MlxQWeight> {
        self.model
            .token_embd_native
            .as_ref()
            .context("Qwen DFlash2 requires native token_embd.weight")
    }

    fn vocabulary_head(&self) -> Result<&MlxQWeight> {
        self.model
            .resolved_native_output_head()?
            .map(|(weight, _)| weight)
            .context("Qwen DFlash2 requires a native output head")
    }

    fn shared_prepared_vocabulary_head(
        &self,
        registry: &mut KernelRegistry,
        device: &MlxDevice,
    ) -> Result<Option<&PreparedGgufWeightPlanes>> {
        self.model.shared_prepared_output_head(registry, device)
    }

    fn embedding_scale(&self) -> f32 {
        1.0
    }

    fn adaptive_verify_budget(&self) -> bool {
        self.model.cfg.moe.is_some()
    }
}

pub struct GemmaDFlash2Adapter<'a> {
    model: &'a MlxModelWeights,
}

impl<'a> GemmaDFlash2Adapter<'a> {
    pub fn new(model: &'a MlxModelWeights, config: &DFlash2Config) -> Result<Self> {
        let adapter = Self { model };
        adapter.validate(config)?;
        adapter.embedding()?;
        adapter.vocabulary_head()?;
        Ok(adapter)
    }
}

impl DFlash2TargetFamily for GemmaDFlash2Adapter<'_> {
    fn family_name(&self) -> &'static str {
        "gemma4"
    }

    fn target_shape(&self) -> DFlash2TargetShape<'_> {
        DFlash2TargetShape {
            architecture: self.family_name(),
            hidden_size: self.model.hidden_size,
            vocab_size: self.model.vocab_size,
            num_hidden_layers: self.model.layers.len(),
        }
    }

    fn embedding(&self) -> Result<&MlxQWeight> {
        Ok(&self.model.embed_weight)
    }

    fn vocabulary_head(&self) -> Result<&MlxQWeight> {
        Ok(self.model.resolved_lm_head())
    }

    fn embedding_scale(&self) -> f32 {
        (self.model.hidden_size as f32).sqrt()
    }
}

fn dispatch_embedding_rows(
    encoder: &mut CommandEncoder,
    registry: &mut KernelRegistry,
    device: &MlxDevice,
    weight: &MlxQWeight,
    token_ids: &mlx_native::MlxBuffer,
    output: &mlx_native::MlxBuffer,
    rows: usize,
    precision: ActivationPrecision,
) -> Result<()> {
    ensure!(
        weight.affine.is_none(),
        "DFlash2 embedding cannot use affine metadata"
    );
    let vocab_size = weight.info.rows;
    let embed_dim = weight.info.cols;
    match weight.info.ggml_dtype {
        GgmlType::F32 | GgmlType::F16 | GgmlType::BF16 => mlx_native::ops::embedding_dense::embedding_gather_dense_with_precision(
            encoder,
            registry,
            device,
            &weight.buffer,
            token_ids,
            output,
            &mlx_native::EmbeddingDenseParams {
                vocab_size,
                embed_dim,
                n_tokens: rows,
            },
            precision,
        )?,
        GgmlType::Q4_0 => mlx_native::ops::embedding_q4_0::embedding_gather_q4_0_with_precision(
            encoder,
            registry,
            device,
            &weight.buffer,
            token_ids,
            output,
            &mlx_native::EmbeddingQ4_0Params {
                vocab_size,
                embed_dim,
                n_tokens: rows,
            },
            precision,
        )?,
        GgmlType::Q5_0 => mlx_native::ops::embedding_q5_0::embedding_gather_q5_0_with_precision(
            encoder,
            registry,
            device,
            &weight.buffer,
            token_ids,
            output,
            &mlx_native::EmbeddingQ5_0Params {
                vocab_size,
                embed_dim,
                n_tokens: rows,
            },
            precision,
        )?,
        GgmlType::Q2_K => mlx_native::ops::embedding_q2_k::embedding_gather_q2_k_with_precision(
            encoder,
            registry,
            device,
            &weight.buffer,
            token_ids,
            output,
            &mlx_native::EmbeddingQ2KParams {
                vocab_size,
                embed_dim,
                n_tokens: rows,
            },
            precision,
        )?,
        GgmlType::Q4_K => mlx_native::ops::embedding_q4_k::embedding_gather_q4_k_with_precision(
            encoder,
            registry,
            device,
            &weight.buffer,
            token_ids,
            output,
            &mlx_native::EmbeddingQ4KParams {
                vocab_size,
                embed_dim,
                n_tokens: rows,
            },
            precision,
        )?,
        GgmlType::Q5_K => mlx_native::ops::embedding_kquant::embedding_gather_q5_k_with_precision(
            encoder,
            registry,
            device,
            &weight.buffer,
            token_ids,
            output,
            &mlx_native::EmbeddingQ5KParams {
                vocab_size,
                embed_dim,
                n_tokens: rows,
            },
            precision,
        )?,
        GgmlType::Q6_K => mlx_native::ops::embedding_kquant::embedding_gather_q6_k_with_precision(
            encoder,
            registry,
            device,
            &weight.buffer,
            token_ids,
            output,
            &mlx_native::EmbeddingQ6KParams {
                vocab_size,
                embed_dim,
                n_tokens: rows,
            },
            precision,
        )?,
        GgmlType::Q8_0 => mlx_native::ops::embedding_q8_0::embedding_gather_q8_0_with_precision(
            encoder,
            registry,
            device,
            &weight.buffer,
            token_ids,
            output,
            &mlx_native::EmbeddingQ8_0Params {
                vocab_size,
                embed_dim,
                n_tokens: rows,
            },
            precision,
        )?,
        other => return Err(anyhow!("DFlash2 embedding does not support {other:?}")),
    }
    Ok(())
}

/// Fill the physical anchor+mask rows and encode the target family's native
/// embedding table directly into the reusable draft input buffer.
pub fn dispatch_dflash2_input<T: DFlash2TargetFamily>(
    tensors: &DFlash2ModelTensors,
    encoder: &mut CommandEncoder,
    registry: &mut KernelRegistry,
    device: &MlxDevice,
    config: &DFlash2Config,
    adapter: &T,
    anchors: &[u32],
    workspace: &mut DFlash2Workspace,
) -> Result<()> {
    if anchors.len() != workspace.max_lanes {
        return Err(anyhow!(
            "DFlash2 anchor count {} != workspace lanes {}",
            anchors.len(),
            workspace.max_lanes
        ));
    }
    adapter.validate(config)?;
    let tokens = workspace.row_tokens.as_mut_slice::<u32>()?;
    for (lane, anchor) in anchors.iter().copied().enumerate() {
        ensure!(
            (anchor as usize) < config.vocab_size,
            "DFlash2 anchor {anchor} exceeds vocabulary {}",
            config.vocab_size
        );
        let lane_rows = &mut tokens[lane * config.block_size..(lane + 1) * config.block_size];
        lane_rows.fill(config.mask_token_id);
        lane_rows[0] = anchor;
    }
    let embedding = adapter.embedding()?;
    ensure!(
        embedding.info.cols == config.hidden_size,
        "DFlash2 {} embedding width {} != draft hidden {}",
        adapter.family_name(),
        embedding.info.cols,
        config.hidden_size
    );
    let rows = workspace.max_lanes * config.block_size;
    let scale = adapter.embedding_scale();
    let precision = if matches!(
        &tensors.context_projection, super::tensors::DFlash2Projection::Af4G64 { .. }
    ) {
        ActivationPrecision::Bf16
    } else {
        ActivationPrecision::F32
    };
    // Only the last writer rounds retained rows. A nonunit scale must consume
    // the unrounded gather; the optional mask writes exact stored BF16 values.
    dispatch_embedding_rows(
        encoder,
        registry,
        device,
        embedding,
        &workspace.row_tokens,
        &workspace.hidden[0],
        rows,
        if scale == 1.0 { precision } else { ActivationPrecision::F32 },
    )?;
    encoder.memory_barrier();
    if scale != 1.0 {
        mlx_native::ops::elementwise::scalar_mul_f32_with_precision(
            encoder,
            registry,
            device.metal_device(),
            &workspace.hidden[0],
            &workspace.hidden[0],
            rows * config.hidden_size,
            scale,
            precision,
        )?;
        encoder.memory_barrier();
    }
    if let Some(mask_embedding) = tensors.mask_embedding.as_ref() {
        dispatch_dflash2_mask_rows_f32(
            encoder,
            registry,
            device,
            mask_embedding,
            &workspace.hidden[0],
            DFlash2MaskRowsParams {
                lanes: workspace.max_lanes as u32,
                rows: config.block_size as u32,
                hidden: config.hidden_size as u32,
            },
        )?;
        encoder.memory_barrier();
    }
    Ok(())
}

/// The target's vocabulary head for one draft command.
///
/// `reads_prepared_head` says whether the command projects its vocabulary
/// through prepared head planes
/// ([`reads_prepared_head`](super::staged::reads_prepared_head)). Only then
/// is the target asked for its shared planes: asking prepares them, and a
/// command that runs the stock head would never read them.
pub fn target_vocabulary_head<'a, T: DFlash2TargetFamily>(
    adapter: &'a T,
    registry: &mut KernelRegistry,
    device: &MlxDevice,
    reads_prepared_head: bool,
) -> Result<DFlash2VocabularyHead<'a>> {
    let weight = adapter.vocabulary_head()?;
    if !reads_prepared_head {
        return Ok(DFlash2VocabularyHead::Native(weight));
    }
    Ok(
        match adapter.shared_prepared_vocabulary_head(registry, device)? {
            Some(prepared) => DFlash2VocabularyHead::SharedPrepared { weight, prepared },
            None => DFlash2VocabularyHead::Native(weight),
        },
    )
}