Elffuss BraidHub

kikocis/coco public

main · 11.4 KiBRawPermalink
1// Step-1 eval harness — deterministic port of lab/evo_merge/eval_fitness.py (FIXED
2// 16 GSM8K + 16 ARC-Easy). fitness = math_acc + general_acc ∈ [0,2].
3//
4// * GSM8K: Qwen2.5 ChatML template, GREEDY up to 640 new tokens, extract the LAST
5// \boxed{...} number (else '#### N' else 'answer is N' else last number), exact
6// match vs gold.
7// * ARC-Easy MCQ: argmax next-token logprob over ' A'/' B'/' C'/' D' via logits_last.
8//
9// Deterministic (greedy, temp 0, no repeat penalty, fixed items) ⇒ a given weight-set
10// always yields the same fitness — a stable GA signal.
11
12use anyhow::{anyhow, Result};
13use candle_core::{DType, Device, Tensor};
14use candle_transformers::generation::LogitsProcessor;
15use regex::Regex;
16use serde::Deserialize;
17use std::collections::HashMap;
18use tokenizers::Tokenizer;
19
20use crate::model::Model;
21
22// Qwen2.5 special-token ids (verified against both parents' tokenizer.json).
23const IM_END: u32 = 151645; // <|im_end|> — turn end for Instruct/Math
24const EOS: u32 = 151643; // <|endoftext|>
25
26// ARC letter token ids: (bare, leading-space). Verified: A 32/362, B 33/425,
27// C 34/356, D 35/422.
28const LETTER_IDS: [(char, u32, u32); 4] =
29 [('A', 32, 362), ('B', 33, 425), ('C', 34, 356), ('D', 35, 422)];
30
31// ─────────────────────────── items ───────────────────────────
32
33#[derive(Debug, Clone, Deserialize)]
34pub struct MathItem {
35 pub q: String,
36 pub gold: String,
37}
38
39#[derive(Debug, Clone, Deserialize)]
40pub struct GenItem {
41 pub q: String,
42 pub choices: HashMap<String, String>,
43 pub gold: String,
44}
45
46#[derive(Debug, Clone, Deserialize)]
47pub struct EvalItems {
48 pub math: Vec<MathItem>,
49 pub general: Vec<GenItem>,
50}
51
52impl EvalItems {
53 /// Load the baked 16+16 items from eval_items.json (dumped once from the Python
54 /// loader — byte-identical to the reference).
55 pub fn load(path: &std::path::Path) -> Result<Self> {
56 let raw = std::fs::read(path)
57 .map_err(|e| anyhow!("reading eval items {}: {e}", path.display()))?;
58 let items: EvalItems = serde_json::from_slice(&raw)
59 .map_err(|e| anyhow!("parsing eval items {}: {e}", path.display()))?;
60 Ok(items)
61 }
62
63 /// Truncate to the first `n_math` / `n_general` items (for --n-math/--n-general).
64 pub fn take(mut self, n_math: usize, n_general: usize) -> Self {
65 self.math.truncate(n_math);
66 self.general.truncate(n_general);
67 self
68 }
69}
70
71#[derive(Debug, Clone, Copy)]
72pub struct Fitness {
73 pub math: f32,
74 pub general: f32,
75 pub combined: f32,
76}
77
78// ─────────────────────────── prompting ───────────────────────────
79
80/// Qwen2.5 ChatML with the explicit system line (suppresses the Math model's default
81/// \boxed{} system injection so both parents get identical prompts). Verbatim of the
82/// template `apply_chat_template` produces for the fixed system+user pair.
83pub fn qwen_chat(user: &str) -> String {
84 format!(
85 "<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n\
86 <|im_start|>user\n{user}<|im_end|>\n<|im_start|>assistant\n"
87 )
88}
89
90const MATH_INSTR: &str = "Solve the problem. Show brief reasoning, then give the final \
91 answer on a new line as '#### <number>'.\n\nProblem: ";
92
93fn encode(tok: &Tokenizer, prompt: &str) -> Result<Vec<u32>> {
94 // add_special_tokens=false — the ChatML template already carries the specials.
95 let enc = tok
96 .encode(prompt, false)
97 .map_err(|e| anyhow!("encoding prompt: {e}"))?;
98 Ok(enc.get_ids().to_vec())
99}
100
101// ─────────────────────────── coco eval primitives ───────────────────────────
102
103/// The MCQ primitive: run a single forward over `ids`, return the last-position
104/// logits as an F32 vocab vector. `.to_dtype(F32)` BEFORE softmax (matches Python
105/// `.float()`). coco's forward already narrows to the last position → [1,1,vocab].
106pub fn logits_last(m: &mut dyn Model, dev: &Device, ids: &[u32]) -> Result<Vec<f32>> {
107 m.clear_kv_cache();
108 let input = Tensor::new(ids, dev)?.unsqueeze(0)?; // [1, seq]
109 let logits = m.forward(&input, 0)?; // [1,1,vocab]
110 let v = logits
111 .squeeze(0)?
112 .squeeze(0)?
113 .to_dtype(DType::F32)?
114 .to_vec1::<f32>()?;
115 Ok(v)
116}
117
118/// Greedy generation lifted from main.rs's loop. temp=None ⇒ argmax; repeat_penalty
119/// 1.0 (Python `do_sample=False, num_beams=1`). Stops on any id in `stops` (pass
120/// [IM_END, EOS] or math runs to the 640-token cap). Returns the decoded new text
121/// (skip_special_tokens=true, matching the Python decode).
122pub fn generate_greedy(
123 m: &mut dyn Model,
124 tok: &Tokenizer,
125 dev: &Device,
126 ids: &[u32],
127 max_new: usize,
128 stops: &[u32],
129) -> Result<String> {
130 m.clear_kv_cache();
131 let mut tokens: Vec<u32> = ids.to_vec();
132 let prompt_len = tokens.len();
133 let mut lp = LogitsProcessor::new(0, None, None); // temp None ⇒ argmax (greedy)
134
135 for index in 0..max_new {
136 let (context, offset) = if index == 0 {
137 (&tokens[..], 0)
138 } else {
139 (&tokens[tokens.len() - 1..], tokens.len() - 1)
140 };
141 let input = Tensor::new(context, dev)?.unsqueeze(0)?;
142 let logits = m.forward(&input, offset)?; // [1,1,vocab]
143 let logits = logits.squeeze(0)?.squeeze(0)?.to_dtype(DType::F32)?;
144 let next = lp.sample(&logits)?;
145 if stops.contains(&next) {
146 break;
147 }
148 tokens.push(next);
149 }
150
151 let gen = &tokens[prompt_len..];
152 let text = tok
153 .decode(gen, true)
154 .map_err(|e| anyhow!("decoding generation: {e}"))?;
155 Ok(text)
156}
157
158// ─────────────────────────── answer extraction (port of _extract_int) ───────────────────────────
159
160/// Pull the last plain number out of a string (handles $, commas, decimals).
161/// Port of `_num_in`.
162fn num_in(s: &str) -> Option<String> {
163 let cleaned = s.replace('$', "");
164 let re = Regex::new(r"[-]?\d[\d,]*(?:\.\d+)?").unwrap();
165 re.find_iter(&cleaned).last().map(|m| m.as_str().to_string())
166}
167
168/// Normalize a number string: strip $/commas, `.0`→int. Port of `_norm_num`.
169pub fn norm_num(s: &str) -> String {
170 let t = s.replace('$', "").replace(',', "");
171 let t = t.trim();
172 if let Ok(f) = t.parse::<f64>() {
173 if f == f.trunc() && f.is_finite() {
174 return (f as i64).to_string();
175 }
176 return f.to_string();
177 }
178 t.to_string()
179}
180
181/// Extract the predicted answer, in the SAME priority order as `_extract_int`:
182/// (1) LAST \boxed{...} inner number, (2) last '#### N', (3) 'answer (is|:|=) N',
183/// (4) last standalone number.
184pub fn extract_int(text: &str) -> Option<String> {
185 // 1) LAST \boxed{...} — inner has no nested braces.
186 let boxed = Regex::new(r"\\boxed\{([^{}]*)\}").unwrap();
187 let boxed_hits: Vec<String> = boxed
188 .captures_iter(text)
189 .map(|c| c[1].to_string())
190 .collect();
191 if let Some(last) = boxed_hits.last() {
192 if let Some(n) = num_in(last) {
193 return Some(norm_num(&n));
194 }
195 }
196 // 2) '#### N'
197 let hashes = Regex::new(r"####\s*([-\$]?[0-9][0-9,\.]*)").unwrap();
198 let hash_hits: Vec<String> = hashes.captures_iter(text).map(|c| c[1].to_string()).collect();
199 if let Some(last) = hash_hits.last() {
200 return Some(norm_num(last));
201 }
202 // 3) 'answer is|:|= N' (case-insensitive)
203 let ans = Regex::new(r"(?i)answer\s*(?:is|:|=)?\s*\$?([-]?[0-9][0-9,\.]*)").unwrap();
204 let ans_hits: Vec<String> = ans.captures_iter(text).map(|c| c[1].to_string()).collect();
205 if let Some(last) = ans_hits.last() {
206 return Some(norm_num(last));
207 }
208 // 4) fallback: last standalone number
209 let any = Regex::new(r"([-\$]?\d[\d,]*(?:\.\d+)?)").unwrap();
210 let any_hits: Vec<String> = any.captures_iter(text).map(|c| c[1].to_string()).collect();
211 if let Some(last) = any_hits.last() {
212 return Some(norm_num(last));
213 }
214 None
215}
216
217// ─────────────────────────── the two evals ───────────────────────────
218
219/// GSM8K greedy exact-match. math_acc = correct / n.
220pub fn score_math(
221 m: &mut dyn Model,
222 tok: &Tokenizer,
223 dev: &Device,
224 items: &[MathItem],
225) -> Result<f32> {
226 if items.is_empty() {
227 return Ok(0.0);
228 }
229 let stops = [IM_END, EOS];
230 let mut correct = 0usize;
231 for it in items {
232 let prompt = qwen_chat(&format!("{MATH_INSTR}{}", it.q));
233 let ids = encode(tok, &prompt)?;
234 let gen = generate_greedy(m, tok, dev, &ids, 640, &stops)?;
235 let pred = extract_int(&gen);
236 let gold = norm_num(&it.gold);
237 if std::env::var("COCO_DEBUG_GEN").is_ok() {
238 eprintln!("--- GEN (gold={gold} pred={:?}) ---\n{}\n--- END (len={}) ---", pred, gen, gen.len());
239 }
240 if pred.as_deref() == Some(gold.as_str()) {
241 correct += 1;
242 }
243 }
244 Ok(correct as f32 / items.len() as f32)
245}
246
247/// log_softmax over an F32 vocab vector (subtract max, exp, log-normalize).
248fn log_softmax(logits: &[f32]) -> Vec<f32> {
249 let max = logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
250 let mut sum = 0f64;
251 for &x in logits {
252 sum += ((x - max) as f64).exp();
253 }
254 let log_sum = sum.ln() as f32;
255 logits.iter().map(|&x| (x - max) - log_sum).collect()
256}
257
258/// ARC-Easy MCQ by next-token letter logprob. general_acc = correct / n.
259pub fn score_arc(
260 m: &mut dyn Model,
261 tok: &Tokenizer,
262 dev: &Device,
263 items: &[GenItem],
264) -> Result<f32> {
265 if items.is_empty() {
266 return Ok(0.0);
267 }
268 let mut correct = 0usize;
269 for it in items {
270 // Options in fixed A,B,C,D order.
271 let mut opts = String::new();
272 for (letter, _, _) in LETTER_IDS.iter() {
273 let key = letter.to_string();
274 if let Some(v) = it.choices.get(&key) {
275 if !opts.is_empty() {
276 opts.push('\n');
277 }
278 opts.push_str(&format!("{letter}. {v}"));
279 }
280 }
281 let user = format!(
282 "Answer the multiple choice question.\n\nQuestion: {}\n{}\n\nRespond with just the letter of the correct answer.",
283 it.q, opts
284 );
285 let prompt = qwen_chat(&user);
286 let ids = encode(tok, &prompt)?;
287 let lp = logits_last(m, dev, &ids)?;
288 let logprobs = log_softmax(&lp);
289 let mut best_letter = 'A';
290 let mut best_score = f32::NEG_INFINITY;
291 for (letter, bare, space) in LETTER_IDS.iter() {
292 let s = logprobs[*bare as usize].max(logprobs[*space as usize]);
293 if s > best_score {
294 best_score = s;
295 best_letter = *letter;
296 }
297 }
298 if best_letter.to_string() == it.gold {
299 correct += 1;
300 }
301 }
302 Ok(correct as f32 / items.len() as f32)
303}
304
305/// fitness = math_acc + general_acc.
306pub fn fitness(
307 m: &mut dyn Model,
308 tok: &Tokenizer,
309 dev: &Device,
310 items: &EvalItems,
311) -> Result<Fitness> {
312 let math = score_math(m, tok, dev, &items.math)?;
313 let general = score_arc(m, tok, dev, &items.general)?;
314 Ok(Fitness {
315 math,
316 general,
317 combined: math + general,
318 })
319}