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'],'','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