File size: 9,844 Bytes
5d32603
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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'],'<augmentation>','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<budget:
            row=rng.choice(groups[rng.choice(keys)])
            selected=[row]
            count=sizes[row['source_id']]
            candidates=[rng.choice(groups[key]) for key in rng.sample(keys,min(64,len(keys)))]+shortest
            for candidate in candidates:
                if candidate['group'] in {r['group'] for r in selected}:continue
                extra=sizes[candidate['source_id']]+2
                if count+extra<=1024:
                    selected.append(candidate)
                    count+=extra
                if len(selected)==4:break
            if len(selected)<2:raise ValueError('Cannot fit two independent focused SFT functions')
            text='\n\n'.join(rendered[r['source_id']] for r in selected)
            size=len(v2.ENC.encode_ordinary(text))
            usable=min(size,budget-tokens)
            result.append(dict(text=text,tokens=size,budget_tokens=usable,examples=[dict(
                source_id=r['source_id'],group=r['group'],reference_sha256=r['provenance']['reference_sha256']) for r in selected]))
            tokens+=usable
            progress.update(usable)
    return result


def build(config: Config):
    source,root=Path(config.source),Path(config.root)
    root.mkdir(parents=True,exist_ok=True)
    if (root/'dataset.json').exists():return json.loads((root/'dataset.json').read_text())
    report=deepcopy(json.loads((source/'dataset.json').read_text()))
    report.update(source=str(source),sft_tokens=config.tokens,source_revision='focused-local-names-v1',
        sft_policy='Authentic SFT-fold benchmark functions, reversible natural local-name variants, and the original two SFT demonstration sources. Sample source groups uniformly before choosing a variant. RL/dev/test files stay byte-identical to the clear-reference control.')
    for task in TASKS:
        original=load_rows(source,task,'sft')
        rows=[]
        authentic=[r for r in original if r['source_id'].startswith(('mbpp-','HumanEval/'))]
        for row in tqdm(authentic,desc=task+' local-name variants',colour='cyan',mininterval=5):
            rows.extend(augment(row,config.variants,random.Random(f'{config.seed}/{row["group"]}')))
        demos=load_rows(source,task,'rl')[0]['demonstrations']
        lookup={r['source_id']:r for r in original}
        for demo in demos:
            if demo['source_id'] not in {r['source_id'] for r in rows}:rows.append(lookup[demo['source_id']])
        sizes={r['source_id']:len(v2.ENC.encode_ordinary(v2.render(r))) for r in rows}
        shortest=sorted(rows,key=lambda r:sizes[r['source_id']])
        excluded=[]
        retained=[]
        for row in rows:
            other=next(r for r in shortest if r['group']!=row['group'])
            if sizes[row['source_id']]+sizes[other['source_id']]+2<=1024:
                retained.append(row)
            else:excluded.append(dict(source_id=row['source_id'],rendered_tokens=sizes[row['source_id']]))
        rows=retained
        if len({r['source_id'] for r in rows})!=len(rows):raise ValueError('Duplicate focused implementation IDs')
        write_rows(root/'data'/task/'sft.jsonl.gz',rows)
        for split in ('rl','calibration','dev','test'):
            path=root/'data'/task/(split+'.jsonl.gz')
            if not path.exists():path.symlink_to(source/'data'/task/(split+'.jsonl.gz'))
        corpus=pack(rows,config.tokens,random.Random(config.seed))
        path=root/'sft'/task/'train.jsonl.gz'
        write_rows(path,corpus)
        report['tasks'][task].update(rows={split:len(load_rows(root,task,split)) for split in ('sft','rl','calibration','dev','test')},
            source_groups=len({r['group'] for r in rows}),authentic_sources=len(authentic),documents=len(corpus),sft_sha256=signature(path),
            excluded_context_variants=excluded,
            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]Focused benchmark SFT ready[/green]',flush=True)
    return report


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