davidheineman's picture
Add experimental clear-reference MBPP and HumanEval 2M data
c357db8 verified
Raw History Blame Contribute Delete
7.19 kB
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
import gzip
import hashlib
import json
from pathlib import Path
import random
from omegaconf import OmegaConf
from rich import print
from tqdm import tqdm
from functional_rl import v2
from hinted_rl.code import execute
from hinted_rl.teacher_programs import canonical
from refined_v4.data import atomic_json,load_rows,write_rows,signature
from . import ROOT,SOURCE,TASKS
from .audit import authentic
from .envs import REVISION,ENC,Pool,available_hints,protected_prefix
@dataclass
class Config:
source: str=str(SOURCE)
root: str=str(ROOT)
tokens: int=2097152
seed: int=6719
workers: int=8
def gold_passes(row: dict) -> bool:
return execute(row['reference'],tuple(row['tests']),row.get('setup',''))
def annotate(row: dict) -> dict:
value=dict(row)
value['revision']=REVISION
value['protected_prefix']=protected_prefix(value)
body=value['reference'][len(value['protected_prefix']):]
count=len(ENC.encode_ordinary(body))
band='body_1_32' if count<=32 else 'body_33_96' if count<=96 else 'body_97_plus'
value['provenance']=dict(row.get('provenance',{}),difficulty=band,body_tokens=count,
reference_sha256=hashlib.sha256(row['reference'].encode()).hexdigest(),
source_family='mbpp' if value['task'].startswith('mbpp') else 'humaneval')
value['hint_levels']=available_hints(value)
if not value['hint_levels']:
raise ValueError('Benchmark source has no protected implementation completion')
return value
def documents(rows: list[dict],budget: int,rng: random.Random) -> list[dict]:
result=[]
tokens=0
rendered={r['source_id']:v2.render(r) for r in rows}
if len(rendered)!=len(rows):
raise ValueError('SFT source IDs must identify individual implementations uniquely')
lengths={key:len(ENC.encode_ordinary(text)) for key,text in rendered.items()}
shortest=sorted(rows,key=lambda r:lengths[r['source_id']])[:16]
if any(n>1024 for n in lengths.values()):
raise ValueError('A source function exceeds the context on its own')
with tqdm(total=budget,desc='Pack benchmark-native few-shot SFT',unit='tok',colour='cyan',mininterval=5) as progress:
while tokens<budget:
first=rng.choice(rows)
selected=[first]
count=lengths[first['source_id']]
candidates=rng.sample(rows,min(64,len(rows)))+shortest
for other in candidates:
if other['group'] in {r['group'] for r in selected}:
continue
extra=lengths[other['source_id']]+2
if count+extra<=1000:
selected.append(other)
count+=extra
if len(selected)==4:
break
if len(selected)<2:
raise ValueError('Cannot fit two independent native examples in one document')
text='\n\n'.join(rendered[r['source_id']] for r in selected)
size=len(ENC.encode_ordinary(text))
if size>1024:
raise ValueError('Packed document exceeds the model context')
usable=min(size,budget-tokens)
result.append(dict(text=text,tokens=size,budget_tokens=usable,examples=[dict(
source_id=r['source_id'],group=r['group'],reference_sha256=r['provenance']['reference_sha256']) for r in selected]))
tokens+=usable
progress.update(usable)
return result
def build(config: Config):
source,root=Path(config.source),Path(config.root)
root.mkdir(parents=True,exist_ok=True)
receipt=root/'dataset.json'
if receipt.exists():
saved=json.loads(receipt.read_text())
if saved['sft_tokens']!=config.tokens:
raise ValueError('A frozen dataset has a different SFT budget')
return saved
original={task:{split:load_rows(source,task,split) for split in ('sft','rl','calibration','dev','test')} for task in TASKS}
blocked={canonical(row['reference']) for pools in original.values() for split,rows in pools.items()
if split!='sft' for row in rows if authentic(row)}
paired={family:set(r['source_id'] for r in original[family]['sft'] if authentic(r))&
set(r['source_id'] for r in original[family+'_docstring']['sft'] if authentic(r))
for family in ('mbpp','humaneval')}
report=dict(revision=REVISION,source=str(source),sft_tokens=config.tokens,seed=config.seed,tasks={})
for task in TASKS:
family='mbpp' if task.startswith('mbpp') else 'humaneval'
pools={split:[r for r in rows if authentic(r)] for split,rows in original[task].items()}
pools['sft']=[r for r in pools['sft'] if r['source_id'] in paired[family] and canonical(r['reference']) not in blocked]
selected=[(split,row) for split,rows in pools.items() for row in rows]
with ThreadPoolExecutor(max_workers=config.workers) as pool:
valid=list(tqdm(pool.map(gold_passes,[row for split,row in selected]),total=len(selected),
desc=task+' trusted reference checks',colour='green',mininterval=5))
failures=[dict(split=split,source_id=row['source_id']) for (split,row),ok in zip(selected,valid,strict=True) if not ok]
if failures:
atomic_json(root/(task+'-gold-failures.json'),dict(failures=failures))
raise ValueError('Original benchmark references failed; investigate before excluding any source')
for split,rows in pools.items():
pools[split]=[annotate({k:v for k,v in r.items() if k!='demonstrations'} if split=='sft' else r) for r in rows]
if split!='sft':
Pool(pools[split])
write_rows(root/'data'/task/(split+'.jsonl.gz'),pools[split])
corpus=documents(pools['sft'],config.tokens,random.Random(config.seed))
target=root/'sft'/task/'train.jsonl.gz'
write_rows(target,corpus)
report['tasks'][task]=dict(rows={s:len(rows) for s,rows in pools.items()},
original_rows={s:len(rows) for s,rows in original[task].items()},
documents=len(corpus),document_example_counts=dict(Counter(len(d['examples']) for d in corpus)),
sft_sha256=signature(target),source_groups=len({r['group'] for r in pools['sft']}),
heldout_questions_tests_implementations='Original dev/test references, questions and executable tests retained verbatim.',
rl_change='Authentic benchmark sources only; synthetic task-survey additions removed.',
hint_coverage={split:{str(n):sum(n in r['hint_levels'] for r in rows) for n in range(1,17)} for split,rows in pools.items()},
assets={str(p.relative_to(root)):signature(p) for p in sorted((root/'data'/task).glob('*.gz'))})
atomic_json(root/'data-build-progress.json',report)
atomic_json(receipt,report)
print('[green]Four benchmark-native task datasets ready[/green]')
return report
if __name__=='__main__':
build(OmegaConf.to_object(OmegaConf.merge(OmegaConf.structured(Config),OmegaConf.from_cli())))