File size: 9,419 Bytes
5d32603 | 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 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 | from collections import Counter,defaultdict
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,benchmark_fraction: float|None=None,balance_groups: bool=False,body_weights: dict[str,float]|None=None) -> 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]
benchmark=[r for r in rows if authentic(r)]
synthetic=[r for r in rows if not authentic(r)]
grouped=defaultdict(list)
for row in rows:grouped[row['group']].append(row)
keys=list(grouped)
origins={kind:[key for key in keys if authentic(grouped[key][0])==kind] for kind in (False,True)}
bands={band:[key for key in keys if grouped[key][0]['provenance']['difficulty']==band]
for band in body_weights} if body_weights is not None else {}
band_origins={band:{kind:[key for key in eligible if authentic(grouped[key][0])==kind]
for kind in (False,True)} for band,eligible in bands.items()}
if body_weights is not None:
if not balance_groups or not body_weights or any(weight<=0 for weight in body_weights.values()):
raise ValueError('Positive body-band weights require source-group sampling')
if any(not keys for keys in bands.values()) or benchmark_fraction is not None and any(
not keys for origins_in_band in band_origins.values() for keys in origins_in_band.values()):
raise ValueError('Every requested body/origin combination requires eligible sources')
if benchmark_fraction is not None and (not 0<benchmark_fraction<1 or not benchmark or not synthetic):
raise ValueError('Benchmark mixture requires both source pools and a fraction strictly between zero and one')
def choose():
if balance_groups:
if body_weights is None:
eligible=keys if benchmark_fraction is None else origins[rng.random()<benchmark_fraction]
else:
band=rng.choices(list(body_weights),weights=list(body_weights.values()))[0]
eligible=bands[band] if benchmark_fraction is None else band_origins[band][rng.random()<benchmark_fraction]
return rng.choice(grouped[rng.choice(eligible)])
pool=rows if benchmark_fraction is None else benchmark if rng.random()<benchmark_fraction else synthetic
return rng.choice(pool)
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=choose()
selected=[first]
count=lengths[first['source_id']]
candidates=(rng.sample(rows,min(64,len(rows))) if benchmark_fraction is None and not balance_groups else [choose() for _ in range(64)])+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())))
|