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)