oxidelm 0.2.0

Bare-metal pure-Rust Transformer engine with reverse-mode autograd, BPE tokenization, and wgpu acceleration
Documentation
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
//! Calibration-light and high-compression weight quantization.
//!
//! - **HQQ** — half-quadratic optimization of scales / zero-points (no activation
//!   calibration required).
//! - **SpQR** — isolate magnitude outliers, quantize the residual dense body.
//! - **QuIP#** — incoherence (Walsh–Hadamard) processing then RTN fold-back.
//! - **AQLM** — residual multi-codebook additive quantization, folded into RTN.

use crate::layers::{Linear, QuantScheme};
use crate::model::CausalLM;
use crate::ptq::PtqError;
use crate::weight_quant::pack_weights_with_scales;

const HQQ_ITERS: usize = 12;
const HQQ_BETA: f32 = 1e2;
const SPQR_OUTLIER_FRAC: f32 = 0.01;
const AQLM_CODEBOOKS: usize = 2;
const AQLM_CODES: usize = 16;

/// Half-Quadratic Quantization: alternating scale/zp / code updates per group.
pub fn apply_hqq(
    model: &mut CausalLM,
    scheme: QuantScheme,
    select: &dyn Fn(&str) -> bool,
) -> Result<Vec<String>, PtqError> {
    if !scheme.format.is_integer() {
        return Err(PtqError::Invalid(
            "HQQ currently supports integer weight formats".into(),
        ));
    }
    if scheme.symmetric {
        return Err(PtqError::Invalid(
            "HQQ requires asymmetric quantization (--asymmetric)".into(),
        ));
    }
    let names = selected_names(model, select);
    for name in &names {
        let linear = find_linear_mut(model, name)
            .ok_or_else(|| PtqError::Invalid(format!("missing linear {name}")))?;
        let matrix = logical_weight_matrix(linear);
        let packed = hqq_pack(
            linear.in_features,
            linear.out_features,
            scheme,
            &matrix,
        )
        .map_err(PtqError::Invalid)?;
        linear
            .set_quantized_weight(crate::layers::QuantizedLinearWeight::from_packed(packed))
            .map_err(PtqError::Invalid)?;
        linear.materialize_dequantized_master();
    }
    Ok(names)
}

/// SpQR-style: clip top-|w| outliers to group median before packing, then restore
/// outliers into the dequantized master so the packed body stays dense/low-bit.
pub fn apply_spqr(
    model: &mut CausalLM,
    scheme: QuantScheme,
    select: &dyn Fn(&str) -> bool,
) -> Result<Vec<String>, PtqError> {
    let names = selected_names(model, select);
    for name in &names {
        let linear = find_linear_mut(model, name)
            .ok_or_else(|| PtqError::Invalid(format!("missing linear {name}")))?;
        let mut matrix = logical_weight_matrix(linear);
        let outliers = extract_outliers(&mut matrix, SPQR_OUTLIER_FRAC);
        write_logical_weights(linear, &matrix);
        linear.quantize_weight_with(scheme);
        linear.materialize_dequantized_master();
        // Overlay outliers onto masters for quality; packed body stays compressed.
        let mut restored = logical_weight_matrix(linear);
        for (index, value) in outliers {
            restored[index] = value;
        }
        write_logical_weights(linear, &restored);
        // Re-pack after overlay so inference uses the corrected approximation.
        linear.quantize_weight_with(scheme);
        linear.materialize_dequantized_master();
    }
    Ok(names)
}

/// QuIP#-style: Walsh–Hadamard incoherence on rows, RTN, inverse transform fold-back.
pub fn apply_quip(
    model: &mut CausalLM,
    scheme: QuantScheme,
    select: &dyn Fn(&str) -> bool,
) -> Result<Vec<String>, PtqError> {
    let names = selected_names(model, select);
    for name in &names {
        let linear = find_linear_mut(model, name)
            .ok_or_else(|| PtqError::Invalid(format!("missing linear {name}")))?;
        let matrix = logical_weight_matrix(linear);
        let transformed = hadamard_rows(&matrix, linear.out_features, linear.in_features);
        write_logical_weights(linear, &transformed);
        linear.quantize_weight_with(scheme);
        linear.materialize_dequantized_master();
        let quantized = logical_weight_matrix(linear);
        let folded = hadamard_rows(&quantized, linear.out_features, linear.in_features);
        write_logical_weights(linear, &folded);
        linear.quantize_weight_with(scheme);
        linear.materialize_dequantized_master();
    }
    Ok(names)
}

/// AQLM-style residual codebook quantization folded into a native packed scheme.
pub fn apply_aqlm(
    model: &mut CausalLM,
    scheme: QuantScheme,
    select: &dyn Fn(&str) -> bool,
) -> Result<Vec<String>, PtqError> {
    let names = selected_names(model, select);
    for name in &names {
        let linear = find_linear_mut(model, name)
            .ok_or_else(|| PtqError::Invalid(format!("missing linear {name}")))?;
        let matrix = logical_weight_matrix(linear);
        let approx = aqlm_approximate(&matrix, linear.in_features);
        write_logical_weights(linear, &approx);
        linear.quantize_weight_with(scheme);
        linear.materialize_dequantized_master();
    }
    Ok(names)
}

fn hqq_pack(
    in_features: usize,
    out_features: usize,
    scheme: QuantScheme,
    matrix_out_in: &[f32],
) -> Result<crate::weight_quant::PackedLinearWeight, String> {
    let scale_count = scheme.scale_count(in_features, out_features);
    let mut scales = vec![1.0f32; scale_count];
    let mut zero_points = vec![0.0f32; scale_count];
    let max_q = scheme.format.int_maximum().unwrap_or(7.0);
    let min_q = -max_q;

    for scale_index in 0..scale_count {
        let values = collect_group(in_features, out_features, scheme, scale_index, matrix_out_in);
        if values.is_empty() {
            continue;
        }
        let mut min_v = values.iter().copied().fold(f32::INFINITY, f32::min);
        let mut max_v = values.iter().copied().fold(f32::NEG_INFINITY, f32::max);
        if !min_v.is_finite() || !max_v.is_finite() || (max_v - min_v).abs() < 1e-12 {
            scales[scale_index] = 1.0;
            zero_points[scale_index] = 0.0;
            continue;
        }
        let mut scale = ((max_v - min_v) / (max_q - min_q)).max(1e-8);
        let mut zp = (min_q - min_v / scale).clamp(min_q, max_q);
        for _ in 0..HQQ_ITERS {
            // Soft threshold around reconstruction residual (half-quadratic proxy).
            let mut w_sum = 0.0f32;
            let mut w_x = 0.0f32;
            let mut w_q = 0.0f32;
            let mut w_qq = 0.0f32;
            for &x in &values {
                let q = (x / scale + zp).round().clamp(min_q, max_q);
                let recon = (q - zp) * scale;
                let residual = (x - recon).abs();
                let weight = 1.0 / (1.0 + HQQ_BETA * residual);
                w_sum += weight;
                w_x += weight * x;
                w_q += weight * q;
                w_qq += weight * q * q;
            }
            if w_sum < 1e-12 || w_qq < 1e-12 {
                break;
            }
            // Update zp then scale from weighted least squares.
            zp = ((w_q / w_sum) - (w_x / (w_sum * scale))).clamp(min_q, max_q);
            let mut num = 0.0f32;
            let mut den = 0.0f32;
            for &x in &values {
                let q = (x / scale + zp).round().clamp(min_q, max_q);
                let recon = (q - zp) * scale;
                let residual = (x - recon).abs();
                let weight = 1.0 / (1.0 + HQQ_BETA * residual);
                num += weight * x * (q - zp);
                den += weight * (q - zp) * (q - zp);
            }
            if den > 1e-12 {
                scale = (num / den).abs().max(1e-8);
            }
            // Shrink observed range using updated params for stability.
            min_v = (min_q - zp) * scale;
            max_v = (max_q - zp) * scale;
            let _ = (min_v, max_v);
        }
        scales[scale_index] = scale;
        zero_points[scale_index] = zp;
    }

    pack_weights_with_scales(
        in_features,
        out_features,
        scheme,
        &scales,
        Some(&zero_points),
        |input, output| matrix_out_in[output * in_features + input],
    )
}

fn collect_group(
    in_features: usize,
    out_features: usize,
    scheme: QuantScheme,
    scale_index: usize,
    matrix_out_in: &[f32],
) -> Vec<f32> {
    let mut values = Vec::new();
    match scheme.granularity {
        crate::layers::QuantGranularity::PerTensor => {
            values.extend_from_slice(matrix_out_in);
        }
        crate::layers::QuantGranularity::PerChannel => {
            let output = scale_index;
            for input in 0..in_features {
                values.push(matrix_out_in[output * in_features + input]);
            }
        }
        crate::layers::QuantGranularity::PerGroup { size } => {
            let size = size.max(1);
            let groups = in_features.div_ceil(size);
            let output = scale_index / groups;
            let group = scale_index % groups;
            let start = group * size;
            let end = (start + size).min(in_features);
            for input in start..end {
                values.push(matrix_out_in[output * in_features + input]);
            }
        }
    }
    let _ = out_features;
    values
}

fn extract_outliers(matrix: &mut [f32], frac: f32) -> Vec<(usize, f32)> {
    if matrix.is_empty() {
        return Vec::new();
    }
    let keep = ((matrix.len() as f32) * frac.clamp(0.0, 0.25)).ceil() as usize;
    let keep = keep.max(1).min(matrix.len());
    let mut order: Vec<usize> = (0..matrix.len()).collect();
    order.sort_by(|&a, &b| {
        matrix[b]
            .abs()
            .partial_cmp(&matrix[a].abs())
            .unwrap_or(std::cmp::Ordering::Equal)
    });
    let mut outliers = Vec::with_capacity(keep);
    let median = {
        let mut sorted = matrix.to_vec();
        sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
        sorted[sorted.len() / 2]
    };
    for &index in order.iter().take(keep) {
        outliers.push((index, matrix[index]));
        matrix[index] = median;
    }
    outliers
}

fn next_pow2(value: usize) -> usize {
    value.next_power_of_two().max(1)
}

fn hadamard_rows(matrix: &[f32], rows: usize, cols: usize) -> Vec<f32> {
    let width = next_pow2(cols);
    let scale = 1.0 / (width as f32).sqrt();
    let mut out = vec![0.0; rows * cols];
    for row in 0..rows {
        let mut buf = vec![0.0f32; width];
        for col in 0..cols {
            buf[col] = matrix[row * cols + col];
        }
        fwht(&mut buf);
        for col in 0..cols {
            out[row * cols + col] = buf[col] * scale;
        }
    }
    out
}

fn fwht(values: &mut [f32]) {
    let n = values.len();
    let mut h = 1usize;
    while h < n {
        for i in (0..n).step_by(h * 2) {
            for j in i..i + h {
                let x = values[j];
                let y = values[j + h];
                values[j] = x + y;
                values[j + h] = x - y;
            }
        }
        h *= 2;
    }
}

fn aqlm_approximate(matrix: &[f32], in_features: usize) -> Vec<f32> {
    let mut residual = matrix.to_vec();
    let mut approx = vec![0.0; matrix.len()];
    for _ in 0..AQLM_CODEBOOKS {
        let codebook = build_codebook(&residual, in_features, AQLM_CODES);
        for (index, value) in residual.iter_mut().enumerate() {
            let code = nearest_code(*value, &codebook);
            approx[index] += code;
            *value -= code;
        }
    }
    approx
}

fn build_codebook(values: &[f32], stride_hint: usize, codes: usize) -> Vec<f32> {
    let _ = stride_hint;
    if values.is_empty() {
        return vec![0.0; codes];
    }
    let mut sorted = values.to_vec();
    sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
    let mut codebook = Vec::with_capacity(codes);
    for i in 0..codes {
        let idx = i * (sorted.len() - 1) / (codes - 1).max(1);
        codebook.push(sorted[idx]);
    }
    codebook
}

fn nearest_code(value: f32, codebook: &[f32]) -> f32 {
    let mut best = codebook[0];
    let mut best_dist = (value - best).abs();
    for &code in codebook.iter().skip(1) {
        let dist = (value - code).abs();
        if dist < best_dist {
            best = code;
            best_dist = dist;
        }
    }
    best
}

fn selected_names(model: &CausalLM, select: &dyn Fn(&str) -> bool) -> Vec<String> {
    model
        .named_linears()
        .into_iter()
        .filter(|(name, _)| select(name))
        .map(|(name, _)| name)
        .collect()
}

fn find_linear_mut<'a>(model: &'a mut CausalLM, name: &str) -> Option<&'a mut Linear> {
    model
        .named_linears_mut()
        .into_iter()
        .find(|(module, _)| module == name)
        .map(|(_, linear)| linear)
}

fn logical_weight_matrix(linear: &Linear) -> Vec<f32> {
    let values = linear.weight.shared_data();
    let mut matrix = vec![0.0; linear.in_features * linear.out_features];
    for input in 0..linear.in_features {
        for output in 0..linear.out_features {
            matrix[output * linear.in_features + input] =
                linear.logical_weight_value(&values, input, output);
        }
    }
    matrix
}

fn write_logical_weights(linear: &mut Linear, matrix: &[f32]) {
    let mut storage = vec![0.0; linear.in_features * linear.out_features];
    for input in 0..linear.in_features {
        for output in 0..linear.out_features {
            let value = matrix[output * linear.in_features + input];
            if linear.transpose_weight {
                storage[output * linear.in_features + input] = value;
            } else {
                storage[input * linear.out_features + output] = value;
            }
        }
    }
    linear.weight.set_data(storage);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::layers::{QuantGranularity, ScaleMethod, WeightQuantization};

    #[test]
    fn hqq_packs_asymmetric_int4() {
        let mut model = CausalLM::new(crate::model::CausalLmConfig {
            vocab_size: 32,
            hidden_size: 16,
            num_layers: 1,
            num_heads: 2,
            num_key_value_heads: 2,
            intermediate_size: 32,
            max_sequence_length: 16,
            rms_norm_epsilon: 1e-5,
            rope_theta: 10_000.0,
            rope_scaling: None,
            eos_token_id: 0,
            seed: 0,
            initializer_std: 0.02,
            tie_word_embeddings: true,
            attention_dropout: 0.0,
            residual_dropout: 0.0,
            embedding_dropout: 0.0,
            use_bias: false,
        })
        .unwrap();
        let scheme = QuantScheme {
            format: WeightQuantization::Int4,
            granularity: QuantGranularity::PerGroup { size: 32 },
            symmetric: false,
            scale_method: ScaleMethod::MinMax,
            percentile: 99.99,
        };
        let names = apply_hqq(&mut model, scheme, &|name| name.contains("q_proj")).unwrap();
        assert!(!names.is_empty());
        assert!(model
            .named_linears()
            .iter()
            .any(|(_, linear)| linear.quantized_weight().is_some()));
    }
}