davidheineman's picture
Add experimental consistent-names-v1 MBPP and HumanEval 2m data
dfdaf38 verified
Raw History Blame Contribute Delete
5.51 kB
import ast
from collections import Counter
from concurrent.futures import ThreadPoolExecutor,as_completed
from dataclasses import dataclass
import fcntl
import hashlib
import json
from pathlib import Path
import random
import shutil
from omegaconf import OmegaConf
from rich import print
from tqdm import tqdm
from hinted_rl import code
from refined_v4.data import load_rows,write_rows,signature,atomic_json
from . import ROOT,TASKS
from .audit import authentic
from .data import documents
@dataclass
class Config:
source: str=str(ROOT/'variants/clear-reference-v1')
root: str=str(ROOT/'variants/verified-reference-pilot-v1')
workers: int=8
seed: int=6719
def contract_key(row: dict):
tree=ast.parse(row['reference'])
for node in ast.walk(tree):
if isinstance(node,(ast.Module,ast.FunctionDef,ast.AsyncFunctionDef,ast.ClassDef)) and node.body:
first=node.body[0]
if isinstance(first,ast.Expr) and isinstance(first.value,ast.Constant) and isinstance(first.value.value,str):
node.body=node.body[1:]
value=[ast.dump(tree),row['tests'],row.get('setup','')]
return hashlib.sha256(json.dumps(value,sort_keys=True).encode()).hexdigest()
def read_checked(path: Path):
checked={}
if not path.exists():return checked
with path.open('r+b') as stream:
while True:
start=stream.tell();line=stream.readline()
if not line:break
if not line.endswith(b'\n'):
stream.seek(start);stream.truncate();break
value=json.loads(line);checked[value['key']]=value['passed']
return checked
def build(config: Config):
source,root=Path(config.source),Path(config.root)
root.mkdir(parents=True,exist_ok=True)
if (root/'dataset.json').exists():raise ValueError('Consistent-example SFT data already frozen')
pools={task:load_rows(source,task,'sft') for task in TASKS}
unique={contract_key(row):row for rows in pools.values() for row in rows}
cache=ROOT/'quality';cache.mkdir(exist_ok=True)
worker=Path(code.__file__).with_name('code_worker.py')
revision=signature(worker)+'-'+signature(Path(code.__file__))+'-'+code.python_version()
path=cache/(hashlib.sha256(revision.encode()).hexdigest()+'.jsonl')
with (cache/'audit.lock').open('a') as lock:
fcntl.flock(lock,fcntl.LOCK_EX)
checked=read_checked(path)
missing=[key for key in unique if key not in checked]
with path.open('a',buffering=1) as stream,ThreadPoolExecutor(max_workers=config.workers) as executor:
futures={executor.submit(code.execute,unique[key]['reference'],tuple(unique[key]['tests']),unique[key].get('setup','')):key for key in missing}
for future in tqdm(as_completed(futures),total=len(futures),desc='Check each unique SFT example once',colour='green',mininterval=5):
key=futures[future];passed=bool(future.result())
checked[key]=passed
stream.write(json.dumps(dict(key=key,passed=passed))+'\n')
report=json.loads((source/'dataset.json').read_text())
report.update(revision='consistent-example-sft-v1',source=str(source),seed=config.seed,
quality_policy='Discard synthetic programs that contradict their existing example assertions. Check each unique program/test contract once, sharing results across native formats. No rewritten expected values or altered benchmark tests. This checks example consistency, not complete semantic correctness.',
verification_cache=str(path),verification_revision=revision)
for task in TASKS:
rows=pools[task]
rejected=[row for row in rows if not checked[contract_key(row)]]
if any(authentic(row) for row in rejected):
atomic_json(root/(task+'-benchmark-failures.json'),[r['source_id'] for r in rejected if authentic(r)])
raise ValueError('Authentic benchmark gold failed; investigate instead of silently dropping it')
retained=[row for row in rows if checked[contract_key(row)]]
shutil.copytree(source/'data'/task,root/'data'/task,dirs_exist_ok=True)
write_rows(root/'data'/task/'sft.jsonl.gz',retained)
corpus=documents(retained,report['sft_tokens'],random.Random(config.seed),balance_groups=True)
target=root/'sft'/task/'train.jsonl.gz';write_rows(target,corpus)
item=report['tasks'][task]
item.update(rows=dict(item['rows'],sft=len(retained)),documents=len(corpus),source_groups=len({r['group'] for r in retained}),
rejected_inconsistent_examples=len(rejected),rejected_source_ids=[r['source_id'] for r in rejected],
document_example_counts=dict(Counter(len(d['examples']) for d in corpus)),sft_sha256=signature(target))
item.setdefault('hint_coverage',{})['sft']={str(n):sum(n in r['hint_levels'] for r in retained) for n in range(1,17)}
item['assets']['data/'+task+'/sft.jsonl.gz']=signature(root/'data'/task/'sft.jsonl.gz')
for split in ('rl','calibration','dev','test'):
assert signature(root/'data'/task/(split+'.jsonl.gz'))==signature(source/'data'/task/(split+'.jsonl.gz'))
atomic_json(root/'build-progress.json',report)
print('[cyan]Example consistency[/cyan]',task,len(retained),'retained;',len(rejected),'rejected',flush=True)
atomic_json(root/'dataset.json',report)
if __name__=='__main__':
build(OmegaConf.to_object(OmegaConf.merge(OmegaConf.structured(Config),OmegaConf.from_cli())))