davidheineman's picture
Add experimental consistent-original-v1 MBPP and HumanEval 2m data
5d32603 verified
Raw History Blame Contribute Delete
9.84 kB
import ast
from collections import defaultdict
from copy import deepcopy
from dataclasses import dataclass
import hashlib
import json
from pathlib import Path
import random
import symtable
import textwrap
from omegaconf import OmegaConf
from rich import print
from tqdm import tqdm
from refined_v4.data import load_rows,write_rows,atomic_json,signature
from functional_rl import v2
from . import ROOT,TASKS
from .data import annotate
@dataclass
class Config:
source: str=str(ROOT/'variants/clear-reference-v1')
root: str=str(ROOT/'variants/clear-focused-v1')
tokens: int=2097152
variants: int=16
seed: int=6719
class Rename(ast.NodeTransformer):
def __init__(self,mapping: dict[str,str]):
self.mapping=mapping
def visit_Name(self,node):
node.id=self.mapping.get(node.id,node.id)
return node
def visit_Nonlocal(self,node):
node.names=[self.mapping.get(name,name) for name in node.names]
return node
def aliases(name: str):
lower=name.lower()
if lower in ('i','j','k','idx','index','pos','position'):
return [name,'index','position','offset','item_index','current_index']
if lower in ('res','result','out','output','answer','ans'):
return [name,'result','output','answer','computed_result','return_value']
if lower=='total':
return [name,'running_total','total_value','aggregate','result']
if 'count' in lower or lower in ('cnt','tally'):
return [name,'count','total','tally','item_count','total_count']
if any(word in lower for word in ('length','size')):
return [name,'length','size','item_count','sequence_length']
if any(word in lower for word in ('largest','maximum','max_')):
return [name,'largest','maximum','max_value','current_max']
if any(word in lower for word in ('smallest','minimum','min_')):
return [name,'smallest','minimum','min_value','current_min']
if lower in ('x','value','val','item','element','elt'):
return [name,'value','item','element','entry','current_value']
base=name.removeprefix('current_')
return [name,base+'_value','current_'+base,base+'_result']
def augment(row: dict,limit: int,rng: random.Random):
tree=ast.parse(row['reference'])
function=next(n for n in tree.body if isinstance(n,ast.FunctionDef))
occupied={n.id for n in ast.walk(tree) if isinstance(n,ast.Name)}
excluded={n.arg for n in ast.walk(tree) if isinstance(n,ast.arg)}
excluded|={n.name for n in ast.walk(tree) if isinstance(n,(ast.FunctionDef,ast.ClassDef))}
excluded|={n.name for n in ast.walk(tree) if isinstance(n,ast.ExceptHandler) and n.name}
scopes=[symtable.symtable(row['reference'],'<augmentation>','exec')]
while scopes:
scope=scopes.pop()
occupied.update(symbol.get_name() for symbol in scope.get_symbols())
excluded|={s.get_name() for s in scope.get_symbols() if s.is_imported() or (scope.get_type()!='module' and s.is_global())}
scopes.extend(scope.get_children())
names=sorted({n.id for n in ast.walk(function) if isinstance(n,ast.Name) and isinstance(n.ctx,ast.Store)}-excluded)
result=[dict(row)]
if not names or any(isinstance(n,ast.Call) and isinstance(n.func,ast.Name) and n.func.id in ('locals','globals','eval','exec','vars') for n in ast.walk(function)):
return result
seen={hashlib.sha256(row['reference'].encode()).hexdigest()}
for attempt in range(limit*8):
mapping={}
used=set(occupied)
for name in names:
choices=[value for value in aliases(name) if value==name or value not in used]
chosen=rng.choice(choices)
used.add(chosen)
if chosen!=name:mapping[name]=chosen
if not mapping:continue
variant=Rename(mapping).visit(deepcopy(tree))
restored=Rename({v:k for k,v in mapping.items()}).visit(deepcopy(variant))
if ast.dump(restored)!=ast.dump(tree):raise ValueError('Identifier transformation is not reversible')
changed=next(n for n in variant.body if isinstance(n,ast.FunctionDef))
statements=changed.body[1:] if ast.get_docstring(changed) is not None else changed.body
body='\n'.join(ast.unparse(statement) for statement in statements)
code=row['protected_prefix']+textwrap.indent(body,' ')
digest=hashlib.sha256(code.encode()).hexdigest()
if digest in seen:continue
seen.add(digest)
try:
value=annotate(dict(row,source_id=row['source_id']+'/locals-'+digest[:16],reference=code,answer=code,
provenance=dict(row['provenance'],augmentation='Scope-safe reversible local identifier renaming',
parent_source_id=row['source_id'],aliases=mapping)))
except ValueError:continue
result.append(value)
if len(result)==limit:break
return result
def pack(rows: list[dict],budget: int,rng: random.Random):
groups=defaultdict(list)
for row in rows:groups[row['group']].append(row)
keys=list(groups)
rendered={r['source_id']:v2.render(r) for r in rows}
sizes={k:len(v2.ENC.encode_ordinary(v)) for k,v in rendered.items()}
shortest=[]
short_groups=set()
for row in sorted(rows,key=lambda r:sizes[r['source_id']]):
if row['group'] not in short_groups:
shortest.append(row)
short_groups.add(row['group'])
if len(shortest)==32:break
result=[]
tokens=0
with tqdm(total=budget,desc='Pack source-balanced native SFT',unit='tok',colour='cyan',mininterval=5) as progress:
while tokens<budget:
row=rng.choice(groups[rng.choice(keys)])
selected=[row]
count=sizes[row['source_id']]
candidates=[rng.choice(groups[key]) for key in rng.sample(keys,min(64,len(keys)))]+shortest
for candidate in candidates:
if candidate['group'] in {r['group'] for r in selected}:continue
extra=sizes[candidate['source_id']]+2
if count+extra<=1024:
selected.append(candidate)
count+=extra
if len(selected)==4:break
if len(selected)<2:raise ValueError('Cannot fit two independent focused SFT functions')
text='\n\n'.join(rendered[r['source_id']] for r in selected)
size=len(v2.ENC.encode_ordinary(text))
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)
if (root/'dataset.json').exists():return json.loads((root/'dataset.json').read_text())
report=deepcopy(json.loads((source/'dataset.json').read_text()))
report.update(source=str(source),sft_tokens=config.tokens,source_revision='focused-local-names-v1',
sft_policy='Authentic SFT-fold benchmark functions, reversible natural local-name variants, and the original two SFT demonstration sources. Sample source groups uniformly before choosing a variant. RL/dev/test files stay byte-identical to the clear-reference control.')
for task in TASKS:
original=load_rows(source,task,'sft')
rows=[]
authentic=[r for r in original if r['source_id'].startswith(('mbpp-','HumanEval/'))]
for row in tqdm(authentic,desc=task+' local-name variants',colour='cyan',mininterval=5):
rows.extend(augment(row,config.variants,random.Random(f'{config.seed}/{row["group"]}')))
demos=load_rows(source,task,'rl')[0]['demonstrations']
lookup={r['source_id']:r for r in original}
for demo in demos:
if demo['source_id'] not in {r['source_id'] for r in rows}:rows.append(lookup[demo['source_id']])
sizes={r['source_id']:len(v2.ENC.encode_ordinary(v2.render(r))) for r in rows}
shortest=sorted(rows,key=lambda r:sizes[r['source_id']])
excluded=[]
retained=[]
for row in rows:
other=next(r for r in shortest if r['group']!=row['group'])
if sizes[row['source_id']]+sizes[other['source_id']]+2<=1024:
retained.append(row)
else:excluded.append(dict(source_id=row['source_id'],rendered_tokens=sizes[row['source_id']]))
rows=retained
if len({r['source_id'] for r in rows})!=len(rows):raise ValueError('Duplicate focused implementation IDs')
write_rows(root/'data'/task/'sft.jsonl.gz',rows)
for split in ('rl','calibration','dev','test'):
path=root/'data'/task/(split+'.jsonl.gz')
if not path.exists():path.symlink_to(source/'data'/task/(split+'.jsonl.gz'))
corpus=pack(rows,config.tokens,random.Random(config.seed))
path=root/'sft'/task/'train.jsonl.gz'
write_rows(path,corpus)
report['tasks'][task].update(rows={split:len(load_rows(root,task,split)) for split in ('sft','rl','calibration','dev','test')},
source_groups=len({r['group'] for r in rows}),authentic_sources=len(authentic),documents=len(corpus),sft_sha256=signature(path),
excluded_context_variants=excluded,
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(root/'dataset.json',report)
print('[green]Focused benchmark SFT ready[/green]',flush=True)
return report
if __name__=='__main__':
build(OmegaConf.to_object(OmegaConf.merge(OmegaConf.structured(Config),OmegaConf.from_cli())))