File size: 6,590 Bytes
d044abe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eeb4100
 
 
d044abe
eeb4100
 
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
"""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
PROMPT_VERSION='smolscript-completion-v1'

def prompt(row):
    # Only these public fields reach the model. No tests, answers or references.
    fixture=row['metadata'].get('fixture','');base=row['metadata'].get('base_css','')
    return ('Write code for the following task. Use the standard library only. Return code only.\n'
        +row['prompt']+'\n'+row['output_format']+'\n'+(row['metadata'].get('input_domain') or '')
        +('\nHTML fixture:\n'+fixture if fixture else '')+('\nExisting CSS:\n'+base if base else '')+'\nCode:\n')

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=384);p.add_argument('--device',default='auto');a=p.parse_args()
    if not a.model and not a.predictions:p.error('--model or --predictions required')
    if a.max_new_tokens<1:p.error('--max-new-tokens 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']+[str(p.relative_to(ROOT)) for p in sorted((ROOT/'runners').glob('*.py'))]+['sandbox/worker.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,'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)
            model=AutoModelForCausalLM.from_pretrained(snapshot,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)
        for row in rows:
            if row['id'] in done:continue
            if state.get('pending',{}).get('id')==row['id']:
                text=state['pending']['generation']
            elif a.predictions:
                if row['id'] not in codes:raise ValueError('Missing prediction '+row['id'])
                text=codes[row['id']]
            else:
                encoded=tokenizer(prompt(row),return_tensors='pt',return_token_type_ids=False).to(model.device)
                native=getattr(model.config,'max_position_embeddings',getattr(model.config,'n_positions',4096))
                if encoded['input_ids'].shape[1]+a.max_new_tokens>native:
                    raise ValueError('Insufficient context for fixed generation settings: '+row['id'])
                with torch.inference_mode():out=model.generate(**encoded,max_new_tokens=a.max_new_tokens,do_sample=False,num_beams=1,pad_token_id=tokenizer.pad_token_id if tokenizer.pad_token_id is not None else tokenizer.eos_token_id)
                text=tokenizer.decode(out[0,encoded['input_ids'].shape[1]:],skip_special_tokens=True)
            state['pending']={'id':row['id'],'generation':text};save(a.output,state)
            try:code=extract_code(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,**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()