| 1 | // coco v0 — minimal but real Rust LLM inference engine. |
| 2 | // |
| 3 | // Loads Qwen2.5-1.5B (standard qwen2 architecture) and generates coherent text |
| 4 | // on Metal (Apple Silicon GPU) with a CPU fallback. fp16/bf16 inference only — |
| 5 | // NO quantization (that is the next step: turboquant / a custom QuantizedLinear). |
| 6 | // |
| 7 | // Structure mirrors the official candle qwen example: |
| 8 | // candle-examples/examples/qwen/main.rs |
| 9 | // (model construction + KV cache + LogitsProcessor sampling loop). |
| 10 | |
| 11 | mod config; |
| 12 | mod model; |
| 13 | mod qlinear; |
| 14 | mod qwen2_legacy; |
| 15 | mod qwen2_q; |
| 16 | mod turboquant; |
| 17 | |
| 18 | use anyhow::{anyhow, Context, Result}; |
| 19 | use candle_core::{DType, Device, Tensor}; |
| 20 | use candle_nn::VarBuilder; |
| 21 | use candle_transformers::generation::LogitsProcessor; |
| 22 | // candle's qwen2 Config/ModelForCausalLM are used ONLY for the dense (non-turboquant) |
| 23 | // fallback path. The quant/fast path goes entirely through coco's own CocoConfig + |
| 24 | // build_model registry — no candle qwen2 type on the moat. |
| 25 | use candle_transformers::models::qwen2::{Config, ModelForCausalLM}; |
| 26 | use clap::Parser; |
| 27 | |
| 28 | use crate::config::CocoConfig; |
| 29 | use crate::model::Model as CocoModel; |
| 30 | use std::collections::HashMap; |
| 31 | use std::io::Write; |
| 32 | use std::path::PathBuf; |
| 33 | use tokenizers::Tokenizer; |
| 34 | |
| 35 | #[derive(Parser, Debug)] |
| 36 | #[command(name = "coco", about = "coco v0 — real Rust LLM inference (Qwen2.5-1.5B)")] |
| 37 | struct Args { |
| 38 | /// Prompt to continue. |
| 39 | #[arg(long, default_value = "Write a haiku about the sea:")] |
| 40 | prompt: String, |
| 41 | |
| 42 | /// Path to the model directory (must contain config.json, tokenizer.json, *.safetensors). |
| 43 | #[arg(long, default_value = "./model")] |
| 44 | model: PathBuf, |
| 45 | |
| 46 | /// Max new tokens to generate. |
| 47 | #[arg(long, default_value_t = 256)] |
| 48 | max_tokens: usize, |
| 49 | |
| 50 | /// Sampling temperature. 0.0 = greedy (argmax). |
| 51 | #[arg(long, default_value_t = 0.7)] |
| 52 | temperature: f64, |
| 53 | |
| 54 | /// Nucleus sampling top-p. Only used when temperature > 0. |
| 55 | #[arg(long)] |
| 56 | top_p: Option<f64>, |
| 57 | |
| 58 | /// RNG seed. |
| 59 | #[arg(long, default_value_t = 299792458)] |
| 60 | seed: u64, |
| 61 | |
| 62 | /// Repeat penalty (>1.0 discourages repetition). 1.0 = off. |
| 63 | #[arg(long, default_value_t = 1.1)] |
| 64 | repeat_penalty: f32, |
| 65 | |
| 66 | /// How many of the last tokens the repeat penalty considers. |
| 67 | #[arg(long, default_value_t = 64)] |
| 68 | repeat_last_n: usize, |
| 69 | |
| 70 | /// Force CPU even if a GPU is available. |
| 71 | #[arg(long)] |
| 72 | cpu: bool, |
| 73 | |
| 74 | /// Weight quantization mode. "none" (default) = v0 fp16/bf16. "turboquant" = |
| 75 | /// data-free turboquant-v2 quantize-then-dequant-at-load (3-bit codebook + |
| 76 | /// FWHT incoherence rotation). Quantized weights are reconstructed to |
| 77 | /// fp16/bf16 before inference (dequant-at-load), proving the Rust quant is |
| 78 | /// correct without a fused kernel yet. |
| 79 | #[arg(long, default_value = "none")] |
| 80 | quant: String, |
| 81 | |
| 82 | /// turboquant: keep the top this-fraction of |rotated| values in fp16 |
| 83 | /// (outlier split). 0.0 disables the split. Default 0.005 (~0.5%). |
| 84 | #[arg(long, default_value_t = 0.005)] |
| 85 | outlier_frac: f32, |
| 86 | |
| 87 | /// Benchmark mode: prefill `--bench-ctx` synthetic tokens (warm the KV cache), |
| 88 | /// then measure PURE decode tok/s over `--bench-decode` steps (median of |
| 89 | /// per-token latencies). Mirrors `llama-bench -d <ctx> -n <decode>`. Prints a |
| 90 | /// one-line machine-readable result. Skips the prompt/streaming path. |
| 91 | #[arg(long)] |
| 92 | bench: bool, |
| 93 | |
| 94 | /// Context depth (already-cached tokens) for `--bench`. The decode is measured |
| 95 | /// with this many tokens in the KV cache (long ctx = bandwidth/cache heavy). |
| 96 | #[arg(long, default_value_t = 0)] |
| 97 | bench_ctx: usize, |
| 98 | |
| 99 | /// How many decode steps to time in `--bench` (after a few warmup steps). |
| 100 | #[arg(long, default_value_t = 64)] |
| 101 | bench_decode: usize, |
| 102 | } |
| 103 | |
| 104 | /// Pick Metal (Apple Silicon GPU) if available, else CPU. |
| 105 | fn pick_device(force_cpu: bool) -> Result<Device> { |
| 106 | if force_cpu { |
| 107 | return Ok(Device::Cpu); |
| 108 | } |
| 109 | if candle_core::utils::metal_is_available() { |
| 110 | // device ordinal 0 |
| 111 | match Device::new_metal(0) { |
| 112 | Ok(d) => return Ok(d), |
| 113 | Err(e) => eprintln!("warning: Metal requested but failed ({e}); falling back to CPU"), |
| 114 | } |
| 115 | } else if candle_core::utils::cuda_is_available() { |
| 116 | match Device::new_cuda(0) { |
| 117 | Ok(d) => return Ok(d), |
| 118 | Err(e) => eprintln!("warning: CUDA requested but failed ({e}); falling back to CPU"), |
| 119 | } |
| 120 | } |
| 121 | Ok(Device::Cpu) |
| 122 | } |
| 123 | |
| 124 | fn device_label(dev: &Device) -> &'static str { |
| 125 | match dev { |
| 126 | Device::Cpu => "CPU", |
| 127 | Device::Metal(_) => "Metal (Apple Silicon GPU)", |
| 128 | Device::Cuda(_) => "CUDA (NVIDIA GPU)", |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | /// Collect every *.safetensors file in the model directory. |
| 133 | fn safetensors_files(dir: &PathBuf) -> Result<Vec<PathBuf>> { |
| 134 | let mut files = Vec::new(); |
| 135 | for entry in std::fs::read_dir(dir) |
| 136 | .with_context(|| format!("reading model dir {}", dir.display()))? |
| 137 | { |
| 138 | let path = entry?.path(); |
| 139 | // Skip macOS AppleDouble sidecars (`._model-*.safetensors`) — 4 KB resource-fork |
| 140 | // junk created when a model dir is copied to exFAT/FAT (e.g. the Lexar drive). |
| 141 | // Reading their first 8 bytes as a safetensors header length → "header too large". |
| 142 | let is_appledouble = path |
| 143 | .file_name() |
| 144 | .and_then(|n| n.to_str()) |
| 145 | .map(|n| n.starts_with("._")) |
| 146 | .unwrap_or(false); |
| 147 | if is_appledouble { |
| 148 | continue; |
| 149 | } |
| 150 | if path.extension().map(|e| e == "safetensors").unwrap_or(false) { |
| 151 | files.push(path); |
| 152 | } |
| 153 | } |
| 154 | if files.is_empty() { |
| 155 | return Err(anyhow!("no *.safetensors files in {}", dir.display())); |
| 156 | } |
| 157 | files.sort(); |
| 158 | Ok(files) |
| 159 | } |
| 160 | |
| 161 | /// Is this a Linear projection weight we should turboquant? |
| 162 | /// (attention q/k/v/o and MLP gate/up/down — the bulk of the parameters — plus the |
| 163 | /// DeepSeek-V2/V3 MLA latent projections kv_a_proj_with_mqa/kv_b_proj and, for the |
| 164 | /// q-LoRA MLA variant, q_a_proj/q_b_proj). We deliberately skip embeddings, norms, |
| 165 | /// biases, routers, and anything not 2-D. |
| 166 | fn is_quant_target(name: &str) -> bool { |
| 167 | const PROJ: [&str; 11] = [ |
| 168 | "q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj", |
| 169 | // DeepSeek MLA (Arch::DeepSeekV2): compressed KV / query latent projections. |
| 170 | "kv_a_proj_with_mqa", "kv_b_proj", "q_a_proj", "q_b_proj", |
| 171 | ]; |
| 172 | name.ends_with(".weight") && PROJ.iter().any(|p| name.contains(&format!(".{p}."))) |
| 173 | } |
| 174 | |
| 175 | /// Is this a projection bias (q/k/v_proj carry biases in Qwen2) we must keep for |
| 176 | /// the fast path's QuantizedLinear? |
| 177 | fn is_proj_bias(name: &str) -> bool { |
| 178 | const PROJ: [&str; 7] = [ |
| 179 | "q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj", |
| 180 | ]; |
| 181 | name.ends_with(".bias") && PROJ.iter().any(|p| name.contains(&format!(".{p}."))) |
| 182 | } |
| 183 | |
| 184 | /// Load every weight from the safetensors files on CPU, turboquant-v2 each Linear |
| 185 | /// projection weight (data-free), reconstruct it (dequant-at-load), and return a |
| 186 | /// HashMap of tensors on `device` at `dtype` ready for `VarBuilder::from_tensors`. |
| 187 | /// |
| 188 | /// Prints the storage win: total compressed bytes vs the fp16 baseline, the |
| 189 | /// effective bpw, and how many matrices were quantized. |
| 190 | /// |
| 191 | /// NOTE (next milestone hook): to keep weights compressed in RAM and fuse a |
| 192 | /// FWHT-dequant Metal kernel, you'd store the `TqWeight`s here instead of |
| 193 | /// decoding, and hand them to a custom QuantizedLinear at model-build time. For |
| 194 | /// v1 we reconstruct fp16 right here — see decode() below. |
| 195 | fn quantize_weights( |
| 196 | weight_files: &[PathBuf], |
| 197 | outlier_frac: f32, |
| 198 | block_hadamard: bool, |
| 199 | dtype: DType, |
| 200 | device: &Device, |
| 201 | ) -> Result<HashMap<String, Tensor>> { |
| 202 | use turboquant::{decode, encode, TqConfig, LLOYD_MAX_3BIT}; |
| 203 | |
| 204 | let cpu = Device::Cpu; |
| 205 | let cfg = TqConfig { outlier_frac, block_hadamard, ..TqConfig::default() }; |
| 206 | let codebook = LLOYD_MAX_3BIT; |
| 207 | |
| 208 | let mut out: HashMap<String, Tensor> = HashMap::new(); |
| 209 | let mut quantized = 0usize; |
| 210 | let mut q_orig_fp16_bytes = 0usize; // fp16 baseline of the quantized matrices |
| 211 | let mut q_comp_bytes = 0usize; // compressed bytes of those matrices |
| 212 | let mut passthrough_bytes = 0usize; // fp16 baseline of everything left alone |
| 213 | let mut total_relfro = 0f64; |
| 214 | |
| 215 | let t0 = std::time::Instant::now(); |
| 216 | for file in weight_files { |
| 217 | // Load this shard's tensors on CPU (so we can pull raw f32 data out). |
| 218 | let shard = candle_core::safetensors::load(file, &cpu) |
| 219 | .with_context(|| format!("loading {}", file.display()))?; |
| 220 | for (name, tensor) in shard.into_iter() { |
| 221 | let dims = tensor.dims().to_vec(); |
| 222 | if is_quant_target(&name) && dims.len() == 2 { |
| 223 | let (rows, cols) = (dims[0], dims[1]); |
| 224 | let w: Vec<f32> = tensor.to_dtype(DType::F32)?.flatten_all()?.to_vec1()?; |
| 225 | |
| 226 | let q = encode(&w, rows, cols, &cfg, &codebook); |
| 227 | let wq = decode(&q); |
| 228 | |
| 229 | total_relfro += turboquant::relative_fro(&w, &wq); |
| 230 | q_orig_fp16_bytes += rows * cols * 2; |
| 231 | q_comp_bytes += q.compressed_bytes(); |
| 232 | quantized += 1; |
| 233 | |
| 234 | let recon = Tensor::from_vec(wq, (rows, cols), &cpu)? |
| 235 | .to_dtype(dtype)? |
| 236 | .to_device(device)?; |
| 237 | out.insert(name, recon); |
| 238 | } else { |
| 239 | // Pass through untouched (embeddings, norms, biases, lm_head). |
| 240 | let n: usize = dims.iter().product(); |
| 241 | passthrough_bytes += n * 2; |
| 242 | out.insert(name, tensor.to_dtype(dtype)?.to_device(device)?); |
| 243 | } |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | let total_fp16 = q_orig_fp16_bytes + passthrough_bytes; |
| 248 | let total_comp = q_comp_bytes + passthrough_bytes; |
| 249 | let mb = |b: usize| b as f64 / (1024.0 * 1024.0); |
| 250 | let avg_relfro = if quantized > 0 { total_relfro / quantized as f64 } else { 0.0 }; |
| 251 | // Effective bpw over the quantized weights only. |
| 252 | let q_weights: usize = q_orig_fp16_bytes / 2; |
| 253 | let eff_bpw = if q_weights > 0 { |
| 254 | (q_comp_bytes * 8) as f64 / q_weights as f64 |
| 255 | } else { |
| 256 | 0.0 |
| 257 | }; |
| 258 | |
| 259 | let mode = if block_hadamard { "block-diagonal FWHT (no pad)" } else { "v2 full-row FWHT (pad-to-pow2)" }; |
| 260 | println!( |
| 261 | "turboquant | rotation: {} | quantized {} Linear matrices, outlier_frac={} in {:.2}s", |
| 262 | mode, |
| 263 | quantized, |
| 264 | outlier_frac, |
| 265 | t0.elapsed().as_secs_f64() |
| 266 | ); |
| 267 | println!( |
| 268 | " quantized-weight storage : {:.1} MB fp16 -> {:.1} MB compressed ({:.2}x, {:.3} bpw)", |
| 269 | mb(q_orig_fp16_bytes), |
| 270 | mb(q_comp_bytes), |
| 271 | q_orig_fp16_bytes as f64 / q_comp_bytes.max(1) as f64, |
| 272 | eff_bpw, |
| 273 | ); |
| 274 | println!( |
| 275 | " whole-model artifact : {:.1} MB fp16 -> {:.1} MB compressed ({:.2}x) | avg relFro {:.4}", |
| 276 | mb(total_fp16), |
| 277 | mb(total_comp), |
| 278 | total_fp16 as f64 / total_comp.max(1) as f64, |
| 279 | avg_relfro, |
| 280 | ); |
| 281 | |
| 282 | Ok(out) |
| 283 | } |
| 284 | |
| 285 | /// Either the upstream dense/dequant-at-load model, or the turboquant-fast model |
| 286 | /// that keeps weights compressed. The fast path is now a `Box<dyn Model>` from the |
| 287 | /// config-driven registry (qwen2 is registry entry #1); the dense fallback stays |
| 288 | /// candle-qwen2-typed. Both expose `forward(input, offset) -> logits`. |
| 289 | enum Engine { |
| 290 | Dense(ModelForCausalLM), |
| 291 | Fast(Box<dyn CocoModel>), |
| 292 | } |
| 293 | |
| 294 | impl Engine { |
| 295 | fn forward(&mut self, input: &Tensor, offset: usize) -> Result<Tensor> { |
| 296 | match self { |
| 297 | Engine::Dense(m) => Ok(m.forward(input, offset)?), |
| 298 | Engine::Fast(m) => m.forward(input, offset), |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | fn clear_kv_cache(&mut self) { |
| 303 | match self { |
| 304 | Engine::Dense(m) => m.clear_kv_cache(), |
| 305 | Engine::Fast(m) => m.clear_kv_cache(), |
| 306 | } |
| 307 | } |
| 308 | } |
| 309 | |
| 310 | /// Pure-decode benchmark: prefill `ctx` synthetic tokens (one forward over the |
| 311 | /// whole synthetic prompt, like a real prompt — warms the KV cache to depth |
| 312 | /// `ctx`), then time `decode` single-token decode steps and report the MEDIAN |
| 313 | /// per-step latency → tok/s. Mirrors `llama-bench -d <ctx> -n <decode>`. We use a |
| 314 | /// fixed, valid token id so the KV cache content is realistic; greedy argmax is |
| 315 | /// irrelevant to decode cost so we skip sampling and just feed a constant token. |
| 316 | fn run_bench( |
| 317 | model: &mut Engine, |
| 318 | device: &Device, |
| 319 | ctx: usize, |
| 320 | decode: usize, |
| 321 | label: &str, |
| 322 | ) -> Result<()> { |
| 323 | model.clear_kv_cache(); |
| 324 | let tok: u32 = 100; // any valid, non-special token id |
| 325 | // Prefill to depth `ctx` in CHUNKS so the non-flash attention never builds a |
| 326 | // [seq, seq] weight matrix bigger than chunk×ctx (a single 32K forward would |
| 327 | // need a [1,heads,32K,32K] tensor → tens of GB → OOM). Real engines chunk |
| 328 | // prefill too; this just warms the KV cache to depth `ctx`. ctx==0 → depth 0. |
| 329 | let mut offset = 0usize; |
| 330 | if ctx > 0 { |
| 331 | let chunk = 512usize; |
| 332 | while offset < ctx { |
| 333 | let n = chunk.min(ctx - offset); |
| 334 | let piece: Vec<u32> = vec![tok; n]; |
| 335 | let input = Tensor::new(piece.as_slice(), device)?.unsqueeze(0)?; |
| 336 | let _ = model.forward(&input, offset)?; |
| 337 | offset += n; |
| 338 | } |
| 339 | device_sync(device)?; |
| 340 | } |
| 341 | |
| 342 | // A few warmup decode steps (shader caches, clocks) — not timed. Sync once |
| 343 | // at the end of warmup so the GPU is settled before timing. |
| 344 | let warmup = 8usize.min(decode.max(1)); |
| 345 | for _ in 0..warmup { |
| 346 | let input = Tensor::new(&[tok], device)?.unsqueeze(0)?; |
| 347 | let _ = model.forward(&input, offset)?; |
| 348 | offset += 1; |
| 349 | } |
| 350 | device_sync(device)?; |
| 351 | |
| 352 | // Steady-state, PIPELINED decode throughput: enqueue all `decode` single-token |
| 353 | // steps back-to-back (Metal pipelines them like a real generation loop / like |
| 354 | // llama-bench's tg), then ONE sync drains the queue. tok/s = decode / wall. |
| 355 | // (Per-step sync would serialize the GPU and report cold-start latency, not |
| 356 | // steady throughput — that's not what we or llama-bench measure.) We also run |
| 357 | // a few repeats and keep the best (lowest-noise) wall time. |
| 358 | let reps = 3usize; |
| 359 | let mut best_tok_s = 0f64; |
| 360 | for _ in 0..reps { |
| 361 | let t0 = std::time::Instant::now(); |
| 362 | for _ in 0..decode { |
| 363 | let input = Tensor::new(&[tok], device)?.unsqueeze(0)?; |
| 364 | let _ = model.forward(&input, offset)?; |
| 365 | offset += 1; |
| 366 | } |
| 367 | device_sync(device)?; |
| 368 | let wall = t0.elapsed().as_secs_f64(); |
| 369 | let tok_s = decode as f64 / wall.max(1e-9); |
| 370 | if tok_s > best_tok_s { |
| 371 | best_tok_s = tok_s; |
| 372 | } |
| 373 | } |
| 374 | println!( |
| 375 | "BENCH {label} | ctx={ctx} decode={decode} | {:.2} tok/s (best of {reps})", |
| 376 | best_tok_s |
| 377 | ); |
| 378 | // If COCO_PROFILE was set, run one extra UNPIPELINED (sync-per-token) decode |
| 379 | // pass so the per-phase timers see real wall time, then report the breakdown. |
| 380 | if std::env::var("COCO_PROFILE").is_ok() { |
| 381 | for _ in 0..decode { |
| 382 | let input = Tensor::new(&[tok], device)?.unsqueeze(0)?; |
| 383 | let _ = model.forward(&input, offset)?; |
| 384 | offset += 1; |
| 385 | } |
| 386 | if let Engine::Fast(_) = model { |
| 387 | model::profile_report(); |
| 388 | } |
| 389 | } |
| 390 | Ok(()) |
| 391 | } |
| 392 | |
| 393 | /// Force the device to finish all queued work so timings are real (Metal is async). |
| 394 | fn device_sync(device: &Device) -> Result<()> { |
| 395 | // Synchronize the whole device (drains the command queue). On Metal this maps |
| 396 | // to wait_until_completed for the in-flight command buffer. |
| 397 | device.synchronize()?; |
| 398 | Ok(()) |
| 399 | } |
| 400 | |
| 401 | /// Load every weight on CPU (f32), build the turboquant-fast `qwen2_q::Model` |
| 402 | /// (encodes target weights data-free, keeps them compressed on the GPU), and |
| 403 | /// report the compressed-vs-fp16 storage of the quantized matrices. |
| 404 | fn build_fast_engine( |
| 405 | weight_files: &[std::path::PathBuf], |
| 406 | config: &CocoConfig, |
| 407 | dense_cfg: Option<&Config>, |
| 408 | dtype: DType, |
| 409 | device: &Device, |
| 410 | model_label: std::path::Display<'_>, |
| 411 | ) -> Result<Engine> { |
| 412 | use turboquant::TqConfig; |
| 413 | |
| 414 | let t0 = std::time::Instant::now(); |
| 415 | let cpu = Device::Cpu; |
| 416 | |
| 417 | // Load ONLY the quant-target tensors (the 7 projections' weights+biases) on |
| 418 | // CPU as f32 so `encode` can pull raw values. Everything else (embeddings, |
| 419 | // norms, lm_head) is read on demand from the mmap'd VarBuilder below — we do |
| 420 | // NOT pull it into this f32 map, keeping the build-time RAM peak bounded. |
| 421 | let mut tensors: HashMap<String, Tensor> = HashMap::new(); |
| 422 | for file in weight_files { |
| 423 | let shard = candle_core::safetensors::load(file, &cpu) |
| 424 | .with_context(|| format!("loading {}", file.display()))?; |
| 425 | for (name, tensor) in shard.into_iter() { |
| 426 | if is_quant_target(&name) || (name.ends_with(".bias") && is_proj_bias(&name)) { |
| 427 | tensors.insert(name, tensor.to_dtype(DType::F32)?); |
| 428 | } |
| 429 | } |
| 430 | } |
| 431 | |
| 432 | // A dense mmap'd VarBuilder for the small passthrough tensors (embeddings, |
| 433 | // norms, lm_head) — read straight from disk in the target dtype. |
| 434 | let vb = unsafe { VarBuilder::from_mmaped_safetensors(weight_files, dtype, device)? }; |
| 435 | |
| 436 | // turboquant-fast requires the clean 3-bit block recipe (no padding, no |
| 437 | // sparse outliers) so the kernel can read fixed-width packed codes. |
| 438 | let cfg = TqConfig { |
| 439 | outlier_frac: 0.0, |
| 440 | block_hadamard: true, |
| 441 | ..TqConfig::default() |
| 442 | }; |
| 443 | |
| 444 | let src = qwen2_q::WeightSource { |
| 445 | tensors, |
| 446 | device: device.clone(), |
| 447 | dtype, |
| 448 | cfg, |
| 449 | total_compressed_bytes: 0, |
| 450 | total_fp16_bytes: 0, |
| 451 | n_quant: 0, |
| 452 | }; |
| 453 | |
| 454 | // COCO_REGISTRY gate (the Step-0 A/B seam). UNSET (default) = the ORIGINAL |
| 455 | // inlined qwen2 forward (qwen2_legacy::Model, candle Config). SET = the NEW |
| 456 | // config-driven registry path (model::build_model, CocoConfig). Both produce a |
| 457 | // `Box<dyn Model>`; the two paths share the SAME load-time turboquant machinery |
| 458 | // (WeightSource) so only the forward wiring differs. |
| 459 | let use_registry = matches!(std::env::var("COCO_REGISTRY").as_deref(), Ok(v) if v != "0"); |
| 460 | let (model, stats): (Box<dyn CocoModel>, qwen2_q::WeightStats) = if use_registry { |
| 461 | eprintln!("COCO_REGISTRY=1 — using the config-driven registry forward (model.rs)"); |
| 462 | model::build_model(config, src, vb)? |
| 463 | } else { |
| 464 | let dense_cfg = dense_cfg.ok_or_else(|| { |
| 465 | anyhow!("legacy fast path (COCO_REGISTRY unset) requires the candle qwen2 Config") |
| 466 | })?; |
| 467 | let (m, stats) = qwen2_legacy::Model::new(dense_cfg, src, vb)?; |
| 468 | (Box::new(m), stats) |
| 469 | }; |
| 470 | |
| 471 | let mb = |b: usize| b as f64 / (1024.0 * 1024.0); |
| 472 | let eff_bpw = (stats.compressed_bytes * 8) as f64 / (stats.fp16_bytes / 2).max(1) as f64; |
| 473 | println!( |
| 474 | "turboquant-fast | compressed {} Linear matrices in {:.2}s (weights stay packed on GPU)", |
| 475 | stats.n_quant, |
| 476 | t0.elapsed().as_secs_f64() |
| 477 | ); |
| 478 | println!( |
| 479 | " quantized-weight storage : {:.1} MB fp16 -> {:.1} MB compressed (resident) ({:.2}x, {:.3} bpw)", |
| 480 | mb(stats.fp16_bytes), |
| 481 | mb(stats.compressed_bytes), |
| 482 | stats.fp16_bytes as f64 / stats.compressed_bytes.max(1) as f64, |
| 483 | eff_bpw, |
| 484 | ); |
| 485 | println!( |
| 486 | "loaded {} ({} layers, hidden {}) in {:.2}s", |
| 487 | model_label, |
| 488 | config.num_hidden_layers, |
| 489 | config.hidden_size, |
| 490 | t0.elapsed().as_secs_f64() |
| 491 | ); |
| 492 | |
| 493 | Ok(Engine::Fast(model)) |
| 494 | } |
| 495 | |
| 496 | /// A tiny candle-qwen2 Config used ONLY by the dense (non-turboquant) fallback path. |
| 497 | /// The quant/fast path never touches this — it goes through CocoConfig + build_model. |
| 498 | fn dense_config_from_dir(dir: &std::path::Path) -> Result<Config> { |
| 499 | let cfg_path = dir.join("config.json"); |
| 500 | let config: Config = serde_json::from_slice( |
| 501 | &std::fs::read(&cfg_path).with_context(|| format!("reading {}", cfg_path.display()))?, |
| 502 | ) |
| 503 | .with_context(|| format!("parsing {}", cfg_path.display()))?; |
| 504 | Ok(config) |
| 505 | } |
| 506 | |
| 507 | fn main() -> Result<()> { |
| 508 | let args = Args::parse(); |
| 509 | |
| 510 | let device = pick_device(args.cpu)?; |
| 511 | // Qwen2.5 weights are bf16. Metal supports bf16; on CPU bf16 also works in candle. |
| 512 | let dtype = if device.is_cpu() { DType::F32 } else { DType::BF16 }; |
| 513 | println!( |
| 514 | "coco v0 | device: {} | dtype: {:?}", |
| 515 | device_label(&device), |
| 516 | dtype |
| 517 | ); |
| 518 | |
| 519 | // ── Tokenizer ──────────────────────────────────────────────────────────── |
| 520 | let tok_path = args.model.join("tokenizer.json"); |
| 521 | let tokenizer = Tokenizer::from_file(&tok_path) |
| 522 | .map_err(|e| anyhow!("loading tokenizer {}: {e}", tok_path.display()))?; |
| 523 | |
| 524 | // ── Config: coco-owned CocoConfig (config.json → architectures[0] → Arch). |
| 525 | // This drives the quant/fast path (the moat). The candle qwen2 Config is loaded |
| 526 | // lazily below ONLY for the dense (non-turboquant) fallback. |
| 527 | let coco_cfg = CocoConfig::from_dir(&args.model)?; |
| 528 | |
| 529 | // ── Weights → VarBuilder → ModelForCausalLM ────────────────────────────── |
| 530 | let weight_files = safetensors_files(&args.model)?; |
| 531 | let load_start = std::time::Instant::now(); |
| 532 | |
| 533 | // (turbo_on, block_hadamard) |
| 534 | let (turbo, block_hadamard) = match args.quant.as_str() { |
| 535 | "none" | "off" | "fp16" => (false, false), |
| 536 | // v2: full-row pad-to-power-of-two FWHT (max quality, padding-bpw cost). |
| 537 | "turboquant" | "turboquant-v2" | "tq" => (true, false), |
| 538 | // block: block-diagonal d-wide Hadamard, no padding (clean ~3.125 bpw). |
| 539 | "turboquant-block" | "tq-block" | "block" => (true, true), |
| 540 | // fast: keep weights COMPRESSED in RAM, fused rotate+quant-matmul kernel. |
| 541 | "turboquant-fast" | "tq-fast" | "fast" => (false, false), // handled below |
| 542 | other => { |
| 543 | return Err(anyhow!( |
| 544 | "unknown --quant mode {other:?} (use none | turboquant | turboquant-block | turboquant-fast)" |
| 545 | )) |
| 546 | } |
| 547 | }; |
| 548 | let fast = matches!(args.quant.as_str(), "turboquant-fast" | "tq-fast" | "fast"); |
| 549 | |
| 550 | let mut model = if fast { |
| 551 | // turboquant-fast: encode every target weight data-free and keep it |
| 552 | // COMPRESSED on the GPU (packed 3-bit codes + fp16 radius). The matmul |
| 553 | // reads the codes directly via a fused rotate-activation + quant-matmul |
| 554 | // Metal kernel — W is NEVER dequantized to fp16. |
| 555 | // The legacy (default) fast path needs candle's qwen2 Config; the registry |
| 556 | // path needs only CocoConfig. Load the candle Config here so build_fast_engine |
| 557 | // can pick either forward based on COCO_REGISTRY. It is OPTIONAL: a qwen3 |
| 558 | // config.json does NOT parse into candle's qwen2 Config (no head_dim field, |
| 559 | // `sliding_window: null`), and the registry path never uses it — so only load |
| 560 | // it when the legacy path will actually consume it (COCO_REGISTRY unset). |
| 561 | let use_registry = matches!(std::env::var("COCO_REGISTRY").as_deref(), Ok(v) if v != "0"); |
| 562 | let dense_cfg = if use_registry { |
| 563 | None |
| 564 | } else { |
| 565 | Some(dense_config_from_dir(&args.model)?) |
| 566 | }; |
| 567 | build_fast_engine( |
| 568 | &weight_files, |
| 569 | &coco_cfg, |
| 570 | dense_cfg.as_ref(), |
| 571 | dtype, |
| 572 | &device, |
| 573 | args.model.display(), |
| 574 | )? |
| 575 | } else { |
| 576 | // Dense/dequant fallback: candle's qwen2 Config + ModelForCausalLM. |
| 577 | let config = dense_config_from_dir(&args.model)?; |
| 578 | let vb = if turbo { |
| 579 | // turboquant: quantize every Linear weight data-free, then reconstruct |
| 580 | // (dequant-at-load). Owns the tensors in a HashMap. |
| 581 | let tensors = |
| 582 | quantize_weights(&weight_files, args.outlier_frac, block_hadamard, dtype, &device)?; |
| 583 | VarBuilder::from_tensors(tensors, dtype, &device) |
| 584 | } else { |
| 585 | unsafe { VarBuilder::from_mmaped_safetensors(&weight_files, dtype, &device)? } |
| 586 | }; |
| 587 | let m = ModelForCausalLM::new(&config, vb)?; |
| 588 | println!( |
| 589 | "loaded {} ({} layers, hidden {}) in {:.2}s", |
| 590 | args.model.display(), |
| 591 | config.num_hidden_layers, |
| 592 | config.hidden_size, |
| 593 | load_start.elapsed().as_secs_f64() |
| 594 | ); |
| 595 | Engine::Dense(m) |
| 596 | }; |
| 597 | |
| 598 | // ── Benchmark mode (pure decode tok/s at a given ctx depth) ────────────── |
| 599 | if args.bench { |
| 600 | let label = format!( |
| 601 | "{} {}", |
| 602 | args.model.file_name().and_then(|s| s.to_str()).unwrap_or("model"), |
| 603 | args.quant |
| 604 | ); |
| 605 | run_bench(&mut model, &device, args.bench_ctx, args.bench_decode, &label)?; |
| 606 | return Ok(()); |
| 607 | } |
| 608 | |
| 609 | // ── Encode prompt ──────────────────────────────────────────────────────── |
| 610 | let encoding = tokenizer |
| 611 | .encode(args.prompt.as_str(), true) |
| 612 | .map_err(|e| anyhow!("encoding prompt: {e}"))?; |
| 613 | let mut tokens: Vec<u32> = encoding.get_ids().to_vec(); |
| 614 | if tokens.is_empty() { |
| 615 | return Err(anyhow!("prompt encoded to zero tokens")); |
| 616 | } |
| 617 | |
| 618 | // eos: Qwen2.5 uses <|endoftext|> (151643) and <|im_end|> (151645). |
| 619 | let eos_token = config_eos(&tokenizer).unwrap_or(151643); |
| 620 | |
| 621 | let mut logits_processor = { |
| 622 | let temp = if args.temperature <= 0.0 { None } else { Some(args.temperature) }; |
| 623 | LogitsProcessor::new(args.seed, temp, args.top_p) |
| 624 | }; |
| 625 | |
| 626 | print!("\n{}", args.prompt); |
| 627 | std::io::stdout().flush().ok(); |
| 628 | |
| 629 | // ── Generation loop (mirrors candle qwen example) ──────────────────────── |
| 630 | let mut generated = 0usize; |
| 631 | let start_gen = std::time::Instant::now(); |
| 632 | let prompt_len = tokens.len(); |
| 633 | |
| 634 | for index in 0..args.max_tokens { |
| 635 | // First pass feeds the whole prompt (offset 0); subsequent passes feed |
| 636 | // only the last token, with seqlen_offset = number of cached tokens. |
| 637 | let (context, offset) = if index == 0 { |
| 638 | (tokens.as_slice(), 0) |
| 639 | } else { |
| 640 | (&tokens[tokens.len() - 1..], tokens.len() - 1) |
| 641 | }; |
| 642 | |
| 643 | let input = Tensor::new(context, &device)?.unsqueeze(0)?; // [1, seq] |
| 644 | let logits = model.forward(&input, offset)?; // [1, 1, vocab] |
| 645 | let logits = logits.squeeze(0)?.squeeze(0)?.to_dtype(DType::F32)?; // [vocab] |
| 646 | |
| 647 | // COCO_DUMP_LOGITS: at the FIRST step (offset 0, identical prompt to any |
| 648 | // reference), print the top-8 (id: logit) pairs. This is the matched-input |
| 649 | // probe used to isolate the MLA math port from sampling drift: the argmax |
| 650 | // and top-k ordering here reflect the full forward, before any greedy fork. |
| 651 | if index == 0 && std::env::var("COCO_DUMP_LOGITS").is_ok() { |
| 652 | let v: Vec<f32> = logits.to_vec1::<f32>()?; |
| 653 | let mut idx: Vec<usize> = (0..v.len()).collect(); |
| 654 | idx.sort_by(|&a, &b| v[b].partial_cmp(&v[a]).unwrap()); |
| 655 | let top: Vec<String> = |
| 656 | idx.iter().take(8).map(|&i| format!("{}:{:.4}", i, v[i])).collect(); |
| 657 | println!("LOGITS0 {}", top.join(",")); |
| 658 | } |
| 659 | |
| 660 | // Repeat penalty over the recent window. |
| 661 | let logits = if args.repeat_penalty == 1.0 { |
| 662 | logits |
| 663 | } else { |
| 664 | let start = tokens.len().saturating_sub(args.repeat_last_n); |
| 665 | candle_transformers::utils::apply_repeat_penalty( |
| 666 | &logits, |
| 667 | args.repeat_penalty, |
| 668 | &tokens[start..], |
| 669 | )? |
| 670 | }; |
| 671 | |
| 672 | let next = logits_processor.sample(&logits)?; |
| 673 | tokens.push(next); |
| 674 | generated += 1; |
| 675 | |
| 676 | if next == eos_token { |
| 677 | break; |
| 678 | } |
| 679 | |
| 680 | // Stream decode: decode the growing tail and print the delta. |
| 681 | if let Some(text) = decode_delta(&tokenizer, &tokens, prompt_len) { |
| 682 | print!("{text}"); |
| 683 | std::io::stdout().flush().ok(); |
| 684 | } |
| 685 | } |
| 686 | |
| 687 | let elapsed = start_gen.elapsed().as_secs_f64(); |
| 688 | let tok_s = generated as f64 / elapsed.max(1e-9); |
| 689 | // COCO_DUMP_TOKENS: print the exact generated token ids (behavior-neutral, |
| 690 | // used by the Step-0 refactor gate to prove token-for-token identity). |
| 691 | if std::env::var("COCO_DUMP_TOKENS").is_ok() { |
| 692 | let gen_ids = &tokens[prompt_len..]; |
| 693 | let ids: Vec<String> = gen_ids.iter().map(|t| t.to_string()).collect(); |
| 694 | println!("TOKENS {}", ids.join(",")); |
| 695 | } |
| 696 | println!( |
| 697 | "\n\n── {} tokens in {:.2}s = {:.2} tok/s ({}) ──", |
| 698 | generated, |
| 699 | elapsed, |
| 700 | tok_s, |
| 701 | device_label(&device) |
| 702 | ); |
| 703 | |
| 704 | Ok(()) |
| 705 | } |
| 706 | |
| 707 | /// Best-effort eos lookup from the tokenizer's added tokens. |
| 708 | fn config_eos(tokenizer: &Tokenizer) -> Option<u32> { |
| 709 | tokenizer.token_to_id("<|endoftext|>") |
| 710 | } |
| 711 | |
| 712 | /// Decode the full token stream and return only the new suffix appended since |
| 713 | /// the previous call (simple, robust streaming that handles multi-byte pieces). |
| 714 | fn decode_delta(tokenizer: &Tokenizer, tokens: &[u32], prompt_len: usize) -> Option<String> { |
| 715 | use std::cell::RefCell; |
| 716 | thread_local! { |
| 717 | static PRINTED: RefCell<usize> = const { RefCell::new(0) }; |
| 718 | } |
| 719 | let gen = &tokens[prompt_len..]; |
| 720 | let full = tokenizer.decode(gen, true).ok()?; |
| 721 | PRINTED.with(|p| { |
| 722 | let mut printed = p.borrow_mut(); |
| 723 | if full.len() > *printed { |
| 724 | let delta = full[*printed..].to_string(); |
| 725 | *printed = full.len(); |
| 726 | Some(delta) |
| 727 | } else { |
| 728 | None |
| 729 | } |
| 730 | }) |
| 731 | } |