File size: 14,259 Bytes
8a4e95e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
#!/usr/bin/env python3
"""Exact finite AIONVITA audit. Standard library only; no claimed unbounded RSI.

Run from bundle root: python exact_kernel.py --output results/exact_audit.json
Every algebraic assertion uses fractions.Fraction, not numerical tolerances.
"""
from __future__ import annotations

import argparse
from fractions import Fraction as F
from functools import lru_cache
from itertools import combinations, permutations, product
import json
from pathlib import Path
import time


DOMAIN = tuple(product((-1, 1), repeat=3))


def transpose(a):
    return [list(x) for x in zip(*a)]


def rank(a):
    if not a:
        return 0
    b = [[F(x) for x in row] for row in a]
    row = 0
    for col in range(len(b[0])):
        p = next((i for i in range(row, len(b)) if b[i][col]), None)
        if p is None:
            continue
        b[row], b[p] = b[p], b[row]
        scale = b[row][col]
        b[row] = [x / scale for x in b[row]]
        for i in range(len(b)):
            if i != row:
                scale = b[i][col]
                b[i] = [x - scale*y for x, y in zip(b[i], b[row])]
        row += 1
        if row == len(b):
            break
    return row


def det(a):
    b = [[F(x) for x in row] for row in a]
    result = F(1)
    for col in range(len(b)):
        p = next((i for i in range(col, len(b)) if b[i][col]), None)
        if p is None:
            return F(0)
        if p != col:
            b[p], b[col] = b[col], b[p]
            result = -result
        pivot = b[col][col]
        result *= pivot
        for i in range(col+1, len(b)):
            scale = b[i][col] / pivot
            for j in range(col+1, len(b)):
                b[i][j] -= scale*b[col][j]
    return result


def solve(a, b):
    n = len(a)
    aug = [[F(x) for x in row] + [F(y)] for row, y in zip(a, b)]
    for col in range(n):
        p = next(i for i in range(col, n) if aug[i][col])
        aug[col], aug[p] = aug[p], aug[col]
        scale = aug[col][col]
        aug[col] = [x / scale for x in aug[col]]
        for i in range(n):
            if i != col:
                scale = aug[i][col]
                aug[i] = [x-scale*y for x,y in zip(aug[i],aug[col])]
    return [row[-1] for row in aug]


def predict_fit(columns, labels):
    """Exact least squares on all eight uniform support inputs, no ridge."""
    gram = [[sum(F(x)*F(y) for x,y in zip(a,b)) for b in columns] for a in columns]
    rhs = [sum(F(x)*F(y) for x,y in zip(a,labels)) for a in columns]
    weights = solve(gram,rhs)
    return [sum(w*c[i] for w,c in zip(weights,columns)) for i in range(len(labels))]


def mse(pred, labels, weights=None):
    weights = weights or [1]*len(pred)
    return sum(F(w)*(F(p)-F(y))**2 for w,p,y in zip(weights,pred,labels))/sum(weights)


def features():
    one = [F(1)]*8
    x1 = [F(x[0]) for x in DOMAIN]
    x2 = [F(x[1]) for x in DOMAIN]
    x3 = [F(x[2]) for x in DOMAIN]
    z12 = [a*b for a,b in zip(x1,x2)]
    return one,x1,x2,x3,z12


def obstruction_audit():
    one,x1,x2,x3,z12 = features()
    old = [one,x1,x2,x3]
    dots = [sum(w*x for w,x in zip(z12,c)) for c in old]
    assert dots == [0]*4
    pred0 = predict_fit(old,z12)
    pred1 = predict_fit(old+[z12],z12)
    assert pred0 == [0]*8 and pred1 == z12
    return {
        "domain_size":8,
        "old_grammar":"rational affine features 1,x1,x2,x3; linear readout only",
        "host_constructor":"multiply(x1,x2), admitted as new learner-language fragment",
        "witness":list(map(str,z12)),
        "witness_dot_old_columns":list(map(str,dots)),
        "witness_dot_target":str(sum(z*z for z in z12)),
        "old_best_uniform_mse":str(mse(pred0,z12)),
        "new_best_uniform_mse":str(mse(pred1,z12)),
        "old_rank":rank(transpose(old)),"new_rank":rank(transpose(old+[z12])),
        "scope":"exact expressiveness relative to this non-universal DSL, not host Python",
    }


def tract_audit():
    one,x1,x2,x3,z12 = features()
    names=["1","x1","x2","x3","x1*x2","2*x1","x1+x2","x3+x1*x2"]
    columns=[one,x1,x2,x3,z12,[2*x for x in x1],
             [a+b for a,b in zip(x1,x2)],[a+b for a,b in zip(x3,z12)]]
    matrix=transpose(columns)
    r=rank(matrix)
    selected=[]
    for i,row in enumerate(matrix):
        if rank([matrix[j] for j in selected]+[row])>len(selected):
            selected.append(i)
    reduced=[matrix[i] for i in selected]
    @lru_cache(None)
    def minor(indices):
        if len(set(indices))<r:
            return F(0)
        inv=sum(indices[i]>indices[j] for i in range(r) for j in range(i+1,r))
        ordered=tuple(sorted(indices))
        if indices!=ordered:
            return (-1)**inv*minor(ordered)
        return det([[row[j] for j in ordered] for row in reduced])
    bases={str(i):str(minor(i)) for i in combinations(range(8),r)}
    checked=nontrivial=0
    for left in combinations(range(8),r-1):
        for right in combinations(range(8),r+1):
            terms=[(-1)**k*minor(left+(right[k],))*minor(right[:k]+right[k+1:])
                   for k in range(r+1)]
            assert sum(terms)==0
            checked+=1
            nontrivial+=int(any(terms))
    circuits=[]
    for size in range(2,r+2):
        for inds in combinations(range(8),size):
            if rank(transpose([columns[i] for i in inds]))==size:
                continue
            if all(rank(transpose([columns[j] for j in inds if j!=i]))==size-1 for i in inds):
                circuits.append([names[i] for i in inds])
    assert ["x1","2*x1"] in circuits
    assert ["x1","x2","x1+x2"] in circuits
    return {
        "tract":"Q field tract: multiplicative group Q^*, null sums are formal finite sums evaluating to 0 in Q",
        "specialization":"ordinary rational-representable strong matroid; no exotic-tract speedup claimed",
        "column_names":names,"rank":r,"independent_rows":selected,
        "maximal_minors":bases,"grassmann_pluecker_relations_checked":checked,
        "relations_with_nonzero_terms":nontrivial,"all_relations_zero":True,
        "minimal_dependent_circuits":circuits,
        "new_interaction_independent":rank(transpose(columns[:5]))==5,
    }


def evaluator_audit():
    """Finite selection functions compose through two-step backward induction."""
    hs=tuple(range(4))
    names=["x1","x2","x1*x2","x1*x3"]
    def output(h,q):
        a,b,c=q
        return (a,b,a*b,a*c)[h]
    def parts(state,q):
        return [tuple(h for h in state if output(h,q)==v) for v in (-1,1)
                if any(output(h,q)==v for h in state)]
    @lru_cache(None)
    def choose(state,depth):
        if depth==0 or len(state)==1:
            return F(len(state)),None
        choices=[]
        for q in DOMAIN:
            loss=sum(F(len(s),len(state))*choose(s,depth-1)[0] for s in parts(state,q))
            choices.append((loss,q))
        return min(choices)
    initial=(1,1,1)
    assert len(set(output(h,initial) for h in hs))==1
    def tree(state,depth):
        value,q=choose(state,depth)
        if q is None:
            return {"hypotheses":[names[h] for h in state],"expected_remaining":str(value)}
        return {"query":q,"expected_remaining":str(value),"children":[tree(s,depth-1) for s in parts(state,q)]}
    value,_=choose(hs,2)
    assert value==1
    return {"hypotheses":names,"initial_alias_probe":initial,"initial_equivalence_class_size":4,
            "optimal_one_step_expected_remaining":str(choose(hs,1)[0]),
            "optimal_two_step_expected_remaining":str(value),"selected_policy":tree(hs,2),
            "construction":"finite argmin selection functions with backward induction; no bar recursion or ludics instantiated"}


def rewrite_audit():
    fragments={"a":("input",0),"b":("input",1),"c":("input",2),
               "u":("mul","a","b"),"v":("mul","a","c")}
    def deps(key):
        return () if fragments[key][0]=="input" else fragments[key][1:]
    def assemble(storage):
        todo=set(storage)
        order=[]
        values={}
        while todo:
            ready=sorted(k for k in todo if all(d in values for d in deps(k)))
            if not ready:
                raise ValueError("cyclic or absent dependency")
            k=ready[0] # independent guide is canonical ready-node order
            f=fragments[k]
            values[k]=([F(x[f[1]]) for x in DOMAIN] if f[0]=="input" else
                       [a*b for a,b in zip(values[f[1]],values[f[2]])])
            todo.remove(k)
            order.append(k)
        return order,values
    orders=[]
    for storage in permutations(fragments):
        order,values=assemble(storage)
        assert values["u"]==[F(x[0]*x[1]) for x in DOMAIN]
        orders.append(order)
    legal_orders=[p for p in permutations(fragments)
                  if all(p.index(d)<p.index(k) for k in p for d in deps(k))]
    # Every pair of simultaneously enabled independent reductions forms a diamond.
    states=[frozenset(s) for n in range(6) for s in combinations(fragments,n)
            if all(set(deps(k))<=set(s) for k in s)]
    diamonds=0
    for state in states:
        ready=[k for k in fragments if k not in state and set(deps(k))<=state]
        for a,b in combinations(ready,2):
            assert (state|{a})|{b} == (state|{b})|{a}
            diamonds+=1
    assert len(set(map(tuple,orders)))==1
    return {"fragment_count":len(fragments),"scrambled_storage_orders_checked":len(orders),
            "canonical_guide":orders[0],"legal_reconstruction_orders":len(legal_orders),
            "commuting_independent_edit_diamonds_checked":diamonds,
            "termination_measure":"unassembled fragment count decreases by one per step",
            "scope":"ordinary terminating DAG rewriting; not a full Squier resolution"}


def dimension_audit():
    one,x1,x2,x3,z12=features()
    old=[one,x1,x2,x3]
    new=old+[z12]
    # Each support-label intervention adds one orthogonal Walsh target.
    # Learners trained from scratch reach any joint rational combination.
    responses=[predict_fit(new,labels) for labels in new]
    assert responses==new
    regimes={"uniform":[1]*8,"full_support_shift":list(range(1,9))}
    dims={}
    for name,weights in regimes.items():
        # Nonzero rational row scaling preserves exact response independence.
        dims[name]=rank([[F(w)*responses[j][i] for j in range(5)] for i,w in enumerate(weights)])
    assert set(dims.values())=={5}
    jointly_reachable=True
    for coeffs in product((-1,0,1),repeat=5):
        labels=[sum(F(c)*col[i] for c,col in zip(coeffs,new)) for i in range(8)]
        jointly_reachable &= predict_fit(new,labels)==labels
    assert jointly_reachable
    shift_gain={name:str(mse(predict_fit(old,z12),z12,w)-mse(predict_fit(new,z12),z12,w))
                for name,w in regimes.items()}
    # With B_e=diag(sqrt(w/sum(w))) W_S, orthogonality W_S^T W_S=8I
    # gives sigma_min(B_e)^2 >= 8 min(w)/sum(w), without floating arithmetic.
    sigma_sq_bounds={name:str(F(8*min(w),sum(w))) for name,w in regimes.items()}
    useful_gains={name:[str(mse([0]*8,c,w)-mse(predict_fit(new,c),c,w)) for c in new]
                  for name,w in regimes.items()}
    assert all(F(g)>=1 for gains in useful_gains.values() for g in gains)
    duplicate=new+[[2*x for x in x1]]
    collapse_rows=[i for i,x in enumerate(DOMAIN) if x[0]==x[1]]
    collapse_rank=rank([[col[i] for col in new] for i in collapse_rows])
    # Rank expansion can harm: old learner only x1 filters x2-aligned support noise.
    support=[a+b for a,b in zip(x1,x2)]
    target=x1
    old_noisy=predict_fit([one,x1],support)
    new_noisy=predict_fit([one,x1,x2],support)
    assert mse(old_noisy,target)==0 and mse(new_noisy,target)==1
    # Exact functional continuity: new regression span contains old contracts.
    retained=[predict_fit(new,c)==c for c in old]
    assert all(retained)
    return {"dimension_definition":"largest jointly reachable response subset independent in every declared full-support regime, with per-target positive heldout loss gain",
            "support_label_interventions":5,"old_useful_dimension":4,"new_useful_dimension":5,
            "regime_response_ranks":dims,"joint_ternary_intervention_vectors_checked":3**5,
            "joint_reachability_verified":jointly_reachable,
            "common_labelled_subset":["1","x1","x2","x3","x1*x2"],
            "normalized_response_sigma_min_squared_lower_bounds":sigma_sq_bounds,
            "per_column_task_gain_vs_zero_baseline":useful_gains,
            "usefulness_threshold_delta":"1","support_cost_per_intervention_points":8,
            "new_target_mse_gain_by_regime":shift_gain,
            "duplicate_column_raw_count":6,"duplicate_column_dimension":rank(transpose(duplicate)),
            "collapse_shift":"only inputs satisfying x1=x2", "collapse_shift_rank":collapse_rank,
            "harmful_rank_counterexample":{"old_rank":2,"new_rank":3,
                "training_labels":"x1+x2","true_target":"x1","old_test_mse":str(mse(old_noisy,target)),
                "new_test_mse":str(mse(new_noisy,target)),
                "interpretation":"x2 fits aligned noise; fails usefulness gate on this task"},
            "lineage_contracts_retained":sum(retained),"lineage_contracts_total":len(retained),
            "lineage_max_prediction_error":"0",
            "lineage_scope":"finite functional contracts; no universal or conscious identity certificate"}


def run():
    started=time.perf_counter()
    output={"schema":"aionvita.exact_audit.v1","arithmetic":"fractions.Fraction (exact rational)",
            "obstruction":obstruction_audit(),"tract":tract_audit(),
            "evaluation":evaluator_audit(),"reconstruction":rewrite_audit(),
            "aionvita":dimension_audit()}
    output["elapsed_seconds"]=time.perf_counter()-started
    return output


if __name__=="__main__":
    parser=argparse.ArgumentParser()
    parser.add_argument("--output",default="results/exact_audit.json")
    args=parser.parse_args()
    result=run()
    target=Path(args.output)
    target.parent.mkdir(parents=True,exist_ok=True)
    target.write_text(json.dumps(result,indent=2)+"\n")
    print(json.dumps({"output":str(target),"all_assertions_passed":True,
                      "elapsed_seconds":result["elapsed_seconds"]}))