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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# =============================================================
|
| 2 |
+
# SINHALAMMLU — MIDDLE E4B V2 TARGETED RECOVERY, 32 QUESTIONS
|
| 3 |
+
# Self-contained fresh Kaggle session, with T4 x2 and Internet ON.
|
| 4 |
+
# Attach: (1) original 41 JSON test question files (questions-set)
|
| 5 |
+
# (2) E4B_COMBINED_2206_WITH_FAILED32.zip as a Kaggle dataset.
|
| 6 |
+
# Saves independent per-question retry records, recovery ZIP and
|
| 7 |
+
# FINAL 2238-row predictions.zip only after 32/32 valid recoveries.
|
| 8 |
+
# NEVER trains on test data, NEVER guesses missing answers.
|
| 9 |
+
# =============================================================
|
| 10 |
+
import os, re, gc, json, time, hashlib, zipfile
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from datetime import datetime, timezone
|
| 13 |
+
from collections import Counter
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
from huggingface_hub import snapshot_download
|
| 17 |
+
from accelerate import init_empty_weights
|
| 18 |
+
from transformers import AutoConfig, AutoProcessor, AutoModelForMultimodalLM
|
| 19 |
+
|
| 20 |
+
ROOT = Path('/kaggle/working/SinhalaMMLU')
|
| 21 |
+
RUN = ROOT / 'experiments/MIDDLE_E4B_RETRY32'
|
| 22 |
+
STORE = RUN / 'retry_records'
|
| 23 |
+
STORE.mkdir(parents=True, exist_ok=True)
|
| 24 |
+
ARCHIVE = ROOT / 'archives/MIDDLE_E4B_RETRY32_LATEST.zip'
|
| 25 |
+
ARCHIVE.parent.mkdir(parents=True, exist_ok=True)
|
| 26 |
+
FINAL_ZIP = ROOT / 'archives/E4B_V2_FINAL_2238_predictions.zip'
|
| 27 |
+
|
| 28 |
+
MODEL_REPO = 'google/gemma-4-E4B-it'
|
| 29 |
+
REVISION = 'ee0ef6023621cff504d758262d4e04895a5af4a2'
|
| 30 |
+
WEIGHT_SHA = 'cfbd3d2f1cd71bd471c37fe2bf8546d5028d41e5736f64e1ca6c6b8893125503'
|
| 31 |
+
PROMPT_SHA = 'f53159bafe22a5d0063a065b6d3aef8167e7a6d6b998ce65e224feeeca68287d'
|
| 32 |
+
V2_PROMPT = (
|
| 33 |
+
'Answer this Sinhala multiple-choice question. '
|
| 34 |
+
'Use your reasoning to select the correct option. '
|
| 35 |
+
'In your final response, provide a brief explanation '
|
| 36 |
+
'in English, approximately 90 words. '
|
| 37 |
+
'Then put ANSWER: X on the last line, '
|
| 38 |
+
'where X is A, B, C, or D. '
|
| 39 |
+
'Do not change the selected answer.'
|
| 40 |
+
)
|
| 41 |
+
assert hashlib.sha256(V2_PROMPT.encode('utf-8')).hexdigest() == PROMPT_SHA
|
| 42 |
+
LETTER_TO_NUMBER = {'A':'1','B':'2','C':'3','D':'4'}
|
| 43 |
+
FIELDS = ['q_no','subject','category','level','answer']
|
| 44 |
+
TOKEN_BUDGET = 4096 # targeted single-question recovery only
|
| 45 |
+
MAX_WALL_SECONDS = 4 * 3600
|
| 46 |
+
|
| 47 |
+
def sha_file(path):
|
| 48 |
+
h = hashlib.sha256()
|
| 49 |
+
with open(path,'rb') as f:
|
| 50 |
+
for chunk in iter(lambda:f.read(8*1024*1024), b''):
|
| 51 |
+
h.update(chunk)
|
| 52 |
+
return h.hexdigest()
|
| 53 |
+
|
| 54 |
+
def atomic_json(path,obj):
|
| 55 |
+
path.parent.mkdir(parents=True,exist_ok=True)
|
| 56 |
+
tmp = path.with_name(path.name+'.tmp')
|
| 57 |
+
tmp.write_text(json.dumps(obj,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
|
| 58 |
+
os.replace(tmp,path)
|
| 59 |
+
|
| 60 |
+
def now():
|
| 61 |
+
return datetime.now(timezone.utc).isoformat()
|
| 62 |
+
|
| 63 |
+
def fingerprint(q):
|
| 64 |
+
keys=('source_file','source_position','q_no','subject','category','level','question','choices')
|
| 65 |
+
s=json.dumps({k:q[k] for k in keys},ensure_ascii=False,sort_keys=True,separators=(',',':'))
|
| 66 |
+
return hashlib.sha256(s.encode('utf-8')).hexdigest()
|
| 67 |
+
|
| 68 |
+
print('▶ RETRY32-A — LOAD AUTHORITY PACKAGE AND TEST DATA',flush=True)
|
| 69 |
+
# Kaggle may mount the ZIP intact OR automatically extract it.
|
| 70 |
+
# Both layouts are supported, with identical content fingerprints.
|
| 71 |
+
required_names=['E4B_COMBINED_VALID_2206_INDEXED.json','E4B_FAILED_ATTEMPTS_32.json',
|
| 72 |
+
'E4B_DATASET_SHA256_41.json','E4B_MERGE_AUDIT.json']
|
| 73 |
+
packages=[]
|
| 74 |
+
for p in Path('/kaggle/input').rglob('*.zip'):
|
| 75 |
+
try:
|
| 76 |
+
with zipfile.ZipFile(p) as z:
|
| 77 |
+
if set(required_names) <= set(z.namelist()):
|
| 78 |
+
packages.append(('zip',p))
|
| 79 |
+
except (zipfile.BadZipFile,OSError):
|
| 80 |
+
pass
|
| 81 |
+
for p in Path('/kaggle/input').rglob(required_names[0]):
|
| 82 |
+
if all((p.parent/n).is_file() for n in required_names):
|
| 83 |
+
packages.append(('extracted',p.parent))
|
| 84 |
+
# An uploaded ZIP may be visible both ways; prefer its intact version.
|
| 85 |
+
zipped=[p for p in packages if p[0]=='zip']
|
| 86 |
+
if zipped:packages=zipped
|
| 87 |
+
assert len(packages)==1, f'Attach the combined-2206 package exactly once. Found: {packages}'
|
| 88 |
+
package_kind,PACKAGE=packages[0]
|
| 89 |
+
if package_kind=='zip':
|
| 90 |
+
with zipfile.ZipFile(PACKAGE) as z:
|
| 91 |
+
assert z.testzip() is None
|
| 92 |
+
source_bytes={name:z.read(name) for name in required_names}
|
| 93 |
+
else:
|
| 94 |
+
source_bytes={name:(PACKAGE/name).read_bytes() for name in required_names}
|
| 95 |
+
previous=json.loads(source_bytes[required_names[0]])
|
| 96 |
+
failures=json.loads(source_bytes[required_names[1]])
|
| 97 |
+
files_hashes=json.loads(source_bytes[required_names[2]])
|
| 98 |
+
merge_audit=json.loads(source_bytes[required_names[3]])
|
| 99 |
+
package_content_sha=hashlib.sha256(b''.join(
|
| 100 |
+
name.encode('utf-8') + b'\0' + source_bytes[name]
|
| 101 |
+
for name in required_names)).hexdigest()
|
| 102 |
+
assert merge_audit['prompt_sha256']==PROMPT_SHA
|
| 103 |
+
assert merge_audit['revision']==REVISION
|
| 104 |
+
assert merge_audit['valid']==2206 and merge_audit['failed']==32
|
| 105 |
+
assert len(previous)==2206 and len(failures)==32 and len(files_hashes)==41
|
| 106 |
+
known_valid={int(r['dataset_index']):r for r in previous}
|
| 107 |
+
fail_by_idx={int(r['dataset_index']):r for r in failures}
|
| 108 |
+
assert len(known_valid)==2206 and len(fail_by_idx)==32
|
| 109 |
+
assert not (known_valid.keys() & fail_by_idx.keys())
|
| 110 |
+
assert set(known_valid)|set(fail_by_idx)==set(range(2238))
|
| 111 |
+
|
| 112 |
+
question_dirs=[]
|
| 113 |
+
for p in Path('/kaggle/input').rglob('Arts_Humanities_easy.json'):
|
| 114 |
+
d=p.parent
|
| 115 |
+
if len(list(d.glob('*.json')))!=41:continue
|
| 116 |
+
if all((d/f['filename']).is_file() and sha_file(d/f['filename'])==f['sha256']
|
| 117 |
+
for f in files_hashes):
|
| 118 |
+
question_dirs.append(d)
|
| 119 |
+
assert len(question_dirs)==1,f'Need original unchanged 41-file questions-set: {question_dirs}'
|
| 120 |
+
TEST_DIR=question_dirs[0]
|
| 121 |
+
questions=[]
|
| 122 |
+
for path in sorted(TEST_DIR.glob('*.json'),key=lambda p:p.name.casefold()):
|
| 123 |
+
obj=json.loads(path.read_text(encoding='utf-8'))
|
| 124 |
+
if isinstance(obj,dict):
|
| 125 |
+
obj=next((obj[k] for k in ('questions','data','items') if isinstance(obj.get(k),list)),None)
|
| 126 |
+
assert isinstance(obj,list),path
|
| 127 |
+
for pos,q in enumerate(obj):
|
| 128 |
+
assert len(q['choices'])==4
|
| 129 |
+
level=q['metadata']['difficulty']
|
| 130 |
+
assert level in ('easy','medium','hard')
|
| 131 |
+
questions.append({'source_file':path.name,'source_position':pos,'q_no':q['q_no'],
|
| 132 |
+
'subject':q['subject'],'category':q['category'],'level':level,
|
| 133 |
+
'question':q['question'],'choices':q['choices']})
|
| 134 |
+
priority={'easy':0,'medium':1,'hard':2}
|
| 135 |
+
questions.sort(key=lambda q:(priority[q['level']],q['source_file'].casefold(),q['source_position']))
|
| 136 |
+
assert len(questions)==2238
|
| 137 |
+
for i,q in enumerate(questions):q['dataset_index']=i
|
| 138 |
+
# Strictly reconcile every question's provided metadata with saved results.
|
| 139 |
+
for i in range(2238):
|
| 140 |
+
q=questions[i]
|
| 141 |
+
meta=known_valid[i] if i in known_valid else fail_by_idx[i]
|
| 142 |
+
assert all(q[k]==meta[k] for k in ('q_no','subject','category','level')),(i,meta)
|
| 143 |
+
if i in fail_by_idx:
|
| 144 |
+
f=fail_by_idx[i]
|
| 145 |
+
assert (q['source_file'],q['source_position'])==(f['source_file'],f['source_position'])
|
| 146 |
+
if f.get('input_fingerprint'):
|
| 147 |
+
assert fingerprint(q)==f['input_fingerprint'],i
|
| 148 |
+
else:
|
| 149 |
+
assert known_valid[i]['answer'] in '1234'
|
| 150 |
+
indices=sorted(fail_by_idx)
|
| 151 |
+
print('Package:',PACKAGE)
|
| 152 |
+
print('Dataset:',TEST_DIR)
|
| 153 |
+
print('Previously valid:',len(known_valid),'| failed:',len(indices))
|
| 154 |
+
print('Retry indices:',indices,flush=True)
|
| 155 |
+
|
| 156 |
+
# Immutable retry configuration. Per-run time limit is NOT part of the experiment identity.
|
| 157 |
+
config={'experiment':'MIDDLE_E4B_RETRY32','model':MODEL_REPO,'revision':REVISION,
|
| 158 |
+
'prompt_sha256':PROMPT_SHA,'native_thinking':True,'batch_size':1,
|
| 159 |
+
'max_new_tokens':TOKEN_BUDGET,'do_sample':False,
|
| 160 |
+
'original_valid':2206,'recovery_indices':indices,
|
| 161 |
+
'dataset_sha256':dict((x['filename'],x['sha256']) for x in files_hashes),
|
| 162 |
+
'package_content_sha256':package_content_sha}
|
| 163 |
+
cfg_path=RUN/'retry_config.json'
|
| 164 |
+
if cfg_path.exists():
|
| 165 |
+
saved_cfg=json.loads(cfg_path.read_text('utf-8'))
|
| 166 |
+
assert saved_cfg==config,'Existing retry configuration conflicts with this package'
|
| 167 |
+
else:
|
| 168 |
+
atomic_json(cfg_path,config)
|
| 169 |
+
|
| 170 |
+
# Restore earlier retry records from a prior archive, if provided.
|
| 171 |
+
# Never overwrite a valid local record with an older ZIP.
|
| 172 |
+
prefix='experiments/MIDDLE_E4B_RETRY32/retry_records/'
|
| 173 |
+
attached=[]
|
| 174 |
+
for p in Path('/kaggle/input').rglob('*.zip'):
|
| 175 |
+
if p==PACKAGE:continue
|
| 176 |
+
try:
|
| 177 |
+
with zipfile.ZipFile(p) as z:
|
| 178 |
+
if any(n.startswith(prefix) for n in z.namelist()):attached.append(p)
|
| 179 |
+
except (OSError,zipfile.BadZipFile):pass
|
| 180 |
+
if ARCHIVE.exists():attached.append(ARCHIVE)
|
| 181 |
+
for p in attached:
|
| 182 |
+
with zipfile.ZipFile(p) as z:
|
| 183 |
+
assert z.testzip() is None
|
| 184 |
+
for name in z.namelist():
|
| 185 |
+
if not(name.startswith(prefix) and name.endswith('.json')):continue
|
| 186 |
+
filename=name[len(prefix):]
|
| 187 |
+
assert filename.startswith('question_') and '/' not in filename and '..' not in filename
|
| 188 |
+
dest=STORE/filename
|
| 189 |
+
raw=z.read(name)
|
| 190 |
+
if dest.exists():
|
| 191 |
+
assert dest.read_bytes()==raw,f'Conflicting retry record {dest}'
|
| 192 |
+
else:dest.write_bytes(raw)
|
| 193 |
+
print('Restored prior retry ZIP:',p,flush=True)
|
| 194 |
+
|
| 195 |
+
def retry_path(i):return STORE/f'question_{i:04d}.json'
|
| 196 |
+
|
| 197 |
+
def validate_retry(r):
|
| 198 |
+
i=int(r['dataset_index'])
|
| 199 |
+
assert i in fail_by_idx
|
| 200 |
+
q=questions[i]
|
| 201 |
+
assert r['input_fingerprint']==fingerprint(q),i
|
| 202 |
+
assert r['max_new_tokens']==TOKEN_BUDGET
|
| 203 |
+
assert r['prompt_sha256']==PROMPT_SHA
|
| 204 |
+
assert r['original_status']==fail_by_idx[i]['status']
|
| 205 |
+
sub=r['submission_record']
|
| 206 |
+
assert list(sub)==FIELDS
|
| 207 |
+
assert all(sub[k]==q[k] for k in FIELDS[:4])
|
| 208 |
+
if r['valid']:
|
| 209 |
+
assert r['status']=='completed'
|
| 210 |
+
assert r['prediction'] in LETTER_TO_NUMBER
|
| 211 |
+
assert sub['answer']==LETTER_TO_NUMBER[r['prediction']]
|
| 212 |
+
assert r['turn_end'] is True and not r['limit_hit']
|
| 213 |
+
else:
|
| 214 |
+
assert sub['answer'] is None
|
| 215 |
+
|
| 216 |
+
def load_retries():
|
| 217 |
+
saved={}
|
| 218 |
+
for p in STORE.glob('question_*.json'):
|
| 219 |
+
r=json.loads(p.read_text(encoding='utf-8'))
|
| 220 |
+
validate_retry(r)
|
| 221 |
+
i=int(r['dataset_index'])
|
| 222 |
+
assert i not in saved
|
| 223 |
+
saved[i]=r
|
| 224 |
+
return saved
|
| 225 |
+
|
| 226 |
+
def checkpoint():
|
| 227 |
+
saved=load_retries()
|
| 228 |
+
state={
|
| 229 |
+
'experiment':config['experiment'],'original_valid':2206,'retry_target':32,
|
| 230 |
+
'attempted':len(saved),'valid':sum(r['valid'] for r in saved.values()),
|
| 231 |
+
'invalid':sum(not r['valid'] for r in saved.values()),
|
| 232 |
+
'not_yet_retried':[i for i in indices if i not in saved],
|
| 233 |
+
'still_invalid':[i for i,r in sorted(saved.items()) if not r['valid']],
|
| 234 |
+
'status_counts':dict(Counter(r['status'] for r in saved.values())),
|
| 235 |
+
'status':'COMPLETE' if len(saved)==32 and all(r['valid'] for r in saved.values()) else 'IN_PROGRESS',
|
| 236 |
+
'timestamp_utc':now()}
|
| 237 |
+
atomic_json(RUN/'retry_manifest.json',state)
|
| 238 |
+
temp=ARCHIVE.with_name(ARCHIVE.name+'.tmp')
|
| 239 |
+
with zipfile.ZipFile(temp,'w',zipfile.ZIP_DEFLATED,compresslevel=5) as z:
|
| 240 |
+
for p in sorted(RUN.rglob('*')):
|
| 241 |
+
if p.is_file():z.write(p,str(p.relative_to(ROOT)))
|
| 242 |
+
os.replace(temp,ARCHIVE)
|
| 243 |
+
with zipfile.ZipFile(ARCHIVE) as z:
|
| 244 |
+
assert z.testzip() is None
|
| 245 |
+
assert sum(n.startswith(prefix) and n.endswith('.json') for n in z.namelist())==len(saved)
|
| 246 |
+
return state
|
| 247 |
+
|
| 248 |
+
state=checkpoint()
|
| 249 |
+
print('\n▶ RETRY32-B — INITIAL STATUS')
|
| 250 |
+
print('Already retried:',state['attempted'],'| valid:',state['valid'],'| still to retry:',len(state['not_yet_retried']))
|
| 251 |
+
|
| 252 |
+
# Do not load a 16GB model if there are no questions left to attempt.
|
| 253 |
+
if state['not_yet_retried']:
|
| 254 |
+
print('\n▶ RETRY32-C — VERIFY AND LOAD GEMMA 4 E4B',flush=True)
|
| 255 |
+
assert torch.cuda.device_count()==2,'Enable T4 x2'
|
| 256 |
+
MODEL_DIR=ROOT/'weights/gemma4_e4b_it'
|
| 257 |
+
MODEL_DIR.mkdir(parents=True,exist_ok=True)
|
| 258 |
+
weights=MODEL_DIR/'model.safetensors'
|
| 259 |
+
if not weights.exists() or weights.stat().st_size!=15992595884:
|
| 260 |
+
snapshot_download(repo_id=MODEL_REPO,revision=REVISION,local_dir=str(MODEL_DIR),
|
| 261 |
+
token=os.getenv('HF_TOKEN') or None)
|
| 262 |
+
assert weights.stat().st_size==15992595884
|
| 263 |
+
assert sha_file(weights)==WEIGHT_SHA
|
| 264 |
+
print('Pinned checkpoint SHA256 VERIFIED',flush=True)
|
| 265 |
+
if 'gemma_model' not in globals():
|
| 266 |
+
assert all(torch.cuda.memory_allocated(i)<1024**3 for i in range(2)),\
|
| 267 |
+
'GPU memory occupied; restart kernel rather than loading a second model'
|
| 268 |
+
mc=AutoConfig.from_pretrained(str(MODEL_DIR),local_files_only=True)
|
| 269 |
+
processor=AutoProcessor.from_pretrained(str(MODEL_DIR),local_files_only=True)
|
| 270 |
+
with init_empty_weights():
|
| 271 |
+
skeleton=AutoModelForMultimodalLM.from_config(mc,torch_dtype=torch.float16)
|
| 272 |
+
layer_prefix='model.language_model.layers'
|
| 273 |
+
assert len(dict(skeleton.named_modules())[layer_prefix])==42
|
| 274 |
+
decoder={f'{layer_prefix}.{i}' for i in range(42)}
|
| 275 |
+
dm={}
|
| 276 |
+
def includes_decoder(name):
|
| 277 |
+
p=name+'.' if name else ''
|
| 278 |
+
return any(d==name or d.startswith(p) for d in decoder)
|
| 279 |
+
def assign(module,name=''):
|
| 280 |
+
if name in decoder:
|
| 281 |
+
dm[name]='cuda:1';return
|
| 282 |
+
if name and not includes_decoder(name):
|
| 283 |
+
dm[name]='cuda:0';return
|
| 284 |
+
assert not list(module.named_parameters(recurse=False))
|
| 285 |
+
assert not list(module.named_buffers(recurse=False))
|
| 286 |
+
for c,child in module.named_children():
|
| 287 |
+
assign(child,f'{name}.{c}' if name else c)
|
| 288 |
+
assign(skeleton)
|
| 289 |
+
assert len(dm)==53 and '' not in dm
|
| 290 |
+
for n,_ in list(skeleton.named_parameters())+list(skeleton.named_buffers()):
|
| 291 |
+
assert sum(n==k or n.startswith(k+'.') for k in dm)==1,n
|
| 292 |
+
del skeleton;gc.collect()
|
| 293 |
+
gemma_model=AutoModelForMultimodalLM.from_pretrained(
|
| 294 |
+
str(MODEL_DIR),local_files_only=True,dtype=torch.float16,
|
| 295 |
+
attn_implementation='sdpa',device_map=dm,low_cpu_mem_usage=True)
|
| 296 |
+
gemma_model.eval()
|
| 297 |
+
else:
|
| 298 |
+
assert 'processor' in globals(),'Found model but not processor'
|
| 299 |
+
assert type(gemma_model).__name__=='Gemma4ForConditionalGeneration'
|
| 300 |
+
assert sum(p.numel() for p in gemma_model.parameters())==7941100832
|
| 301 |
+
assert not gemma_model.training
|
| 302 |
+
print('E4B loaded, GPU GiB:',[round(torch.cuda.memory_allocated(i)/2**30,3) for i in range(2)],flush=True)
|
| 303 |
+
|
| 304 |
+
tokenizer=processor.tokenizer
|
| 305 |
+
tokenizer.padding_side='left'
|
| 306 |
+
pad_id=tokenizer.pad_token_id
|
| 307 |
+
turn_id=tokenizer.convert_tokens_to_ids('<turn|>')
|
| 308 |
+
assert pad_id is not None and tokenizer.decode([turn_id],skip_special_tokens=False)=='<turn|>'
|
| 309 |
+
eos=gemma_model.generation_config.eos_token_id
|
| 310 |
+
stop_ids=({eos} if isinstance(eos,int) else set(eos or []))|{turn_id}
|
| 311 |
+
|
| 312 |
+
def score_single(q):
|
| 313 |
+
opts='\n'.join(f'{letter}. {choice}' for letter,choice in zip('ABCD',q['choices']))
|
| 314 |
+
text=V2_PROMPT+'\n\n'+q['question']+'\n\n'+opts
|
| 315 |
+
msg=[{'role':'user','content':[{'type':'text','text':text}]}]
|
| 316 |
+
enc=processor.apply_chat_template(msg,tokenize=True,add_generation_prompt=True,
|
| 317 |
+
enable_thinking=True,return_dict=True,return_tensors='pt').to('cuda:0')
|
| 318 |
+
width=enc['input_ids'].shape[1]
|
| 319 |
+
for gpu in range(2):torch.cuda.synchronize(gpu)
|
| 320 |
+
t=time.perf_counter()
|
| 321 |
+
with torch.inference_mode():
|
| 322 |
+
sequence=gemma_model.generate(**enc,max_new_tokens=TOKEN_BUDGET,
|
| 323 |
+
do_sample=False,use_cache=True,pad_token_id=pad_id)
|
| 324 |
+
for gpu in range(2):torch.cuda.synchronize(gpu)
|
| 325 |
+
elapsed=time.perf_counter()-t
|
| 326 |
+
ids=sequence[0,width:].tolist()
|
| 327 |
+
actual=[];ended=False
|
| 328 |
+
for tok in ids:
|
| 329 |
+
if tok==pad_id:break
|
| 330 |
+
actual.append(tok)
|
| 331 |
+
if tok in stop_ids:
|
| 332 |
+
ended=True;break
|
| 333 |
+
raw=tokenizer.decode(actual,skip_special_tokens=False)
|
| 334 |
+
parts=re.split(r'<\|channel>final|<channel\|>',raw)
|
| 335 |
+
final=re.sub(r'<[^>\n]+>','',parts[-1]).strip()
|
| 336 |
+
lines=[x.strip() for x in final.splitlines() if x.strip()]
|
| 337 |
+
last=lines[-1] if lines else ''
|
| 338 |
+
match=re.fullmatch(r'\*{0,2}\s*ANSWER\s*:\s*([ABCD])\s*[.!]?\s*\*{0,2}',last,flags=re.I)
|
| 339 |
+
pred=match.group(1).upper() if match else None
|
| 340 |
+
hit_limit=not ended and len(actual)>=TOKEN_BUDGET
|
| 341 |
+
valid=pred in LETTER_TO_NUMBER and ended and len(actual)>0
|
| 342 |
+
status=('completed' if valid else 'token_limit' if hit_limit else
|
| 343 |
+
'padding_only' if not actual else 'unparseable_or_unterminated')
|
| 344 |
+
return {'dataset_index':q['dataset_index'],'source_file':q['source_file'],
|
| 345 |
+
'source_position':q['source_position'],'input_fingerprint':fingerprint(q),
|
| 346 |
+
'prompt_sha256':PROMPT_SHA,'max_new_tokens':TOKEN_BUDGET,
|
| 347 |
+
'original_status':fail_by_idx[q['dataset_index']]['status'],
|
| 348 |
+
'native_thinking':True,'generated_tokens':len(actual),'seconds':round(elapsed,3),
|
| 349 |
+
'prediction':pred,'valid':bool(valid),'status':status,
|
| 350 |
+
'turn_end':turn_id in actual,'limit_hit':bool(hit_limit),
|
| 351 |
+
'last_line':last,'raw_output':raw,
|
| 352 |
+
'submission_record':{'q_no':q['q_no'],'subject':q['subject'],
|
| 353 |
+
'category':q['category'],'level':q['level'],
|
| 354 |
+
'answer':LETTER_TO_NUMBER[pred] if valid else None}}
|
| 355 |
+
|
| 356 |
+
print('\n▶ RETRY32-D — TARGETED SINGLE-QUESTION INFERENCE (4 HOURS)',flush=True)
|
| 357 |
+
start=time.perf_counter()
|
| 358 |
+
for idx in indices:
|
| 359 |
+
if retry_path(idx).exists():continue
|
| 360 |
+
if time.perf_counter()-start>=MAX_WALL_SECONDS:
|
| 361 |
+
print('Configured 4-hour inference limit reached',flush=True);break
|
| 362 |
+
try:
|
| 363 |
+
result=score_single(questions[idx])
|
| 364 |
+
validate_retry(result)
|
| 365 |
+
atomic_json(retry_path(idx),result)
|
| 366 |
+
except Exception:
|
| 367 |
+
checkpoint()
|
| 368 |
+
raise
|
| 369 |
+
state=checkpoint() # archive after every retry, not every 5
|
| 370 |
+
print(f'Index {idx} | status={result["status"]} | answer={result["submission_record"]["answer"]} '
|
| 371 |
+
f'| tokens={result["generated_tokens"]} | seconds={result["seconds"]:.1f} '
|
| 372 |
+
f'| retry valid={state["valid"]}/32',flush=True)
|
| 373 |
+
|
| 374 |
+
state=checkpoint()
|
| 375 |
+
print('\n=== E4B TARGETED RECOVERY STATUS ===')
|
| 376 |
+
print('Previously valid: 2206')
|
| 377 |
+
print('Retried:',state['attempted'],'/32')
|
| 378 |
+
print('New valid:',state['valid'])
|
| 379 |
+
print('Still failed:',state['still_invalid'])
|
| 380 |
+
print('Not yet retried:',state['not_yet_retried'])
|
| 381 |
+
print('Recovery ZIP:',ARCHIVE,flush=True)
|
| 382 |
+
|
| 383 |
+
# Export only if every one of the 32 recoveries is valid.
|
| 384 |
+
if state['attempted']==32 and state['valid']==32:
|
| 385 |
+
recovered=load_retries()
|
| 386 |
+
assert set(recovered)==set(indices)
|
| 387 |
+
combined=[]
|
| 388 |
+
for i in range(2238):
|
| 389 |
+
q=questions[i]
|
| 390 |
+
row=known_valid[i] if i in known_valid else recovered[i]['submission_record']
|
| 391 |
+
sub={field:row[field] for field in FIELDS}
|
| 392 |
+
assert list(sub)==FIELDS and sub['answer'] in ('1','2','3','4')
|
| 393 |
+
assert all(sub[k]==q[k] for k in FIELDS[:4])
|
| 394 |
+
combined.append(sub)
|
| 395 |
+
assert len(combined)==2238
|
| 396 |
+
# File ordering by canonical index is an internal reproducibility detail.
|
| 397 |
+
payload=(''.join(json.dumps(r,ensure_ascii=False,separators=(',',':'))+'\n' for r in combined)).encode('utf-8')
|
| 398 |
+
jpath=RUN/'predictions.jsonl'
|
| 399 |
+
jpath.write_bytes(payload)
|
| 400 |
+
with zipfile.ZipFile(FINAL_ZIP,'w',zipfile.ZIP_DEFLATED) as z:
|
| 401 |
+
z.writestr('predictions.jsonl',payload)
|
| 402 |
+
with zipfile.ZipFile(FINAL_ZIP) as z:
|
| 403 |
+
assert z.testzip() is None and z.namelist()==['predictions.jsonl']
|
| 404 |
+
lines=[json.loads(s) for s in z.read('predictions.jsonl').decode('utf-8').splitlines()]
|
| 405 |
+
assert lines==combined
|
| 406 |
+
atomic_json(RUN/'final_submission_audit.json',{
|
| 407 |
+
'total_rows':2238,'original_valid':2206,'recovered_valid':32,
|
| 408 |
+
'model':MODEL_REPO,'revision':REVISION,'prompt_sha256':PROMPT_SHA,
|
| 409 |
+
'submission_zip':str(FINAL_ZIP),'predictions_sha256':sha_file(jpath),
|
| 410 |
+
'validated_at':now(),'status':'READY_FOR_SUBMISSION'})
|
| 411 |
+
checkpoint()
|
| 412 |
+
print('▶ FINAL 2238/2238 SUBMISSION CREATED AND VERIFIED:',FINAL_ZIP,flush=True)
|
| 413 |
+
else:
|
| 414 |
+
print('Submission ZIP NOT created. Resolve remaining invalid retries separately.',flush=True)
|
| 415 |
+
print('▶ MIDDLE E4B RETRY32 COMPLETE',flush=True)
|
| 416 |
+
|
recovery/README.md
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Historical inference and recovery evidence
|
| 2 |
+
|
| 3 |
+
- `MIDDLE_E4B_RETRY32_COLDSTART.py` and `.ipynb`: original Kaggle RETRY32 recovery implementation, preserved as supplied.
|
| 4 |
+
- `evidence/E4B_COMBINED_2206_WITH_FAILED32.zip`: the original 2,206-valid + 32-failed combined package. It contains records, failed raw outputs, merge audit, 41-file dataset SHA manifest and historical merge source.
|
| 5 |
+
- `evidence/build_e4b_complete_firstpass.py`: the original merge script (preserved verbatim); it depends on three source shard ZIPs not included here.
|
| 6 |
+
- `evidence/OFFLINE_CONSISTENCY_AUDIT.json`: independently computed offline audit of the supplied artifacts.
|
| 7 |
+
|
| 8 |
+
**Verified:** All 2,206 first-pass valid rows are identical to the same-index rows in final `predictions.jsonl`. All 32 failed rows occupy the remaining unique positions and their question metadata matches the final submission. The first-pass merge audit and RETRY32 code specify the same V2 prompt SHA-256. This does **not** prove fresh GPU inference will produce exactly the same 2,238 outputs.
|
| 9 |
+
|
| 10 |
+
## Optional source shard archives (not included)
|
| 11 |
+
|
| 12 |
+
The first-pass historical merge audit gives these names and hashes; add only if available, with filenames preserved:
|
| 13 |
+
|
| 14 |
+
| Source | Historical filename | SHA-256 |
|
| 15 |
+
|---|---|---|
|
| 16 |
+
| RIGHT | `LEFT_E4B_TEST_V2_RECOVERY_LATEST (6).zip` | `7a47cce96320d72ca3af31d2ac396b5621a3c113f3e68db2a9b0f786b31e3fb0` |
|
| 17 |
+
| MIDDLE_TAIL500 | `MIDDLE_E4B_TAIL500_LATEST (2).zip` | `1ab6c129f48bea527cf9f1ea1be1b2e9b1e0bb1d954c1a02f01c89a788b16d6a` |
|
| 18 |
+
| MIDDLE_GAP386 | `MIDDLE_E4B_GAP386_LATEST (2).zip` | `5e3db357b1a732b34c4b1f8ff3900f6c7220d13eac1eeb548fdb9aeea877ceee` |
|
| 19 |
+
|
| 20 |
+
`recovery` files document historical inference; they are **not training artifacts** and do not provide precomputed answers to the organizer's standalone `inference.py`.
|