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
//! Quantization-Aware Training (QAT) Module
//!
//! This module implements QAT infrastructure for ruvLLM as specified in ADR-090 Phase 2.
//! QAT enables training models with quantization in the loop, preserving ~90% of reasoning
//! capability at 2-3 bit precision vs ~40% for post-training quantization (PTQ).
//!
//! ## Module Structure
//!
//! ```text
//! qat/
//! +-- mod.rs # This file: public API and documentation
//! +-- config.rs # QatConfig, SteVariant, QuantGranularity
//! +-- ste.rs # Straight-Through Estimator implementations
//! +-- differentiable_quant.rs # DifferentiableQuantizer trait and impls
//! +-- calibration.rs # CalibrationEngine for scale initialization
//! +-- distillation.rs # Knowledge distillation loss (L_task + L_KD)
//! +-- reasoning_loss.rs # Chain-of-thought fidelity loss
//! +-- training_loop.rs # QatTrainer orchestrator
//! +-- lora_qat.rs # LoRA-QAT integration
//! ```
//!
//! ## Architecture
//!
//! The QAT system consists of:
//!
//! 1. **Configuration** (`config.rs`): Training hyperparameters, STE variants, loss weights
//! 2. **STE Backward Pass** (`ste.rs`): Gradient flow through quantization operations
//! 3. **Differentiable Quantizers** (`differentiable_quant.rs`): Forward/backward quantization
//! 4. **Calibration** (`calibration.rs`): Scale initialization from activation statistics
//! 5. **Distillation** (`distillation.rs`): Knowledge distillation from teacher model
//! 6. **Reasoning Loss** (`reasoning_loss.rs`): Chain-of-thought preservation
//! 7. **Training Loop** (`training_loop.rs`): Full pipeline orchestration
//! 8. **LoRA-QAT** (`lora_qat.rs`): Memory-efficient fine-tuning with quantization
//!
//! ## System Invariants (ADR-090)
//!
//! | Invariant | Description | Module |
//! |-----------|-------------|--------|
//! | INV-1 | STE gradient flow - no zero regions except clipping | `ste.rs` |
//! | INV-2 | Scale positivity (alpha > 0) | `differentiable_quant.rs`, `calibration.rs` |
//! | INV-3 | Step size constraint (step = alpha * pi / k) | `differentiable_quant.rs` |
//! | INV-5 | Calibration artifacts serializable | `calibration.rs` |
//! | INV-6 | LoRA rank constraints (r <= min(d_in, d_out)) | `lora_qat.rs` |
//!
//! ## Usage
//!
//! ### Basic QAT Configuration
//!
//! ```rust,ignore
//! use ruvllm::qat::{QatConfig, SteVariant, QuantGranularity};
//!
//! // Create default 4-bit QAT config
//! let config = QatConfig::default();
//!
//! // Create 3-bit Pi-quantization config (PiQ3)
//! let piq3_config = QatConfig::piq3();
//!
//! // Custom configuration with builder pattern
//! let custom = QatConfig::default()
//! .with_bits(3)
//! .with_ste(SteVariant::LearnedStepSize)
//! .with_granularity(QuantGranularity::PerChannel)
//! .with_epochs(5)
//! .with_learning_rate(1e-4);
//!
//! // Validate configuration
//! custom.validate()?;
//! ```
//!
//! ### Using Differentiable Quantizers
//!
//! ```rust,ignore
//! use ruvllm::qat::{QatConfig, DifferentiableQuantizer, PiQuantDifferentiable, create_quantizer};
//!
//! // Create quantizer from config
//! let config = QatConfig::piq3();
//! let mut quantizer = create_quantizer(&config);
//!
//! // Initialize scales from weight statistics
//! let weights: Vec<f32> = load_weights();
//! quantizer.init_scale_from_weights(&weights);
//!
//! // Forward pass (during inference or training)
//! let (q_int, q_dequant) = quantizer.forward(&weights);
//!
//! // Backward pass (during training)
//! let grad_out = compute_loss_gradient(&q_dequant);
//! let grad_weights = quantizer.backward(&weights, &q_dequant, &grad_out);
//! ```
//!
//! ### STE Variants
//!
//! ```rust,ignore
//! use ruvllm::qat::SteVariant;
//!
//! // Standard STE (identity gradient)
//! let standard = SteVariant::Standard;
//! assert_eq!(standard.backward(0.5, 0.4, 1.0), 1.0);
//!
//! // Clipped STE (zero gradient outside range)
//! let clipped = SteVariant::Clipped { clip_val: 1.0 };
//! assert_eq!(clipped.backward(1.5, 1.0, 1.0), 0.0); // Outside range
//!
//! // EWGS (gradient scaling for better convergence)
//! let ewgs = SteVariant::Ewgs { lambda: 0.1 };
//! let grad = ewgs.backward(0.5, 0.3, 1.0); // > 1.0 due to scaling
//!
//! // Learned Step Size (for adaptive quantization)
//! let lsq = SteVariant::LearnedStepSize;
//! ```
//!
//! ## Performance Targets (ADR-090)
//!
//! | Metric | Target | Measurement |
//! |--------|--------|-------------|
//! | QAT step time (0.5B model) | <500 ms | Per training step |
//! | LoRA-QAT memory (0.5B) | <2 GB | Total GPU memory |
//! | Scale gradient computation | <1 ms | Per layer |
//!
//! ## References
//!
//! - ADR-090: Ultra-Low-Bit QAT & Pi-Quantization
//! - Bengio et al., "Estimating or Propagating Gradients Through Stochastic Neurons"
//! - Esser et al., "Learned Step Size Quantization" (LSQ)
//! - Lee et al., "Element-Wise Gradient Scaling" (EWGS)
// ============================================================================
// Module Declarations
// ============================================================================
// ============================================================================
// Public Re-exports
// ============================================================================
// Configuration types
pub use ;
// Differentiable quantization
pub use ;
// Calibration (ADR-090 Phase 2)
pub use ;
// Distillation loss (ADR-090 Phase 2)
pub use ;
// Reasoning loss (ADR-090 Phase 2)
pub use ;
// Training loop (ADR-090 Phase 2)
pub use ;
// LoRA-QAT integration (ADR-090 Phase 2)
pub use ;
// STE SIMD optimizations (platform-specific)
pub use simd as ste_simd;
// ============================================================================
// Module-Level Constants
// ============================================================================
/// Default bit width for QAT
pub const DEFAULT_BITS: u8 = 4;
/// Default learning rate for quantization parameters
pub const DEFAULT_QAT_LR: f32 = 1e-4;
/// Maximum supported bit width
pub const MAX_BITS: u8 = 8;
/// Minimum supported bit width
pub const MIN_BITS: u8 = 2;
// ============================================================================
// Convenience Functions
// ============================================================================
/// Create a PiQ3 quantizer (3-bit Pi-quantization with k=4)
///
/// This is the recommended configuration for 3-bit quantization,
/// providing ~0.5 effective bit improvement over uniform quantization.
///
/// # Example
///
/// ```rust,ignore
/// let quantizer = ruvllm::qat::piq3_quantizer();
/// ```
/// Create a PiQ2 quantizer (2-bit Pi-quantization with k=3)
///
/// For 2-bit quantization. Typically used with incoherence processing
/// (Hadamard rotation) for best results.
///
/// # Example
///
/// ```rust,ignore
/// let quantizer = ruvllm::qat::piq2_quantizer();
/// ```
/// Create a uniform quantizer with standard STE
///
/// # Arguments
///
/// * `bits` - Number of bits (2-8)
///
/// # Example
///
/// ```rust,ignore
/// let quantizer = ruvllm::qat::uniform_quantizer(4);
/// ```
// ============================================================================
// Tests
// ============================================================================