| 1 | // ds2_ref — ORACLE reference runner for the MLA port validation. |
| 2 | // |
| 3 | // Loads DeepSeek-V2-Lite with candle-transformers 0.11's OWN deepseek2.rs |
| 4 | // (DeepSeekV2 + DeepSeekV2Config), greedy-generates N tokens for a fixed prompt, |
| 5 | // and prints the exact generated token ids as `TOKENS id,id,...` — the same |
| 6 | // format coco's COCO_DUMP_TOKENS uses. This is the ground truth the coco MLA |
| 7 | // port is compared against at matched precision (fp16/bf16). |
| 8 | |
| 9 | use anyhow::{anyhow, Result}; |
| 10 | use candle_core::{DType, Device, Tensor}; |
| 11 | use candle_nn::VarBuilder; |
| 12 | use candle_transformers::models::deepseek2::{DeepSeekV2, DeepSeekV2Config}; |
| 13 | use clap::Parser; |
| 14 | use std::path::PathBuf; |
| 15 | use tokenizers::Tokenizer; |
| 16 | |
| 17 | #[derive(Parser, Debug)] |
| 18 | struct Args { |
| 19 | #[arg(long, default_value = "The capital of France is")] |
| 20 | prompt: String, |
| 21 | #[arg(long)] |
| 22 | model: PathBuf, |
| 23 | #[arg(long, default_value_t = 20)] |
| 24 | max_tokens: usize, |
| 25 | #[arg(long)] |
| 26 | cpu: bool, |
| 27 | } |
| 28 | |
| 29 | fn pick_device(force_cpu: bool) -> Result<Device> { |
| 30 | if force_cpu { |
| 31 | return Ok(Device::Cpu); |
| 32 | } |
| 33 | if candle_core::utils::metal_is_available() { |
| 34 | match Device::new_metal(0) { |
| 35 | Ok(d) => return Ok(d), |
| 36 | Err(e) => eprintln!("warning: Metal failed ({e}); CPU"), |
| 37 | } |
| 38 | } |
| 39 | Ok(Device::Cpu) |
| 40 | } |
| 41 | |
| 42 | fn safetensors_files(dir: &PathBuf) -> Result<Vec<PathBuf>> { |
| 43 | let mut files = Vec::new(); |
| 44 | for entry in std::fs::read_dir(dir)? { |
| 45 | let path = entry?.path(); |
| 46 | if path.extension().map(|e| e == "safetensors").unwrap_or(false) { |
| 47 | files.push(path); |
| 48 | } |
| 49 | } |
| 50 | if files.is_empty() { |
| 51 | return Err(anyhow!("no *.safetensors in {}", dir.display())); |
| 52 | } |
| 53 | files.sort(); |
| 54 | Ok(files) |
| 55 | } |
| 56 | |
| 57 | fn main() -> Result<()> { |
| 58 | let args = Args::parse(); |
| 59 | let device = pick_device(args.cpu)?; |
| 60 | // Match coco: BF16 on GPU (Metal), F32 on CPU. DeepSeek weights are bf16. |
| 61 | let dtype = if device.is_cpu() { DType::F32 } else { DType::BF16 }; |
| 62 | eprintln!("ds2_ref | device: {device:?} | dtype: {dtype:?}"); |
| 63 | |
| 64 | let tokenizer = Tokenizer::from_file(args.model.join("tokenizer.json")) |
| 65 | .map_err(|e| anyhow!("tokenizer: {e}"))?; |
| 66 | |
| 67 | let cfg: DeepSeekV2Config = |
| 68 | serde_json::from_slice(&std::fs::read(args.model.join("config.json"))?)?; |
| 69 | |
| 70 | let weight_files = safetensors_files(&args.model)?; |
| 71 | let vb = unsafe { VarBuilder::from_mmaped_safetensors(&weight_files, dtype, &device)? }; |
| 72 | let mut model = DeepSeekV2::new(&cfg, vb)?; |
| 73 | eprintln!("ds2_ref | model loaded ({} layers)", cfg_num_layers(&args.model)?); |
| 74 | |
| 75 | let encoding = tokenizer |
| 76 | .encode(args.prompt.as_str(), true) |
| 77 | .map_err(|e| anyhow!("encode: {e}"))?; |
| 78 | let mut tokens: Vec<u32> = encoding.get_ids().to_vec(); |
| 79 | if tokens.is_empty() { |
| 80 | return Err(anyhow!("empty prompt")); |
| 81 | } |
| 82 | let prompt_len = tokens.len(); |
| 83 | |
| 84 | for index in 0..args.max_tokens { |
| 85 | let (context, offset) = if index == 0 { |
| 86 | (tokens.as_slice(), 0) |
| 87 | } else { |
| 88 | (&tokens[tokens.len() - 1..], tokens.len() - 1) |
| 89 | }; |
| 90 | let input = Tensor::new(context, &device)?.unsqueeze(0)?; |
| 91 | let logits = model.forward(&input, offset)?; // [1, seq, vocab] or [1, vocab] |
| 92 | // deepseek2.rs returns [b, vocab] (last-token) already; be robust either way. |
| 93 | let logits = logits.to_dtype(DType::F32)?; |
| 94 | let logits = match logits.dims().len() { |
| 95 | 3 => logits.i((0, logits.dim(1)? - 1))?, // [vocab] |
| 96 | 2 => logits.i(0)?, // [vocab] |
| 97 | 1 => logits, |
| 98 | _ => return Err(anyhow!("unexpected logits shape {:?}", logits.dims())), |
| 99 | }; |
| 100 | // At the first step (identical prompt), dump the top-8 (id: logit) pairs — |
| 101 | // the matched-input probe compared against coco's LOGITS0. |
| 102 | if index == 0 { |
| 103 | let v: Vec<f32> = logits.to_vec1::<f32>()?; |
| 104 | let mut ix: Vec<usize> = (0..v.len()).collect(); |
| 105 | ix.sort_by(|&a, &b| v[b].partial_cmp(&v[a]).unwrap()); |
| 106 | let top: Vec<String> = |
| 107 | ix.iter().take(8).map(|&i| format!("{}:{:.4}", i, v[i])).collect(); |
| 108 | println!("LOGITS0 {}", top.join(",")); |
| 109 | } |
| 110 | // Greedy argmax. |
| 111 | let next = logits.argmax(candle_core::D::Minus1)?.to_scalar::<u32>()?; |
| 112 | tokens.push(next); |
| 113 | } |
| 114 | |
| 115 | let gen_ids = &tokens[prompt_len..]; |
| 116 | let ids: Vec<String> = gen_ids.iter().map(|t| t.to_string()).collect(); |
| 117 | println!("TOKENS {}", ids.join(",")); |
| 118 | // Also print the decoded text for a human sanity read. |
| 119 | if let Ok(text) = tokenizer.decode(gen_ids, true) { |
| 120 | eprintln!("TEXT: {}{}", args.prompt, text); |
| 121 | } |
| 122 | Ok(()) |
| 123 | } |
| 124 | |
| 125 | use candle_core::IndexOp; |
| 126 | |
| 127 | fn cfg_num_layers(dir: &PathBuf) -> Result<usize> { |
| 128 | #[derive(serde::Deserialize)] |
| 129 | struct P { |
| 130 | num_hidden_layers: usize, |
| 131 | } |
| 132 | let p: P = serde_json::from_slice(&std::fs::read(dir.join("config.json"))?)?; |
| 133 | Ok(p.num_hidden_layers) |
| 134 | } |