File size: 7,293 Bytes
d044abe 234f07a 4106468 d044abe 4106468 d044abe 4106468 d044abe 234f07a d044abe 4106468 d044abe eeb4100 d044abe 234f07a d044abe 4106468 d044abe 4106468 d044abe 4106468 d044abe 234f07a d044abe 234f07a d044abe | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | """One deterministic generation per task, followed by isolated execution."""
import argparse
import hashlib
import json
from pathlib import Path
import sys
from validators.dataset import load
from runners import get_runner,LANGUAGES
from runners.common import extract_code
from runners.sandbox import Sandbox
from metrics import aggregate
ROOT=Path(__file__).resolve().parent
from completion import prompt,assemble,PROMPT_VERSION
from generation_settings import PROTOCOL,DEFAULT_BATCH_SIZE,token_budget
def save(path,value):
path.parent.mkdir(parents=True,exist_ok=True);temp=path.with_suffix('.tmp');temp.write_text(json.dumps(value,indent=2,allow_nan=False)+'\n');temp.replace(path)
def main():
p=argparse.ArgumentParser(description=__doc__);p.add_argument('--model');p.add_argument('--revision',default='main');p.add_argument('--output',type=Path,required=True)
p.add_argument('--language',nargs='+',choices=LANGUAGES);p.add_argument('--difficulty',nargs='+',choices=('easy','medium','moderate'))
p.add_argument('--resume',action='store_true');p.add_argument('--predictions',type=Path,help='JSONL with id and code; bypass model inference')
p.add_argument('--image',default='smolscript-runtime:0.1.0');p.add_argument('--engine',default='docker');p.add_argument('--max-new-tokens',type=int,default=None);p.add_argument('--device',default='auto');p.add_argument('--batch-size',type=int,default=DEFAULT_BATCH_SIZE);a=p.parse_args()
if not a.model and not a.predictions:p.error('--model or --predictions required')
if a.max_new_tokens is not None and a.max_new_tokens<1:p.error('--max-new-tokens must be positive')
if a.batch_size<1:p.error('--batch-size must be positive')
sandbox=Sandbox(a.image,a.engine)
rows=[r for r in load(ROOT/'data/smolscript.jsonl') if (not a.language or r['language'] in a.language) and (not a.difficulty or r['difficulty'] in a.difficulty)]
hidden={r['id']:r for r in load(ROOT/'private_tests/hidden.jsonl')}
files=['data/smolscript.jsonl','private_tests/hidden.jsonl','evaluate.py','metrics.py','generation_settings.py','completion.py']+[str(p.relative_to(ROOT)) for p in sorted((ROOT/'runners').glob('*.py'))]+['sandbox/worker.py','sandbox/supervisor.py']
fingerprint={f:hashlib.sha256((ROOT/f).read_bytes()).hexdigest() for f in files}
settings={'model':a.model,'requested_revision':a.revision,'language':a.language,'difficulty':a.difficulty,
'max_new_tokens':a.max_new_tokens,'batch_size':a.batch_size,'decode_protocol':PROTOCOL,'prompt_version':PROMPT_VERSION,'dataset':fingerprint,'sandbox':sandbox.identity,
'predictions_sha':hashlib.sha256(a.predictions.read_bytes()).hexdigest() if a.predictions else None}
if a.output.exists() and not a.resume:p.error('Output exists; use --resume or a new path')
state=json.loads(a.output.read_text()) if a.output.exists() else {'settings':settings,'results':[],'complete':False}
if state['settings']!=settings:p.error('Resume settings mismatch')
if a.resume and not a.output.exists():p.error('Resume output missing')
# Lock the output across processes to prevent concurrent checkpoint overwrites.
import fcntl
lock=a.output.with_suffix(a.output.suffix+'.lock');lock.parent.mkdir(parents=True,exist_ok=True)
with lock.open('a') as stream:
fcntl.flock(stream,fcntl.LOCK_EX|fcntl.LOCK_NB)
codes={}
if a.predictions:codes={r['id']:r['code'] for r in load(a.predictions)}
else:
import torch
from transformers import AutoTokenizer,AutoModelForCausalLM,AutoConfig
from huggingface_hub import snapshot_download
snapshot=snapshot_download(a.model,revision=state.get('resolved_revision') or a.revision)
revision=Path(snapshot).name
state['resolved_revision']=revision
tokenizer=AutoTokenizer.from_pretrained(snapshot,trust_remote_code=True)
model=AutoModelForCausalLM.from_pretrained(snapshot,trust_remote_code=True,torch_dtype='auto',device_map=a.device)
model.eval();torch.manual_seed(0)
import importlib.metadata
state['environment']={'python':sys.version,'packages':{n:importlib.metadata.version(n) for n in ('torch','transformers','huggingface-hub')},'device':str(model.device)}
done={r['id'] for r in state['results']}
if len(done)!=len(state['results']) or done-set(r['id'] for r in rows):raise ValueError('Corrupt resume IDs')
save(a.output,state)
if not a.predictions:
from runners.hf_runtime import Progress,generate_batches
generated=state.setdefault('generations',{})
if state.get('pending'):generated[state['pending']['id']]=state['pending']['generation']
pending=[r for r in rows if r['id'] not in done and r['id'] not in generated]
if tokenizer.pad_token_id is None:tokenizer.pad_token=tokenizer.eos_token
tokenizer.padding_side='left'
encoded=tokenizer([prompt(r) for r in pending],return_token_type_ids=False) if pending else {'input_ids':[],'attention_mask':[]}
compiled={r['id']:{'input_ids':encoded['input_ids'][i],'attention_mask':encoded['attention_mask'][i]} for i,r in enumerate(pending)}
budgets={r['id']:a.max_new_tokens or token_budget(r) for r in pending}
native=getattr(model.config,'max_position_embeddings',getattr(model.config,'n_positions',4096))
for r in pending:
if len(compiled[r['id']]['input_ids'])+budgets[r['id']]>native:
raise ValueError('Insufficient context for generation: '+r['id'])
def emit(batch):
generated.update({rid:text for rid,text,_ in batch});save(a.output,state)
with Progress('SmolScript',len(pending)) as progress:
state['generation_stats']=generate_batches(model,tokenizer,compiled,pending,
lambda r:budgets[r['id']],a.batch_size,emit,progress,stream_tokens=False)
for row in rows:
if row['id'] in done:continue
if a.predictions:
if row['id'] not in codes:raise ValueError('Missing prediction '+row['id'])
text=codes[row['id']]
else:text=state['generations'][row['id']]
state['pending']={'id':row['id'],'generation':text};save(a.output,state)
code=None
try:code=extract_code(text) if a.predictions else assemble(row,text)
except ValueError as e:result={'passed':False,'syntax_success':False,'tests':[],'error':str(e)}
else:result=get_runner(row['language']).evaluate(row,code,hidden[row['id']],sandbox)
state['results'].append({'id':row['id'],'language':row['language'],'difficulty':row['difficulty'],'generation':text,'evaluated_code':code,**result})
state.pop('pending',None)
save(a.output,state);print(f"{len(state['results'])}/{len(rows)} {row['id']} {'PASS' if result['passed'] else 'FAIL'}",flush=True)
state['metrics']=aggregate(state['results'],[r['id'] for r in rows],full_run=not(a.language or a.difficulty));state['complete']=True;save(a.output,state)
print(json.dumps(state['metrics'],indent=2))
if __name__=='__main__':main()
|