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
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
"""Optional H7 hyperoptimization for the frozen 0.4.0 compiler.

This module contains inference-only code.  It loads frozen H4/H5 memory,
H6 expression-hole rules, the H7 neural retriever, and the H7 learned cost
selector.  It never loads training witnesses or evaluation targets.  Every
candidate is guarded structurally and compiled by the existing tensor backend;
any failure returns the ordinary compiler result.
"""
from __future__ import annotations

import hashlib
import json
import math
import re
from pathlib import Path

import torch
from torch import nn
import torch.nn.functional as F

from scaling_impl.phase_d.audit_transfer import audit_transfer
import ssa9_backend as backend
from scaling_impl.round16_adapters.normalization import tokens


def _same(x, y):
    return x.keys() == y.keys() and all(
        x[k].shape == y[k].shape and x[k].dtype == y[k].dtype and
        torch.equal(x[k], y[k]) for k in x)


def _signature(z):
    return {k: v.detach().cpu().clone() for k, v in z.items()}


def _cat(zs):
    return {k: torch.cat([z[k] for z in zs], 0) for k in zs[0]}


def _lane(z, i):
    return {k: v[i:i + 1].clone() for k, v in z.items()}


class _Capture:
    def __init__(self):
        self.z = None

    def compile(self, z, timer=None, *, audit=False):
        self.z = _signature(z)
        return None, None


class _H45Rule:
    @classmethod
    def from_state(cls, state):
        obj = cls.__new__(cls)
        obj.__dict__.update(state)
        return obj

    def apply(self, source, z):
        try:
            skeleton, values = _split_source(source)
        except (ValueError, IndexError, StopIteration):
            return None
        if skeleton != self.skeleton or len(values) != self.n:
            return None
        if any(values[i] != v for i, v in self.fixed.items()):
            return None
        if any(not lo <= values[i] <= hi or values[i] > 0xffffffff
               for i, (lo, hi) in self.bounds.items()):
            return None
        expected = self._instantiate(self.base, self.bmap, values)
        if expected is None or not _same(expected, z):
            return None
        return self._instantiate(self.target, self.tmap, values)

    @staticmethod
    def _instantiate(z, mapping, values):
        out = _signature(z)
        for (i, j), slots in mapping:
            value = values[slots[0]]
            if any(values[k] != value for k in slots):
                return None
            out['operands'][0, i, j] = value
        return out


def _split_source(source):
    match = re.search(r'\bkernel\s*\(', source)
    if match is None:
        raise ValueError('H7 source header')
    values = []
    start = source.index('{', match.end())
    body = source[start:]
    def replace(m):
        values.append(int(m.group(1)))
        return '<H45-U>'
    return source[:start] + re.sub(r'(?<![A-Za-z_0-9])([0-9]+)u\b', replace, body), tuple(values)


# H6's expression parser is intentionally narrow.  It is reproduced here as
# inference code so production does not import the training/evaluation driver.
_PREC = {'|': 1, '^': 2, '&': 3, '<<': 4, '>>': 4,
         '+': 5, '-': 5, '*': 6}
_UINT = re.compile(r'[0-9]+[uU]$')
_DEC = re.compile(r'[0-9]+$')


def _parse_expr(ts, start):
    index = None
    arrays = set()
    count = 0

    def unsigned(x):
        return x[0] in ('load', 'u', 'op', 'select')

    def expr(i, minp=0):
        nonlocal index, count
        count += 1
        if count > 512 or i >= len(ts):
            raise ValueError('expression budget')
        t = ts[i]
        if t == '(':
            left, i = expr(i + 1)
            if i >= len(ts) or ts[i] != ')':
                raise ValueError('paren')
            i += 1
        elif t in ('a', 'b') and i + 1 < len(ts) and ts[i + 1] == '[':
            end = i + 2
            while end < len(ts) and ts[end] != ']':
                end += 1
            idx = tuple(ts[i + 2:end])
            if end == len(ts) or not idx:
                raise ValueError('index')
            if index is not None and idx != index:
                raise ValueError('mixed index')
            index = idx
            arrays.add(t)
            left = ('load', t)
            i = end + 1
        elif _UINT.fullmatch(t) and int(t[:-1]) <= 0xffffffff:
            left, i = ('u', int(t[:-1])), i + 1
        elif _DEC.fullmatch(t) and int(t) <= 31:
            left, i = ('small', int(t)), i + 1
        else:
            raise ValueError('atom')
        while i < len(ts) and ts[i] in _PREC and _PREC[ts[i]] >= minp:
            op = ts[i]
            old = (index, set(arrays))
            try:
                right, j = expr(i + 1, _PREC[op] + 1)
            except ValueError:
                index, old_arrays = old
                arrays.clear(); arrays.update(old_arrays)
                break
            if op in ('<<', '>>') and not (right[0] in ('u', 'small') and right[1] < 32):
                raise ValueError('shift range')
            if op not in ('<<', '>>') and not (unsigned(left) or unsigned(right)):
                raise ValueError('signed arithmetic')
            if op in ('<<', '>>') and not unsigned(left):
                raise ValueError('signed shift')
            left, i = ('op', op, left, right), j
        if minp == 0 and i < len(ts) and ts[i] == '?':
            yes, j = expr(i + 1)
            if j >= len(ts) or ts[j] != ':':
                raise ValueError('ternary')
            no, i = expr(j + 1)
            if not unsigned(yes) or not unsigned(no):
                raise ValueError('ternary type')
            left = ('select', left, yes, no)
        return left, i

    tree, end = expr(start)
    if 'a' not in arrays or not unsigned(tree):
        raise ValueError('no a load')
    return tree, end, index


def _analyze(source):
    ts = [x[0] for x in tokens(source)]
    pos = next(i for i in range(len(ts) - 1) if ts[i:i + 2] == ['kernel', '('])
    start = ts.index('{', pos)
    expected = ['using', 'U', '=', 'unsigned', 'int', ';', 'using', 'I', '=',
                '__SIZE_TYPE__', ';', 'extern', '"C"', '__attribute__', '(',
                '(', 'noinline', ')', ')', 'void', 'kernel', '(', 'const',
                'U', '*', '__restrict', 'a', ',', 'const', 'U', '*',
                '__restrict', 'b', ',', 'U', '*', '__restrict', 'out', ',',
                'U', 'n', ')']
    if ts[:start] != expected or ts[-1] != '}':
        raise ValueError('H7 ABI/header')
    spans = []
    i = start + 1
    while i < len(ts) - 1:
        if ts[i] in ('(', 'a', 'b'):
            try:
                tree, end, idx = _parse_expr(ts, i)
                spans.append((i, end, tree, idx)); i = end; continue
            except ValueError:
                pass
        i += 1
    if not spans or any(x[2] != spans[0][2] for x in spans):
        raise ValueError('H7 expression holes')
    key = []; last = 0; parts = []; offset = 0
    for lo, hi, tree, idx in spans:
        key.extend(ts[last:lo]); key.append(['HOLE', list(idx)]); last = hi
        parts.append([source[offset:tokens(source)[lo][1]], list(idx)])
        offset = tokens(source)[hi - 1][2]
    key.extend(ts[last:])
    return json.dumps(key, separators=(',', ':')), spans[0][2], parts, source[offset:]


def _render(tree, idx):
    if tree[0] == 'load': return f"{tree[1]}[{' '.join(idx)}]"
    if tree[0] == 'u': return f'{tree[1]}u'
    if tree[0] == 'small': return str(tree[1])
    if tree[0] == 'op': return '(' + _render(tree[2], idx) + ' ' + tree[1] + ' ' + _render(tree[3], idx) + ')'
    if tree[0] == 'select': return '(' + ' ? '.join((_render(tree[1], idx), _render(tree[2], idx))) + ' : ' + _render(tree[3], idx) + ')'
    raise ValueError('invalid H7 tree')


def _shape(tree):
    if tree[0] in ('u', 'small'): return (tree[0],)
    if tree[0] == 'op': return (tree[0], tree[1], _shape(tree[2]), _shape(tree[3]))
    if tree[0] == 'select': return (tree[0], *(_shape(x) for x in tree[1:]))
    return tree


def _stable(value):
    return json.dumps(value, sort_keys=True, separators=(',', ':'))


def _expression_apply(rule, source):
    try:
        key, tree, _, _ = _analyze(source)
    except (ValueError, StopIteration):
        return None
    if key != rule.get('input_key'):
        return None
    guard = rule.get('shape_guard')
    if guard is not None and _stable(_shape(tree)) != guard:
        return None
    try:
        candidate = ''.join(s + _render(tree, idx) for s, idx in rule['parts']) + rule['tail']
        target_key, target_tree, _, _ = _analyze(candidate)
    except (ValueError, StopIteration):
        return None
    return candidate if target_key == rule.get('target_key') and tree == target_tree else None


class _GraphEncoder(nn.Module):
    def __init__(self, classes, width=48):
        super().__init__(); self.width = width
        self.op = nn.Embedding(512, width); self.role = nn.Embedding(4, 8)
        self.arg = nn.Embedding(5, width); self.block = nn.Embedding(128, 8)
        self.inp = nn.Linear(width + 64 + 8 + 8, width)
        self.msg = nn.ModuleList(nn.Linear(2 * width, width) for _ in range(3))
        self.norm = nn.ModuleList(nn.LayerNorm(width) for _ in range(3))
        self.proj = nn.Linear(2 * width, width)
        self.keys = nn.Parameter(torch.randn(classes, width))

    def embed(self, z):
        m, t, r, v = z['mask'], z['template'], z['role'], z['operands']
        batch, n, d = *t.shape, self.width
        args = r.eq(1) & v.lt(4) & v.ge(0); argcode = torch.where(args, v + 1, 0)
        h = self.inp(torch.cat([self.op(t.clamp(0, 511)), self.role(r.clamp(0, 3)).flatten(-2), self.block(z['block'].clamp(0, 127)), argcode.float() / 4], -1)) * m[..., None]
        ix = (v - 4).clamp(0, n - 1); ok = r.eq(1) & v.ge(4) & v.lt(n + 4) & m[..., None]
        for layer, norm in zip(self.msg, self.norm):
            g = h.gather(1, ix.reshape(batch, n, 8, 1).expand(-1, -1, -1, d).reshape(batch, -1, d)).reshape(batch, n, 8, d)
            g = (g * ok[..., None] + self.arg(argcode.clamp(0, 4)) * args[..., None]).sum(2)
            h = norm(h + F.gelu(layer(torch.cat([h, g], -1)))) * m[..., None]
        mean = h.sum(1) / m.sum(1, keepdim=True).clamp_min(1)
        mx = h.masked_fill(~m[..., None], -1e4).amax(1)
        return F.normalize(self.proj(torch.cat([mean, mx], -1)), dim=-1)

    def forward(self, z):
        return 12 * (self.embed(z) @ F.normalize(self.keys, dim=-1).T)


def _lexical(source, dim=128):
    ts = [t[0] for t in tokens(source)]; values = torch.zeros(dim)
    pieces = ts + [' '.join(ts[i:i + 2]) for i in range(len(ts) - 1)]
    for piece in pieces:
        values[int(hashlib.sha256(piece.encode()).hexdigest()[:8], 16) % dim] += 1
    return torch.log1p(values)


class _Retriever(nn.Module):
    def __init__(self, n, width=48):
        super().__init__(); self.graph = _GraphEncoder(n, width)
        self.lex = nn.Sequential(nn.Linear(128, width), nn.GELU(), nn.Linear(width, width))
        self.keys = nn.Parameter(torch.randn(n, width))

    def forward(self, z, lex):
        graph = self.graph.embed(z); h = F.normalize(graph + self.lex(lex), dim=-1)
        return 12 * h @ F.normalize(self.keys, dim=-1).T


class _Cost(nn.Module):
    def __init__(self, d):
        super().__init__(); self.net = nn.Sequential(nn.Linear(d, 48), nn.GELU(), nn.Linear(48, 1))

    def forward(self, x): return self.net(x).squeeze(-1)


def _features(x, z, rules, physical_count, byte_count):
    def one(packet):
        mask = packet['mask'][0]; template = packet['template'][0, mask]
        roles = packet['role'][0, mask]; vals = packet['operands'][0, mask][roles == 3].double().abs()
        hist = torch.bincount(template.clamp(0, 511), minlength=512).reshape(32, 16).sum(1)
        return [math.log1p(int(mask.sum())), math.log1p(int(packet['block'][0, mask].max()) + 1) if mask.any() else 0., math.log1p(float(vals.max())) if vals.numel() else 0., float(torch.log1p(vals).mean()) if vals.numel() else 0.] + torch.log1p(hist.float()).tolist()
    hashed = [0.] * 64
    for rule in rules:
        hashed[int(hashlib.sha256(rule.encode()).hexdigest()[:8], 16) % 64] = 1.
    return one(x) + one(z) + hashed + [math.log1p(physical_count), math.log1p(byte_count)]


class H7Optimizer:
    """Optional guarded optimizer layered in front of an existing compiler."""
    def __init__(self, compiler, asset_root, *, topk=3):
        self.compiler = compiler
        self.asset_root = Path(asset_root)
        self.topk = topk
        self.device = compiler.device
        h45 = torch.load(self.asset_root / 'h45_memory.pt', weights_only=True, map_location='cpu')
        if h45.get('schema') != 'neurocc.h45.research.v1': raise ValueError('unsupported H45 asset')
        self.h45_rules = [_H45Rule.from_state(x) for x in h45['rules']]
        self.h45_net = _GraphEncoder(len(self.h45_rules), h45['width']).to(self.device)
        self.h45_net.load_state_dict(h45['model']); self.h45_net.eval()
        self.rules = json.loads((self.asset_root / 'expression_rules.json').read_text())
        saved = torch.load(self.asset_root / 'retriever.pt', weights_only=True, map_location='cpu')
        if saved.get('schema') != 'neurocc.h7.retriever.v1': raise ValueError('unsupported H7 retriever')
        self.keys = saved['keys']; self.retriever = _Retriever(len(self.keys), saved['width']).to(self.device)
        self.retriever.load_state_dict(saved['model']); self.retriever.eval()
        cost = torch.load(self.asset_root / 'cost.pt', weights_only=True, map_location='cpu')
        if cost.get('schema') != 'neurocc.h7.cost.v1': raise ValueError('unsupported H7 cost')
        self.mean, self.std = cost['mean'].to(self.device), cost['std'].to(self.device)
        self.cost = _Cost(int(self.mean.numel())).to(self.device); self.cost.load_state_dict(cost['model']); self.cost.eval()
        self.timed_rules = set(cost['timed_rules'])

    def _capture(self, source):
        original = self.compiler.backend; cap = _Capture(); self.compiler.backend = cap
        try:
            _, order, records, _ = self.compiler.compile([source], evidence=False)
        finally:
            self.compiler.backend = original
        if cap.z is None or not order or not records[0].get('ssa_valid', False): return None
        return _lane(cap.z, order.index(0)) if 0 in order else None

    def _rank(self, x, source):
        with torch.no_grad():
            scores = self.retriever({k: v.to(self.device) for k, v in x.items()}, _lexical(source)[None].to(self.device))[0]
        return [self.keys[i] for i in scores.argsort(descending=True).cpu().tolist()]

    def _candidate_packets(self, source, x):
        options = [{'z': x, 'kind': 'ordinary', 'rules': ['ordinary']}]
        with torch.no_grad():
            top = self.h45_net({k: v.to(self.device) for k, v in x.items()})[0].argsort(descending=True).cpu().tolist()[:self.topk]
        for i in top:
            z = self.h45_rules[i].apply(source, x)
            if z is not None: options.append({'z': z, 'kind': 'h45', 'rules': ['h45:' + self.h45_rules[i].key]})
        ranked = self._rank(x, source); order = {rid: i for i, rid in enumerate(ranked)}
        matches = []
        for rid, rule in self.rules.items():
            candidate = _expression_apply(rule, source)
            if candidate is not None: matches.append((rid, candidate))
        matches.sort(key=lambda pair: order.get(pair[0], len(order)))
        # Neural ranking orders the guarded bank; all structurally compatible
        # rules remain available as a safe exhaustive fallback.
        for rid, candidate_source in matches:
            z = self._capture(candidate_source)
            if z is not None: options.append({'z': z, 'kind': 'h7_expression', 'rules': [rid]})
        unique = []
        for option in options:
            if any(_same(option['z'], old['z']) for old in unique): continue
            unique.append(option)
        return unique, ranked

    def _compile_options(self, options):
        raw_backend = getattr(self.compiler.backend, 'backend', self.compiler.backend)
        z = _cat([q['z'] for q in options])
        out, details = raw_backend.compile({k: v.to(self.device) for k, v in z.items()}, audit=True)
        details = audit_transfer(*details)
        valid = []
        for i, q in enumerate(options):
            try:
                if not bool(details[5]['valid'][i]) or out is None or not bool(out['valid'][i]): continue
                physical = backend.physical_rows(details[5], i); backend.audit(details[1], details[2], details[3], details[4], i)
                size = int(out['size'][i]); code = bytes(out['code'][i, :size].cpu().tolist())
                q = dict(q, physical_count=len(physical), byte_count=len(code), code=code, size=size, backend_valid=True)
                q['features'] = _features(options[0]['z'], q['z'], q['rules'], len(physical), size)
                valid.append(q)
            except Exception:
                continue
        return valid

    @torch.no_grad()
    def compile_batch(self, sources):
        ordinary = self.compiler.compile_for_neurold(sources, evidence=True)
        packet, records = ordinary
        results = []
        for i, source in enumerate(sources):
            record = dict(records[i]); record['hyperopt_enabled'] = True; record['hyperopt_selected'] = False
            base_ok = bool(packet['valid'][i]); base_size = int(packet['size'][i]) if base_ok else 0
            base_code = bytes(packet['code'][i, :base_size].detach().cpu().tolist()) if base_ok else b''
            x = self._capture(source) if base_ok else None
            if x is not None:
                try:
                    options, ranked = self._candidate_packets(source, x); valid = self._compile_options(options)
                    if valid:
                        allowed = [q for q in valid if q['kind'] == 'ordinary' or set(q['rules']) & self.timed_rules]
                        if not allowed: allowed = [q for q in valid if q['kind'] == 'ordinary']
                        features = (torch.tensor([q['features'] for q in allowed], device=self.device) - self.mean) / self.std
                        scores = self.cost(features).cpu().tolist(); j = max(range(len(allowed)), key=lambda k: (scores[k], -k))
                        ordinary_i = next((k for k, q in enumerate(allowed) if q['kind'] == 'ordinary'), None)
                        if ordinary_i is not None and scores[j] < scores[ordinary_i] + math.log(1.05): j = ordinary_i
                        chosen = allowed[j]; record.update(hyperopt_selected=chosen['kind'] != 'ordinary', hyperopt_kind=chosen['kind'], hyperopt_rules=chosen['rules'], hyperopt_candidates=len(valid), hyperopt_neural_rank=ranked[:self.topk])
                        if chosen['kind'] != 'ordinary':
                            base_code, base_size = chosen['code'], chosen['size']
                except Exception as exc:
                    record['hyperopt_fallback'] = f'{type(exc).__name__}: {exc}'
            results.append((base_code, base_size, base_ok, record))
        return results