hf2q 0.1.32

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
//! Pinned DFlash2 artifact identities and family bindings (ADR-067 D0).

use super::config::{DFlash2Config, DFlash2ConfigError, DFlash2TargetShape};
use sha2::{Digest, Sha256};
use std::borrow::Cow;

#[path = "checkpoint_configs.rs"]
mod checkpoint_configs;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DFlash2FamilyAdapter {
    QwenDense,
    QwenMoe,
    Gemma4,
    DeepSeek4,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DFlash2ConfigSchema {
    FlatTransformersV1,
    NestedSpeculatorsV1,
}

/// Architecture, dimensions, bound tensor shapes and tokenizer identity of a
/// Qwen target. A target with the geometry of a pinned descriptor's target
/// is the same base model: a fine-tune or another quantization of it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct QwenTargetGeometry {
    pub architecture: Cow<'static, str>,
    pub hidden_size: u32,
    /// Transformer blocks, the MTP block excluded.
    pub layers: u32,
    pub vocab_size: u32,
    pub attention_heads: u32,
    pub attention_kv_heads: u32,
    pub head_dim: u32,
    pub linear_key_heads: u32,
    pub linear_value_heads: u32,
    pub linear_key_head_dim: u32,
    pub linear_value_head_dim: u32,
    pub full_attention_interval: u32,
    /// Dense FFN rows; zero for a MoE target.
    pub intermediate_size: u32,
    /// Zero for a dense target, as are the three fields below.
    pub moe_experts: u32,
    pub moe_top_k: u32,
    pub moe_intermediate_size: u32,
    pub moe_shared_intermediate_size: u32,
    /// `token_embd.weight`, which the drafter's target adapter embeds with.
    pub embedding_shape: [usize; 2],
    /// The output head the adapter projects the vocabulary with.
    pub head_shape: [usize; 2],
    /// `qwen35::tokenizer::tokenizer_identity` of the GGUF: supported pre-type,
    /// effective vocabulary, ordered merges, atomic specials and serving stops.
    pub tokenizer_sha256: Cow<'static, str>,
}

impl QwenTargetGeometry {
    /// The first field in which this geometry differs from `pinned`.
    pub fn mismatch(&self, pinned: &Self) -> Option<String> {
        macro_rules! compare {
            ($($field:ident),+ $(,)?) => {
                $(if self.$field != pinned.$field {
                    return Some(format!(
                        "{} {:?} != pinned {:?}",
                        stringify!($field),
                        self.$field,
                        pinned.$field
                    ));
                })+
            };
        }
        compare!(
            architecture,
            hidden_size,
            layers,
            vocab_size,
            attention_heads,
            attention_kv_heads,
            head_dim,
            linear_key_heads,
            linear_value_heads,
            linear_key_head_dim,
            linear_value_head_dim,
            full_attention_interval,
            intermediate_size,
            moe_experts,
            moe_top_k,
            moe_intermediate_size,
            moe_shared_intermediate_size,
            embedding_shape,
            head_shape,
            tokenizer_sha256,
        );
        None
    }
}

/// Effective tokenizer identity derived from both pinned Qwen target headers.
/// The same semantics also admit compatible external conversions and fine-tunes.
const QWEN_TOKENIZER_SHA256: &str =
    "baa78d2301c7f7a6ddff10ee9440884816d8ffaf414dae224ca567bb814312ab";

/// Geometry of `Qwen/Qwen3.8-27B`.
pub static QWEN38_TARGET_GEOMETRY: QwenTargetGeometry = QwenTargetGeometry {
    architecture: Cow::Borrowed("qwen35"),
    hidden_size: 5_120,
    layers: 64,
    vocab_size: 248_320,
    attention_heads: 24,
    attention_kv_heads: 4,
    head_dim: 256,
    linear_key_heads: 16,
    linear_value_heads: 48,
    linear_key_head_dim: 128,
    linear_value_head_dim: 128,
    full_attention_interval: 4,
    intermediate_size: 17_408,
    moe_experts: 0,
    moe_top_k: 0,
    moe_intermediate_size: 0,
    moe_shared_intermediate_size: 0,
    embedding_shape: [248_320, 5_120],
    head_shape: [248_320, 5_120],
    tokenizer_sha256: Cow::Borrowed(QWEN_TOKENIZER_SHA256),
};

/// Geometry of `Qwen/Qwen3.6-35B-A3B`.
pub static QWEN36_TARGET_GEOMETRY: QwenTargetGeometry = QwenTargetGeometry {
    architecture: Cow::Borrowed("qwen35moe"),
    hidden_size: 2_048,
    layers: 40,
    vocab_size: 248_320,
    attention_heads: 16,
    attention_kv_heads: 2,
    head_dim: 256,
    linear_key_heads: 16,
    linear_value_heads: 32,
    linear_key_head_dim: 128,
    linear_value_head_dim: 128,
    full_attention_interval: 4,
    intermediate_size: 0,
    moe_experts: 256,
    moe_top_k: 8,
    moe_intermediate_size: 512,
    moe_shared_intermediate_size: 512,
    embedding_shape: [248_320, 2_048],
    head_shape: [248_320, 2_048],
    tokenizer_sha256: Cow::Borrowed(QWEN_TOKENIZER_SHA256),
};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DFlash2CheckpointDescriptor {
    pub id: &'static str,
    pub family_adapter: DFlash2FamilyAdapter,
    pub config_schema: DFlash2ConfigSchema,
    pub repository: &'static str,
    pub revision: &'static str,
    pub config_sha256: &'static str,
    pub weights_sha256: &'static str,
    pub weights_bytes: u64,
    pub tensor_count: usize,
    pub target_architecture: &'static str,
    pub target_model: &'static str,
    /// Canonical hf2q source-bundle identity of the exact target weights.
    /// `None` keeps production activation unavailable for this descriptor.
    pub target_source_sha256: Option<&'static str>,
    /// Geometry of that target. A target with this geometry qualifies for
    /// the drafter without the source identity; `None` admits pinned pairs
    /// only.
    pub target_geometry: Option<&'static QwenTargetGeometry>,
    pub target_hidden_size: usize,
    pub target_vocab_size: usize,
    pub target_layers: usize,
    pub reference_repository: &'static str,
    pub reference_revision: &'static str,
}

pub const QWEN38_DFLASH2: DFlash2CheckpointDescriptor = DFlash2CheckpointDescriptor {
    id: "qwen38-27b-dflash2-50307d4c",
    family_adapter: DFlash2FamilyAdapter::QwenDense,
    config_schema: DFlash2ConfigSchema::FlatTransformersV1,
    repository: "z-lab/Qwen3.8-27B-DFlash2",
    revision: "50307d4c4cde6860d4eee73e2547cd786fe8e8a4",
    config_sha256: "873e3556509b0da06e29654ba00d4944888d4b5e8a33afde25f7eb27d321e980",
    weights_sha256: "67fc76d68dc5a9415511a4f394ef744d67510cd20e93b37cc2cc7d28e4bab65c",
    weights_bytes: 3_848_817_896,
    tensor_count: 81,
    target_architecture: "qwen35",
    target_model: "Qwen/Qwen3.8-27B",
    target_source_sha256: Some("73ded708c49c2d0a47c790ce1d6181e848ac7591dab741de83dbb57218cc6873"),
    target_geometry: Some(&QWEN38_TARGET_GEOMETRY),
    target_hidden_size: 5_120,
    target_vocab_size: 248_320,
    target_layers: 64,
    reference_repository: "splash",
    reference_revision: "031a25a6125af2d7acf7096580afe56eb33d65bc",
};

pub const QWEN36_DFLASH2: DFlash2CheckpointDescriptor = DFlash2CheckpointDescriptor {
    id: "qwen36-35b-a3b-dflash2-51ef7b69",
    family_adapter: DFlash2FamilyAdapter::QwenMoe,
    config_schema: DFlash2ConfigSchema::FlatTransformersV1,
    repository: "incoai/Qwen3.6-35B-A3B-DFlash2",
    revision: "51ef7b6923ad6c14cb1bb41c37a9041446496ab6",
    config_sha256: "86d2e8e57e7c70bb867240708d00c0535ae9ed3c828dbdcb21584471c7bbce59",
    weights_sha256: "d1f16c0ff85afbe6166fabfae998af3ec16fa11da87da4391b5e0e0a7c796a4d",
    weights_bytes: 1_052_513_456,
    tensor_count: 96,
    target_architecture: "qwen35moe",
    target_model: "Qwen/Qwen3.6-35B-A3B",
    target_source_sha256: Some("851811f43867ae177636f0c536bb98c33731d992ce357831809a1eda5eb974ca"),
    target_geometry: Some(&QWEN36_TARGET_GEOMETRY),
    target_hidden_size: 2_048,
    target_vocab_size: 248_320,
    target_layers: 40,
    reference_repository: "splash",
    reference_revision: "031a25a6125af2d7acf7096580afe56eb33d65bc",
};

pub const GEMMA4_E2B_DFLASH2: DFlash2CheckpointDescriptor = DFlash2CheckpointDescriptor {
    id: "gemma4-e2b-dflash2-6eb3ade2",
    family_adapter: DFlash2FamilyAdapter::Gemma4,
    config_schema: DFlash2ConfigSchema::NestedSpeculatorsV1,
    repository: "rasyosef/gemma-4-E2B-it-dflash2",
    revision: "6eb3ade2e4ae841974d692e9edc177dcaa7e20ff",
    config_sha256: "44a97c599f09cf1b32859841e1b0ba4a5b8124b250b236db0e1335c545306f3e",
    weights_sha256: "842a33bc4f38cc054dc5df0784ee332b49b2a824956d60795d8e94f269024fee",
    weights_bytes: 646_093_904,
    tensor_count: 81,
    target_architecture: "gemma4",
    target_model: "google/gemma-4-E2B-it",
    target_source_sha256: None,
    target_geometry: None,
    target_hidden_size: 1_536,
    target_vocab_size: 262_144,
    target_layers: 35,
    reference_repository: "rasyosef/train-dspark-draft-models",
    reference_revision: "ca13206b7399cc54ee1fecf7a4c233741121289d",
};

pub const GEMMA4_31B_DFLASH2: DFlash2CheckpointDescriptor = DFlash2CheckpointDescriptor {
    id: "gemma4-31b-dflash2-b0cd01b4",
    family_adapter: DFlash2FamilyAdapter::Gemma4,
    config_schema: DFlash2ConfigSchema::NestedSpeculatorsV1,
    repository: "RedHatAI/gemma-4-31B-it-speculator.dflash2",
    revision: "b0cd01b4918aae6b6388272950c4f9851734674b",
    config_sha256: "2eb1b6cad1c0736b7735a1b3f12f398d7e835c00e2f0c97c1e40ed9eb90135ba",
    weights_sha256: "3e82ec115f31020a81a69c6145aee727996ea9d83664f6285728e6bff0dd6b0f",
    weights_bytes: 5_494_652_680,
    tensor_count: 81,
    target_architecture: "gemma4",
    target_model: "google/gemma-4-31B-it",
    target_source_sha256: None,
    target_geometry: None,
    target_hidden_size: 5_376,
    target_vocab_size: 262_144,
    target_layers: 60,
    reference_repository: "vllm-project/speculators",
    reference_revision: "442ce1bf4e2f70dd0b45f36e63bd5849fbb35912",
};

pub const KNOWN_DFLASH2_CHECKPOINTS: &[DFlash2CheckpointDescriptor] = &[
    QWEN38_DFLASH2,
    QWEN36_DFLASH2,
    GEMMA4_E2B_DFLASH2,
    GEMMA4_31B_DFLASH2,
];

#[derive(Debug, thiserror::Error)]
pub enum DFlash2SchemaError {
    #[error("unknown DFlash2 checkpoint {repository}@{revision}")]
    Unknown {
        repository: String,
        revision: String,
    },
    #[error("DFlash2 artifact IO error: {0}")]
    Io(#[from] std::io::Error),
    #[error("DFlash2 artifact {artifact} has {actual}, expected {expected}")]
    Identity {
        artifact: &'static str,
        actual: String,
        expected: String,
    },
    #[error(transparent)]
    Config(#[from] DFlash2ConfigError),
}

pub fn descriptor(
    repository: &str,
    revision: &str,
) -> Result<&'static DFlash2CheckpointDescriptor, DFlash2SchemaError> {
    KNOWN_DFLASH2_CHECKPOINTS
        .iter()
        .find(|entry| entry.repository == repository && entry.revision == revision)
        .ok_or_else(|| DFlash2SchemaError::Unknown {
            repository: repository.into(),
            revision: revision.into(),
        })
}

fn sha256(bytes: &[u8]) -> String {
    hex::encode(Sha256::digest(bytes))
}

impl DFlash2CheckpointDescriptor {
    /// Exact cached checkpoint geometry for pre-load planning, without IO.
    pub fn allocation_config(&self) -> Result<&'static DFlash2Config, DFlash2SchemaError> {
        static QWEN36: std::sync::OnceLock<DFlash2Config> = std::sync::OnceLock::new();
        static QWEN38: std::sync::OnceLock<DFlash2Config> = std::sync::OnceLock::new();
        let bytes = self.allocation_config_bytes()?;
        let cache = if self == &QWEN36_DFLASH2 { &QWEN36 } else { &QWEN38 };
        if let Some(config) = cache.get() {
            return Ok(config);
        }
        let config = self.parse_config(bytes)?;
        Ok(cache.get_or_init(|| config))
    }

    pub(crate) fn allocation_config_bytes(&self) -> Result<&'static [u8], DFlash2SchemaError> {
        if self == &QWEN36_DFLASH2 {
            Ok(checkpoint_configs::QWEN36_CONFIG_JSON)
        } else if self == &QWEN38_DFLASH2 {
            Ok(checkpoint_configs::QWEN38_CONFIG_JSON)
        } else {
            Err(DFlash2SchemaError::Identity {
                artifact: "allocation config descriptor",
                actual: format!("{}@{}", self.repository, self.revision),
                expected: "canonical Qwen3.6 or Qwen3.8 DFlash2 descriptor".into(),
            })
        }
    }

    pub fn parse_config(&self, bytes: &[u8]) -> Result<DFlash2Config, DFlash2SchemaError> {
        let actual = sha256(bytes);
        if actual != self.config_sha256 {
            return Err(DFlash2SchemaError::Identity {
                artifact: "config.json SHA256",
                actual,
                expected: self.config_sha256.into(),
            });
        }
        let config =
            DFlash2Config::from_json_str(std::str::from_utf8(bytes).map_err(|error| {
                DFlash2ConfigError::Invalid(format!("config.json must be UTF-8: {error}"))
            })?)?;
        config.validate_target(DFlash2TargetShape {
            architecture: self.target_architecture,
            hidden_size: self.target_hidden_size,
            vocab_size: self.target_vocab_size,
            num_hidden_layers: self.target_layers,
        })?;
        Ok(config)
    }

    pub fn verify_weights_bytes(&self, bytes: &[u8]) -> Result<(), DFlash2SchemaError> {
        if bytes.len() as u64 != self.weights_bytes {
            return Err(DFlash2SchemaError::Identity {
                artifact: "model.safetensors byte length",
                actual: bytes.len().to_string(),
                expected: self.weights_bytes.to_string(),
            });
        }
        let actual = sha256(bytes);
        if actual != self.weights_sha256 {
            return Err(DFlash2SchemaError::Identity {
                artifact: "model.safetensors SHA256",
                actual,
                expected: self.weights_sha256.into(),
            });
        }
        Ok(())
    }

    pub fn validate_target_identity(
        &self,
        architecture: &str,
        source_model: &str,
    ) -> Result<(), DFlash2SchemaError> {
        if architecture != self.target_architecture {
            return Err(DFlash2SchemaError::Identity {
                artifact: "target architecture",
                actual: architecture.into(),
                expected: self.target_architecture.into(),
            });
        }
        if source_model != self.target_model {
            return Err(DFlash2SchemaError::Identity {
                artifact: "target source model",
                actual: source_model.into(),
                expected: self.target_model.into(),
            });
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn unsupported_allocation_config_descriptors_fail_closed() {
        let mut revision = QWEN36_DFLASH2;
        revision.revision = "main";
        let mut identity = QWEN36_DFLASH2;
        identity.config_sha256 = QWEN38_DFLASH2.config_sha256;
        let mut family = QWEN36_DFLASH2;
        family.family_adapter = DFlash2FamilyAdapter::QwenDense;
        let mut geometry = QWEN36_DFLASH2;
        geometry.target_hidden_size = QWEN38_DFLASH2.target_hidden_size;
        for descriptor in [
            GEMMA4_E2B_DFLASH2,
            GEMMA4_31B_DFLASH2,
            revision,
            identity,
            family,
            geometry,
        ] {
            assert!(matches!(
                descriptor.allocation_config(),
                Err(DFlash2SchemaError::Identity {
                    artifact: "allocation config descriptor",
                    ..
                })
            ));
        }
    }

    #[test]
    fn unknown_revision_is_fail_closed() {
        let error = descriptor(QWEN38_DFLASH2.repository, "main").unwrap_err();
        assert!(matches!(error, DFlash2SchemaError::Unknown { .. }));
    }

    #[test]
    fn cross_family_target_is_rejected() {
        let error = GEMMA4_E2B_DFLASH2
            .validate_target_identity("qwen35", GEMMA4_E2B_DFLASH2.target_model)
            .unwrap_err();
        assert!(matches!(
            error,
            DFlash2SchemaError::Identity {
                artifact: "target architecture",
                ..
            }
        ));
    }
}