import asyncio from collections import Counter from concurrent.futures import ThreadPoolExecutor from copy import deepcopy from dataclasses import dataclass import fcntl import hashlib import json from pathlib import Path import random import textwrap import time import ast import httpx from openai import AsyncOpenAI,DefaultAioHttpClient,RateLimitError from omegaconf import OmegaConf from pydantic import BaseModel from rich import print from tqdm import tqdm from functional_rl import v2 from hinted_rl.teacher_programs import canonical from refined_v4.data import load_rows,write_rows,atomic_json,signature from refined_v4.fast_generate import Limiter from . import ROOT,TASKS from .data import annotate,documents,gold_passes from .envs import Pool,available_hints SPLITS=('sft','rl','calibration','dev','test') @dataclass class Config: action: str='generate' source: str=str(ROOT) teacher: str=str(ROOT/'variants/diverse-completion-v2') root: str=str(ROOT/'variants/clear-reference-v1') model: str='gpt-6-luna' concurrency: int=96 rpm: int=6000 tpm: int=3000000 limit: int=0 tokens: int=2097152 seed: int=6719 workers: int=8 class Body(BaseModel): body: str def jobs_for(config: Config): jobs=[] for family in ('mbpp','humaneval'): for split in SPLITS: for row in load_rows(Path(config.source),family,split): jobs.append(dict(family=family,split=split,identity=row['source_id'],row=row)) if not config.limit or len(jobs)=config.limit:break if config.limit:jobs=jobs[:config.limit] for job in jobs: row=job['row'] payload=dict(revision='clear-implementations-v1',model=config.model, family=job['family'],identity=job['identity'],question=row['question'],reference=row['reference']) job['key']=hashlib.sha256(json.dumps(payload,sort_keys=True).encode()).hexdigest() assert len({j['key'] for j in jobs})==len(jobs) return jobs def cached(root: Path): path=root/'rewrites.jsonl' result={} if path.exists(): for line in path.read_text().splitlines(): try: record=json.loads(line) except json.JSONDecodeError: continue if record.get('body'): result[record['key']]=record return result def prompt(job: dict): row=job['row'] return ('Rewrite the implementation of this existing Python exercise in clear, ordinary, idiomatic Python. ' 'Preserve the exact contract, signature and behavior on every valid input. ' 'Use natural short local names and direct returns when an intermediate variable is unnecessary. ' 'Prefer a simple builtin or comprehension when that is the clearest correct solution. ' 'Keep loops when they make the algorithm clearer. Do not golf code or compress multiple statements onto a line. ' 'Do not add padding, aliases, artificial final statements, redundant return variables, or comments chosen to make the ending predictable. ' 'Return only the implementation body, with relative indentation, without the function signature, docstring, tests or Markdown. ' 'Any newly needed standard-library import must be inside the function. Nested helpers are allowed when needed. ' 'The existing instruction and signature prefix will be preserved verbatim.\n'+ json.dumps(dict(question=row['question'],original_program=row['reference'],tests=row['tests']),ensure_ascii=False)) async def generate(config: Config): root=Path(config.root) root.mkdir(parents=True,exist_ok=True) jobs=jobs_for(config) if config.limit:jobs=jobs[:config.limit] done=cached(root) pending=[j for j in jobs if j['key'] not in done] limiter=Limiter(config.rpm,config.tpm) stats=Counter() lock=(root/'generation.lock').open('a') fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) stream=(root/'rewrites.jsonl').open('a',buffering=1024*1024) semaphore=asyncio.Semaphore(config.concurrency) progress=tqdm(total=len(pending),desc='Clear benchmark and SFT implementations',colour='cyan',mininterval=5) limits=httpx.Limits(max_connections=config.concurrency+8,max_keepalive_connections=config.concurrency) transport=DefaultAioHttpClient(limits=limits,timeout=60.) try: async with AsyncOpenAI(http_client=transport,max_retries=0,timeout=60.) as client: async def one(job): async with semaphore: text=prompt(job) body_tokens=len(v2.ENC.encode_ordinary(job['row']['reference'][len(job['row']['protected_prefix']):])) output=max(256,min(1400,int(body_tokens*1.5)+128)) for attempt in range(3): ticket=await limiter.acquire(len(v2.ENC.encode_ordinary(text))+min(output,body_tokens+64)) try: response=await client.responses.parse(model=config.model,input=text,text_format=Body, reasoning={'effort':'none'},max_output_tokens=output,store=False) usage=response.usage.model_dump() if response.usage else {} await limiter.settle(ticket,usage.get('total_tokens',0)) if response.output_parsed is None: raise ValueError('No structured implementation body') record=dict(key=job['key'],family=job['family'],source_id=job['row']['source_id'], body=response.output_parsed.body,response_id=response.id,model=config.model,usage=usage) stream.write(json.dumps(record,ensure_ascii=False)+'\n') stats['success']+=1 stats['input_tokens']+=usage.get('input_tokens',0) stats['output_tokens']+=usage.get('output_tokens',0) break except Exception as error: await limiter.settle(ticket,0) stats[type(error).__name__]+=1 if isinstance(error,RateLimitError):limiter.backoff(2.+attempt*2.) if attempt<2:await asyncio.sleep(1.+attempt) progress.update() if stats['success']%50==0: stream.flush() atomic_json(root/'generation-progress.json',dict(stats=stats,requested=len(pending),updated=time.time())) await asyncio.gather(*(one(job) for job in pending)) finally: stream.close() progress.close() lock.close() atomic_json(root/'generation-progress.json',dict(stats=stats,requested=len(pending),updated=time.time())) if stats['success']<.9*len(pending): raise RuntimeError('Too many API failures; resume missing cached bodies before building') print('[green]Implementation rewrites cached[/green]',dict(stats),flush=True) def proposed(row: dict,body: str): code=row['protected_prefix']+textwrap.indent(textwrap.dedent(body).strip(),' ') ast.parse(code) if len(v2.ENC.encode_ordinary(v2.header(row)+code))>1000: raise ValueError('Rewritten function exceeds context') return annotate(dict(row,reference=code,answer=code,provenance=dict(row['provenance'], reference_style='clear-implementations-v1',original_reference_sha256=hashlib.sha256(row['reference'].encode()).hexdigest()))) def build(config: Config): if config.limit: raise ValueError('A smoke-generation limit cannot build a completed task dataset') root=Path(config.root) if (root/'dataset.json').exists():return json.loads((root/'dataset.json').read_text()) records=cached(root) jobs=jobs_for(config) if sum(j['key'] in records for j in jobs)<.9*len(jobs): raise ValueError('Generate the complete implementation cache before building') accepted={} stats=Counter() candidates=[] for job in tqdm(jobs,desc='Parse rewritten native functions',colour='cyan',mininterval=5): try: row=proposed(job['row'],records[job['key']]['body']) if job['family']=='teacher':accepted[(job['family'],canonical(job['row']['reference']))]=records[job['key']] else:candidates.append((job,row)) except (KeyError,SyntaxError,ValueError):stats['format_fallback']+=1 with ThreadPoolExecutor(max_workers=config.workers) as pool: passed=list(tqdm(pool.map(gold_passes,[r for j,r in candidates]),total=len(candidates), desc='Check unchanged benchmark tests once',colour='green',mininterval=5)) for (job,row),ok in zip(candidates,passed,strict=True): if ok: accepted[(job['family'],job['identity'])]=records[job['key']] stats['benchmark_rewrites']+=1 else:stats['benchmark_test_fallback']+=1 report=dict(source=str(config.source),teacher=str(config.teacher),sft_tokens=config.tokens,seed=config.seed, revision='clear-implementations-v1',tasks={},rewrites=dict(stats), reference_policy='Original questions, protected signatures/instructions, tests and source split groups are preserved. Rewrite implementation bodies only; unchanged-test failures retain the original reference. No padding or artificial endings.', sft_validation='Teacher SFT implementations receive syntax/context checks only; benchmark full programs execute unchanged tests once.') for task in TASKS: family='mbpp' if task.startswith('mbpp') else 'humaneval' pools={split:load_rows(Path(config.source),task,split) for split in SPLITS} pools['sft']+=[r for r in load_rows(Path(config.teacher),task,'sft') if r['source_id'].startswith('diverse-contract/')] for split,rows in pools.items(): cleaned=[] for row in rows: origin='teacher' if row['source_id'].startswith('diverse-contract/') else family identity=canonical(row['reference']) if origin=='teacher' else row['source_id'] record=accepted.get((origin,identity)) try: value=proposed(row,record['body']) if record is not None else annotate(dict(row)) except (SyntaxError,ValueError):value=annotate(dict(row)) if record is not None: value['provenance'].update(reference_teacher_model=record.get('model',config.model), reference_response_id=record.get('response_id'),reference_rewrite_key=record['key']) value.pop('demonstrations',None) cleaned.append(value) pools[split]=cleaned heldout={canonical(r['reference']) for split in ('calibration','dev','test') for r in pools[split]} pools['rl']=[r for r in pools['rl'] if canonical(r['reference']) not in heldout] blocked=heldout|{canonical(r['reference']) for r in pools['rl']} seen=set(blocked) unique=[] for row in pools['sft']: identity=canonical(row['reference']) if identity not in seen: seen.add(identity) unique.append(row) pools['sft']=unique short=sorted(unique,key=lambda r:len(v2.ENC.encode_ordinary(v2.render(r)))) for split in SPLITS: if split!='sft': for row in pools[split]: groups={row['group']} row['demonstrations']=[] for demo in short: if demo['group'] not in groups: row['demonstrations'].append(demo) groups.add(demo['group']) if len(row['demonstrations'])==2:break row['hint_levels']=available_hints(row) if not row['hint_levels']: raise ValueError('A rewritten benchmark source cannot fit its protected prefix and two demonstrations') Pool(pools[split]) write_rows(root/'data'/task/(split+'.jsonl.gz'),pools[split]) corpus=documents(unique,config.tokens,random.Random(config.seed)) path=root/'sft'/task/'train.jsonl.gz' write_rows(path,corpus) report['tasks'][task]=dict(rows={s:len(r) for s,r in pools.items()},documents=len(corpus), source_groups=len({r['group'] for r in unique}),sft_sha256=signature(path), 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]Clear-reference task control ready[/green]',dict(stats),flush=True) return report def main(config: Config): if config.action in ('generate','all'):asyncio.run(generate(config)) if config.action in ('build','all'):build(config) if __name__=='__main__': main(OmegaConf.to_object(OmegaConf.merge(OmegaConf.structured(Config),OmegaConf.from_cli())))