| 1 | // Shared load-time turboquant machinery for the config-driven decoder. |
| 2 | // |
| 3 | // STEP 0 refactor: the inlined qwen2 forward (RmsNorm/RoPE/GQA-flash-decode/SwiGLU + |
| 4 | // the Model struct) moved to `model.rs` behind the `Model`/`SequenceMixer` traits. |
| 5 | // What remains here is the arch-agnostic LOAD-TIME machinery the design says to reuse |
| 6 | // verbatim (design §1.2, §1.4): the `Proj` projection enum (dense fp16 OR compressed |
| 7 | // QWeight), the `WeightSource` turboquant encoder, and `WeightStats`. These know only |
| 8 | // linear shapes — zero architecture knowledge — so every arch's wiring calls the same |
| 9 | // `quant` / `quant_group` / `quant_lm_head` here. |
| 10 | |
| 11 | use anyhow::Result; |
| 12 | use candle_core::{DType, Device, Tensor}; |
| 13 | use candle_nn::VarBuilder; |
| 14 | use std::collections::HashMap; |
| 15 | |
| 16 | use crate::qlinear::{QGroup, QWeight}; |
| 17 | use crate::turboquant::{encode, TqConfig, LLOYD_MAX_3BIT}; |
| 18 | |
| 19 | /// A projection that is either a dense fp16 Linear or a compressed QWeight. |
| 20 | /// (`Dense` is the documented fp16 fallback; the fast path uses `Quant` for all |
| 21 | /// seven projections.) Design §1.2 promotes this toward the shared `QLinear`. |
| 22 | #[allow(dead_code)] |
| 23 | pub enum Proj { |
| 24 | Dense(candle_nn::Linear), |
| 25 | Quant(QWeight), |
| 26 | } |
| 27 | |
| 28 | impl Proj { |
| 29 | pub fn forward(&self, x: &Tensor) -> Result<Tensor> { |
| 30 | match self { |
| 31 | Proj::Dense(l) => Ok(candle_core::Module::forward(l, x)?), |
| 32 | Proj::Quant(q) => q.forward(x), |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | /// forward + residual, with the residual folded into the qmatvec store |
| 37 | /// epilogue on the quant path (COCO_FUSE_RESID). Dense keeps the plain add. |
| 38 | pub fn forward_resid(&self, x: &Tensor, resid: &Tensor) -> Result<Tensor> { |
| 39 | match self { |
| 40 | Proj::Dense(l) => Ok((candle_core::Module::forward(l, x)? + resid)?), |
| 41 | Proj::Quant(q) => q.forward_resid(x, resid), |
| 42 | } |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | /// Holds the raw fp16 weights pulled from safetensors, used to build projections. |
| 47 | /// We turboquant-encode the target weights at build time (data-free) and hand |
| 48 | /// the compressed `TqWeight` to the GPU; non-target weights stay dense. |
| 49 | pub struct WeightSource { |
| 50 | pub tensors: HashMap<String, Tensor>, // CPU f32 copies of the quant-target tensors |
| 51 | pub device: Device, |
| 52 | pub dtype: DType, |
| 53 | pub cfg: TqConfig, |
| 54 | pub total_compressed_bytes: usize, |
| 55 | pub total_fp16_bytes: usize, |
| 56 | pub n_quant: usize, |
| 57 | } |
| 58 | |
| 59 | impl WeightSource { |
| 60 | /// Bias tensor (if present) on device, in model dtype. Removed from the map. |
| 61 | fn bias(&mut self, name: &str) -> Result<Option<Tensor>> { |
| 62 | match self.tensors.remove(&format!("{name}.bias")) { |
| 63 | Some(t) => Ok(Some(t.to_dtype(self.dtype)?.to_device(&self.device)?)), |
| 64 | None => Ok(None), |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | /// Build a projection: turboquant-encode the weight data-free and keep it |
| 69 | /// COMPRESSED on the GPU. The f32 source weight is REMOVED from the map (freed) |
| 70 | /// right after encoding so the build-time RAM peak stays bounded. |
| 71 | fn quant(&mut self, name: &str, bias: bool) -> Result<Proj> { |
| 72 | let wt = self |
| 73 | .tensors |
| 74 | .remove(&format!("{name}.weight")) |
| 75 | .ok_or_else(|| anyhow::anyhow!("missing {name}.weight"))?; |
| 76 | let dims = wt.dims().to_vec(); |
| 77 | let (out, inn) = (dims[0], dims[1]); |
| 78 | let w: Vec<f32> = wt.to_dtype(DType::F32)?.flatten_all()?.to_vec1()?; |
| 79 | drop(wt); |
| 80 | let q = encode(&w, out, inn, &self.cfg, &LLOYD_MAX_3BIT); |
| 81 | |
| 82 | let b = if bias { self.bias(name)? } else { None }; |
| 83 | let qw = QWeight::from_tq(&q, b, &self.device)?; |
| 84 | |
| 85 | self.total_compressed_bytes += qw.compressed_bytes; |
| 86 | self.total_fp16_bytes += out * inn * 2; |
| 87 | self.n_quant += 1; |
| 88 | Ok(Proj::Quant(qw)) |
| 89 | } |
| 90 | |
| 91 | /// Build a projection, choosing dense vs quant. (Currently always quant.) |
| 92 | pub fn proj(&mut self, name: &str, bias: bool) -> Result<Proj> { |
| 93 | self.quant(name, bias) |
| 94 | } |
| 95 | |
| 96 | /// Build a FUSED group of projections that share the same input activation |
| 97 | /// (q/k/v, or gate/up): encode each data-free, then concatenate their codes |
| 98 | /// into one `QGroup` so the group runs as one rotate + one qmatvec. |
| 99 | pub fn quant_group(&mut self, members: &[(&str, bool)]) -> Result<QGroup> { |
| 100 | let mut qs = Vec::with_capacity(members.len()); |
| 101 | let mut biases = Vec::with_capacity(members.len()); |
| 102 | for (name, has_bias) in members { |
| 103 | let wt = self |
| 104 | .tensors |
| 105 | .remove(&format!("{name}.weight")) |
| 106 | .ok_or_else(|| anyhow::anyhow!("missing {name}.weight"))?; |
| 107 | let dims = wt.dims().to_vec(); |
| 108 | let (out, inn) = (dims[0], dims[1]); |
| 109 | let w: Vec<f32> = wt.to_dtype(DType::F32)?.flatten_all()?.to_vec1()?; |
| 110 | drop(wt); |
| 111 | let q = encode(&w, out, inn, &self.cfg, &LLOYD_MAX_3BIT); |
| 112 | biases.push(if *has_bias { self.bias(name)? } else { None }); |
| 113 | self.total_fp16_bytes += out * inn * 2; |
| 114 | self.n_quant += 1; |
| 115 | qs.push(q); |
| 116 | } |
| 117 | let refs: Vec<&_> = qs.iter().collect(); |
| 118 | let group = QGroup::from_tqs(&refs, biases, &self.device)?; |
| 119 | self.total_compressed_bytes += group.compressed_bytes; |
| 120 | Ok(group) |
| 121 | } |
| 122 | |
| 123 | /// Turboquant-compress a SEPARATE lm_head weight (pulled from the mmap'd VarBuilder, |
| 124 | /// not the f32 map), data-free the same way a layer weight is. Returns the compressed |
| 125 | /// weight + (compressed_bytes, fp16_bytes) for the caller's report. Stats are also |
| 126 | /// folded into the running totals. Mirrors the old inlined COCO_QUANT_HEAD path. |
| 127 | pub fn quant_lm_head( |
| 128 | &mut self, |
| 129 | vb: &VarBuilder, |
| 130 | vocab_size: usize, |
| 131 | hidden_size: usize, |
| 132 | ) -> Result<(QWeight, usize, usize)> { |
| 133 | let w = vb |
| 134 | .get((vocab_size, hidden_size), "lm_head.weight")? |
| 135 | .to_dtype(DType::F32)? |
| 136 | .flatten_all()? |
| 137 | .to_vec1::<f32>()?; |
| 138 | let q = encode(&w, vocab_size, hidden_size, &self.cfg, &LLOYD_MAX_3BIT); |
| 139 | drop(w); |
| 140 | let qw = QWeight::from_tq(&q, None, &self.device)?; |
| 141 | let comp = qw.compressed_bytes; |
| 142 | let fp16 = vocab_size * hidden_size * 2; |
| 143 | self.total_compressed_bytes += comp; |
| 144 | self.total_fp16_bytes += fp16; |
| 145 | self.n_quant += 1; |
| 146 | Ok((qw, comp, fp16)) |
| 147 | } |
| 148 | |
| 149 | /// Snapshot the accumulated load-time weight stats. |
| 150 | pub fn stats(&self) -> WeightStats { |
| 151 | WeightStats { |
| 152 | n_quant: self.n_quant, |
| 153 | compressed_bytes: self.total_compressed_bytes, |
| 154 | fp16_bytes: self.total_fp16_bytes, |
| 155 | } |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | pub struct WeightStats { |
| 160 | pub n_quant: usize, |
| 161 | pub compressed_bytes: usize, |
| 162 | pub fp16_bytes: usize, |
| 163 | } |