""" collect_data_helpers.py ======================= Shared utilities: model loading, prompt formatting, answer scoring. All four domains now have clean ground-truth answer keys loaded directly from HuggingFace (no RouterBench, no reference-answer extraction): gsm8k — answer_key is the numeric final answer humaneval — answer_key is canonical_solution; scored by actually EXECUTING the generated code against test_code in a subprocess sandbox with a timeout mmlu — answer_key is a letter A/B/C/D commonsenseqa — answer_key is a letter A-E No verbal confidence anywhere — all routing signals come from model internals (log-prob, entropy, hidden states), extracted in 01_collect_data.py. """ import re import subprocess import tempfile import os import torch from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig def build_prompt(prompt_text, tokenizer, model_key, dataset=None): """ Apply the correct prompt format per model and task. qwen25_math (all tasks): Requires a system prompt instructing it to reason step by step and put the final answer in \boxed{}. Without this system prompt, Qwen-Math either refuses or outputs prose with no parseable answer — this is why it scored near 0% on GSM8K in the first run. Source: https://huggingface.co/Qwen/Qwen2.5-Math-1.5B-Instruct qwen25_coder (HumanEval): IS an instruct model — should receive a user message asking it to complete the function. Raw completion mode caused it to continue the docstring text rather than implement the function body. Source: https://huggingface.co/Qwen/Qwen2.5-Coder-1.5B-Instruct HumanEval for all OTHER models: Raw completion — non-coder instruct models produce better code completing a function signature directly than conversationally. All other combinations: Standard chat template with no system prompt. """ # ── Qwen-Math: CoT system prompt required for all tasks ──────────────────── if model_key == "qwen25_math": messages = [ { "role": "system", "content": "Please reason step by step, and put your final answer within \\boxed{}.", }, {"role": "user", "content": prompt_text}, ] try: return tokenizer.apply_chat_template( messages, tokenize=False, add_generation_prompt=True ) except Exception: # Fallback: prepend instruction manually return ("Please reason step by step, and put your final answer " "within \\boxed{}.\n\n" + prompt_text) # ── Qwen-Coder on HumanEval: instruct-style, not raw completion ───────── if model_key == "qwen25_coder" and dataset == "humaneval": messages = [ { "role": "system", "content": "You are Qwen, created by Alibaba Cloud. You are a helpful assistant.", }, { "role": "user", "content": ( "Complete the following Python function. " "Return only the completed function, no explanation.\n\n" + prompt_text ), }, ] try: return tokenizer.apply_chat_template( messages, tokenize=False, add_generation_prompt=True ) except Exception: return prompt_text # ── HumanEval for all other models: raw completion ──────────────────────── if dataset == "humaneval": return prompt_text # ── Default: standard chat template, no system prompt ───────────────────── try: messages = [{"role": "user", "content": prompt_text}] return tokenizer.apply_chat_template( messages, tokenize=False, add_generation_prompt=True ) except Exception: return prompt_text def load_model(model_key, model_id, logger, use_4bit=False, trust_remote_code=True): """ Load with configurable precision and trust_remote_code. use_4bit=False (default) — fp16 for all models in our pool (≤3.8B). 4-bit quantisation overhead is not worth it at this size; fp16 is actually faster on a T4 for models this small. trust_remote_code — set False for Phi-3, whose remote modeling code has a rope_scaling KeyError on some transformers versions. All other models in the pool use standard architectures and need it True (or it's simply ignored). output_hidden_states=True so hidden states are available for the probe. """ use_cuda = torch.cuda.is_available() tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=trust_remote_code) if tokenizer.pad_token is None: tokenizer.pad_token = tokenizer.eos_token if use_4bit and use_cuda: bnb_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_compute_dtype=torch.float16, bnb_4bit_use_double_quant=True, bnb_4bit_quant_type="nf4", ) model = AutoModelForCausalLM.from_pretrained( model_id, quantization_config=bnb_config, device_map={"": 0}, # explicit single-GPU placement — "auto" has # been observed silently placing some models # (e.g. Phi-3) on CPU instead of GPU output_hidden_states=True, trust_remote_code=trust_remote_code, ) elif use_cuda: model = AutoModelForCausalLM.from_pretrained( model_id, torch_dtype=torch.float16, device_map={"": 0}, output_hidden_states=True, trust_remote_code=trust_remote_code, ) else: model = AutoModelForCausalLM.from_pretrained( model_id, torch_dtype=torch.float32, output_hidden_states=True, trust_remote_code=trust_remote_code, ) model.eval() logger.info( f"Loaded {model_id} | CUDA: {use_cuda} | 4bit: {use_4bit} | " f"trust_remote_code: {trust_remote_code}" ) return model, tokenizer # ── MCQ scoring (mmlu, commonsenseqa) ─────────────────────────────────────────── def _extract_letter(text: str) -> str: """ Extract the first answer letter (A-E) from a model response. Handles: "A", "A)", "A.", "(A)", "The answer is A", etc. """ text = text.strip() if text and text[0].upper() in "ABCDE": return text[0].upper() m = re.search(r'\b([ABCDE])[).:\s]', text.upper()) if m: return m.group(1) m = re.search(r'answer[^A-E]*([ABCDE])', text.upper()) if m: return m.group(1) m = re.search(r'[ABCDE]', text.upper()) if m: return m.group(0) return "" # ── GSM8K scoring ──────────────────────────────────────────────────────────────── def _extract_number(text: str) -> str: """ Extract the final numeric answer from a math response. Qwen-Math puts its answer inside \\boxed{} — check that first. Fall back to the last number in the text for other models. """ # Priority 1: \boxed{42} or \boxed{42.5} — Qwen-Math format boxed = re.findall(r'\\boxed\{([^}]+)\}', text) if boxed: # Take the last \boxed{} in case there are intermediate ones candidate = boxed[-1].replace(",", "").strip() nums = re.findall(r"-?\d+(?:\.\d+)?", candidate) if nums: return nums[-1] # Priority 2: "The answer is 42" or "= 42" patterns m = re.search(r'(?:answer is|=)\s*(-?\d[\d,]*(?:\.\d+)?)', text, re.IGNORECASE) if m: return m.group(1).replace(",", "") # Priority 3: last number in the response text_clean = text.replace(",", "") nums = re.findall(r"-?\d+(?:\.\d+)?", text_clean) return nums[-1] if nums else "" # ── HumanEval scoring — real code execution ───────────────────────────────────── def _extract_code(response: str) -> str: """ Extract Python code from a model response. Since HumanEval now uses raw completion (not chat-wrapped), the response is typically the direct continuation of the function body. Markdown fences are still stripped defensively in case the model adds them anyway (common even in raw completion mode for instruct-tuned models). """ fence_match = re.search(r"```(?:python)?\s*\n(.*?)```", response, re.DOTALL) if fence_match: return fence_match.group(1) return response def _score_humaneval(response: str, prompt_dict: dict, timeout: int = 5) -> int: """ Execute the generated code against HumanEval's unit tests in a subprocess sandbox with a timeout. Returns 1 if all tests pass, 0 otherwise. Since generation is raw completion (build_prompt skips the chat template for humaneval), the response is the direct continuation of the prompt's function signature. The full program is therefore: original_prompt + response + test_code + check(entry_point) If the model's response happens to redeclare "def {entry_point}" from scratch (some instruct models do this even in completion mode), we use the response alone instead of prompt+response to avoid a duplicate/ conflicting function definition. Truncation handling: if generation hit max_new_tokens before completing the function body, the code will fail to parse/execute — scored as 0. This is the expected and correct behaviour (an incomplete answer is a wrong answer), not an error case requiring retry at this stage. """ prompt_text = prompt_dict["prompt"] # function signature + docstring test_code = prompt_dict["test_code"] # unit test code entry_point = prompt_dict["entry_point"] # function name being tested code = _extract_code(response) if f"def {entry_point}" in code: # Model redeclared the full function — use its version standalone full_program = code else: # Normal case: response is the continuation of the prompt's signature full_program = prompt_text + code full_program += "\n\n" + test_code + f"\n\ncheck({entry_point})\n" with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f: f.write(full_program) tmp_path = f.name try: result = subprocess.run( ["python3", tmp_path], capture_output=True, timeout=timeout, text=True, ) return 1 if result.returncode == 0 else 0 except subprocess.TimeoutExpired: return 0 except Exception: return 0 finally: try: os.unlink(tmp_path) except OSError: pass # ── Unified scoring entry point ───────────────────────────────────────────────── def score_answer(response: str, prompt_dict: dict) -> int: """ Score a model's response as 0 (wrong) or 1 (correct). Dispatches by prompt_dict['dataset']: gsm8k — numeric match against answer_key humaneval — real code execution against test_code (subprocess) mmlu — letter match against answer_key commonsenseqa — letter match against answer_key All four domains have clean ground-truth answer_key values loaded directly from HuggingFace — no reference-answer extraction needed. """ dataset = prompt_dict.get("dataset", "") answer_key = prompt_dict.get("answer_key", "") if dataset == "gsm8k": our_num = _extract_number(response) if not our_num or not answer_key: return 0 try: # Tolerance comparison — exact float equality fails on values # like 33.33 vs 33.333..., which are "correct" but not bit-equal return int(abs(float(our_num) - float(answer_key)) < 1e-4) except ValueError: return 0 elif dataset == "humaneval": return _score_humaneval(response, prompt_dict) elif dataset in ("mmlu", "commonsenseqa"): our_letter = _extract_letter(response) ref_letter = str(answer_key).strip().upper() if answer_key else "" if not our_letter or not ref_letter: return 0 return int(our_letter == ref_letter) else: # Fallback — substring match return int(str(answer_key).strip().lower() in response.strip().lower())