File size: 11,631 Bytes
dfdaf38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
import ast
import asyncio
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
import hashlib
import heapq
import json
from pathlib import Path
import shutil

from openai import AsyncOpenAI,DefaultAioHttpClient
from omegaconf import OmegaConf
from pydantic import BaseModel
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 load_rows,write_rows,atomic_json,signature
from refined_v4.fast_generate import CodeExample,code_row,Limiter
from . import ROOT,TASKS
from .data import annotate
from .envs import available_hints,Pool


@dataclass
class Config:
    root: str=str(ROOT/'variants/clear-practice-rl-v1')
    source: str=str(ROOT/'variants/clear-reference-v1')
    candidates: int=1536
    target: int=1024
    concurrency: int=64
    workers: int=16
    seed: int=7169


class TestSet(BaseModel):
    identity: str
    tests: list[str]


class Batch(BaseModel):
    items: list[TestSet]


def candidates(config: Config):
    root,source=Path(config.root),Path(config.source)
    path=root/'candidates.jsonl'
    if path.exists():return [json.loads(line) for line in path.read_text().splitlines()]
    root.mkdir(parents=True,exist_ok=True)
    blocked_groups,blocked_code,blocked_questions=set(),set(),set()
    for task in TASKS:
        for split in ('sft','rl','calibration','dev','test'):
            for row in load_rows(source,task,split):
                blocked_groups.add(row['group'])
                blocked_questions.add(row['question'])
                blocked_code.add(canonical(row['reference']))
    cache=Path('/nlp/scr/dhei/tiny-rl/experiments/refined-tasks-v4/fast-api/mbpp/rows.jsonl')
    heap=[]
    fingerprints=set()
    seen=set()
    for line in tqdm(cache.open(),desc='Select fresh RL contracts',colour='cyan',mininterval=10):
        row=json.loads(line)
        group=row['group']
        if not row['source_id'].startswith('fast-api/') or group in blocked_groups or group in seen or row['question'] in blocked_questions:
            continue
        seen.add(group)
        rank=int(hashlib.sha256((str(config.seed)+group).encode()).hexdigest()[:15],16)
        if len(heap)==config.candidates and rank>=-heap[0][0]:continue
        try:
            tree=ast.parse(row['reference'])
            functions=[n for n in tree.body if isinstance(n,ast.FunctionDef)]
            fingerprint=canonical(row['reference'])
            if len(functions)!=1 or ast.get_docstring(functions[0]) is not None or fingerprint in blocked_code or fingerprint in fingerprints:continue
            if not row['reference'].isascii() or len(v2.ENC.encode_ordinary(row['question']+row['reference']))>550:continue
            key=hashlib.sha256((group+row['reference']).encode()).hexdigest()
            value=(-rank,key,dict(row,identity=key),fingerprint)
            if len(heap)<config.candidates:heapq.heappush(heap,value)
            else:
                removed=heapq.heapreplace(heap,value)
                fingerprints.remove(removed[3])
            fingerprints.add(fingerprint)
        except (SyntaxError,ValueError):continue
    rows=[]
    used=set()
    for rank,key,row,fingerprint in sorted(heap,reverse=True):
        fingerprint=canonical(row['reference'])
        if fingerprint in used:continue
        used.add(fingerprint)
        rows.append(row)
    path.write_text(''.join(json.dumps(row)+'\n' for row in rows))
    return rows


async def generate(config: Config,rows: list[dict]):
    root=Path(config.root)
    path=root/'tests.jsonl'
    saved=[json.loads(line) for line in path.read_text().splitlines()] if path.exists() else []
    done={r['identity']:r for r in saved}
    pending=[r for r in rows if r['identity'] not in done]
    limiter=Limiter(6000,3000000)
    semaphore=asyncio.Semaphore(config.concurrency)
    stream=path.open('a',buffering=1)
    progress=tqdm(total=len(pending),desc='Generate independent RL tests',colour='cyan',mininterval=5)
    async with AsyncOpenAI(http_client=DefaultAioHttpClient(),max_retries=0,timeout=90.) as client:
        async def one(batch):
            text=('For each Python exercise, write five distinct direct assert tests for its stated contract. '
                'Use the exact function name, deterministic literal arguments and literal expected values. '
                'Cover ordinary cases and valid empty, boundary or tie cases. Do not reuse the given example. '
                'Do not use imports, helper functions, comprehensions, random inputs, oracle calls or reference implementations inside tests. '
                'Each assert must call the target function exactly once. Return each identity unchanged.\n'+
                json.dumps([dict(identity=str(index),question=r['question'],reference=r['reference'],example=r['tests'][0])
                            for index,r in enumerate(batch)]))
            async with semaphore:
                for attempt in range(3):
                    ticket=await limiter.acquire(len(v2.ENC.encode_ordinary(text))+1400)
                    try:
                        response=await client.responses.parse(model='gpt-6-luna',input=text,text_format=Batch,
                            reasoning={'effort':'none'},max_output_tokens=2200,store=False)
                        usage=response.usage.model_dump()
                        await limiter.settle(ticket,usage['total_tokens'])
                        if response.output_parsed is None:raise ValueError('Missing structured test cases')
                        lookup={str(index):r for index,r in enumerate(batch)}
                        accepted=[]
                        for value in response.output_parsed.items:
                            if value.identity not in lookup:raise ValueError('Unknown test identity')
                            tests=list(dict.fromkeys(value.tests))
                            if len(tests)<4:raise ValueError('At least four distinct tests required')
                            function=next(n for n in ast.parse(lookup[value.identity]['reference']).body if isinstance(n,ast.FunctionDef))
                            for test in tests:
                                parsed=ast.parse(test)
                                if len(parsed.body)!=1 or not isinstance(parsed.body[0],ast.Assert):raise ValueError('Expected a direct assert')
                                calls=[n for n in ast.walk(parsed) if isinstance(n,ast.Call) and isinstance(n.func,ast.Name) and n.func.id==function.name]
                                if len(calls)!=1:raise ValueError('Each assert must call its target once')
                            accepted.append(dict(identity=lookup[value.identity]['identity'],tests=tests,response_id=response.id))
                        if {r['identity'] for r in accepted}!={r['identity'] for r in batch}:raise ValueError('Missing test identities')
                        for record in accepted:
                            record['usage_batch']=usage
                            stream.write(json.dumps(record)+'\n')
                            done[record['identity']]=record
                        break
                    except Exception as error:
                        await limiter.settle(ticket,0)
                        if attempt==2:print('[yellow]Test generation failed[/yellow]',type(error).__name__,flush=True)
                        else:await asyncio.sleep(attempt+1)
                progress.update(len(batch))
        try:await asyncio.gather(*(one(pending[i:i+4]) for i in range(0,len(pending),4)))
        finally:stream.close();progress.close()
    return done


def checked(row: dict,testset: dict):
    tests=list(dict.fromkeys(row['tests']+testset['tests']))
    return execute(row['reference'],tuple(tests),row.get('setup',''))


def build(config: Config,rows: list[dict],tests: dict):
    root,source=Path(config.root),Path(config.source)
    if (root/'dataset.json').exists():raise ValueError('RL environment is already frozen')
    pending=[r for r in rows if r['identity'] in tests]
    with ThreadPoolExecutor(max_workers=config.workers) as pool:
        valid=list(tqdm(pool.map(checked,pending,[tests[r['identity']] for r in pending]),total=len(pending),
                        desc='Verify RL reference and independent tests once',colour='green',mininterval=5))
    selected=[r for r,ok in zip(pending,valid,strict=True) if ok][:config.target]
    if len(selected)<config.target:raise ValueError(f'Only {len(selected)} reward contracts verified; need {config.target}')
    report=json.loads((source/'dataset.json').read_text())
    report.update(revision='clear-practice-rl-v1',source=str(source),practice_sources=len(selected),
        practice_candidate_sources=len(rows),practice_tested=len(pending),practice_passed=sum(valid),
        rl_policy='Uniform missing length, then uniform benchmark/practice origin, then eligible contract. Fresh practice groups/questions/canonical code excluded from all existing SFT/RL/dev/test pools. SFT and held-out bytes unchanged.')
    for task in TASKS:
        shutil.copytree(source/'data'/task,root/'data'/task,dirs_exist_ok=True)
        base=load_rows(source,task,'rl')
        practice=[]
        for row in selected:
            tree=ast.parse(row['reference'])
            function=next(n for n in tree.body if isinstance(n,ast.FunctionDef))
            lines=row['reference'].splitlines(keepends=True)
            start=function.body[0].lineno-1
            item=CodeExample(index=0,instruction=row['question'],signature=''.join(lines[:start]).strip(),
                body=''.join(lines[start:]),example=row['tests'][0])
            converted=code_row(task,item,row['provenance']['response_id'])
            if converted is None:raise ValueError('Fresh RL contract failed native formatting')
            converted.update(source_id='rl-contract/'+row['identity'],group=row['group'],
                tests=list(dict.fromkeys(row['tests']+tests[row['identity']]['tests'])),
                demonstrations=base[0]['demonstrations'],sampling_origin='practice')
            converted['provenance'].update(tests_origin='Original example plus independent gpt-6-luna edge-case assertions; all passed unchanged reference.',
                tests_response_id=tests[row['identity']]['response_id'],source='Fresh synthetic RL contract',source_family='synthetic_practice')
            converted=annotate(converted)
            converted['hint_levels']=available_hints(converted)
            if converted['hint_levels']:practice.append(converted)
        combined=[dict(r,sampling_origin='benchmark') for r in base]+practice
        Pool(combined)
        target=root/'data'/task/'rl.jsonl.gz'
        write_rows(target,combined)
        report['tasks'][task]['rows']['rl']=len(combined)
        report['tasks'][task]['assets'][str(target.relative_to(root))]=signature(target)
        for split in ('sft','calibration','dev','test'):
            assert signature(root/'data'/task/(split+'.jsonl.gz'))==signature(source/'data'/task/(split+'.jsonl.gz'))
    (root/'sft').symlink_to(source/'sft',target_is_directory=True)
    atomic_json(root/'dataset.json',report)
    print('[green]Fresh, verified practice environments built with unchanged SFT and held-out data[/green]',flush=True)


def main(config: Config):
    rows=candidates(config)
    tests=asyncio.run(generate(config,rows))
    build(config,rows,tests)


if __name__=='__main__':
    main(OmegaConf.to_object(OmegaConf.merge(OmegaConf.structured(Config),OmegaConf.from_cli())))