File size: 14,036 Bytes
248ea7d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
#!/usr/bin/env python3
"""Certified generative pruning (CGP), a bounded symbolic self-improver.

Only the finite candidate-generator automaton is rewritten. Primitive task
semantics, proof checking, objectives, and evaluator are outside that interface.
Python 3.10+; standard library only. No network, subprocess, eval, or exec.
"""
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
import hashlib, json, random, time

Word = tuple[int, ...]
Map = tuple[int, ...]


def family(seed: int, n: int = 8) -> tuple[Map, ...]:
    """Cycle, its inverse, and two adjacent transpositions in a random cycle.

    The alphabet order varies by seed. These generate S_n; no laws are seeded.
    """
    rng = random.Random(seed)
    order = list(range(n)); rng.shuffle(order)
    cycle = list(range(n))
    for i in range(n): cycle[order[i]] = order[(i+1) % n]
    inverse = [0]*n
    for i,j in enumerate(cycle): inverse[j] = i
    swaps = []
    for i in rng.sample(range(n), 2):
        p = list(range(n)); a,b = order[i],order[(i+1)%n]
        p[a],p[b] = p[b],p[a]; swaps.append(tuple(p))
    gs = [tuple(cycle),tuple(inverse),*swaps]; rng.shuffle(gs)
    return tuple(gs)


def ref_eval(word: Word, generators: tuple[Map,...]) -> Map:
    """Independent exact checker: run every boundary input instruction by instruction."""
    n = len(generators[0]); out = []
    for initial in range(n):
        x = initial
        for symbol in word:
            if type(symbol) is not int or not 0 <= symbol < len(generators):
                raise ValueError('invalid instruction')
            x = generators[symbol][x]
        out.append(x)
    return tuple(out)


def shortlex(w: Word) -> tuple:
    return len(w), w


@dataclass(frozen=True)
class Rule:
    lhs: Word
    rhs: Word

    def export(self) -> dict:
        return {'lhs':list(self.lhs),'rhs':list(self.rhs)}


def check_rule(rule: Rule, generators: tuple[Map,...]) -> bool:
    if not rule.lhs or shortlex(rule.rhs) >= shortlex(rule.lhs): return False
    try:
        return ref_eval(rule.lhs,generators) == ref_eval(rule.rhs,generators)
    except (ValueError, IndexError, TypeError):
        return False


class Guard:
    """Aho-Corasick automaton rejecting any certified left-hand-side factor."""
    def __init__(self, forbidden: list[Word], alphabet: int):
        self.alphabet = alphabet
        edges = [{}]; terminal = [False]; self.prefixes = [()]
        for word in forbidden:
            state = 0
            for symbol in word:
                if symbol not in edges[state]:
                    edges[state][symbol] = len(edges)
                    edges.append({}); terminal.append(False)
                    self.prefixes.append(self.prefixes[state]+(symbol,))
                state = edges[state][symbol]
            terminal[state] = True
        self.next = [[0]*alphabet for _ in edges]
        fail = [0]*len(edges)
        q = deque()
        for symbol,state in edges[0].items():
            self.next[0][symbol] = state; q.append(state)
        while q:
            state=q.popleft(); terminal[state] |= terminal[fail[state]]
            for symbol in range(alphabet):
                if symbol in edges[state]:
                    child=edges[state][symbol]
                    fail[child]=self.next[fail[state]][symbol]
                    self.next[state][symbol]=child; q.append(child)
                else:
                    self.next[state][symbol]=self.next[fail[state]][symbol]
        self.bad = terminal

    def scan(self, word: Word) -> int | None:
        state=0
        for symbol in word:
            state=self.next[state][symbol]
            if self.bad[state]: return None
        return state

    def digest(self) -> str:
        raw=json.dumps([self.next,self.bad],separators=(',',':')).encode()
        return hashlib.sha256(raw).hexdigest()


class Improver:
    def __init__(self, generators: tuple[Map,...], rules: list[Rule] | None=None,
                 semantic_dedup: bool=False):
        if not generators or len({len(g) for g in generators}) != 1:
            raise ValueError('incompatible primitive maps')
        n=len(generators[0])
        if any(any(type(x) is not int or not 0 <= x < n for x in g) for g in generators):
            raise ValueError('map outside finite domain')
        self.generators=generators
        self.rules=list(rules or [])
        if not all(check_rule(r,generators) for r in self.rules):
            raise ValueError('unverified initial rule')
        self.guard=Guard([r.lhs for r in self.rules],len(generators))
        ident=tuple(range(n))
        self.frontier=deque([((),ident,0)])
        self.best={ident:()}
        self.seen_for_queue={ident}
        self.pending: dict[Word,Rule]={}
        self.semantic_dedup=semantic_dedup
        self.stats={'popped':0,'semantic_products':0,'guard_probes':0,
                    'guard_rejections':0,'queue_filtered':0,'rules_checked':0,
                    'checker_instruction_steps':0,'rebuild_scan_steps':0,
                    'peak_queue':1,'installations':0,'independent_checks':0}

    def advance(self, expansions: int, product_budget: int | None=None) -> dict:
        before=len(self.best); p0=self.stats['popped']; t=time.perf_counter()
        g=self.guard; gs=self.generators
        product_start=self.stats['semantic_products']
        for _ in range(expansions):
            if not self.frontier: break
            if product_budget is not None and self.stats['semantic_products']-product_start >= product_budget: break
            word,signature,state=self.frontier.popleft(); self.stats['popped']+=1
            for symbol,primitive in enumerate(gs):
                self.stats['guard_probes']+=1
                ns=g.next[state][symbol]
                if g.bad[ns]:
                    self.stats['guard_rejections']+=1; continue
                child=word+(symbol,)
                value=tuple(primitive[x] for x in signature)
                self.stats['semantic_products']+=1
                previous=self.best.get(value)
                if previous is None:
                    self.best[value]=child
                elif shortlex(child) < shortlex(previous):
                    self.best[value]=child
                    self.pending.setdefault(previous,Rule(previous,child))
                elif child != previous:
                    self.pending.setdefault(child,Rule(child,previous))
                if self.semantic_dedup:
                    if value in self.seen_for_queue: continue
                    self.seen_for_queue.add(value)
                self.frontier.append((child,value,ns))
            self.stats['peak_queue']=max(self.stats['peak_queue'],len(self.frontier))
        return {'new_semantics':len(self.best)-before,
                'expansions':self.stats['popped']-p0,
                'wall_seconds':time.perf_counter()-t,
                'known_semantics':len(self.best),'queue':len(self.frontier),
                'semantic_products':self.stats['semantic_products']-product_start}

    def install(self, max_rules: int=600) -> dict:
        """Select sound shortest obstructions; rebuild and replace search-control code.

        Selection is data-driven, deterministic. No hardcoded semantic identities.
        Old forbidden languages are retained; this gives monotone pruning.
        """
        start=time.perf_counter(); old=self.guard.digest(); accepted=[]
        room=max_rules-len(self.rules)
        # Pending laws with a previously forbidden factor cannot add pruning.
        pending=sorted(self.pending.values(),key=lambda r:shortlex(r.lhs))
        self.pending={}
        trial_lhs=[r.lhs for r in self.rules]
        trial=self.guard
        new_lefts=set()
        for rule in pending:
            if len(accepted)>=room: break
            if self.guard.scan(rule.lhs) is None: continue
            if any(rule.lhs[i:j] in new_lefts
                   for i in range(len(rule.lhs))
                   for j in range(i+1,len(rule.lhs)+1)): continue
            self.stats['rules_checked']+=1
            self.stats['checker_instruction_steps']+=len(self.generators[0])*(len(rule.lhs)+len(rule.rhs))
            if not check_rule(rule,self.generators):
                raise AssertionError('untrusted proposal failed verification')
            accepted.append(rule); trial_lhs.append(rule.lhs); new_lefts.add(rule.lhs)
        if accepted:
            self.rules.extend(accepted)
            trial=Guard(trial_lhs,len(self.generators))
            from verifier import verify
            candidate={'generators':self.generators,
                       'rules':[r.export() for r in self.rules],
                       'guard':{'transition':trial.next,'reject':trial.bad,
                                'prefixes':trial.prefixes,'sha256':trial.digest()}}
            receipt=verify(candidate)
            if not receipt['accepted']:
                self.rules=self.rules[:-len(accepted)]
                raise AssertionError('independent checker rejected update: '+str(receipt))
            self.stats['independent_checks']+=1
            self.guard=trial
            filtered=deque()
            for word,value,_ in self.frontier:
                self.stats['rebuild_scan_steps']+=len(word)
                ns=trial.scan(word)
                if ns is not None: filtered.append((word,value,ns))
                else: self.stats['queue_filtered']+=1
            self.frontier=filtered; self.stats['installations']+=1
        return {'accepted':len(accepted),'rules_total':len(self.rules),
                'automaton_states':len(self.guard.next),'before_hash':old,
                'after_hash':self.guard.digest(),
                'wall_seconds':time.perf_counter()-start}

    def export(self) -> dict:
        return {'generators':[list(x) for x in self.generators],
                'rules':[r.export() for r in self.rules],
                'guard':{'transition':self.guard.next,'reject':self.guard.bad,
                         'prefixes':[list(p) for p in self.guard.prefixes],
                         'sha256':self.guard.digest()},
                'stats':self.stats.copy(),'known_semantics':len(self.best)}


def train(seed: int, n: int=8, rounds: int=8, batch: int=300,
          mode: str='recursive', max_rules: int=600, product_batches: bool=False) -> tuple[Improver,list[dict]]:
    if mode not in {'recursive','frozen','oneshot','semantic_bfs','recursive_bfs','oneshot_bfs'}:
        raise ValueError('unknown mode')
    engine=Improver(family(seed,n),semantic_dedup=(mode in {'semantic_bfs','recursive_bfs','oneshot_bfs'}))
    records=[]
    for generation in range(rounds):
        growth=engine.advance(100000,product_budget=batch) if product_batches else engine.advance(batch)
        if mode in {'recursive','recursive_bfs'} or (mode in {'oneshot','oneshot_bfs'} and generation==0):
            upgrade=engine.install(max_rules)
        else:
            # Pending rules may be kept as data in a frozen control; they do not
            # change the generator. Clear to avoid irrelevant memory accumulation.
            engine.pending={}; upgrade={'accepted':0,'wall_seconds':0.0,
                                        'rules_total':len(engine.rules)}
        records.append({'generation':generation+1,'growth':growth,'upgrade':upgrade})
    return engine,records


if __name__=='__main__':
    for mode in ['frozen','oneshot','recursive','semantic_bfs']:
        t=time.perf_counter(); e,h=train(7101,mode=mode)
        print(mode,round(time.perf_counter()-t,4),len(e.best),len(e.rules),
              [r['growth']['known_semantics'] for r in h],
              [r['upgrade']['accepted'] for r in h])


def cold_search(generators: tuple[Map,...], rules: list[Rule], expansions: int,
                dedup: bool=False, product_budget: int | None=None, wall_budget: float | None=None) -> dict:
    """Task deployment: no proof mining or pending-law overhead in either control.

    For dedup=True this is conventional semantic BFS with an optimized inner loop,
    not a deliberately slowed variant of the self-improver.
    Construction of the supplied automaton is included in measured deployment time.
    """
    t=time.perf_counter(); ident=tuple(range(len(generators[0])))
    best={ident:()}; products=0; probes=0; popped=0; peak=1
    if dedup and not rules:
        todo=deque([(ident,())])
        while todo and popped < expansions:
            if product_budget is not None and products>=product_budget: break
            if wall_budget is not None and time.perf_counter()-t>=wall_budget: break
            signature,word=todo.popleft(); popped+=1
            for a,g in enumerate(generators):
                value=tuple(g[x] for x in signature); products+=1
                if value not in best:
                    child=word+(a,);best[value]=child;todo.append((value,child))
            peak=max(peak,len(todo))
        states=0
    else:
        guard=Guard([r.lhs for r in rules],len(generators)); states=len(guard.next)
        todo=deque([(ident,(),0)])
        while todo and popped < expansions:
            if product_budget is not None and products>=product_budget: break
            if wall_budget is not None and time.perf_counter()-t>=wall_budget: break
            signature,word,state=todo.popleft(); popped+=1
            for a,g in enumerate(generators):
                probes+=1; ns=guard.next[state][a]
                if guard.bad[ns]: continue
                value=tuple(g[x] for x in signature);products+=1
                child=word+(a,)
                if value not in best:
                    best[value]=child;todo.append((value,child,ns))
                elif not dedup:todo.append((value,child,ns))
            peak=max(peak,len(todo))
    return {'known_semantics':len(best),'semantic_products':products,'popped':popped,
            'guard_probes':probes,'automaton_states':states,'peak_queue':peak,
            'wall_seconds':time.perf_counter()-t,'best':best}