| 1 | // Step-1 merge primitive: data-free evolutionary merge of two same-arch parents. |
| 2 | // |
| 3 | // Both parents are loaded ONCE as CPU-resident f32 tensor maps. Per candidate a |
| 4 | // `num_layers+2` genome lerps every tensor (child = (1-a)*A + a*B) into ONE |
| 5 | // in-memory HashMap<String,Tensor>, which is handed straight to a runnable coco |
| 6 | // Model on Metal — no temp safetensors, no disk round-trip. Deterministic `drop` |
| 7 | // between candidates makes the Python Metal-fragmentation crash structurally |
| 8 | // impossible (constant-shape children ⇒ candle Metal pool reuse). |
| 9 | // |
| 10 | // Two build paths: |
| 11 | // * build_child_dense — candle ModelForCausalLM (fp16/bf16, NO turboquant). The |
| 12 | // numeric-parity gate vs the Python reference. |
| 13 | // * build_child_quant — coco build_model (3-bit turboquant, the GA search rep). |
| 14 | |
| 15 | use std::collections::HashMap; |
| 16 | |
| 17 | use anyhow::{anyhow, Context, Result}; |
| 18 | use candle_core::{DType, Device, Tensor}; |
| 19 | use candle_nn::VarBuilder; |
| 20 | use candle_transformers::models::qwen2::{Config as DenseConfig, ModelForCausalLM}; |
| 21 | |
| 22 | use crate::config::CocoConfig; |
| 23 | use crate::model::{build_model, Model}; |
| 24 | use crate::qwen2_q::WeightSource; |
| 25 | use crate::turboquant::TqConfig; |
| 26 | |
| 27 | // ─────────────────────────── genome grouping (port of merge.py) ─────────────────────────── |
| 28 | |
| 29 | /// Map a state_dict key → genome group index. Order: `[L0..L(n-1), embed, norm]`, |
| 30 | /// so `embed = genome_len-2`, `norm = genome_len-1`. Verbatim semantics of |
| 31 | /// `merge.py::tensor_group`: `model.layers.<L>.` → L, `embed_tokens`/`lm_head.weight` |
| 32 | /// → embed, `model.norm.weight` (or any stray key) → norm. |
| 33 | pub fn group_index(key: &str, genome_len: usize) -> usize { |
| 34 | let embed = genome_len - 2; |
| 35 | let norm = genome_len - 1; |
| 36 | // model.layers.<n>. → n |
| 37 | if let Some(rest) = key.strip_prefix("model.layers.") { |
| 38 | if let Some(dot) = rest.find('.') { |
| 39 | if let Ok(n) = rest[..dot].parse::<usize>() { |
| 40 | return n; |
| 41 | } |
| 42 | } |
| 43 | } |
| 44 | if key.contains("embed_tokens") || key == "lm_head.weight" { |
| 45 | return embed; |
| 46 | } |
| 47 | // model.norm.weight and any stray key → norm group (matches merge.py fallback). |
| 48 | norm |
| 49 | } |
| 50 | |
| 51 | /// Is this a Linear projection weight coco turboquants? (attention q/k/v/o + MLP |
| 52 | /// gate/up/down.) Mirrors `main.rs::is_quant_target` for the qwen2/qwen3 path. |
| 53 | pub fn is_quant_target(name: &str) -> bool { |
| 54 | const PROJ: [&str; 11] = [ |
| 55 | "q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj", |
| 56 | "kv_a_proj_with_mqa", "kv_b_proj", "q_a_proj", "q_b_proj", |
| 57 | ]; |
| 58 | name.ends_with(".weight") && PROJ.iter().any(|p| name.contains(&format!(".{p}."))) |
| 59 | } |
| 60 | |
| 61 | /// Is this a projection bias (q/k/v_proj carry biases in Qwen2)? Mirrors |
| 62 | /// `main.rs::is_proj_bias`. |
| 63 | pub fn is_proj_bias(name: &str) -> bool { |
| 64 | const PROJ: [&str; 7] = [ |
| 65 | "q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj", |
| 66 | ]; |
| 67 | name.ends_with(".bias") && PROJ.iter().any(|p| name.contains(&format!(".{p}."))) |
| 68 | } |
| 69 | |
| 70 | // ─────────────────────────── parent loading ─────────────────────────── |
| 71 | |
| 72 | /// Load one parent's FULL safetensors as a CPU-resident f32 tensor map (loaded ONCE, |
| 73 | /// held for the whole search). CPU RAM never fragments the Metal heap. |
| 74 | pub fn load_parent_f32(dir: &std::path::Path) -> Result<HashMap<String, Tensor>> { |
| 75 | let files = safetensors_files(dir)?; |
| 76 | let cpu = Device::Cpu; |
| 77 | let mut out: HashMap<String, Tensor> = HashMap::new(); |
| 78 | for file in &files { |
| 79 | let shard = candle_core::safetensors::load(file, &cpu) |
| 80 | .with_context(|| format!("loading {}", file.display()))?; |
| 81 | for (name, tensor) in shard.into_iter() { |
| 82 | out.insert(name, tensor.to_dtype(DType::F32)?); |
| 83 | } |
| 84 | } |
| 85 | if out.is_empty() { |
| 86 | return Err(anyhow!("no tensors loaded from {}", dir.display())); |
| 87 | } |
| 88 | Ok(out) |
| 89 | } |
| 90 | |
| 91 | /// Collect every *.safetensors file in a model directory (sorted). |
| 92 | pub fn safetensors_files(dir: &std::path::Path) -> Result<Vec<std::path::PathBuf>> { |
| 93 | let mut files = Vec::new(); |
| 94 | for entry in std::fs::read_dir(dir) |
| 95 | .with_context(|| format!("reading model dir {}", dir.display()))? |
| 96 | { |
| 97 | let path = entry?.path(); |
| 98 | if path.extension().map(|e| e == "safetensors").unwrap_or(false) { |
| 99 | files.push(path); |
| 100 | } |
| 101 | } |
| 102 | if files.is_empty() { |
| 103 | return Err(anyhow!("no *.safetensors files in {}", dir.display())); |
| 104 | } |
| 105 | files.sort(); |
| 106 | Ok(files) |
| 107 | } |
| 108 | |
| 109 | /// candle-qwen2 `Config` for the dense (--no-quant) parity path. |
| 110 | pub fn dense_config_from_dir(dir: &std::path::Path) -> Result<DenseConfig> { |
| 111 | let cfg_path = dir.join("config.json"); |
| 112 | let cfg: DenseConfig = serde_json::from_slice( |
| 113 | &std::fs::read(&cfg_path).with_context(|| format!("reading {}", cfg_path.display()))?, |
| 114 | ) |
| 115 | .with_context(|| format!("parsing {}", cfg_path.display()))?; |
| 116 | Ok(cfg) |
| 117 | } |
| 118 | |
| 119 | // ─────────────────────────── the blend ─────────────────────────── |
| 120 | |
| 121 | /// Union over both parents' keys (identical shapes; every key present in both). Blend |
| 122 | /// each tensor in f32: `child = (1-a)*A + a*B`, `a = genome[group_index(key)]`. Bit- |
| 123 | /// faithful to the validated `torch.lerp(...float())`; cast to eval dtype at build. |
| 124 | /// |
| 125 | /// Fast paths: `a<=0` → clone A, `a>=1` → clone B (no blend), matching `merge.py`. |
| 126 | pub fn merge_full( |
| 127 | genome: &[f32], |
| 128 | a_map: &HashMap<String, Tensor>, |
| 129 | b_map: &HashMap<String, Tensor>, |
| 130 | ) -> Result<HashMap<String, Tensor>> { |
| 131 | let mut out = HashMap::with_capacity(a_map.len()); |
| 132 | for (k, ta) in a_map { |
| 133 | let tb = b_map |
| 134 | .get(k) |
| 135 | .ok_or_else(|| anyhow!("key {k} present in parent A but missing in parent B"))?; |
| 136 | let a = genome[group_index(k, genome.len())] as f64; |
| 137 | let blended = if a <= 0.0 { |
| 138 | ta.clone() |
| 139 | } else if a >= 1.0 { |
| 140 | tb.clone() |
| 141 | } else { |
| 142 | // f32 lerp: (1-a)*ta + a*tb |
| 143 | ((ta * (1.0 - a))? + (tb * a)?)? |
| 144 | }; |
| 145 | out.insert(k.clone(), blended); |
| 146 | } |
| 147 | Ok(out) |
| 148 | } |
| 149 | |
| 150 | // ─────────────────────────── build path 1: dense fp16 (parity gate) ─────────────────────────── |
| 151 | |
| 152 | /// A candle `ModelForCausalLM` wrapped in coco's `Model` trait so the SAME |
| 153 | /// `eval::fitness` drives either build path via `&mut dyn Model`. Both expose the |
| 154 | /// identical `forward(ids, offset) -> [1,1,vocab]` last-position contract. |
| 155 | pub struct DenseChild(pub ModelForCausalLM); |
| 156 | |
| 157 | impl Model for DenseChild { |
| 158 | fn forward(&mut self, ids: &Tensor, offset: usize) -> Result<Tensor> { |
| 159 | Ok(self.0.forward(ids, offset)?) |
| 160 | } |
| 161 | fn clear_kv_cache(&mut self) { |
| 162 | self.0.clear_kv_cache(); |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | /// `--no-quant` dense fp16 build: feed the FULL blended map to candle's dense path. |
| 167 | /// Zero turboquant, fp16-faithful, apples-to-apples with the Python reference. Tied |
| 168 | /// lm_head handled by candle when `lm_head.weight` is absent (Qwen2.5-1.5B ties). |
| 169 | pub fn build_child_dense( |
| 170 | full: &HashMap<String, Tensor>, |
| 171 | cfg: &DenseConfig, |
| 172 | dev: &Device, |
| 173 | dtype: DType, |
| 174 | ) -> Result<Box<dyn Model>> { |
| 175 | let vb = VarBuilder::from_tensors(full.clone(), dtype, dev); |
| 176 | let m = ModelForCausalLM::new(cfg, vb)?; |
| 177 | Ok(Box::new(DenseChild(m))) |
| 178 | } |
| 179 | |
| 180 | // ─────────────────────────── build path 2: turboquant (GA search rep) ─────────────────────────── |
| 181 | |
| 182 | /// Split a full blended map into (a) quant-target weights+biases → `WeightSource.tensors` |
| 183 | /// (CPU f32); (b) everything else (embeds, norms) → `VarBuilder::from_tensors` on device. |
| 184 | /// Mirrors `main.rs::build_fast_engine` (410-441) but sourced from the blended map. |
| 185 | pub fn split_weightsource( |
| 186 | full: HashMap<String, Tensor>, |
| 187 | dev: &Device, |
| 188 | dtype: DType, |
| 189 | ) -> Result<(WeightSource, VarBuilder<'static>)> { |
| 190 | let mut quant: HashMap<String, Tensor> = HashMap::new(); |
| 191 | let mut rest: HashMap<String, Tensor> = HashMap::new(); |
| 192 | for (name, t) in full.into_iter() { |
| 193 | if is_quant_target(&name) || is_proj_bias(&name) { |
| 194 | // quant targets stay CPU f32 (encode() pulls raw values). |
| 195 | quant.insert(name, t); |
| 196 | } else { |
| 197 | // embeds/norms go straight to device in the model dtype. |
| 198 | rest.insert(name, t.to_dtype(dtype)?.to_device(dev)?); |
| 199 | } |
| 200 | } |
| 201 | let vb = VarBuilder::from_tensors(rest, dtype, dev); |
| 202 | // Clean 3-bit block recipe (no padding, no sparse outliers) — the fast kernel's contract. |
| 203 | let cfg = TqConfig { |
| 204 | outlier_frac: 0.0, |
| 205 | block_hadamard: true, |
| 206 | ..TqConfig::default() |
| 207 | }; |
| 208 | let src = WeightSource { |
| 209 | tensors: quant, |
| 210 | device: dev.clone(), |
| 211 | dtype, |
| 212 | cfg, |
| 213 | total_compressed_bytes: 0, |
| 214 | total_fp16_bytes: 0, |
| 215 | n_quant: 0, |
| 216 | }; |
| 217 | Ok((src, vb)) |
| 218 | } |
| 219 | |
| 220 | /// turboquant build: blended map → `build_model` (3-bit turboquant + Metal wiring). |
| 221 | /// Uses the config-driven registry path (Arch::Qwen2 → DenseDecoder), same as the |
| 222 | /// `coco` bin under COCO_REGISTRY=1. Baselines here differ slightly from Python fp16 |
| 223 | /// (turboquant offset) — that's expected; the parity gate uses `build_child_dense`. |
| 224 | pub fn build_child_quant( |
| 225 | full: HashMap<String, Tensor>, |
| 226 | cfg: &CocoConfig, |
| 227 | dev: &Device, |
| 228 | dtype: DType, |
| 229 | ) -> Result<Box<dyn Model>> { |
| 230 | let (src, vb) = split_weightsource(full, dev, dtype)?; |
| 231 | let (model, _stats) = build_model(cfg, src, vb)?; |
| 232 | Ok(model) |
| 233 | } |