File size: 13,132 Bytes
c950b9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
"""
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())