Text Generation
Transformers
Safetensors
qwen3
conversational
text-generation-inference
4-bit precision
awq
Instructions to use Santhoshini/iol-solver-v3 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Santhoshini/iol-solver-v3 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="Santhoshini/iol-solver-v3") messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# Load model directly from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("Santhoshini/iol-solver-v3") model = AutoModelForCausalLM.from_pretrained("Santhoshini/iol-solver-v3") messages = [ {"role": "user", "content": "Who are you?"}, ] inputs = tokenizer.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", ).to(model.device) outputs = model.generate(**inputs, max_new_tokens=40) print(tokenizer.decode(outputs[0][inputs["input_ids"].shape[-1]:])) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use Santhoshini/iol-solver-v3 with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "Santhoshini/iol-solver-v3" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Santhoshini/iol-solver-v3", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/Santhoshini/iol-solver-v3
- SGLang
How to use Santhoshini/iol-solver-v3 with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "Santhoshini/iol-solver-v3" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Santhoshini/iol-solver-v3", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "Santhoshini/iol-solver-v3" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Santhoshini/iol-solver-v3", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use Santhoshini/iol-solver-v3 with Docker Model Runner:
docker model run hf.co/Santhoshini/iol-solver-v3
Create script.py
Browse files
script.py
ADDED
|
@@ -0,0 +1,609 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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prompt).
|
| 3 |
+
# =============================================================================
|
| 4 |
+
# WHAT CHANGED vs the 0.104 baseline (single conceptual variable = the model):
|
| 5 |
+
# 1. Base model: Qwen2.5-14B-bnb-4bit -> Qwen3-14B-AWQ.
|
| 6 |
+
# 2. Dependency install: instead of `pip install --no-deps bitsandbytes`
|
| 7 |
+
# (base env), we install the Qwen3 stack from BUNDLED wheels with
|
| 8 |
+
# `pip install --no-index --no-deps --target <RUNTIME_DIR>` and prepend
|
| 9 |
+
# that dir to sys.path. This NEVER touches the network and NEVER mutates
|
| 10 |
+
# base site-packages, so the grader's later hf_hub_download (metric.py)
|
| 11 |
+
# runs on the pristine base huggingface_hub -- the RemoteDisconnected
|
| 12 |
+
# class of failure cannot recur.
|
| 13 |
+
# 3. Chat template: pass enable_thinking=False (Qwen3 supports it; harmless
|
| 14 |
+
# on models that ignore it). We keep OUR own decomposition reasoning in
|
| 15 |
+
# the prompt rather than paying for Qwen3's <think> phase.
|
| 16 |
+
# Everything else -- symbolic evidence, FINAL ANSWERS contract, safe
|
| 17 |
+
# arithmetic, explanations, per-row crash safety, dynamic token budget,
|
| 18 |
+
# guaranteed one row per id -- is IDENTICAL to the proven 0.104 pipeline.
|
| 19 |
+
# match_letters bijection decoding is deliberately NOT added here; that is the
|
| 20 |
+
# next, separate experiment.
|
| 21 |
+
# =============================================================================
|
| 22 |
+
import os
|
| 23 |
+
import atexit
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
_ORIGINAL_HF_HUB_OFFLINE = os.environ.get("HF_HUB_OFFLINE")
|
| 26 |
+
_ORIGINAL_TRANSFORMERS_OFFLINE = os.environ.get("TRANSFORMERS_OFFLINE")
|
| 27 |
+
def _restore_offline_env_vars():
|
| 28 |
+
for key, original in (("HF_HUB_OFFLINE", _ORIGINAL_HF_HUB_OFFLINE),
|
| 29 |
+
("TRANSFORMERS_OFFLINE", _ORIGINAL_TRANSFORMERS_OFFLINE)):
|
| 30 |
+
if original is None:
|
| 31 |
+
os.environ.pop(key, None)
|
| 32 |
+
else:
|
| 33 |
+
os.environ[key] = original
|
| 34 |
+
atexit.register(_restore_offline_env_vars)
|
| 35 |
+
os.environ.setdefault("HF_HUB_OFFLINE", "1")
|
| 36 |
+
os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")
|
| 37 |
+
import subprocess, sys
|
| 38 |
+
import importlib
|
| 39 |
+
import importlib.metadata
|
| 40 |
+
SCRIPT_DIR = Path(__file__).resolve().parent
|
| 41 |
+
def emergency_submission_csv(reason, rows_so_far=None):
|
| 42 |
+
try:
|
| 43 |
+
import pandas as pd
|
| 44 |
+
if rows_so_far:
|
| 45 |
+
pd.DataFrame(rows_so_far).to_csv("submission.csv", index=False)
|
| 46 |
+
return
|
| 47 |
+
try:
|
| 48 |
+
df = pd.read_csv("/tmp/data/test.csv", dtype=str).fillna("")
|
| 49 |
+
ids = df["id"].tolist()
|
| 50 |
+
except Exception:
|
| 51 |
+
ids = []
|
| 52 |
+
import json as _json
|
| 53 |
+
rows = [{"id": i, "pred": _json.dumps([""]),
|
| 54 |
+
"explanation": f"EMERGENCY FALLBACK: {str(reason)[:150]}"} for i in ids]
|
| 55 |
+
pd.DataFrame(rows, columns=["id", "pred", "explanation"]).to_csv("submission.csv", index=False)
|
| 56 |
+
except Exception:
|
| 57 |
+
try:
|
| 58 |
+
with open("submission.csv", "w") as f:
|
| 59 |
+
f.write("id,pred,explanation\n")
|
| 60 |
+
except Exception:
|
| 61 |
+
pass
|
| 62 |
+
def write_submission_csv(rows_list):
|
| 63 |
+
import csv as _csv
|
| 64 |
+
tmp_path = "submission.csv.tmp"
|
| 65 |
+
with open(tmp_path, "w", newline="", encoding="utf-8") as f:
|
| 66 |
+
w = _csv.DictWriter(f, fieldnames=["id", "pred", "explanation"])
|
| 67 |
+
w.writeheader()
|
| 68 |
+
for row in rows_list:
|
| 69 |
+
w.writerow(row)
|
| 70 |
+
os.replace(tmp_path, "submission.csv")
|
| 71 |
+
# =============================================================================
|
| 72 |
+
# OFFLINE WHEELHOUSE INSTALL (adapted from the public 0.147 submissions).
|
| 73 |
+
# Installs the Qwen3-compatible stack from wheels bundled inside this repo,
|
| 74 |
+
# to an isolated --target dir that we prepend to sys.path. --no-index means
|
| 75 |
+
# pip never contacts the network (the sandbox has no working index anyway);
|
| 76 |
+
# --target means base site-packages is untouched, so scoring stays safe.
|
| 77 |
+
# =============================================================================
|
| 78 |
+
WHEELHOUSE = Path(os.environ.get("QWEN3_WHEELHOUSE", str(SCRIPT_DIR / "wheelhouse")))
|
| 79 |
+
RUNTIME_DIR = Path(os.environ.get("QWEN3_RUNTIME_DIR", "/tmp/qwen3deps"))
|
| 80 |
+
RUNTIME_PACKAGES = {
|
| 81 |
+
"transformers": "4.51.3",
|
| 82 |
+
"tokenizers": "0.21.1",
|
| 83 |
+
"huggingface_hub": "0.30.2",
|
| 84 |
+
"autoawq": "0.2.9",
|
| 85 |
+
}
|
| 86 |
+
RUNTIME_WHEELS = (
|
| 87 |
+
"transformers-4.51.3-py3-none-any.whl",
|
| 88 |
+
"tokenizers-0.21.1-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl",
|
| 89 |
+
"huggingface_hub-0.30.2-py3-none-any.whl",
|
| 90 |
+
"autoawq-0.2.9-py3-none-any.whl",
|
| 91 |
+
)
|
| 92 |
+
def ensure_runtime_dependencies():
|
| 93 |
+
wheel_paths = [WHEELHOUSE / name for name in RUNTIME_WHEELS]
|
| 94 |
+
missing = [str(p) for p in wheel_paths if not p.is_file()]
|
| 95 |
+
if missing:
|
| 96 |
+
raise FileNotFoundError(f"Missing offline runtime wheels: {missing}")
|
| 97 |
+
marker = RUNTIME_DIR / ".iol-qwen3-runtime-v1"
|
| 98 |
+
if not marker.is_file():
|
| 99 |
+
RUNTIME_DIR.mkdir(parents=True, exist_ok=True)
|
| 100 |
+
subprocess.run(
|
| 101 |
+
[sys.executable, "-m", "pip", "install",
|
| 102 |
+
"--disable-pip-version-check", "--no-index", "--no-deps",
|
| 103 |
+
"--upgrade", "--target", str(RUNTIME_DIR),
|
| 104 |
+
*(str(p) for p in wheel_paths)],
|
| 105 |
+
check=True, timeout=300,
|
| 106 |
+
)
|
| 107 |
+
marker.write_text("offline Qwen3 runtime installed\n", encoding="utf-8")
|
| 108 |
+
runtime_path = str(RUNTIME_DIR)
|
| 109 |
+
if runtime_path in sys.path:
|
| 110 |
+
sys.path.remove(runtime_path)
|
| 111 |
+
sys.path.insert(0, runtime_path)
|
| 112 |
+
importlib.invalidate_caches()
|
| 113 |
+
versions = {}
|
| 114 |
+
for pkg in RUNTIME_PACKAGES:
|
| 115 |
+
try:
|
| 116 |
+
versions[pkg] = importlib.metadata.version(pkg)
|
| 117 |
+
except importlib.metadata.PackageNotFoundError:
|
| 118 |
+
versions[pkg] = "missing"
|
| 119 |
+
print(f"offline runtime active: {versions}", flush=True)
|
| 120 |
+
try:
|
| 121 |
+
ensure_runtime_dependencies()
|
| 122 |
+
except Exception as e:
|
| 123 |
+
emergency_submission_csv(f"wheelhouse install failed: {e}")
|
| 124 |
+
raise
|
| 125 |
+
import re, json, time, ast as pyast
|
| 126 |
+
import pandas as pd
|
| 127 |
+
import torch
|
| 128 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 129 |
+
MODEL_ID = "."
|
| 130 |
+
TIME_LIMIT_S = 30 * 60
|
| 131 |
+
SETUP_BUFFER_S = 360
|
| 132 |
+
start_time = time.time()
|
| 133 |
+
try:
|
| 134 |
+
df = pd.read_csv("/tmp/data/test.csv", dtype=str).fillna("")
|
| 135 |
+
placeholder_rows = [{"id": rid, "pred": json.dumps([""]),
|
| 136 |
+
"explanation": "Placeholder written before model load."}
|
| 137 |
+
for rid in df["id"].tolist()]
|
| 138 |
+
write_submission_csv(placeholder_rows)
|
| 139 |
+
print(f"Pre-load checkpoint written for {len(placeholder_rows)} rows.", flush=True)
|
| 140 |
+
# AWQ backend preflight (diagnostic only, never fatal).
|
| 141 |
+
try:
|
| 142 |
+
from awq.modules.linear import gemm as awq_gemm
|
| 143 |
+
print(f"AWQ backends: extension={awq_gemm.awq_ext is not None}, "
|
| 144 |
+
f"triton={getattr(awq_gemm, 'TRITON_AVAILABLE', None)}", flush=True)
|
| 145 |
+
except Exception as exc:
|
| 146 |
+
print(f"AWQ backend preflight warning: {exc}", flush=True)
|
| 147 |
+
try:
|
| 148 |
+
tok = AutoTokenizer.from_pretrained(MODEL_ID, local_files_only=True)
|
| 149 |
+
print("Tokenizer loaded (fast).", flush=True)
|
| 150 |
+
except Exception as e:
|
| 151 |
+
print(f"Fast tokenizer failed ({e}); falling back to use_fast=False.", flush=True)
|
| 152 |
+
tok = AutoTokenizer.from_pretrained(MODEL_ID, use_fast=False, local_files_only=True)
|
| 153 |
+
print("Tokenizer loaded (slow fallback).", flush=True)
|
| 154 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 155 |
+
MODEL_ID, torch_dtype=torch.float16, device_map="auto", local_files_only=True,
|
| 156 |
+
).eval()
|
| 157 |
+
print(f"Model loaded | memory footprint: {round(model.get_memory_footprint()/1e9, 1)} GB | "
|
| 158 |
+
f"quantized: {getattr(model.config, 'quantization_config', None) is not None}", flush=True)
|
| 159 |
+
except Exception as e:
|
| 160 |
+
emergency_submission_csv(f"tokenizer/model load or test.csv read failed: {e}")
|
| 161 |
+
raise
|
| 162 |
+
n_rows = len(df)
|
| 163 |
+
actual_setup_elapsed = time.time() - start_time
|
| 164 |
+
per_row_budget = max(20, (TIME_LIMIT_S - actual_setup_elapsed) / max(n_rows, 1))
|
| 165 |
+
print(f"Setup took {actual_setup_elapsed:.0f}s | per_row_budget={per_row_budget:.0f}s "
|
| 166 |
+
f"for {n_rows} rows", flush=True)
|
| 167 |
+
# ---- Query parsing ----
|
| 168 |
+
def parse_items(query: str):
|
| 169 |
+
item_pat = re.compile(r"(?m)^\s*(\d+)\s*[.\)]\s*(.*)$")
|
| 170 |
+
matches = list(item_pat.finditer(query))
|
| 171 |
+
if matches:
|
| 172 |
+
preamble = query[:matches[0].start()].strip()
|
| 173 |
+
items = []
|
| 174 |
+
for i, m in enumerate(matches):
|
| 175 |
+
end = matches[i + 1].start() if i + 1 < len(matches) else len(query)
|
| 176 |
+
text = re.sub(r"^\s*\d+\s*[.\)]\s*", "", query[m.start():end].strip())
|
| 177 |
+
items.append(text)
|
| 178 |
+
return preamble, items, True
|
| 179 |
+
rng = re.search(r"[\(\[]?\s*(\d+)\s*(?:[-–—:]|to)\s*(\d+)\s*[\)\]]?", query, flags=re.IGNORECASE)
|
| 180 |
+
if rng:
|
| 181 |
+
lo, hi = int(rng.group(1)), int(rng.group(2))
|
| 182 |
+
if 0 < hi - lo < 100:
|
| 183 |
+
items = []
|
| 184 |
+
for k in range(lo, hi + 1):
|
| 185 |
+
line_match = re.search(rf"(?m)^.*\(\s*{k}\s*\).*$", query)
|
| 186 |
+
if line_match:
|
| 187 |
+
clue = re.sub(rf"\(\s*{k}\s*\)", "", line_match.group(0)).strip()
|
| 188 |
+
clue = re.sub(r"\|\s*\|", "|", clue)
|
| 189 |
+
clue = re.sub(r"\s{2,}", " ", clue).strip(" |")
|
| 190 |
+
items.append(clue if clue else f"the numbered item {k} from the examples above")
|
| 191 |
+
else:
|
| 192 |
+
items.append(f"the numbered item {k} from the examples above")
|
| 193 |
+
return query.strip(), items, True
|
| 194 |
+
csv_nums = re.findall(r"(?m)^\s*(\d+)\s*,\s*(\d+(?:\s*,\s*\d+)*)\s*$", query)
|
| 195 |
+
if csv_nums:
|
| 196 |
+
all_nums = re.findall(r"\d+", " ".join(csv_nums[0]))
|
| 197 |
+
return query.strip(), [f"the numbered item {n}" for n in all_nums], True
|
| 198 |
+
return query.strip(), [], False
|
| 199 |
+
TASK_GUIDANCE = {
|
| 200 |
+
"translation": "give the translated form only, in the language asked.",
|
| 201 |
+
"fill_blanks": "give only the missing form for each blank.",
|
| 202 |
+
"match_letters": "give only the option letter (for example A, B, C).",
|
| 203 |
+
"text_to_num": "give the number in digits.",
|
| 204 |
+
"num_to_text": "give the number written out in words, in the language asked.",
|
| 205 |
+
}
|
| 206 |
+
DEFAULT_GUIDANCE = "give exactly what the instruction asks, nothing else."
|
| 207 |
+
from difflib import SequenceMatcher
|
| 208 |
+
from collections import defaultdict
|
| 209 |
+
def extract_forms_from_context(context: str):
|
| 210 |
+
forms = []
|
| 211 |
+
for line in context.splitlines():
|
| 212 |
+
line = line.strip()
|
| 213 |
+
if not line:
|
| 214 |
+
continue
|
| 215 |
+
pipe_count = line.count("|")
|
| 216 |
+
if 0 < pipe_count <= 3:
|
| 217 |
+
first_field = re.sub(r"^\s*\d+\s*[.\)]\s*", "", line.split("|")[0].strip()).strip()
|
| 218 |
+
if first_field:
|
| 219 |
+
forms.append(first_field)
|
| 220 |
+
elif pipe_count == 0:
|
| 221 |
+
for t in line.split():
|
| 222 |
+
t_clean = re.sub(r"^\s*\d+\s*[.\)]\s*", "", t).strip(".,;:")
|
| 223 |
+
if t_clean and len(t_clean) > 1:
|
| 224 |
+
forms.append(t_clean)
|
| 225 |
+
seen, unique_forms = set(), []
|
| 226 |
+
for f in forms:
|
| 227 |
+
if f not in seen:
|
| 228 |
+
seen.add(f)
|
| 229 |
+
unique_forms.append(f)
|
| 230 |
+
return unique_forms
|
| 231 |
+
def extract_explicit_pairs(context: str):
|
| 232 |
+
pairs = []
|
| 233 |
+
for line in context.splitlines():
|
| 234 |
+
line = line.strip()
|
| 235 |
+
if not (0 < line.count("|") <= 3):
|
| 236 |
+
continue
|
| 237 |
+
fields = [re.sub(r"^\s*\d+\s*[.\)]\s*", "", f.strip()).strip() for f in line.split("|")]
|
| 238 |
+
fields = [f for f in fields if f]
|
| 239 |
+
if len(fields) >= 2:
|
| 240 |
+
pairs.append((fields[0], fields[1]))
|
| 241 |
+
return pairs
|
| 242 |
+
def edit_signature(a: str, b: str):
|
| 243 |
+
sm = SequenceMatcher(None, a, b, autojunk=False)
|
| 244 |
+
all_ops = sm.get_opcodes()
|
| 245 |
+
ops = [op for op in all_ops if op[0] != "equal"]
|
| 246 |
+
if not ops or len(ops) > 2:
|
| 247 |
+
return None
|
| 248 |
+
equal_len = sum((i2 - i1) for tag, i1, i2, j1, j2 in all_ops if tag == "equal")
|
| 249 |
+
if equal_len < 2:
|
| 250 |
+
return None
|
| 251 |
+
tag, i1, i2, j1, j2 = ops[0]
|
| 252 |
+
removed, inserted = a[i1:i2], b[j1:j2]
|
| 253 |
+
if i1 == 0:
|
| 254 |
+
pos = "prefix"
|
| 255 |
+
elif i2 == len(a):
|
| 256 |
+
pos = "suffix"
|
| 257 |
+
else:
|
| 258 |
+
pos = "infix"
|
| 259 |
+
return (pos, removed, inserted)
|
| 260 |
+
def find_transformation_families(pairs):
|
| 261 |
+
groups = defaultdict(list)
|
| 262 |
+
for a, b in pairs:
|
| 263 |
+
if not a or not b or a == b:
|
| 264 |
+
continue
|
| 265 |
+
sig = edit_signature(a, b)
|
| 266 |
+
if sig:
|
| 267 |
+
groups[sig].append((a, b))
|
| 268 |
+
families = []
|
| 269 |
+
for sig, grp in groups.items():
|
| 270 |
+
unique_pairs = list(dict.fromkeys(grp))
|
| 271 |
+
if len(unique_pairs) >= 2:
|
| 272 |
+
pos, removed, inserted = sig
|
| 273 |
+
removed_disp = removed if removed else "(nothing)"
|
| 274 |
+
inserted_disp = inserted if inserted else "(nothing)"
|
| 275 |
+
examples = "; ".join(f"{a}->{b}" for a, b in unique_pairs[:4])
|
| 276 |
+
families.append((len(unique_pairs),
|
| 277 |
+
f"{pos} change: '{removed_disp}' -> '{inserted_disp}' (seen in: {examples})"))
|
| 278 |
+
families.sort(key=lambda x: -x[0])
|
| 279 |
+
return [f for _, f in families]
|
| 280 |
+
def detect_reduplication(forms):
|
| 281 |
+
findings = []
|
| 282 |
+
for w in forms:
|
| 283 |
+
n = len(w)
|
| 284 |
+
found = False
|
| 285 |
+
for length in range(2, n // 2 + 1):
|
| 286 |
+
for start in range(0, n - 2 * length + 1):
|
| 287 |
+
chunk = w[start:start + length]
|
| 288 |
+
nxt = w[start + length:start + 2 * length]
|
| 289 |
+
if chunk == nxt:
|
| 290 |
+
findings.append(f"reduplication in '{w}': '{chunk}' repeated")
|
| 291 |
+
found = True
|
| 292 |
+
break
|
| 293 |
+
if found:
|
| 294 |
+
break
|
| 295 |
+
return findings
|
| 296 |
+
def build_symbolic_evidence(context: str) -> str:
|
| 297 |
+
forms = extract_forms_from_context(context)
|
| 298 |
+
pairs = extract_explicit_pairs(context)
|
| 299 |
+
families = find_transformation_families(pairs) if pairs else []
|
| 300 |
+
redup = detect_reduplication(forms) if forms else []
|
| 301 |
+
lines = []
|
| 302 |
+
if families:
|
| 303 |
+
lines.append("Transformation families found (patterns supported by multiple examples):")
|
| 304 |
+
for f in families[:3]:
|
| 305 |
+
lines.append(f"- {f}")
|
| 306 |
+
if redup:
|
| 307 |
+
lines.append("Reduplication detected:")
|
| 308 |
+
for r in redup[:2]:
|
| 309 |
+
lines.append(f"- {r}")
|
| 310 |
+
if not lines:
|
| 311 |
+
return ""
|
| 312 |
+
return ("\n\nSYMBOLIC EVIDENCE (deterministically computed from the examples above; "
|
| 313 |
+
"may be incomplete -- verify against the examples, do not trust blindly):\n"
|
| 314 |
+
+ "\n".join(lines))
|
| 315 |
+
def build_messages(context, query, task_type):
|
| 316 |
+
preamble, items, count_known = parse_items(query)
|
| 317 |
+
guidance = TASK_GUIDANCE.get(task_type, DEFAULT_GUIDANCE)
|
| 318 |
+
symbolic_evidence = build_symbolic_evidence(context)
|
| 319 |
+
system = (
|
| 320 |
+
"You solve puzzles about a language you have never seen. Everything you "
|
| 321 |
+
"need is in the examples below. Use only the examples, not outside "
|
| 322 |
+
"knowledge of any language. You may meet a task type you have never "
|
| 323 |
+
"seen -- read the instruction and examples, and answer in the same "
|
| 324 |
+
"form they use."
|
| 325 |
+
)
|
| 326 |
+
number_note = ""
|
| 327 |
+
if task_type == "text_to_num":
|
| 328 |
+
number_note = (
|
| 329 |
+
"\n\nAlso add one more line after your answers, exactly like this:\n"
|
| 330 |
+
"COMPUTE: expr1 | expr2\n"
|
| 331 |
+
"where each expr is a plain arithmetic expression (digits, +, -, *, "
|
| 332 |
+
"parentheses only) for that item's value, one per answer, matching "
|
| 333 |
+
"the rule you found."
|
| 334 |
+
)
|
| 335 |
+
options_note = ""
|
| 336 |
+
if task_type == "match_letters":
|
| 337 |
+
options = extract_match_letter_options(context)
|
| 338 |
+
if options:
|
| 339 |
+
options_note = (
|
| 340 |
+
f"\n\nThe only valid answers are: {', '.join(options)}. "
|
| 341 |
+
f"Do not use any other letter."
|
| 342 |
+
)
|
| 343 |
+
if count_known:
|
| 344 |
+
n_items = len(items)
|
| 345 |
+
slots = "\n\n".join(f"Question {i+1}: {it}\nAnswer {i+1}:" for i, it in enumerate(items))
|
| 346 |
+
user = (
|
| 347 |
+
f"EXAMPLES:\n{context.strip()}"
|
| 348 |
+
f"{symbolic_evidence}\n\n"
|
| 349 |
+
f"--- The examples end here. The questions begin below. ---\n\n"
|
| 350 |
+
f"For each question: find the rule that explains ALL the examples above "
|
| 351 |
+
f"(not just one). Check it against every example before answering. "
|
| 352 |
+
f"For this task type, {guidance}\n\n"
|
| 353 |
+
f"{preamble}\n\n{slots}\n\n"
|
| 354 |
+
f"After answering all {n_items} questions, finish with exactly one line, "
|
| 355 |
+
f"all {n_items} answers in order separated by ' | ':\n"
|
| 356 |
+
f"FINAL ANSWERS: answer1 | answer2"
|
| 357 |
+
f"{number_note}"
|
| 358 |
+
f"{options_note}"
|
| 359 |
+
)
|
| 360 |
+
else:
|
| 361 |
+
n_items = None
|
| 362 |
+
user = (
|
| 363 |
+
f"EXAMPLES:\n{context.strip()}"
|
| 364 |
+
f"{symbolic_evidence}\n\n"
|
| 365 |
+
f"--- The examples end here. The question begins below. ---\n\n"
|
| 366 |
+
f"Find the rule that explains ALL the examples above (not just one). "
|
| 367 |
+
f"Check it against every example before answering. "
|
| 368 |
+
f"For this task type, {guidance}\n\n"
|
| 369 |
+
f"{preamble}\n\n"
|
| 370 |
+
f"Answer every item asked above, in order, one per answer. Finish "
|
| 371 |
+
f"with exactly one line, all your answers in order separated by ' | ':\n"
|
| 372 |
+
f"FINAL ANSWERS: answer1 | answer2"
|
| 373 |
+
f"{number_note}"
|
| 374 |
+
f"{options_note}"
|
| 375 |
+
)
|
| 376 |
+
return [{"role": "system", "content": system}, {"role": "user", "content": user}], n_items
|
| 377 |
+
def build_repair_messages(query, n_items, bad_text):
|
| 378 |
+
n_desc = f"exactly {n_items}" if n_items is not None else "one per item asked"
|
| 379 |
+
system = "You reformat answers. Output nothing except the requested line."
|
| 380 |
+
user = (
|
| 381 |
+
f"Question:\n{query.strip()}\n\n"
|
| 382 |
+
f"A previous attempt produced:\n{bad_text[:600]}\n\n"
|
| 383 |
+
f"Extract or restate {n_desc} final answers, in order, as ONE line:\n"
|
| 384 |
+
f"FINAL ANSWERS: answer1 | answer2"
|
| 385 |
+
)
|
| 386 |
+
return [{"role": "system", "content": system}, {"role": "user", "content": user}]
|
| 387 |
+
_ALLOWED_BINOPS = (pyast.Add, pyast.Sub, pyast.Mult)
|
| 388 |
+
def safe_arithmetic(expr: str):
|
| 389 |
+
try:
|
| 390 |
+
tree = pyast.parse(expr.strip(), mode="eval")
|
| 391 |
+
except Exception:
|
| 392 |
+
return None
|
| 393 |
+
def _eval(node):
|
| 394 |
+
if isinstance(node, pyast.Expression):
|
| 395 |
+
return _eval(node.body)
|
| 396 |
+
if isinstance(node, pyast.Constant) and isinstance(node.value, (int, float)):
|
| 397 |
+
return node.value
|
| 398 |
+
if isinstance(node, pyast.BinOp) and isinstance(node.op, _ALLOWED_BINOPS):
|
| 399 |
+
left, right = _eval(node.left), _eval(node.right)
|
| 400 |
+
if left is None or right is None:
|
| 401 |
+
return None
|
| 402 |
+
if isinstance(node.op, pyast.Add): return left + right
|
| 403 |
+
if isinstance(node.op, pyast.Sub): return left - right
|
| 404 |
+
if isinstance(node.op, pyast.Mult): return left * right
|
| 405 |
+
if isinstance(node, pyast.UnaryOp) and isinstance(node.op, pyast.USub):
|
| 406 |
+
v = _eval(node.operand)
|
| 407 |
+
return -v if v is not None else None
|
| 408 |
+
return None
|
| 409 |
+
return _eval(tree)
|
| 410 |
+
def clean_answer(a: str) -> str:
|
| 411 |
+
a = re.sub(r"(?i)^\s*(the\s+)?(final\s+)?answer\s*\d*\s*(is)?\s*:\s*", "", a).strip()
|
| 412 |
+
a = re.sub(r"(?i)^\s*is\s*:\s*", "", a).strip()
|
| 413 |
+
a = a.strip("* ")
|
| 414 |
+
return a.strip(" .\"'“”‘’")
|
| 415 |
+
def extract(text):
|
| 416 |
+
m = list(re.finditer(r"final answers?\s*:?\s*\**", text, flags=re.IGNORECASE))
|
| 417 |
+
if m:
|
| 418 |
+
tail = text[m[-1].end():]
|
| 419 |
+
stop = re.search(r"(?i)compute\s*:", tail)
|
| 420 |
+
if stop:
|
| 421 |
+
tail = tail[:stop.start()]
|
| 422 |
+
tail = tail.replace("**", " ").strip()
|
| 423 |
+
candidate = " ".join(tail.splitlines())
|
| 424 |
+
parts = [clean_answer(p) for p in candidate.split("|") if p.strip()]
|
| 425 |
+
if parts:
|
| 426 |
+
return parts, m[-1].start()
|
| 427 |
+
lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
|
| 428 |
+
fallback = []
|
| 429 |
+
for ln in lines:
|
| 430 |
+
ln_clean = re.sub(r"^\s*\d+\s*[.\)]\s*", "", ln)
|
| 431 |
+
if "|" in ln_clean:
|
| 432 |
+
fallback.extend(clean_answer(p) for p in ln_clean.split("|") if p.strip())
|
| 433 |
+
else:
|
| 434 |
+
fallback.append(clean_answer(ln_clean))
|
| 435 |
+
return fallback, None
|
| 436 |
+
def extract_compute_overrides(text, n_answers):
|
| 437 |
+
m = re.search(r"compute\s*:\s*(.+)", text, flags=re.IGNORECASE)
|
| 438 |
+
if not m:
|
| 439 |
+
return {}
|
| 440 |
+
exprs = [e.strip() for e in m.group(1).split("|")]
|
| 441 |
+
overrides = {}
|
| 442 |
+
for i, e in enumerate(exprs[:n_answers]):
|
| 443 |
+
val = safe_arithmetic(e)
|
| 444 |
+
if val is not None:
|
| 445 |
+
overrides[i] = str(int(val)) if float(val).is_integer() else str(val)
|
| 446 |
+
return overrides
|
| 447 |
+
# ---- Generation. enable_thinking=False keeps Qwen3 in its fast, non-<think>
|
| 448 |
+
# mode; our decomposition prompt supplies the reasoning instead. The kwarg is
|
| 449 |
+
# harmless on templates that ignore it. Both API-shape branches pass it. ----
|
| 450 |
+
def generate(messages, max_new_tokens, constraint_fn=None):
|
| 451 |
+
def _try_generate(gen_kwargs):
|
| 452 |
+
try:
|
| 453 |
+
enc = tok.apply_chat_template(
|
| 454 |
+
messages, add_generation_prompt=True, enable_thinking=False,
|
| 455 |
+
return_tensors="pt", return_dict=True,
|
| 456 |
+
).to(model.device)
|
| 457 |
+
input_len = enc["input_ids"].shape[-1]
|
| 458 |
+
with torch.no_grad():
|
| 459 |
+
out = model.generate(**enc, **gen_kwargs)
|
| 460 |
+
except Exception:
|
| 461 |
+
ids = tok.apply_chat_template(
|
| 462 |
+
messages, add_generation_prompt=True, enable_thinking=False,
|
| 463 |
+
return_tensors="pt",
|
| 464 |
+
).to(model.device)
|
| 465 |
+
input_len = ids.shape[-1]
|
| 466 |
+
with torch.no_grad():
|
| 467 |
+
out = model.generate(ids, **gen_kwargs)
|
| 468 |
+
return out, input_len
|
| 469 |
+
base_kwargs = {"max_new_tokens": max_new_tokens, "do_sample": False}
|
| 470 |
+
if constraint_fn is not None:
|
| 471 |
+
try:
|
| 472 |
+
out, input_len = _try_generate({**base_kwargs, "prefix_allowed_tokens_fn": constraint_fn})
|
| 473 |
+
except Exception:
|
| 474 |
+
out, input_len = _try_generate(base_kwargs)
|
| 475 |
+
else:
|
| 476 |
+
out, input_len = _try_generate(base_kwargs)
|
| 477 |
+
return tok.decode(out[0][input_len:], skip_special_tokens=True).strip()
|
| 478 |
+
EXPLANATION_SYSTEM = (
|
| 479 |
+
"Summarize the following reasoning into a few short bullet points: the "
|
| 480 |
+
"rule or pattern found in the data and the key evidence for the answer. "
|
| 481 |
+
"Be concise and structured -- do not repeat the full reasoning."
|
| 482 |
+
)
|
| 483 |
+
EXPLANATION_FALLBACK = "Answer derived from patterns found in the examples above."
|
| 484 |
+
_LETTER_CONSTRAINT_CACHE = {}
|
| 485 |
+
def build_letter_constraint_fn(tok, valid_letters):
|
| 486 |
+
cache_key = (id(tok), tuple(sorted(valid_letters)))
|
| 487 |
+
if cache_key in _LETTER_CONSTRAINT_CACHE:
|
| 488 |
+
return _LETTER_CONSTRAINT_CACHE[cache_key]
|
| 489 |
+
try:
|
| 490 |
+
allowed_chars = set(valid_letters) | set(" |\n\t\r")
|
| 491 |
+
eos = tok.eos_token_id
|
| 492 |
+
pieces = []
|
| 493 |
+
for token_id in range(len(tok)):
|
| 494 |
+
if token_id == eos:
|
| 495 |
+
continue
|
| 496 |
+
piece = tok.decode([token_id], skip_special_tokens=False)
|
| 497 |
+
if piece and all(c in allowed_chars for c in piece):
|
| 498 |
+
pieces.append(token_id)
|
| 499 |
+
allowed_ids = ([eos] if eos is not None else []) + pieces
|
| 500 |
+
def allowed(_batch_id, _input_ids):
|
| 501 |
+
return allowed_ids if allowed_ids else list(range(len(tok)))
|
| 502 |
+
_LETTER_CONSTRAINT_CACHE[cache_key] = allowed
|
| 503 |
+
return allowed
|
| 504 |
+
except Exception:
|
| 505 |
+
return None
|
| 506 |
+
def extract_match_letter_options(context: str):
|
| 507 |
+
found = set()
|
| 508 |
+
for line in context.splitlines():
|
| 509 |
+
for m in re.finditer(r"(?:^|\s)([A-Z])[.\)]\s+\S", line):
|
| 510 |
+
found.add(m.group(1))
|
| 511 |
+
if not found:
|
| 512 |
+
return None
|
| 513 |
+
letters = sorted(found)
|
| 514 |
+
expected = [chr(ord("A") + i) for i in range(len(letters))]
|
| 515 |
+
if letters != expected:
|
| 516 |
+
return None
|
| 517 |
+
if not (2 <= len(letters) <= 26):
|
| 518 |
+
return None
|
| 519 |
+
return letters
|
| 520 |
+
rows = []
|
| 521 |
+
processed_ids = set()
|
| 522 |
+
try:
|
| 523 |
+
for _, r in df.iterrows():
|
| 524 |
+
try:
|
| 525 |
+
elapsed = time.time() - start_time
|
| 526 |
+
remaining = TIME_LIMIT_S - elapsed
|
| 527 |
+
budget_left_rows = max(n_rows - len(rows), 1)
|
| 528 |
+
row_budget = remaining / budget_left_rows
|
| 529 |
+
time_based_cap = 1280 if row_budget > per_row_budget else 640
|
| 530 |
+
task_type = r.get("task_type", "")
|
| 531 |
+
messages, n_items = build_messages(r["context"], r["query"], task_type)
|
| 532 |
+
if n_items:
|
| 533 |
+
item_based_cap = max(640, min(1536, n_items * 48 + 256))
|
| 534 |
+
tokens_cap = min(time_based_cap, item_based_cap)
|
| 535 |
+
else:
|
| 536 |
+
tokens_cap = time_based_cap
|
| 537 |
+
text = generate(messages, tokens_cap)
|
| 538 |
+
answers, marker_pos = extract(text)
|
| 539 |
+
if task_type == "text_to_num":
|
| 540 |
+
overrides = extract_compute_overrides(text, len(answers))
|
| 541 |
+
for idx, val in overrides.items():
|
| 542 |
+
if idx < len(answers):
|
| 543 |
+
answers[idx] = val
|
| 544 |
+
if (marker_pos is None or not answers) and remaining > SETUP_BUFFER_S:
|
| 545 |
+
repair_constraint = None
|
| 546 |
+
if task_type == "match_letters":
|
| 547 |
+
repair_options = extract_match_letter_options(r["context"])
|
| 548 |
+
if repair_options:
|
| 549 |
+
repair_constraint = build_letter_constraint_fn(tok, repair_options)
|
| 550 |
+
repair_text = generate(build_repair_messages(r["query"], n_items, text), 128,
|
| 551 |
+
constraint_fn=repair_constraint)
|
| 552 |
+
rep, rep_pos = extract(repair_text)
|
| 553 |
+
if rep:
|
| 554 |
+
answers, marker_pos = rep, rep_pos
|
| 555 |
+
if n_items is not None:
|
| 556 |
+
if len(answers) < n_items:
|
| 557 |
+
answers = answers + [answers[-1] if answers else ""] * (n_items - len(answers))
|
| 558 |
+
elif len(answers) > n_items and marker_pos is None:
|
| 559 |
+
answers = answers[:n_items]
|
| 560 |
+
if not answers:
|
| 561 |
+
answers = [""]
|
| 562 |
+
remaining_after = TIME_LIMIT_S - (time.time() - start_time)
|
| 563 |
+
budget_left_after = max(n_rows - len(rows) - 1, 0)
|
| 564 |
+
comfortable = remaining_after > (budget_left_after + 1) * per_row_budget * 1.3
|
| 565 |
+
if comfortable:
|
| 566 |
+
try:
|
| 567 |
+
explanation = generate(
|
| 568 |
+
[{"role": "system", "content": EXPLANATION_SYSTEM},
|
| 569 |
+
{"role": "user", "content": text}], 300,
|
| 570 |
+
) or EXPLANATION_FALLBACK
|
| 571 |
+
except Exception:
|
| 572 |
+
explanation = EXPLANATION_FALLBACK
|
| 573 |
+
else:
|
| 574 |
+
snippet = re.sub(r"\s{2,}", " ", text[:300]).strip()
|
| 575 |
+
explanation = snippet if snippet else EXPLANATION_FALLBACK
|
| 576 |
+
rows.append({"id": r["id"], "pred": json.dumps(answers, ensure_ascii=False),
|
| 577 |
+
"explanation": explanation})
|
| 578 |
+
processed_ids.add(r["id"])
|
| 579 |
+
write_submission_csv(rows)
|
| 580 |
+
print(f"{len(rows)}/{n_rows} answers={len(answers)} elapsed={time.time()-start_time:.0f}s", flush=True)
|
| 581 |
+
except Exception as e:
|
| 582 |
+
try:
|
| 583 |
+
_, fallback_items, fk = parse_items(r["query"])
|
| 584 |
+
n_fallback = len(fallback_items) if fk else 1
|
| 585 |
+
except Exception:
|
| 586 |
+
n_fallback = 1
|
| 587 |
+
rows.append({"id": r["id"], "pred": json.dumps([""] * n_fallback, ensure_ascii=False),
|
| 588 |
+
"explanation": EXPLANATION_FALLBACK})
|
| 589 |
+
processed_ids.add(r["id"])
|
| 590 |
+
write_submission_csv(rows)
|
| 591 |
+
print(f"ROW ERROR on {r['id']}: {e}", flush=True)
|
| 592 |
+
if time.time() - start_time > TIME_LIMIT_S - 60:
|
| 593 |
+
print("Time budget nearly exhausted, stopping early.", flush=True)
|
| 594 |
+
break
|
| 595 |
+
for _, r in df.iterrows():
|
| 596 |
+
if r["id"] in processed_ids:
|
| 597 |
+
continue
|
| 598 |
+
try:
|
| 599 |
+
_, fallback_items, fk = parse_items(r["query"])
|
| 600 |
+
n_fallback = len(fallback_items) if fk else 1
|
| 601 |
+
except Exception:
|
| 602 |
+
n_fallback = 1
|
| 603 |
+
rows.append({"id": r["id"], "pred": json.dumps([""] * n_fallback, ensure_ascii=False),
|
| 604 |
+
"explanation": EXPLANATION_FALLBACK})
|
| 605 |
+
write_submission_csv(rows)
|
| 606 |
+
print("DONE.", flush=True)
|
| 607 |
+
except Exception as e:
|
| 608 |
+
emergency_submission_csv(f"main loop failed: {e}", rows_so_far=rows if rows else None)
|
| 609 |
+
print(f"FATAL, but submission.csv was written with {len(rows)} rows. Error: {e}", flush=True)
|