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
//! Role-aware DeepSeek-V4 weight residency.
//!
//! Matmul weights stay in their GGUF representation. Only tensors consumed
//! by elementwise kernels are expanded to F32; hash routing remains I32.

use std::collections::HashMap;

use mlx_native::gguf::GgufFile;
use mlx_native::ops::quantized_matmul_ggml::GgmlType;
use mlx_native::{DType, MlxBuffer, MlxDevice, MlxError};
use thiserror::Error;

use super::weights::{validate_tensor_catalog, TensorRole, WeightCatalogError};
use super::Deepseek4Config;
use crate::inference::models::route_default::Resolved;

#[derive(Debug, Error)]
pub enum WeightResidencyError {
    #[error(transparent)]
    Catalog(#[from] WeightCatalogError),
    #[error("tensor '{name}' with role {role:?} cannot use GGML storage {actual:?}")]
    StorageType {
        name: String,
        role: TensorRole,
        actual: GgmlType,
    },
    #[error("failed to make DeepSeek-V4 tensor '{name}' resident: {source}")]
    Load {
        name: String,
        #[source]
        source: MlxError,
    },
    #[error("resident tensor '{name}' has dtype {actual}, expected {expected}")]
    LoadedDtype {
        name: String,
        expected: DType,
        actual: DType,
    },
    #[error("resident tensor '{name}' uses {actual} bytes, expected {expected}")]
    LoadedBytes {
        name: String,
        expected: u64,
        actual: u64,
    },
    #[error("resident-byte accounting overflowed while adding tensor '{name}'")]
    ByteOverflow { name: String },
    #[error("tensor '{name}' disappeared after exact catalog validation")]
    MissingAfterCatalog { name: String },
}

#[derive(Debug, Error, Eq, PartialEq)]
pub enum WeightLookupError {
    #[error("DeepSeek-V4 tensor '{name}' is not resident")]
    Missing { name: String },
    #[error("DeepSeek-V4 tensor '{name}' has role {actual:?}, requested {expected:?}")]
    RoleMismatch {
        name: String,
        expected: TensorRole,
        actual: TensorRole,
    },
}

struct ResidentTensor {
    role: TensorRole,
    ggml_type: GgmlType,
    shape: Vec<usize>,
    buffer: MlxBuffer,
}

/// Kernel family of the few-row (`m <= 8`) F16 and Q8_0 products one model
/// issues. Chosen once at model load, so the serial, joint-decode, prefill
/// and verifier graphs of a process share one family. Both families produce
/// the same bits; they differ in how many dispatches and weight reads a
/// joint step costs.
///
/// `Default` is [`Self::Stock`], the family fixtures build with; the serving
/// default is [`Self::resolve`] of an unset switch ([`Self::RowExact`]).
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum MatvecKernels {
    /// The routes of every release through v0.1.29 (kill switch): the F16
    /// `m = 1` matvec (L9) with tiled kernels above it, the canonical GGUF
    /// matvec family (Q8_0 NR2) for block storage; independent F16 rows run
    /// one dispatch per row.
    #[default]
    Stock,
    /// mlx-native `row_exact_matvec_stock` where it reproduces the stock
    /// route bitwise: F16 at `m = 1` and independent F16 rows, Q8_0 at
    /// `m <= 8` and Q8_0 grouped output-A at `rows <= 8` while the stock Q8_0
    /// route at that width is the NR2 matvec (not under
    /// `HF2Q_Q8_0_MV_NR2=0`, nor at 2..=8 rows under `HF2Q_DECODE_MV_EXT=1`;
    /// those products keep the stock route). One dispatch reads the weights
    /// once for all rows, and every row is the stock one-row result.
    RowExact,
}

impl MatvecKernels {
    /// Process switch read by [`Self::from_env`].
    pub const ENV: &'static str = "HF2Q_DEEPSEEK_ROW_EXACT_MATVEC";

    /// `HF2Q_DEEPSEEK_ROW_EXACT_MATVEC`: unset or `1` selects
    /// [`Self::RowExact`] (the release-gate family), `0` [`Self::Stock`]
    /// (kill switch); anything else is an error.
    pub(crate) fn from_env() -> anyhow::Result<Resolved<Self>> {
        Self::resolve(std::env::var_os(Self::ENV).as_deref())
    }

    /// Resolution rule of [`Self::from_env`].
    pub(crate) fn resolve(value: Option<&std::ffi::OsStr>) -> anyhow::Result<Resolved<Self>> {
        super::route_defaults::resolve_zero_one(Self::ENV, value, Self::Stock, Self::RowExact)
    }
}

pub struct RawMatrixRef<'a> {
    pub buffer: &'a MlxBuffer,
    pub ggml_type: GgmlType,
    pub shape: &'a [usize],
    /// The owning model's few-row kernel family.
    pub matvec: MatvecKernels,
}

pub struct Deepseek4Weights {
    tensors: HashMap<String, ResidentTensor>,
    resident_bytes: u64,
    file_backed_bytes: u64,
    anonymous_bytes: u64,
    mapped_segment_count: usize,
    matvec: MatvecKernels,
    _device: MlxDevice,
}

impl Deepseek4Weights {
    /// Validate the complete verifier catalog, then load each tensor according
    /// to its runtime role. No allocation occurs before catalog and storage
    /// types have both passed validation.
    pub fn load_from_gguf(
        gguf: &GgufFile,
        cfg: &Deepseek4Config,
        device: MlxDevice,
    ) -> Result<Self, WeightResidencyError> {
        let specs = validate_tensor_catalog(gguf, cfg)?;
        for spec in &specs {
            let info = gguf.tensor_info(&spec.name).ok_or_else(|| {
                WeightResidencyError::MissingAfterCatalog {
                    name: spec.name.clone(),
                }
            })?;
            validate_storage_type(&spec.name, spec.role, info.ggml_type)?;
        }

        let mut tensors = HashMap::with_capacity(specs.len());
        let mut resident_bytes = 0_u64;
        let mut file_backed_bytes = 0_u64;
        let mut anonymous_bytes = 0_u64;
        let map_raw_weights = std::env::var("HF2Q_DEEPSEEK_MMAP_WEIGHTS").as_deref() != Ok("0");
        let mapped_tensor_data = map_raw_weights
            .then(|| {
                gguf.map_tensor_data(&device)
                    .map_err(|source| WeightResidencyError::Load {
                        name: "GGUF tensor data".to_string(),
                        source,
                    })
            })
            .transpose()?;
        let mapped_segment_count = mapped_tensor_data
            .as_ref()
            .map_or(0, |mapping| mapping.segment_count());
        for spec in specs {
            let info = gguf.tensor_info(&spec.name).ok_or_else(|| {
                WeightResidencyError::MissingAfterCatalog {
                    name: spec.name.clone(),
                }
            })?;
            let buffer = match spec.role {
                TensorRole::RawMatrix | TensorRole::IntegerLookupI32 if map_raw_weights => {
                    mapped_tensor_data
                        .as_ref()
                        .expect("mapped tensor data exists when mmap weights are enabled")
                        .load_tensor(&spec.name)
                        .map_err(|source| WeightResidencyError::Load {
                            name: spec.name.clone(),
                            source,
                        })?
                }
                TensorRole::RawMatrix | TensorRole::IntegerLookupI32 => gguf
                    .load_tensor(&spec.name, &device)
                    .map_err(|source| WeightResidencyError::Load {
                        name: spec.name.clone(),
                        source,
                    })?,
                TensorRole::ElementwiseF32 => {
                    gguf.load_tensor_f32(&spec.name, &device)
                        .map_err(|source| WeightResidencyError::Load {
                            name: spec.name.clone(),
                            source,
                        })?
                }
            };
            validate_loaded_buffer(&spec.name, spec.role, info.byte_len, &buffer)?;
            let bytes = u64::try_from(buffer.data_byte_len()).map_err(|_| {
                WeightResidencyError::ByteOverflow {
                    name: spec.name.clone(),
                }
            })?;
            resident_bytes = resident_bytes.checked_add(bytes).ok_or_else(|| {
                WeightResidencyError::ByteOverflow {
                    name: spec.name.clone(),
                }
            })?;
            if buffer.is_file_backed() {
                file_backed_bytes = file_backed_bytes.checked_add(bytes).ok_or_else(|| {
                    WeightResidencyError::ByteOverflow {
                        name: spec.name.clone(),
                    }
                })?;
            } else {
                anonymous_bytes = anonymous_bytes.checked_add(bytes).ok_or_else(|| {
                    WeightResidencyError::ByteOverflow {
                        name: spec.name.clone(),
                    }
                })?;
            }
            tensors.insert(
                spec.name,
                ResidentTensor {
                    role: spec.role,
                    ggml_type: info.ggml_type,
                    shape: info.shape.clone(),
                    buffer,
                },
            );
        }
        Ok(Self {
            tensors,
            resident_bytes,
            file_backed_bytes,
            anonymous_bytes,
            mapped_segment_count,
            matvec: MatvecKernels::Stock,
            _device: device,
        })
    }

    pub fn len(&self) -> usize {
        self.tensors.len()
    }

    pub fn is_empty(&self) -> bool {
        self.tensors.is_empty()
    }

    /// Sum of logical Metal tensor bytes, including F32 expansion only for
    /// elementwise state and excluding page-alignment padding.
    pub fn resident_bytes(&self) -> u64 {
        self.resident_bytes
    }

    /// Immutable raw weight bytes served directly from the GGUF mapping.
    pub fn file_backed_bytes(&self) -> u64 {
        self.file_backed_bytes
    }

    /// Weight bytes copied or expanded into anonymous Metal allocations.
    pub fn anonymous_bytes(&self) -> u64 {
        self.anonymous_bytes
    }

    /// Number of shared Metal resources spanning the file-backed tensors.
    pub fn mapped_segment_count(&self) -> usize {
        self.mapped_segment_count
    }

    /// Select the few-row kernel family; the model loader calls this once,
    /// before any graph is built.
    pub fn set_matvec_kernels(&mut self, matvec: MatvecKernels) {
        self.matvec = matvec;
    }

    pub fn tensor(
        &self,
        name: &str,
        expected: TensorRole,
    ) -> Result<&MlxBuffer, WeightLookupError> {
        let entry = self
            .tensors
            .get(name)
            .ok_or_else(|| WeightLookupError::Missing {
                name: name.to_string(),
            })?;
        if entry.role != expected {
            return Err(WeightLookupError::RoleMismatch {
                name: name.to_string(),
                expected,
                actual: entry.role,
            });
        }
        Ok(&entry.buffer)
    }

    pub fn raw_matrix(&self, name: &str) -> Result<&MlxBuffer, WeightLookupError> {
        self.tensor(name, TensorRole::RawMatrix)
    }

    pub fn raw_matrix_ref(&self, name: &str) -> Result<RawMatrixRef<'_>, WeightLookupError> {
        let entry = self
            .tensors
            .get(name)
            .ok_or_else(|| WeightLookupError::Missing {
                name: name.to_string(),
            })?;
        if entry.role != TensorRole::RawMatrix {
            return Err(WeightLookupError::RoleMismatch {
                name: name.to_string(),
                expected: TensorRole::RawMatrix,
                actual: entry.role,
            });
        }
        Ok(RawMatrixRef {
            buffer: &entry.buffer,
            ggml_type: entry.ggml_type,
            shape: &entry.shape,
            matvec: self.matvec,
        })
    }

    pub fn f32_state(&self, name: &str) -> Result<&MlxBuffer, WeightLookupError> {
        self.tensor(name, TensorRole::ElementwiseF32)
    }

    pub fn i32_lookup(&self, name: &str) -> Result<&MlxBuffer, WeightLookupError> {
        self.tensor(name, TensorRole::IntegerLookupI32)
    }
}

fn validate_storage_type(
    name: &str,
    role: TensorRole,
    actual: GgmlType,
) -> Result<(), WeightResidencyError> {
    let valid = match role {
        TensorRole::RawMatrix => !matches!(actual, GgmlType::I16 | GgmlType::I32),
        TensorRole::ElementwiseF32 => actual != GgmlType::I32,
        TensorRole::IntegerLookupI32 => actual == GgmlType::I32,
    };
    if valid {
        Ok(())
    } else {
        Err(WeightResidencyError::StorageType {
            name: name.to_string(),
            role,
            actual,
        })
    }
}

fn validate_loaded_buffer(
    name: &str,
    role: TensorRole,
    disk_bytes: usize,
    buffer: &MlxBuffer,
) -> Result<(), WeightResidencyError> {
    let expected_dtype = match role {
        TensorRole::ElementwiseF32 => Some(DType::F32),
        TensorRole::IntegerLookupI32 => Some(DType::I32),
        TensorRole::RawMatrix => None,
    };
    if let Some(expected) = expected_dtype {
        if buffer.dtype() != expected {
            return Err(WeightResidencyError::LoadedDtype {
                name: name.to_string(),
                expected,
                actual: buffer.dtype(),
            });
        }
    } else if !matches!(buffer.dtype(), DType::F32 | DType::F16 | DType::U8) {
        return Err(WeightResidencyError::LoadedDtype {
            name: name.to_string(),
            expected: DType::U8,
            actual: buffer.dtype(),
        });
    }

    let expected = match role {
        TensorRole::ElementwiseF32 => buffer
            .element_count()
            .checked_mul(DType::F32.size_of())
            .and_then(|bytes| u64::try_from(bytes).ok()),
        _ => u64::try_from(disk_bytes).ok(),
    }
    .ok_or_else(|| WeightResidencyError::ByteOverflow {
        name: name.to_string(),
    })?;
    let actual =
        u64::try_from(buffer.data_byte_len()).map_err(|_| WeightResidencyError::ByteOverflow {
            name: name.to_string(),
        })?;
    if actual != expected {
        return Err(WeightResidencyError::LoadedBytes {
            name: name.to_string(),
            expected,
            actual,
        });
    }
    Ok(())
}

#[cfg(test)]
pub(super) fn metadata_storage_valid(spec: &super::weights::TensorSpec, actual: GgmlType) -> bool {
    validate_storage_type(&spec.name, spec.role, actual).is_ok()
}