Download basic-python-v1/canonical-2m/code/refined_python/data.py from davidheineman/tiny-rl-refined-tasks-v4: direct link, hf CLI and curl.
- Browser
- Download file 5.92 kB
-
https://huggingface.co/datasets/davidheineman/tiny-rl-refined-tasks-v4/resolve/main/basic-python-v1/canonical-2m/code/refined_python/data.py
- Command line
-
hf download hf://datasets/davidheineman/tiny-rl-refined-tasks-v4/basic-python-v1/canonical-2m/code/refined_python/data.py
-
curl -L -o data.py https://huggingface.co/datasets/davidheineman/tiny-rl-refined-tasks-v4/resolve/main/basic-python-v1/canonical-2m/code/refined_python/data.py
5.92 kB
| from collections import Counter | |
| from dataclasses import dataclass | |
| import hashlib | |
| import json | |
| from pathlib import Path | |
| import random | |
| from omegaconf import OmegaConf | |
| from rich import print | |
| from tqdm import tqdm | |
| from refined_v4.data import atomic_json, write_rows, signature | |
| from . import REVISION | |
| from .catalog import skills, program | |
| from .envs import ENC, available_hints | |
| ROOT = Path('/nlp/scr/dhei/tiny-rl/experiments/refined-basic-python-v1') | |
| class Config: | |
| root: str = str(ROOT) | |
| tokens: int = 2097152 | |
| seed: int = 4517 | |
| interfaces: str = 'varied' | |
| def build(config: Config): | |
| root = Path(config.root) | |
| if config.interfaces not in ('varied','canonical'): | |
| raise ValueError('Unknown Python interface design') | |
| manifest = root/'dataset.json' | |
| if manifest.exists(): | |
| existing = json.loads(manifest.read_text()) | |
| if existing['sft_tokens'] != config.tokens or existing.get('interfaces','varied') != config.interfaces: | |
| raise ValueError('Frozen dataset already has a different token budget') | |
| return existing | |
| folds = {name: [] for name in ('sft','rl','dev','test')} | |
| for skill in skills(): | |
| count=4 if config.interfaces=='canonical' else 16 | |
| order = list(range(count)) | |
| random.Random(config.seed+int(hashlib.sha256(skill.names[0].encode()).hexdigest()[:8],16)).shuffle(order) | |
| assignment = ({index:split for index,split in zip(order,('sft','rl','dev','test'),strict=True)} | |
| if config.interfaces=='canonical' else | |
| {index: ('sft' if rank<8 else 'rl' if rank<12 else 'dev' if rank<14 else 'test') | |
| for rank,index in enumerate(order)}) | |
| for index in range(count): | |
| name_index=index if config.interfaces=='canonical' else index//4 | |
| name, header, reference = program(skill,name_index,index%4,config.interfaces=='canonical') | |
| tests = [f'assert {name}({", ".join(repr(arg) for arg in case)}) == {skill.oracle(*case)!r}' | |
| for case in skill.cases] | |
| key = hashlib.sha256((skill.family+'/'+reference).encode()).hexdigest()[:20] | |
| row = dict(task='basic_python', revision=REVISION, source_id=key, group=key, | |
| question=skill.description, reference=reference, protected_prefix=header, | |
| answer=reference[len(header):], tests=tests, setup='', function_name=name, | |
| provenance=dict(family=skill.family,skill=skill.names[0],difficulty=skill.family, | |
| body_tokens=len(ENC.encode_ordinary(reference[len(header):])))) | |
| folds[assignment[index]].append(row) | |
| rng = random.Random(config.seed) | |
| for split,rows in folds.items(): | |
| for row in rows: | |
| if split != 'sft': | |
| candidates = [d for d in folds['sft'] if d['function_name'] != row['function_name'] | |
| and d['provenance']['skill'] != row['provenance']['skill']] | |
| demo1 = rng.choice(candidates) | |
| demo2 = rng.choice([d for d in candidates if d['function_name'] != demo1['function_name'] | |
| and d['provenance']['family'] != demo1['provenance']['family']]) | |
| row['demonstrations'] = [dict(source_id=d['source_id'],group=d['group'],reference=d['reference']) | |
| for d in (demo1,demo2)] | |
| row['hint_levels'] = available_hints(row) | |
| if not row['hint_levels']: | |
| raise ValueError('A function has no valid completion boundaries') | |
| write_rows(root/'data/basic_python'/f'{split}.jsonl.gz',rows) | |
| documents, tokens = [], 0 | |
| with tqdm(total=config.tokens,desc='Clean Python SFT',unit='tok',colour='cyan') as progress: | |
| while tokens < config.tokens: | |
| selected = [] | |
| for family in rng.sample(sorted({s.family for s in skills()}),4): | |
| candidates = [row for row in folds['sft'] if row['provenance']['family']==family | |
| and row['function_name'] not in {d['function_name'] for d in selected}] | |
| selected.append(rng.choice(candidates)) | |
| text = '\n\n'.join(row['reference'] for row in selected) | |
| count = len(ENC.encode_ordinary(text)) | |
| usable = min(count,config.tokens-tokens) | |
| documents.append(dict(text=text,tokens=count,budget_tokens=usable, | |
| groups=[row['group'] for row in selected],examples=len(selected))) | |
| tokens += usable | |
| progress.update(usable) | |
| write_rows(root/'sft/basic_python/train.jsonl.gz',documents) | |
| result = dict(revision=REVISION,interfaces=config.interfaces,sft_tokens=tokens,documents=len(documents),skills=len(skills()), | |
| rows={name:len(rows) for name,rows in folds.items()}, | |
| split_policy='Shared elementary skills; disjoint named function/signature contracts. All examples of one contract stay in one fold. Evaluation demonstrations use SFT only.', | |
| sampling='Uniform missing length 1..16, uniform eligible family, uniform eligible contract. Short functions are never padded.', | |
| families=sorted({s.family for s in skills()}),seed=config.seed, | |
| coverage={name:{str(level):dict(Counter(row['provenance']['family'] for row in rows if level in row['hint_levels'])) | |
| for level in range(1,17)} for name,rows in folds.items()}, | |
| assets={str(path.relative_to(root)):signature(path) for path in sorted(root.glob('data/basic_python/*.gz'))}, | |
| sft_sha256=signature(root/'sft/basic_python/train.jsonl.gz')) | |
| atomic_json(manifest,result) | |
| print('[green]Dataset ready[/green]',{k:v for k,v in result.items() if k not in ('assets','coverage')}) | |
| return result | |
| if __name__ == '__main__': | |
| build(OmegaConf.to_object(OmegaConf.merge(OmegaConf.structured(Config),OmegaConf.from_cli()))) | |