Santhoshini commited on
Commit
e16a894
·
verified ·
1 Parent(s): c7dbd32

Update script.py

Browse files
Files changed (1) hide show
  1. script.py +846 -0
script.py CHANGED
@@ -0,0 +1,846 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """IOL-AI 2026 submission: Qwen2.5-14B-Instruct (bnb-4bit via
3
+ unsloth/Qwen2.5-14B-Instruct-bnb-4bit), offline-only dependency install,
4
+ a decomposition-and-verification prompt augmented with a deterministic
5
+ symbolic-evidence layer, item-count-aware token budgeting, a fail-open
6
+ closed-answer-space constraint for match_letters, and guaranteed
7
+ explanations.
8
+
9
+ History, briefly: every piece below was individually diagnosed against a
10
+ real failure on real Linguini/IOL problems (a markdown-formatted answer
11
+ marker, a COMPUTE-line bleeding into the answer list, an "is:" prefix
12
+ surviving into a near-miss answer, a match_letters bijection violation,
13
+ truncation on multi-item problems) before being combined here. Nothing in
14
+ this file is speculative -- every module states the specific failure it
15
+ closes.
16
+
17
+ Compliance: fully offline before any Hugging Face import, MODEL_ID=".",
18
+ reads only /tmp/data/test.csv, writes only submission.csv with
19
+ id/pred/explanation, float16 (the T4 is Turing, no native bfloat16), the
20
+ 30-minute budget is respected with a real safety margin, every row is
21
+ guaranteed a submission.csv entry even under a crash or a timeout.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import atexit
27
+ import os
28
+ import time
29
+ from pathlib import Path
30
+
31
+ SCRIPT_STARTED_AT = time.monotonic()
32
+
33
+ # ---------------------------------------------------------------------------
34
+ # Offline mode, set before any Hugging Face import. Restored on exit (see
35
+ # _restore_offline_env_vars below) -- if the evaluation harness ever runs
36
+ # this script in-process rather than as an isolated subprocess, leftover
37
+ # offline-mode env vars could otherwise affect a later, unrelated
38
+ # huggingface_hub call made by the harness itself after this script exits.
39
+ # ---------------------------------------------------------------------------
40
+ _ORIGINAL_HF_HUB_OFFLINE = os.environ.get("HF_HUB_OFFLINE")
41
+ _ORIGINAL_TRANSFORMERS_OFFLINE = os.environ.get("TRANSFORMERS_OFFLINE")
42
+
43
+
44
+ def _restore_offline_env_vars() -> None:
45
+ """Restores HF_HUB_OFFLINE/TRANSFORMERS_OFFLINE to their exact
46
+ pre-script state on exit, via atexit so it fires regardless of how or
47
+ where the script exits. Costs nothing; cannot make anything worse."""
48
+ for key, original in (("HF_HUB_OFFLINE", _ORIGINAL_HF_HUB_OFFLINE),
49
+ ("TRANSFORMERS_OFFLINE", _ORIGINAL_TRANSFORMERS_OFFLINE)):
50
+ if original is None:
51
+ os.environ.pop(key, None)
52
+ else:
53
+ os.environ[key] = original
54
+
55
+
56
+ atexit.register(_restore_offline_env_vars)
57
+ os.environ["HF_HUB_OFFLINE"] = "1"
58
+ os.environ["TRANSFORMERS_OFFLINE"] = "1"
59
+
60
+ import subprocess
61
+ import sys
62
+
63
+ # ---------------------------------------------------------------------------
64
+ # Configuration -- env-var overridable, sensible defaults otherwise.
65
+ # ---------------------------------------------------------------------------
66
+ SCRIPT_DIR = Path(__file__).resolve().parent
67
+ INPUT_CSV = Path(os.environ.get("IOL_INPUT", "/tmp/data/test.csv"))
68
+ OUTPUT_CSV = Path(os.environ.get("IOL_OUTPUT", "submission.csv"))
69
+ MODEL_ID = os.environ.get("IOL_MODEL_ID", ".")
70
+
71
+ TIME_LIMIT_S = float(os.environ.get("IOL_TIME_LIMIT_S", 30 * 60))
72
+ SETUP_BUFFER_S = float(os.environ.get("IOL_SETUP_BUFFER_S", 420)) # 14B bnb-4bit is ~8-9GB, slow to load
73
+ EXIT_RESERVE_S = float(os.environ.get("IOL_EXIT_RESERVE_S", 60))
74
+
75
+ TOKENS_CAP_FLOOR = int(os.environ.get("IOL_TOKENS_FLOOR", 640))
76
+ TOKENS_CAP_CEIL = int(os.environ.get("IOL_TOKENS_CEIL", 1536))
77
+ TOKENS_PER_ITEM = int(os.environ.get("IOL_TOKENS_PER_ITEM", 48))
78
+ TOKENS_PER_ITEM_BASE = int(os.environ.get("IOL_TOKENS_PER_ITEM_BASE", 256))
79
+
80
+
81
+ def elapsed_seconds() -> float:
82
+ return time.monotonic() - SCRIPT_STARTED_AT
83
+
84
+
85
+ # ---------------------------------------------------------------------------
86
+ # Crash safety: two independent write paths, neither depending on the
87
+ # other, neither depending on anything that might have just failed.
88
+ # ---------------------------------------------------------------------------
89
+ def write_submission_csv(rows_list: list[dict]) -> None:
90
+ """Stdlib csv, not pandas -- avoids a real, documented pandas/numpy ABI
91
+ crash ('TypeError: Cannot convert numpy.ndarray to numpy.ndarray' inside
92
+ pandas' Index construction) that a top-scoring public IOL-AI 2026
93
+ submission hit in this exact sandbox. Atomic: writes to a temp file
94
+ then os.replace()s it into place, so a reader can never observe a
95
+ partially-written file mid-save."""
96
+ import csv
97
+ tmp_path = OUTPUT_CSV.with_suffix(OUTPUT_CSV.suffix + ".tmp")
98
+ with tmp_path.open("w", newline="", encoding="utf-8") as f:
99
+ writer = csv.DictWriter(f, fieldnames=["id", "pred", "explanation"])
100
+ writer.writeheader()
101
+ for row in rows_list:
102
+ writer.writerow(row)
103
+ os.replace(tmp_path, OUTPUT_CSV)
104
+
105
+
106
+ def emergency_submission_csv(reason: str, rows_so_far: list[dict] | None = None) -> None:
107
+ """Last-resort guarantee: no matter WHERE the script dies, a valid
108
+ submission.csv exists before the process exits -- the single fix for
109
+ the pattern where a crash with nothing written turns a scoreable zero
110
+ into a hard evaluation failure. Independent of write_submission_csv:
111
+ uses only the standard library, so it cannot fail for the same reason
112
+ a pandas-based path might."""
113
+ import csv
114
+ import json
115
+ try:
116
+ if rows_so_far:
117
+ write_submission_csv(rows_so_far)
118
+ return
119
+ ids: list[str] = []
120
+ try:
121
+ with INPUT_CSV.open(newline="", encoding="utf-8") as f:
122
+ for row in csv.DictReader(f):
123
+ if row.get("id"):
124
+ ids.append(row["id"])
125
+ except Exception:
126
+ pass
127
+ rows = [{"id": i, "pred": json.dumps([""]),
128
+ "explanation": f"EMERGENCY FALLBACK: {str(reason)[:150]}"} for i in ids]
129
+ write_submission_csv(rows)
130
+ except Exception:
131
+ try:
132
+ with OUTPUT_CSV.open("w") as f:
133
+ f.write("id,pred,explanation\n")
134
+ except Exception:
135
+ pass
136
+
137
+
138
+ # ---------------------------------------------------------------------------
139
+ # Offline dependency install.
140
+ # ---------------------------------------------------------------------------
141
+ def ensure_dependencies() -> None:
142
+ """Split deliberately: torch is NOT force-upgraded (a multi-GB
143
+ CUDA-specific wheel; forcing -U risks pulling a build mismatched with
144
+ the sandbox's actual driver -- a worse failure than a missing
145
+ package). bitsandbytes needs no upgrade evidence behind it.
146
+ transformers/accelerate/tokenizers have a CONFIRMED version-related
147
+ failure behind them -- those are the only ones forced."""
148
+ subprocess.run([sys.executable, "-m", "pip", "install", "-q",
149
+ "torch>=2.2", "bitsandbytes", "pandas"], check=True)
150
+ subprocess.run([sys.executable, "-m", "pip", "install", "-q", "-U",
151
+ "transformers>=4.43", "accelerate>=0.30", "tokenizers"], check=True)
152
+
153
+
154
+ try:
155
+ ensure_dependencies()
156
+ except Exception as exc:
157
+ emergency_submission_csv(f"pip install failed: {exc}")
158
+ raise
159
+
160
+ import re
161
+ import json
162
+ import unicodedata
163
+ import ast as pyast
164
+ import pandas as pd
165
+ import torch
166
+ from difflib import SequenceMatcher
167
+ from collections import defaultdict
168
+ from transformers import AutoTokenizer, AutoModelForCausalLM
169
+
170
+
171
+ # ---------------------------------------------------------------------------
172
+ # Model loading.
173
+ # ---------------------------------------------------------------------------
174
+ def load_model():
175
+ """Fast tokenizer first; on failure, falls back to use_fast=False --
176
+ bypasses TokenizerFast.from_file() entirely, which is exactly the call
177
+ that fails on a tokenizer.json saved by a newer tokenizers library than
178
+ the sandbox has."""
179
+ try:
180
+ tok = AutoTokenizer.from_pretrained(MODEL_ID)
181
+ print("Tokenizer loaded (fast).", flush=True)
182
+ except Exception as exc:
183
+ print(f"Fast tokenizer failed ({exc}); falling back to use_fast=False.", flush=True)
184
+ tok = AutoTokenizer.from_pretrained(MODEL_ID, use_fast=False)
185
+ print("Tokenizer loaded (slow fallback).", flush=True)
186
+
187
+ model = AutoModelForCausalLM.from_pretrained(
188
+ MODEL_ID, torch_dtype=torch.float16, device_map="auto",
189
+ ).eval()
190
+ print(f"Model loaded | memory footprint: {round(model.get_memory_footprint() / 1e9, 1)} GB | "
191
+ f"quantized: {getattr(model.config, 'quantization_config', None) is not None}", flush=True)
192
+ return tok, model
193
+
194
+
195
+ # ---------------------------------------------------------------------------
196
+ # Query parsing: widened patterns + honest "unknown count" fallback.
197
+ # ---------------------------------------------------------------------------
198
+ def parse_items(query: str) -> tuple[str, list[str], bool]:
199
+ """Returns (preamble, items, count_known). count_known=False means no
200
+ pattern matched -- we do NOT guess a count, we let the model's own
201
+ answer list stand rather than risk truncating real content."""
202
+ item_pat = re.compile(r"(?m)^\s*(\d+)\s*[.\)]\s*(.*)$")
203
+ matches = list(item_pat.finditer(query))
204
+ if matches:
205
+ preamble = query[:matches[0].start()].strip()
206
+ items = []
207
+ for i, m in enumerate(matches):
208
+ end = matches[i + 1].start() if i + 1 < len(matches) else len(query)
209
+ text = re.sub(r"^\s*\d+\s*[.\)]\s*", "", query[m.start():end].strip())
210
+ items.append(text)
211
+ return preamble, items, True
212
+
213
+ rng = re.search(r"[\(\[]?\s*(\d+)\s*(?:[-\u2013\u2014:]|to)\s*(\d+)\s*[\)\]]?", query, flags=re.IGNORECASE)
214
+ if rng:
215
+ lo, hi = int(rng.group(1)), int(rng.group(2))
216
+ if 0 < hi - lo < 100:
217
+ items = []
218
+ for k in range(lo, hi + 1):
219
+ line_match = re.search(rf"(?m)^.*\(\s*{k}\s*\).*$", query)
220
+ if line_match:
221
+ clue = re.sub(rf"\(\s*{k}\s*\)", "", line_match.group(0)).strip()
222
+ clue = re.sub(r"\|\s*\|", "|", clue)
223
+ clue = re.sub(r"\s{2,}", " ", clue).strip(" |")
224
+ items.append(clue if clue else f"the numbered item {k} from the examples above")
225
+ else:
226
+ items.append(f"the numbered item {k} from the examples above")
227
+ return query.strip(), items, True
228
+
229
+ csv_nums = re.findall(r"(?m)^\s*(\d+)\s*,\s*(\d+(?:\s*,\s*\d+)*)\s*$", query)
230
+ if csv_nums:
231
+ all_nums = re.findall(r"\d+", " ".join(csv_nums[0]))
232
+ return query.strip(), [f"the numbered item {n}" for n in all_nums], True
233
+
234
+ return query.strip(), [], False
235
+
236
+
237
+ TASK_GUIDANCE = {
238
+ "translation": "give the translated form only, in the language asked.",
239
+ "fill_blanks": "give only the missing form for each blank.",
240
+ "match_letters": "give only the option letter (for example A, B, C).",
241
+ "text_to_num": "give the number in digits.",
242
+ "num_to_text": "give the number written out in words, in the language asked.",
243
+ }
244
+ DEFAULT_GUIDANCE = "give exactly what the instruction asks, nothing else."
245
+
246
+
247
+ # ---------------------------------------------------------------------------
248
+ # Symbolic preprocessing layer -- pure standard library, no new
249
+ # dependencies, deterministic, CPU-only, negligible runtime. Survived a
250
+ # multi-round falsification pass: only the two evidence objects that (a)
251
+ # compute something a fast read is likely to miss by construction and (b)
252
+ # cannot mislead when wrong (worst case is silence, never false
253
+ # confidence) were kept. Augments the raw context; never replaces it.
254
+ # ---------------------------------------------------------------------------
255
+ def extract_forms_from_context(context: str) -> list[str]:
256
+ """Pulls candidate unknown-language 'forms' for reduplication's
257
+ per-word self-check ONLY. Pipe-delimited lines contribute ONLY their
258
+ FIRST field -- including gloss/meaning fields would let ordinary
259
+ English words trigger false reduplication hits. Lines with more than 3
260
+ pipes are skipped defensively -- Hadza (a confirmed IOL 2026 language)
261
+ is a click language, and '|' is sometimes used informally to
262
+ transcribe click consonants, which would misparse as our delimiter."""
263
+ forms = []
264
+ for line in context.splitlines():
265
+ line = line.strip()
266
+ if not line:
267
+ continue
268
+ pipe_count = line.count("|")
269
+ if 0 < pipe_count <= 3:
270
+ first_field = re.sub(r"^\s*\d+\s*[.\)]\s*", "", line.split("|")[0].strip()).strip()
271
+ if first_field:
272
+ forms.append(first_field)
273
+ elif pipe_count == 0:
274
+ for t in line.split():
275
+ t_clean = re.sub(r"^\s*\d+\s*[.\)]\s*", "", t).strip(".,;:")
276
+ if t_clean and len(t_clean) > 1:
277
+ forms.append(t_clean)
278
+ seen, unique_forms = set(), []
279
+ for f in forms:
280
+ if f not in seen:
281
+ seen.add(f)
282
+ unique_forms.append(f)
283
+ return unique_forms
284
+
285
+
286
+ def extract_explicit_pairs(context: str) -> list[tuple[str, str]]:
287
+ """Genuine (input, output) pairs from pipe-delimited rows -- e.g.
288
+ fill_blanks' 'given | derived | gloss' structure. The ONLY source of
289
+ pairs fed to transformation-family detection: forms from DIFFERENT
290
+ rows are never cross-compared, which would manufacture spurious
291
+ 'transformations' between unrelated words."""
292
+ pairs = []
293
+ for line in context.splitlines():
294
+ line = line.strip()
295
+ if not (0 < line.count("|") <= 3):
296
+ continue
297
+ fields = [re.sub(r"^\s*\d+\s*[.\)]\s*", "", f.strip()).strip() for f in line.split("|")]
298
+ fields = [f for f in fields if f]
299
+ if len(fields) >= 2:
300
+ pairs.append((fields[0], fields[1]))
301
+ return pairs
302
+
303
+
304
+ def edit_signature(a: str, b: str):
305
+ """A clean single-region transformation signature, or None if the
306
+ difference is scattered (too noisy to call one transformation), OR if
307
+ there is no genuine shared stem of at least 2 characters -- without
308
+ this check, two totally unrelated words with zero characters in
309
+ common were being accepted as a fake signature, since SequenceMatcher
310
+ returns a single 'replace' opcode for a total mismatch too."""
311
+ sm = SequenceMatcher(None, a, b, autojunk=False)
312
+ all_ops = sm.get_opcodes()
313
+ ops = [op for op in all_ops if op[0] != "equal"]
314
+ if not ops or len(ops) > 2:
315
+ return None
316
+ equal_len = sum((i2 - i1) for tag, i1, i2, j1, j2 in all_ops if tag == "equal")
317
+ if equal_len < 2:
318
+ return None
319
+ tag, i1, i2, j1, j2 = ops[0]
320
+ removed, inserted = a[i1:i2], b[j1:j2]
321
+ if i1 == 0:
322
+ pos = "prefix"
323
+ elif i2 == len(a):
324
+ pos = "suffix"
325
+ else:
326
+ pos = "infix"
327
+ return (pos, removed, inserted)
328
+
329
+
330
+ def find_transformation_families(pairs: list[tuple[str, str]]) -> list[str]:
331
+ """Clusters GENUINELY PAIRED forms (same row only) sharing an
332
+ identical clean edit signature. Emits a family only if 2+ separate
333
+ given pairs share it -- one occurrence is worse than silence."""
334
+ groups = defaultdict(list)
335
+ for a, b in pairs:
336
+ if not a or not b or a == b:
337
+ continue
338
+ sig = edit_signature(a, b)
339
+ if sig:
340
+ groups[sig].append((a, b))
341
+
342
+ families = []
343
+ for sig, grp in groups.items():
344
+ unique_pairs = list(dict.fromkeys(grp))
345
+ if len(unique_pairs) >= 2:
346
+ pos, removed, inserted = sig
347
+ removed_disp = removed if removed else "(nothing)"
348
+ inserted_disp = inserted if inserted else "(nothing)"
349
+ examples = "; ".join(f"{a}->{b}" for a, b in unique_pairs[:4])
350
+ families.append((len(unique_pairs),
351
+ f"{pos} change: '{removed_disp}' -> '{inserted_disp}' (seen in: {examples})"))
352
+ families.sort(key=lambda x: -x[0])
353
+ return [f for _, f in families]
354
+
355
+
356
+ def detect_reduplication(forms: list[str]) -> list[str]:
357
+ """Flags a word only if it contains an exact adjacent doubled
358
+ substring (length >= 2). Emits nothing if absent."""
359
+ findings = []
360
+ for w in forms:
361
+ n = len(w)
362
+ found = False
363
+ for length in range(2, n // 2 + 1):
364
+ for start in range(0, n - 2 * length + 1):
365
+ chunk = w[start:start + length]
366
+ nxt = w[start + length:start + 2 * length]
367
+ if chunk == nxt:
368
+ findings.append(f"reduplication in '{w}': '{chunk}' repeated")
369
+ found = True
370
+ break
371
+ if found:
372
+ break
373
+ return findings
374
+
375
+
376
+ def build_symbolic_evidence(context: str) -> str:
377
+ """Returns "" if no supported transformation family and no
378
+ reduplication is found -- augments the prompt only with real,
379
+ multi-supported evidence. Never replaces context."""
380
+ forms = extract_forms_from_context(context)
381
+ pairs = extract_explicit_pairs(context)
382
+ families = find_transformation_families(pairs) if pairs else []
383
+ redup = detect_reduplication(forms) if forms else []
384
+
385
+ lines = []
386
+ if families:
387
+ lines.append("Transformation families found (patterns supported by multiple examples):")
388
+ for f in families[:3]:
389
+ lines.append(f"- {f}")
390
+ if redup:
391
+ lines.append("Reduplication detected:")
392
+ for r in redup[:2]:
393
+ lines.append(f"- {r}")
394
+ if not lines:
395
+ return ""
396
+ return ("\n\nSYMBOLIC EVIDENCE (deterministically computed from the examples above; "
397
+ "may be incomplete -- verify against the examples, do not trust blindly):\n"
398
+ + "\n".join(lines))
399
+
400
+
401
+ # ---------------------------------------------------------------------------
402
+ # Closed-answer-space pre-constraint, match_letters only. Deterministic,
403
+ # read-only, zero generate() calls of its own. Extracts the closed set of
404
+ # option letters genuinely present in the context (always explicitly
405
+ # given -- "A. water", "B. child", ...) and states that exact set as a
406
+ # soft hint in the prompt. FAIL-OPEN: if extraction isn't clean and
407
+ # unambiguous, the hint is skipped -- baseline behavior for that row is
408
+ # byte-identical to not having this module at all.
409
+ # ---------------------------------------------------------------------------
410
+ def extract_match_letter_options(context: str) -> list[str] | None:
411
+ """Returns a sorted list of option letters if extraction is CLEAN and
412
+ UNAMBIGUOUS, else None. Deliberately strict: must never guess."""
413
+ found = set()
414
+ for line in context.splitlines():
415
+ for m in re.finditer(r"(?:^|\s)([A-Z])[.\)]\s+\S", line):
416
+ found.add(m.group(1))
417
+ if not found:
418
+ return None
419
+ letters = sorted(found)
420
+ expected = [chr(ord("A") + i) for i in range(len(letters))]
421
+ if letters != expected:
422
+ return None
423
+ if not (2 <= len(letters) <= 26):
424
+ return None
425
+ return letters
426
+
427
+
428
+ def build_messages(context: str, query: str, task_type: str) -> tuple[list[dict], int | None]:
429
+ """The proven decomposition-and-verification scaffold, augmented with
430
+ the symbolic evidence layer and the match_letters closed-option hint.
431
+ Nothing else about the reasoning instructions has changed since the
432
+ version that scored 0.083/0.0296/0.2323 on the real leaderboard."""
433
+ preamble, items, count_known = parse_items(query)
434
+ guidance = TASK_GUIDANCE.get(task_type, DEFAULT_GUIDANCE)
435
+ symbolic_evidence = build_symbolic_evidence(context)
436
+
437
+ system = (
438
+ "You solve puzzles about a language you have never seen. Everything you "
439
+ "need is in the examples below. Use only the examples, not outside "
440
+ "knowledge of any language. You may meet a task type you have never "
441
+ "seen -- read the instruction and examples, and answer in the same "
442
+ "form they use."
443
+ )
444
+ number_note = ""
445
+ if task_type == "text_to_num":
446
+ number_note = (
447
+ "\n\nAlso add one more line after your answers, exactly like this:\n"
448
+ "COMPUTE: expr1 | expr2\n"
449
+ "where each expr is a plain arithmetic expression (digits, +, -, *, "
450
+ "parentheses only) for that item's value, one per answer, matching "
451
+ "the rule you found."
452
+ )
453
+ options_note = ""
454
+ if task_type == "match_letters":
455
+ options = extract_match_letter_options(context)
456
+ if options:
457
+ options_note = (
458
+ f"\n\nThe only valid answers are: {', '.join(options)}. "
459
+ f"Do not use any other letter."
460
+ )
461
+
462
+ if count_known:
463
+ n_items = len(items)
464
+ slots = "\n\n".join(f"Question {i + 1}: {it}\nAnswer {i + 1}:" for i, it in enumerate(items))
465
+ user = (
466
+ f"EXAMPLES:\n{context.strip()}"
467
+ f"{symbolic_evidence}\n\n"
468
+ f"--- The examples end here. The questions begin below. ---\n\n"
469
+ f"For each question: find the rule that explains ALL the examples above "
470
+ f"(not just one). Check it against every example before answering. "
471
+ f"For this task type, {guidance}\n\n"
472
+ f"{preamble}\n\n{slots}\n\n"
473
+ f"After answering all {n_items} questions, finish with exactly one line, "
474
+ f"all {n_items} answers in order separated by ' | ':\n"
475
+ f"FINAL ANSWERS: answer1 | answer2"
476
+ f"{number_note}"
477
+ f"{options_note}"
478
+ )
479
+ else:
480
+ n_items = None
481
+ user = (
482
+ f"EXAMPLES:\n{context.strip()}"
483
+ f"{symbolic_evidence}\n\n"
484
+ f"--- The examples end here. The question begins below. ---\n\n"
485
+ f"Find the rule that explains ALL the examples above (not just one). "
486
+ f"Check it against every example before answering. "
487
+ f"For this task type, {guidance}\n\n"
488
+ f"{preamble}\n\n"
489
+ f"Answer every item asked above, in order, one per answer. Finish "
490
+ f"with exactly one line, all your answers in order separated by ' | ':\n"
491
+ f"FINAL ANSWERS: answer1 | answer2"
492
+ f"{number_note}"
493
+ f"{options_note}"
494
+ )
495
+ return [{"role": "system", "content": system}, {"role": "user", "content": user}], n_items
496
+
497
+
498
+ def build_repair_messages(query: str, n_items: int | None, bad_text: str) -> list[dict]:
499
+ n_desc = f"exactly {n_items}" if n_items is not None else "one per item asked"
500
+ system = "You reformat answers. Output nothing except the requested line."
501
+ user = (
502
+ f"Question:\n{query.strip()}\n\n"
503
+ f"A previous attempt produced:\n{bad_text[:600]}\n\n"
504
+ f"Extract or restate {n_desc} final answers, in order, as ONE line:\n"
505
+ f"FINAL ANSWERS: answer1 | answer2"
506
+ )
507
+ return [{"role": "system", "content": system}, {"role": "user", "content": user}]
508
+
509
+
510
+ # ---------------------------------------------------------------------------
511
+ # Safe arithmetic: no exec(), no eval() of arbitrary code.
512
+ # ---------------------------------------------------------------------------
513
+ _ALLOWED_BINOPS = (pyast.Add, pyast.Sub, pyast.Mult)
514
+
515
+
516
+ def safe_arithmetic(expr: str) -> float | int | None:
517
+ try:
518
+ tree = pyast.parse(expr.strip(), mode="eval")
519
+ except Exception:
520
+ return None
521
+
522
+ def _eval(node):
523
+ if isinstance(node, pyast.Expression):
524
+ return _eval(node.body)
525
+ if isinstance(node, pyast.Constant) and isinstance(node.value, (int, float)):
526
+ return node.value
527
+ if isinstance(node, pyast.BinOp) and isinstance(node.op, _ALLOWED_BINOPS):
528
+ left, right = _eval(node.left), _eval(node.right)
529
+ if left is None or right is None:
530
+ return None
531
+ if isinstance(node.op, pyast.Add):
532
+ return left + right
533
+ if isinstance(node.op, pyast.Sub):
534
+ return left - right
535
+ if isinstance(node.op, pyast.Mult):
536
+ return left * right
537
+ if isinstance(node, pyast.UnaryOp) and isinstance(node.op, pyast.USub):
538
+ v = _eval(node.operand)
539
+ return -v if v is not None else None
540
+ return None
541
+
542
+ return _eval(tree)
543
+
544
+
545
+ def clean_answer(a: str) -> str:
546
+ """Broadened: strips "Answer N:", "is:", "the answer is:", "final
547
+ answer:" prefixes, applies NFC Unicode normalization and collapses
548
+ internal whitespace runs -- both target exact-match killers the
549
+ organizers' own documented normalization does not cover (Unicode form,
550
+ internal whitespace)."""
551
+ a = re.sub(r"(?i)^\s*(the\s+)?(final\s+)?answer\s*\d*\s*(is)?\s*:\s*", "", a).strip()
552
+ a = re.sub(r"(?i)^\s*is\s*:\s*", "", a).strip()
553
+ a = a.strip("* ")
554
+ a = unicodedata.normalize("NFC", a)
555
+ a = re.sub(r"\s{2,}", " ", a)
556
+ return a.strip(" .\"'\u201c\u201d\u2018\u2019")
557
+
558
+
559
+ def extract(text: str) -> tuple[list[str], int | None]:
560
+ """Fixed against three real bugs found on real Linguini output:
561
+ (1) markdown-bold marker with content on the NEXT line, not same line;
562
+ (2) a following COMPUTE: line bleeding into the answer list;
563
+ (3) NO marker found + answers dumped on one pipe-separated line --
564
+ splits each fallback line further by "|" instead of treating the
565
+ whole line as one answer."""
566
+ m = list(re.finditer(r"final answers?\s*:?\s*\**", text, flags=re.IGNORECASE))
567
+ if m:
568
+ tail = text[m[-1].end():]
569
+ stop = re.search(r"(?i)compute\s*:", tail)
570
+ if stop:
571
+ tail = tail[:stop.start()]
572
+ tail = tail.replace("**", " ").strip()
573
+ candidate = " ".join(tail.splitlines())
574
+ parts = [clean_answer(p) for p in candidate.split("|") if p.strip()]
575
+ if parts:
576
+ return parts, m[-1].start()
577
+ lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
578
+ fallback = []
579
+ for ln in lines:
580
+ ln_clean = re.sub(r"^\s*\d+\s*[.\)]\s*", "", ln)
581
+ if "|" in ln_clean:
582
+ fallback.extend(clean_answer(p) for p in ln_clean.split("|") if p.strip())
583
+ else:
584
+ fallback.append(clean_answer(ln_clean))
585
+ return fallback, None
586
+
587
+
588
+ def extract_compute_overrides(text: str, n_answers: int) -> dict[int, str]:
589
+ m = re.search(r"compute\s*:\s*(.+)", text, flags=re.IGNORECASE)
590
+ if not m:
591
+ return {}
592
+ exprs = [e.strip() for e in m.group(1).split("|")]
593
+ overrides = {}
594
+ for i, e in enumerate(exprs[:n_answers]):
595
+ val = safe_arithmetic(e)
596
+ if val is not None:
597
+ overrides[i] = str(int(val)) if float(val).is_integer() else str(val)
598
+ return overrides
599
+
600
+
601
+ # ---------------------------------------------------------------------------
602
+ # Generation: defensive against both chat-template return shapes (the
603
+ # sandbox's transformers version may return a bare tensor from
604
+ # apply_chat_template rather than a dict), and against a constrained
605
+ # decoding attempt failing for any reason.
606
+ # ---------------------------------------------------------------------------
607
+ def generate(tok, model, messages: list[dict], max_new_tokens: int, constraint_fn=None) -> str:
608
+ """constraint_fn: optional prefix_allowed_tokens_fn, default None means
609
+ byte-identical behavior to an unconstrained call. If a constrained
610
+ attempt fails for ANY reason, falls back to a fully UNCONSTRAINED
611
+ generation (not a retry with the same broken kwarg) -- the two
612
+ concerns (dict-vs-tensor API shape, constrained-vs-unconstrained) are
613
+ isolated from each other so a failure in one never masks as the
614
+ other."""
615
+ def _try_generate(gen_kwargs):
616
+ try:
617
+ enc = tok.apply_chat_template(
618
+ messages, add_generation_prompt=True, return_tensors="pt", return_dict=True,
619
+ ).to(model.device)
620
+ input_len = enc["input_ids"].shape[-1]
621
+ with torch.no_grad():
622
+ out = model.generate(**enc, **gen_kwargs)
623
+ except Exception:
624
+ ids = tok.apply_chat_template(
625
+ messages, add_generation_prompt=True, return_tensors="pt",
626
+ ).to(model.device)
627
+ input_len = ids.shape[-1]
628
+ with torch.no_grad():
629
+ out = model.generate(ids, **gen_kwargs)
630
+ return out, input_len
631
+
632
+ base_kwargs = {"max_new_tokens": max_new_tokens, "do_sample": False}
633
+ if constraint_fn is not None:
634
+ try:
635
+ out, input_len = _try_generate({**base_kwargs, "prefix_allowed_tokens_fn": constraint_fn})
636
+ except Exception:
637
+ out, input_len = _try_generate(base_kwargs)
638
+ else:
639
+ out, input_len = _try_generate(base_kwargs)
640
+ return tok.decode(out[0][input_len:], skip_special_tokens=True).strip()
641
+
642
+
643
+ # Adapted from a top-1 public submission's prefix_allowed_tokens_fn
644
+ # technique -- but scoped correctly for OUR prompt architecture. Their
645
+ # version applies across an ENTIRE generation because their prompt has no
646
+ # reasoning phase (plain newline-per-answer output). Ours does have a
647
+ # reasoning phase (decomposition + "FINAL ANSWERS:" marker); applying a
648
+ # letter-only constraint there would silently break the model's ability to
649
+ # reason at all. Scoped here to ONLY the repair call, whose entire
650
+ # expected output is already a short answer line. Fail-open throughout.
651
+ _LETTER_CONSTRAINT_CACHE: dict = {}
652
+
653
+
654
+ def build_letter_constraint_fn(tok, valid_letters: list[str]):
655
+ cache_key = (id(tok), tuple(sorted(valid_letters)))
656
+ if cache_key in _LETTER_CONSTRAINT_CACHE:
657
+ return _LETTER_CONSTRAINT_CACHE[cache_key]
658
+ try:
659
+ allowed_chars = set(valid_letters) | set(" |\n\t\r")
660
+ eos = tok.eos_token_id
661
+ pieces = []
662
+ for token_id in range(len(tok)):
663
+ if token_id == eos:
664
+ continue
665
+ piece = tok.decode([token_id], skip_special_tokens=False)
666
+ if piece and all(c in allowed_chars for c in piece):
667
+ pieces.append(token_id)
668
+ allowed_ids = ([eos] if eos is not None else []) + pieces
669
+
670
+ def allowed(_batch_id, _input_ids):
671
+ return allowed_ids if allowed_ids else list(range(len(tok)))
672
+
673
+ _LETTER_CONSTRAINT_CACHE[cache_key] = allowed
674
+ return allowed
675
+ except Exception:
676
+ return None
677
+
678
+
679
+ EXPLANATION_SYSTEM = (
680
+ "Summarize the following reasoning into a few short bullet points: the "
681
+ "rule or pattern found in the data and the key evidence for the answer. "
682
+ "Be concise and structured -- do not repeat the full reasoning."
683
+ )
684
+ EXPLANATION_FALLBACK = "Answer derived from patterns found in the examples above."
685
+
686
+
687
+ def dynamic_tokens_cap(n_items: int | None, time_based_cap: int) -> int:
688
+ """Item-count-aware token budget, evidenced by a top-1 public
689
+ submission citing truncation on multi-item problems as "a pure
690
+ unforced loss". Combined with, not replacing, the time-based
691
+ adaptation via min() -- a multi-item problem gets more room, but never
692
+ more than time allows."""
693
+ if not n_items:
694
+ return time_based_cap
695
+ item_based_cap = max(TOKENS_CAP_FLOOR, min(TOKENS_CAP_CEIL, n_items * TOKENS_PER_ITEM + TOKENS_PER_ITEM_BASE))
696
+ return min(time_based_cap, item_based_cap)
697
+
698
+
699
+ def process_row(tok, model, row: dict, n_rows: int, n_done: int, per_row_budget: float) -> tuple[dict, bool]:
700
+ """Processes one row. Returns (result_row, ok) -- ok=False means a
701
+ fallback row was produced after an exception, not a real answer."""
702
+ try:
703
+ remaining = TIME_LIMIT_S - elapsed_seconds()
704
+ budget_left_rows = max(n_rows - n_done, 1)
705
+ row_budget = remaining / budget_left_rows
706
+ time_based_cap = 1280 if row_budget > per_row_budget else 640
707
+
708
+ task_type = row.get("task_type", "")
709
+ messages, n_items = build_messages(row["context"], row["query"], task_type)
710
+ tokens_cap = dynamic_tokens_cap(n_items, time_based_cap)
711
+ text = generate(tok, model, messages, tokens_cap)
712
+ answers, marker_pos = extract(text)
713
+
714
+ if task_type == "text_to_num":
715
+ overrides = extract_compute_overrides(text, len(answers))
716
+ for idx, val in overrides.items():
717
+ if idx < len(answers):
718
+ answers[idx] = val
719
+
720
+ # Repair only on TRUE extraction failure (no marker / nothing found)
721
+ # -- not a mere count difference, since extra answers are harmless
722
+ # and our own count guess may be the thing that's wrong.
723
+ if (marker_pos is None or not answers) and remaining > SETUP_BUFFER_S:
724
+ repair_constraint = None
725
+ if task_type == "match_letters":
726
+ repair_options = extract_match_letter_options(row["context"])
727
+ if repair_options:
728
+ repair_constraint = build_letter_constraint_fn(tok, repair_options)
729
+ repair_text = generate(tok, model, build_repair_messages(row["query"], n_items, text),
730
+ 128, constraint_fn=repair_constraint)
731
+ rep, rep_pos = extract(repair_text)
732
+ if rep:
733
+ answers, marker_pos = rep, rep_pos
734
+
735
+ if n_items is not None:
736
+ if len(answers) < n_items:
737
+ answers = answers + [answers[-1] if answers else ""] * (n_items - len(answers))
738
+ elif len(answers) > n_items and marker_pos is None:
739
+ answers = answers[:n_items]
740
+ # else: marker found, more answers than our guess -> keep them all
741
+
742
+ if not answers:
743
+ answers = [""]
744
+
745
+ # Explanation: dedicated call if time is comfortable, else a cheap
746
+ # truncated fallback -- never blank, never a second full generation
747
+ # under time pressure.
748
+ remaining_after = TIME_LIMIT_S - elapsed_seconds()
749
+ budget_left_after = max(n_rows - n_done - 1, 0)
750
+ comfortable = remaining_after > (budget_left_after + 1) * per_row_budget * 1.3
751
+ if comfortable:
752
+ try:
753
+ explanation = generate(
754
+ tok, model,
755
+ [{"role": "system", "content": EXPLANATION_SYSTEM},
756
+ {"role": "user", "content": text}], 300,
757
+ ) or EXPLANATION_FALLBACK
758
+ except Exception:
759
+ explanation = EXPLANATION_FALLBACK
760
+ else:
761
+ snippet = re.sub(r"\s{2,}", " ", text[:300]).strip()
762
+ explanation = snippet if snippet else EXPLANATION_FALLBACK
763
+
764
+ return {"id": row["id"], "pred": json.dumps(answers, ensure_ascii=False),
765
+ "explanation": explanation}, True
766
+
767
+ except Exception as exc:
768
+ try:
769
+ _, fallback_items, fk = parse_items(row["query"])
770
+ n_fallback = len(fallback_items) if fk else 1
771
+ except Exception:
772
+ n_fallback = 1
773
+ print(f"ROW ERROR on {row.get('id', '?')}: {exc}", flush=True)
774
+ return {"id": row["id"], "pred": json.dumps([""] * n_fallback, ensure_ascii=False),
775
+ "explanation": EXPLANATION_FALLBACK}, False
776
+
777
+
778
+ def main() -> None:
779
+ if not INPUT_CSV.exists():
780
+ emergency_submission_csv(f"input CSV not found: {INPUT_CSV}")
781
+ raise FileNotFoundError(f"Missing input CSV: {INPUT_CSV}")
782
+
783
+ try:
784
+ # Read test.csv and checkpoint a placeholder submission FIRST,
785
+ # before the slowest and most failure-prone step (model loading,
786
+ # ~7-9 min for this checkpoint size) even starts -- matching a
787
+ # top-1 public submission's proven order. If loading hangs or gets
788
+ # killed, something valid already exists on disk.
789
+ df = pd.read_csv(INPUT_CSV, dtype=str).fillna("")
790
+ placeholder_rows = [{"id": rid, "pred": json.dumps([""]),
791
+ "explanation": "Placeholder written before model load."}
792
+ for rid in df["id"].tolist()]
793
+ write_submission_csv(placeholder_rows)
794
+ print(f"Pre-load checkpoint written for {len(placeholder_rows)} rows.", flush=True)
795
+
796
+ tok, model = load_model()
797
+ except Exception as exc:
798
+ emergency_submission_csv(f"tokenizer/model load or test.csv read failed: {exc}")
799
+ raise
800
+
801
+ n_rows = len(df)
802
+ actual_setup_elapsed = elapsed_seconds()
803
+ per_row_budget = max(20, (TIME_LIMIT_S - actual_setup_elapsed) / max(n_rows, 1))
804
+ print(f"Setup took {actual_setup_elapsed:.0f}s (estimated {SETUP_BUFFER_S:.0f}s) | "
805
+ f"per_row_budget={per_row_budget:.0f}s for {n_rows} rows", flush=True)
806
+
807
+ rows: list[dict] = []
808
+ processed_ids: set[str] = set()
809
+
810
+ try:
811
+ for _, row in df.iterrows():
812
+ result_row, _ok = process_row(tok, model, row, n_rows, len(rows), per_row_budget)
813
+ rows.append(result_row)
814
+ processed_ids.add(row["id"])
815
+ write_submission_csv(rows)
816
+ print(f"{len(rows)}/{n_rows} elapsed={elapsed_seconds():.0f}s", flush=True)
817
+
818
+ if elapsed_seconds() > TIME_LIMIT_S - EXIT_RESERVE_S:
819
+ print("Time budget nearly exhausted, stopping early.", flush=True)
820
+ break
821
+
822
+ # Guarantee one row per test.csv id, even under a timeout.
823
+ for _, row in df.iterrows():
824
+ if row["id"] in processed_ids:
825
+ continue
826
+ try:
827
+ _, fallback_items, fk = parse_items(row["query"])
828
+ n_fallback = len(fallback_items) if fk else 1
829
+ except Exception:
830
+ n_fallback = 1
831
+ rows.append({"id": row["id"], "pred": json.dumps([""] * n_fallback, ensure_ascii=False),
832
+ "explanation": EXPLANATION_FALLBACK})
833
+
834
+ write_submission_csv(rows)
835
+ print(f"DONE. Wrote {len(rows)} rows in {elapsed_seconds():.0f}s.", flush=True)
836
+
837
+ except Exception as exc:
838
+ # Final safety net: even if something escapes every inner
839
+ # try/except above, whatever rows were collected so far still get
840
+ # written.
841
+ emergency_submission_csv(f"main loop failed: {exc}", rows_so_far=rows if rows else None)
842
+ print(f"FATAL, but submission.csv was written with {len(rows)} rows. Error: {exc}", flush=True)
843
+
844
+
845
+ if __name__ == "__main__":
846
+ main()