hhhar's picture
Update script.py
a4c4f63 verified
Raw History Blame Contribute Delete
17.5 kB
# ============================================================================
# IOL-AI 2026 — script.py v2 (dual-mode: submission + Colab)
#
# Rebuilt from the ablation harness. Our old CoT+methods submission scored EM
# 0.0046 because CoT-extraction is fragile on unseen structure. The harness (on
# Linguini + obfuscation-resistant LingOly-TOO) showed the robust winner is:
# * TRIVIAL prompt, NO chain-of-thought (answers on their own lines -> naive
# parse can't catastrophically zero out),
# * per-task HINTS (safe: help Linguini, neutral on LingOly-TOO),
# * repetition_penalty = 1.0 (Qwen's silent 1.05 default costs EM),
# * COUNT-GUARD ONLY WHEN CONFIDENT — forcing to a *guessed* count was the
# catastrophe (LingOly-TOO C+forceN = 0.000). Force only when count_items
# actually detected explicit numbering; else stay naive.
# * never emit a blank (geo-mean metric: blank = 0 on both axes),
# * crash-safe: write a complete submission.csv before the model loads, then
# overwrite after every improvement.
# ============================================================================
import os, re, json, time, gc
os.environ.setdefault("HF_HUB_OFFLINE", "1")
os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
import pandas as pd
import torch
T0 = time.time()
SUBMISSION = os.path.exists("/tmp/data/test.csv")
MODEL_ID = "." if SUBMISSION else "Qwen/Qwen2.5-14B-Instruct-AWQ"
TIME_LIMIT = 1650.0 # 27.5 min
SAFETY = 120.0
DEADLINE = T0 + TIME_LIMIT - SAFETY
MAX_NEW = 512 # trivial answers are short
REP = 1.0 # <- the fix: override Qwen's silent 1.05
BATCH = 4
WANT_EXPL = True
def left():
return DEADLINE - time.time()
# ---- prompt: trivial + per-task hint ---------------------------------------
SYS = ("You solve International Linguistics Olympiad problems. Answer every numbered "
"item. Put each answer on its own line, in order, with no numbering and no "
"extra text.")
HINT = {
"translation": "Give only the translated form, in the language asked.",
"match_letters": "Answer each item with a single option letter only (for example: C).",
"fill_blanks": "Give only the missing form for each blank.",
"text_to_num": "Give the number in digits only.",
"num_to_text": "Write the number out in words, in the language asked.",
}
PHON = (" Each answer is a phonetic transcription in [square brackets], using the same "
"symbols, length marks and diacritics as the examples.")
_IPA_HINT = re.compile(r"[ɐ-ʯʰ-˿̀-ͯᴀ-ᵿøœæðθŋɣʔ]")
_ASKS_NON_PHON = re.compile(r"(?i)translate\s+into\s+english|in\s+the\s+[\w'’-]+\s+orthography")
_ASKS_TRANS = re.compile(r"(?i)\b(transcribe|transcription|phonetic)\b")
def _brk(t):
return [m.group(1).strip() for m in re.finditer(r"\[([^\[\]\n]{1,40})\]", t)
if m.group(1).strip() and not re.fullmatch(r"[\d\s,.\-]+", m.group(1).strip())]
def is_phonetic(context, query, min_forms=3):
if _ASKS_NON_PHON.search(query):
return False
if _brk(query) and not _ASKS_TRANS.search(query):
return False
forms = _brk(context) + _brk(query)
if len(forms) < min_forms:
return False
return sum(1 for f in forms if _IPA_HINT.search(f) or ":" in f) >= max(2, len(forms) // 4)
# ---- item count WITH confidence (only force when we actually detected it) ---
_RANGE = re.compile(r"\(?(\d{1,3})\s*(?:[-‐-―−]|to)\s*(\d{1,3})\)?")
_LINE_NUM = re.compile(r"(?m)^\s*\(?(\d{1,3})[.)\]]")
_LINE_LET = re.compile(r"(?m)^\s*([A-Z])[.)\]]\s")
def count_items(query, context=""):
"""Return (n, confident). confident=True only when explicit structure was found."""
q = query or ""
m = _RANGE.search(q)
if m:
a, b = int(m.group(1)), int(m.group(2))
if 0 < b - a < 60:
return b - a + 1, True
n = len(set(_LINE_NUM.findall(q)))
if n > 1:
return n, True
lines = [l.strip() for l in q.splitlines() if l.strip()]
if len(lines) > 1:
body = lines[1:] if lines[0].endswith((":", ".")) else lines
if len(body) > 1:
return len(body), True
if context:
cn = len(set(_LINE_NUM.findall(context)))
if cn > 1:
return cn, True
cl = len(set(_LINE_LET.findall(context)))
if cl > 1:
return cl, True
return 1, False
def extract_sources(query, n):
"""Source string of each item, for a never-blank fallback (shares chars with target)."""
q = query or ""; out = []
for ln in q.splitlines():
m = re.match(r"^\s*\(?(\d{1,3})\)?[.):\]]\s*(.+)$", ln.strip())
if m:
out.append(m.group(2).strip())
if not out:
lines = [l.strip() for l in q.splitlines() if l.strip()]
if len(lines) > 1 and lines[0].endswith((":", ".")):
out = lines[1:]
out = [o.split("|")[0].strip() if "|" in o else o for o in out]
out = [o for o in out if o]
while len(out) < max(n, 1):
out.append(out[-1] if out else "?")
return out[:max(n, 1)]
def build_messages(row):
tt = (row.get("task_type") or "").strip().lower()
h = HINT.get(tt, "")
if is_phonetic(row["context"], row["query"]):
h += PHON
n, conf = count_items(row["query"], row["context"])
u = f"{str(row['context']).strip()}\n\n{str(row['query']).strip()}"
if conf and n > 1:
u += f"\n\nGive exactly {n} answers, one per line, in order."
return [{"role": "system", "content": SYS + (" " + h if h else "")},
{"role": "user", "content": u}], n, conf
# ---- parse (naive; force to N only when confident; never blank) -------------
_PROSE = re.compile(r"(?i)^(here (are|is)|the (final )?answers?\b|answers?\s*:?\s*$|"
r"based on|therefore|thus|in summary|note\b|reasoning\b|explanation\b|"
r"let me\b|first,|so,|okay\b|solution\b)")
def parse_answers(text, n, conf, sources):
lines = []
for ln in (text or "").splitlines():
s = ln.strip()
if s.startswith("```"):
continue
s = re.sub(r"^\s*\(?\d{1,3}\)?[.):\]]\s*", "", s) # strip "1." / "(2)"
s = s.strip().strip('"').strip("'").strip()
if not s or _PROSE.match(s):
continue
lines.append(s)
if conf and n > 0:
if len(lines) > n:
lines = lines[-n:] # answers come last
while len(lines) < n:
lines.append(sources[len(lines)] if len(lines) < len(sources) else
(lines[-1] if lines else "?"))
lines = lines[:n]
if not lines:
lines = list(sources[:max(n, 1)]) or ["?"]
return [s if s.strip() else (sources[i] if i < len(sources) else "?")
for i, s in enumerate(lines)]
# ---- match_letters as a logprob assignment (bijection) ----------------------
_OPT_LINE = re.compile(r"(?m)^\s*\(?([A-Za-z])[.)]\s+(.+)$")
_ITEM_LINE = re.compile(r"(?m)^\s*\(?(\d{1,3})[.)]\s+(.+)$")
def parse_matching_block(text):
text = text or ""
items, seen = [], set()
for a, b in _ITEM_LINE.findall(text):
a = int(a)
if a not in seen:
seen.add(a); items.append((a, b.strip()))
opts, seen = [], set()
for a, b in _OPT_LINE.findall(text):
if a not in seen:
seen.add(a); opts.append((a, b.strip()))
return items, opts
def best_assignment(score):
import numpy as np
n, m = len(score), len(score[0])
try:
from scipy.optimize import linear_sum_assignment
r, c = linear_sum_assignment(-np.array(score))
amap = dict(zip(r.tolist(), c.tolist()))
return [amap.get(i, int(np.argmax(score[i]))) for i in range(n)]
except Exception:
used, out = set(), [0] * n
for i in sorted(range(n), key=lambda i: -max(score[i])):
j = max((j for j in range(m) if j not in used), key=lambda j: score[i][j], default=0)
used.add(j); out[i] = j
return out
@torch.inference_mode()
def solve_matching(row):
ctx = str(row.get("context", ""))
items, opts = parse_matching_block(ctx + "\n" + str(row.get("query", "")))
if len(items) < 2 or len(opts) < 2 or len(items) > len(opts):
return None
letters = [o[0] for o in opts]
cand_ids = []
for L in letters:
s = set()
for form in (L, " " + L):
t = tok.encode(form, add_special_tokens=False)
if t:
s.add(t[0])
cand_ids.append(sorted(s))
if any(not c for c in cand_ids):
return None
prompts = []
for num, itext in items:
m = [{"role": "system", "content": "You match items to their correct counterparts "
"in a linguistics problem. Reply with one option letter only."},
{"role": "user", "content": f"{ctx.strip()}\n\nWhich lettered option corresponds "
f"to item {num} ({itext})? Reply with the option letter only."}]
prompts.append(tok.apply_chat_template(m, tokenize=False, add_generation_prompt=True))
score, bs = [], 4
for s0 in range(0, len(prompts), bs):
if left() < 25:
return None
chunk = prompts[s0:s0 + bs]
enc = tok(chunk, return_tensors="pt", padding=True, truncation=True, max_length=6144).to(model.device)
lp = torch.log_softmax(model(**enc).logits[:, -1, :].float(), dim=-1)
for b in range(len(chunk)):
score.append([max(lp[b, i].item() for i in ids) for ids in cand_ids])
return [letters[c] for c in best_assignment(score)]
# ---- jury explanation (solution-key style) ----------------------------------
EXPL_SYS = ("You are writing the solution key for a linguistics olympiad problem, for "
"expert judges. State the rules (affixes and what they mark, sound changes with "
"their environment, word order, any numeral base), citing forms from the data. "
"Do not restate the answers or narrate reasoning. Under 150 words.")
# ============================================================================
# I/O
# ============================================================================
def write_submission(path, ids, preds, expls):
rows = [{"id": i, "pred": json.dumps(preds.get(i, []), ensure_ascii=False),
"explanation": (expls or {}).get(i, "")} for i in ids]
pd.DataFrame(rows).to_csv(path, index=False)
if SUBMISSION:
df = pd.read_csv("/tmp/data/test.csv", dtype=str).fillna("")
OUT = "submission.csv"
else:
assert "df" in dir(), "Colab: load `df` (context, query, task_type[, answer, id])"
df = df.fillna("")
OUT = "submission.csv"
if "id" not in df.columns:
df["id"] = range(len(df))
df["id"] = df["id"].astype(str)
ids = df["id"].tolist()
meta = {} # id -> (n, conf, sources)
for _, r in df.iterrows():
n, conf = count_items(r["query"], r["context"])
meta[str(r["id"])] = (n, conf, extract_sources(r["query"], n))
# crash-safe: a complete, correctly-shaped file BEFORE loading the model
preds = {i: list(meta[i][2]) for i in ids}
expls = {i: "" for i in ids}
write_submission(OUT, ids, preds, expls)
print(f"[{time.time()-T0:.0f}s] placeholder {OUT} written ({len(ids)} rows)", flush=True)
# ---- model ------------------------------------------------------------------
_need = True
try: _need = model is None or tok is None # type: ignore # noqa
except NameError: _need = True
if _need:
from transformers import AutoTokenizer, AutoModelForCausalLM
gc.collect(); torch.cuda.empty_cache()
tok = AutoTokenizer.from_pretrained(MODEL_ID); tok.padding_side = "left"
if tok.pad_token_id is None:
tok.pad_token = tok.eos_token
def _load(dm):
try:
return AutoModelForCausalLM.from_pretrained(MODEL_ID, torch_dtype=torch.float16, device_map=dm).eval()
except TypeError:
return AutoModelForCausalLM.from_pretrained(MODEL_ID, dtype=torch.float16, device_map=dm).eval()
try:
model = _load({"": 0} if torch.cuda.is_available() else "auto")
except Exception:
model = _load("auto")
print(f"[{time.time()-T0:.0f}s] loaded {MODEL_ID}", flush=True)
from transformers import StoppingCriteria, StoppingCriteriaList
class _Deadline(StoppingCriteria):
def __init__(self, t): self.t = t
def __call__(self, i, s, **k): return time.time() > self.t
@torch.inference_mode()
def gen_batch(prompts, max_new):
outs = [""] * len(prompts)
order = sorted(range(len(prompts)), key=lambda i: len(prompts[i]))
bs, i = BATCH, 0
while i < len(order):
if left() < 20:
print(" out of time in gen_batch; returning partial", flush=True); break
idx = order[i:i+bs]; chunk = [prompts[j] for j in idx]
try:
enc = tok(chunk, return_tensors="pt", padding=True, truncation=True, max_length=6144).to(model.device)
out = model.generate(**enc, max_new_tokens=max_new, do_sample=False,
repetition_penalty=REP, pad_token_id=tok.pad_token_id,
stopping_criteria=StoppingCriteriaList([_Deadline(DEADLINE - 8)]))
for k, j in enumerate(idx):
outs[j] = tok.decode(out[k][enc["input_ids"].shape[1]:], skip_special_tokens=True)
i += bs
except torch.cuda.OutOfMemoryError:
torch.cuda.empty_cache(); bs = max(1, bs // 2)
print(f" OOM -> batch {bs}", flush=True)
except Exception as e:
print(f" gen error: {type(e).__name__}: {e}", flush=True); i += bs
return outs
# ---- pass 1a: match_letters via logprob assignment (falls back to gen) ------
match_done = set()
for _, r in df.iterrows():
if (r.get("task_type") or "").strip().lower() != "match_letters" or left() < 45:
continue
i = str(r["id"])
try:
res = solve_matching(r)
if res:
preds[i] = res
match_done.add(i)
except Exception as e:
print(f" matching {i} failed: {type(e).__name__}: {e}", flush=True)
if match_done:
write_submission(OUT, ids, preds, expls)
print(f"[{time.time()-T0:.0f}s] matching solver used on {len(match_done)} problem(s)", flush=True)
# ---- pass 1b: everything else via trivial generation ------------------------
msgs, order_ids = [], []
for _, r in df.iterrows():
i = str(r["id"])
if i in match_done:
continue
m, n, conf = build_messages(r)
msgs.append(tok.apply_chat_template(m, tokenize=False, add_generation_prompt=True))
order_ids.append(i)
texts = gen_batch(msgs, MAX_NEW)
for i, txt in zip(order_ids, texts):
n, conf, src = meta[i]
preds[i] = parse_answers(txt, n, conf, src)
write_submission(OUT, ids, preds, expls)
print(f"[{time.time()-T0:.0f}s] answers written", flush=True)
# ---- pass 2: explanations (optional, time permitting) -----------------------
if WANT_EXPL and left() > 90:
ep = []
for _, r in df.iterrows():
i = str(r["id"])
blk = "\n".join(f"{k+1}. {a}" for k, a in enumerate(preds[i]) if str(a).strip())
ep.append(tok.apply_chat_template(
[{"role": "system", "content": EXPL_SYS},
{"role": "user", "content": f"{str(r['context']).strip()}\n\n{str(r['query']).strip()}"
f"\n\nAnswers:\n{blk}\n\nWrite the solution key."}],
tokenize=False, add_generation_prompt=True))
et = gen_batch(ep, 300)
for i, e in zip(order_ids, et):
e = re.sub(r"\s+", " ", (e or "").strip())
if e:
expls[i] = e[:1200]
write_submission(OUT, ids, preds, expls)
print(f"[{time.time()-T0:.0f}s] explanations written", flush=True)
print(f"[{time.time()-T0:.0f}s] DONE. {len(ids)} rows.", flush=True)
# ---- Colab scoring ----------------------------------------------------------
if not SUBMISSION and "answer" in df.columns and any(str(x).strip() for x in df["answer"]):
import ast, math
from collections import Counter
def _ng(s, k):
s = re.sub(r"\s+", "", s)
return Counter(s[i:i+k] for i in range(len(s)-k+1)) if len(s) >= k else Counter()
def chrf(h, r, mx=6, b=2.0):
if not h or not r: return 0.0
ps, rs = [], []
for k in range(1, mx+1):
H, R = _ng(h, k), _ng(r, k)
if not H or not R: continue
ov = sum((H & R).values()); ps.append(ov/max(1,sum(H.values()))); rs.append(ov/max(1,sum(R.values())))
if not ps: return 0.0
p, r2 = sum(ps)/len(ps), sum(rs)/len(rs)
return 0.0 if p+r2 == 0 else (1+b*b)*p*r2/(b*b*p+r2)
def pgold(c):
try:
v = ast.literal_eval(c)
if isinstance(v, (list, tuple)): return list(v)
except Exception: pass
return [c]
em = cf = ntot = 0
for _, r in df.iterrows():
gold = pgold(r["answer"]); p = preds[str(r["id"])]
p = p[:len(gold)] + [""]*max(0, len(gold)-len(p))
for gi, pi in zip(gold, p):
alts = gi if isinstance(gi, (list, tuple)) else [gi]; alts = [str(a) for a in alts]
em += int(any(pi.strip() == a.strip() for a in alts))
cf += max((chrf(pi, a) for a in alts), default=0.0); ntot += 1
E, C = em/max(1, ntot), cf/max(1, ntot)
print(f"SCORE EM {E:.4f} | chrF {C:.4f} | geo-mean {math.sqrt(E*C):.4f} ({ntot} items)")