From 216e44a60b474ca7b09d591a7eb288282b85a734 Mon Sep 17 00:00:00 2001 From: Nick Petalas Date: Wed, 11 Nov 2026 12:47:55 +0000 Subject: [PATCH] feat(research): prove sharp approximate native-fusion error --- .../sharp-approximate-native-fusion/PROOF.md | 158 +++++++++++ .../sharp-approximate-native-fusion/README.md | 90 +++++++ .../SOURCES.json | 18 ++ .../sharp-approximate-native-fusion/TASK.json | 79 ++++++ .../VERIFY.json | 34 +++ .../sharp-approximate-native-fusion/verify.py | 251 ++++++++++++++++++ 6 files changed, 630 insertions(+) create mode 100644 research/sharp-approximate-native-fusion/PROOF.md create mode 100644 research/sharp-approximate-native-fusion/README.md create mode 100644 research/sharp-approximate-native-fusion/SOURCES.json create mode 100644 research/sharp-approximate-native-fusion/TASK.json create mode 100644 research/sharp-approximate-native-fusion/VERIFY.json create mode 100644 research/sharp-approximate-native-fusion/verify.py diff --git a/research/sharp-approximate-native-fusion/PROOF.md b/research/sharp-approximate-native-fusion/PROOF.md new file mode 100644 index 0000000000..d9875c19c4 --- /dev/null +++ b/research/sharp-approximate-native-fusion/PROOF.md @@ -0,0 +1,158 @@ +# Sharp error with norm-bounded rectangular adapters + +This is a scoped written proof over the complex numbers, with exact finite +corroboration. It is not a physical fusion construction or a multiplication +theorem. The result was produced by Nick Petalas. + +## Model and theorem + +Put a=(1+i)/2, b=(1-i)/2 and + +``` +C = [a b; b a], U_f = C^(tensor f). +``` + +Let f>=1 and r>=2 be integers. Write d=2^f, N=2^(rf), and +alpha=sqrt(d/N)=2^(-(r-1)f/2). The target is T=diag(U_f,U_f), on two +independent d-coordinate inputs. Every target column has exactly d nonzero +entries of modulus 1/sqrt(d) and Euclidean norm one. + +Permit any finite spectator multiplicity s>=1 for the child K=I_s tensor U_(rf). +Every child entry has modulus at most 1/sqrt(N). Permutations and unit +rephasings of the child preserve this fact and the lower bound below. + +The relaxed returned map is F=BKA+H. Both adapters may be rectangular, complex, +width dependent and singular. For a prescribed real M>=0 require + +``` +||A||_1 ||B||_infinity <= M, +``` + +where these are maximum absolute column sum and maximum absolute row sum. +The bypass H has at most h nonzeros per column, for an integer 0<=h<=d. It has +no coefficient-size, row-support or implementation restriction. Additional +workspace may be initialized and discarded; no inverse is required. + +Define E_col(F,T)=max_j ||(F-T)e_j||_2. This is precisely the induced +l1-to-l2 norm of F-T. Define E_rms(F,T)=||F-T||_F/sqrt(2d), the root mean +square of the Euclidean column errors. + +**Theorem.** In this relaxation, allowing any finite spectator multiplicity, +the minimum of either error is + +``` +E_min(f,r,M,h) = sqrt(1-h/d) max(0, 1-M alpha). +``` + +Both minima are attained simultaneously with s=2. The lower bound applies to +each individual column for every permitted s. In particular, restricting the +bank stock cannot invalidate this necessary bound, but may remove its attainer. + +## Lower bound + +For every pair of external indices i,j, the triangle inequality gives + +``` +|(BKA)_ij| + <= max_uv |K_uv| sum_u |B_iu| sum_v |A_vj| + <= M/sqrt(N). +``` + +In column j, at most h of the d nonzero target positions can belong to the +support of H. At each of the remaining at least d-h positions, + +``` +|(T-F)_ij| >= max(0, 1/sqrt(d) - M/sqrt(N)). +``` + +Squaring and summing just those positions gives the stated squared lower +bound for every column. Taking a maximum or an average proves both claims. +This proof allows arbitrary cancellation, cross-spectator mixing and arbitrary +coefficients in both adapters. It uses no assumption of a reversible decoder. + +## Attainment + +Take s=2 and K=diag(U_(rf),U_(rf)). Let E embed each target lane into its +own child block by fixing the high (r-1)f tensor coordinates at zero. Let P +project the same coordinates back out. Since C_00=a, + +``` +P K E = a^((r-1)f) T. +``` + +Set m=(r-1)f, gamma=min(1,M alpha), A=E and +B=gamma a^(-m) P. Each encoder column has one unit entry, and each readout row +has one entry of modulus gamma/alpha. Thus + +``` +||A||_1 ||B||_infinity = gamma/alpha <= M, B K A = gamma T. +``` + +For each column choose any h of its d target positions and set H to +(1-gamma)T there and zero elsewhere. Its column support is at most h. +The error is zero on the chosen positions and (1-gamma)T on exactly d-h +others. Every column therefore has squared error +(1-h/d)(1-gamma)^2. This equals the lower bound, including M=0, h=d and the +zero-error norm threshold M=1/alpha. + +The construction uses 2N child coordinates for 2d external coordinates, a +bank expansion N/d=2^((r-1)f). Moreover the bypass is only a sparse linear +map in this relaxation. No preparation, coefficient, routing, precision, +restoration, returned-owner or tape cost has been supplied for it. Attainment +of the mathematical minimum does not supply an affordable paid child. + +## Consequences and one exact example + +For fixed M and r>=2, if h/2^f tends to zero, both minimum errors tend to one. +Thus this norm-bounded class cannot approach even a fixed error less than one +using a sublinear number of bypass entries per column. This statement concerns +the retained normalization and these two error metrics. + +When M alpha<1 and a prescribed tolerance delta satisfies +0<=delta<1-M alpha, the exact minimum bypass support is + +``` +ceil(d [1-(delta/(1-M alpha))^2]). +``` + +At f=8, r=2, M=1, alpha=1/16. Error at most 1/2 requires h>=184 out of +256 target positions per column. The verifier enumerates all 257 integral +supports to obtain this threshold. The formula is sharp in the same relaxed +model. It is not a spectral-norm optimum, an error estimate for a full rounded +caller, or a recursive invoice. + +## Relation to predecessor work + +ToikY's [#7166 proof](https://github.com/ToikY/integer-mult-bounds/blob/6efb5d028b3212fba68edfb725608413622d6ab6/research/p104-rectangular-clifford-adapter-bound/PROOF.md) +supplies the exact rectangular amplitude obstruction and the projected tensor +control. Those are credited starting points. The new step counts every target +position missed by the bypass, proves a positive approximation floor and shows +that this floor is the exact relaxed optimum for every parameter above. +No predecessor scientific verifier or count is replayed. + +Earlier fusion boundaries include Clear1nsight's #4932 Fourier-grade model, +#4045 monomial model and #3989 paid nonmonomial transfer. Their physical words, +counts and recursive bills are not assumptions of this self-contained theorem. +The Gaussian tensor normalization follows the retained native lineage, +including zxv, Clear1nsight #7161 and Rohan Arun #7113 as credited in #7166. + +## Verification boundary + +The universal quantifiers rest on this written proof. The finite checker uses +Gaussian-rational pairs, literal rectangular matrix multiplication and separate +Kronecker/bit-count constructions. It tests six (f,r) pairs with rf<=6, five +rational gains and every support h in each target lane. Gains parametrize +M=gamma/alpha exactly, so odd m is checked without floating point. Additional +mixed-lane rectangular adapters and bypasses test the lower bound at even m. +All checks remain active with Python optimization enabled. + +The Python verifier has managed-runtime allocation and diagnostic limits. +Fraction arithmetic, matrices and Python runtime objects allocate +dynamically. All matrices have at most 128 rows and columns, exponents are at +most six, and the fixture lists bound every loop. This compensates the memory +deviation only within this finite checker. Warning-strict normal and optimized +runs plus source compilation are the available diagnostics; a repository-wide +static-analysis policy is outside this isolated package. A larger fixture must +first raise and justify these explicit capacities. The checker has no recursive +calls, network access or subprocesses; its sole optional write creates a new +receipt with exclusive creation and refuses overwrite. diff --git a/research/sharp-approximate-native-fusion/README.md b/research/sharp-approximate-native-fusion/README.md new file mode 100644 index 0000000000..b07210e97b --- /dev/null +++ b/research/sharp-approximate-native-fusion/README.md @@ -0,0 +1,90 @@ +# Sharp approximation floor for rectangular native fusion + +This scoped written proof with exact finite corroboration was produced by Nick Petalas. +It extends the exact amplitude boundary of ToikY +[#7166](https://github.com/CrocSwap/integer-mult-bounds/pull/7166) to approximate +returned maps. It does not recheck that package's native word or invoice. + +For two independent f-bit Gaussian tensor targets, put d=2^f and let a +rank-r child have flat entries of modulus 2^(-rf/2), with r>=2. Allow arbitrary +rectangular complex adapters whose maximum column-sum/row-sum norm product is +at most M, and an arbitrary bypass with at most h nonzeros per column. +The exact minimum maximum Euclidean column error is + +``` +sqrt(1-h/2^f) max(0,1-M*2^(-(r-1)f/2)). +``` + +The same formula is the exact minimum normalized Frobenius error. Every column +satisfies the lower bound. A two-spectator projected construction attains both +minima simultaneously, using bank expansion 2^((r-1)f). For fixed M and +sublinear bypass support, the error tends to one. At f=8, r=2 and M=1, error +at most 1/2 needs at least 184 bypass entries per 256-entry target column. + +[PROOF.md](PROOF.md) states the full model, proof, attainment and limitations. +The attainer is an algebraic relaxation with expanded banks and an unpriced +bypass. No affordable physical fusion, improved kappa, selected-frontier change +or complete multiplication theorem is claimed. The error metrics are column +error and normalized Frobenius error; spectral-norm optimality is not claimed. + +## Reproduction + +From the repository root, use CPython 3.12 and the standard library: + +```sh +~/git/integer-mult-bounds/.venv/bin/python3.12 -I -W error -B research/sharp-approximate-native-fusion/verify.py +~/git/integer-mult-bounds/.venv/bin/python3.12 -I -O -W error -B research/sharp-approximate-native-fusion/verify.py +~/git/integer-mult-bounds/.venv/bin/python3.12 -B scripts/research_package.py --package research/sharp-approximate-native-fusion +~/git/integer-mult-bounds/.venv/bin/python3.12 -B scripts/check_research_commit.py --package research/sharp-approximate-native-fusion --check-source-history +``` + +The direct marker is `PASS_SHARP_APPROXIMATE_NATIVE_FUSION`. The checker +performs exact Gaussian-rational matrix multiplication, independent tensor-entry +checks, all bypass supports in six small tensor shapes, additional mixed-lane +adapters and phase/support/capacity controls. `--receipt PATH` creates a +hash-bound JSON receipt outside the checkout and refuses overwrite. Without +that option the checker writes only stdout. The all-parameter theorem is the +written proof, not an exhaustive numerical search. + +Local CPython 3.12.15 checks passed for 140 attainers and 1,300 columns, +40 general adapter cases and 320 columns, 8,784 independent tensor entries, +three semantic controls, four capacity rejections and all 257 supports of the +threshold example. Normal and optimized generated receipts agree byte for byte. +Both registered checks passed. These finite checks corroborate the proof. + +The registered replay runs both direct modes. No predecessor scientific suite, +selected cold replay, physical consumer, Lean or Docker check is required or +claimed. Independent human and formal proof-kernel review are unclaimed. + +## Sources and scope + +The canonical base is e54523517d0f03e58352e647c403a5af3e525a57, priority +revision 8, selected #7000. `SOURCES.json` pins the catalogue and selected record +as provenance. The card `coverage-law-change` changes to a local approximate +interface obstruction. This limits an attempted higher-rank fusion before +its full physical bill is known; it does not admit or exclude all suppliers. + +The main predecessor is ToikY's #7166, proof at +`6efb5d028b3212fba68edfb725608413622d6ab6`. Its exact amplitude inequality and +projected tensor control are credited inputs. This package independently +implements its own small matrix definitions and uses no predecessor code or +external runtime inputs. Clear1nsight's #4932, #4045 and #3989 give related +scoped fusion boundaries. The retained Gaussian lineage includes zxv, +Clear1nsight #7161 and Rohan Arun #7113. Their results are cited, not audited. + +[Advance claim](https://github.com/CrocSwap/integer-mult-bounds/discussions/1166#discussioncomment-19541721). + +## Open next questions + +1. What is the exact spectral-norm optimum with the same adapter and bypass + constraints? Column error bounds it below, but the sharp column attainer + can leave correlated residual columns. Start with f=1 and h=1 and compare + different bypass support patterns. A proof needs control of all input + directions, rather than only individual columns. +2. What error is attainable under a charged bank expansion strictly below two? + The present equality construction expands by 2^((r-1)f), so it does not + meet that favorable paid-fusion allowance. Start with one exact rectangular + source/consumer layout and price its bank stock, routing, restoration and + bypass. This is blocked by a complete physical contract and invoice. + +These questions and their blockers are also recorded in `TASK.json`. diff --git a/research/sharp-approximate-native-fusion/SOURCES.json b/research/sharp-approximate-native-fusion/SOURCES.json new file mode 100644 index 0000000000..5335fa97d9 --- /dev/null +++ b/research/sharp-approximate-native-fusion/SOURCES.json @@ -0,0 +1,18 @@ +{ + "schema_version": 1, + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "files": [ + { + "path": "certificates/selected-result.json", + "usage": "provenance", + "git_blob": "75d77b328ea02ded535e7f23aee5b1e55d0bb1a8", + "sha256": "154c3d30455d778fd3343b6b4851f0fa4665f0f7625b0adb3675e2bafbbf6bf1" + }, + { + "path": "docs/research/agent-task-catalog.json", + "usage": "provenance", + "git_blob": "3404fbdd5e7529a0674eef26114b5071e4586cec", + "sha256": "ead6cdc9d0af6d58e8a49744d8ec8c7c15e13d2ba93c276c434bcf9b51b93a81" + } + ] +} diff --git a/research/sharp-approximate-native-fusion/TASK.json b/research/sharp-approximate-native-fusion/TASK.json new file mode 100644 index 0000000000..11b35c96aa --- /dev/null +++ b/research/sharp-approximate-native-fusion/TASK.json @@ -0,0 +1,79 @@ +{ + "schema_version": 1, + "task_id": "coverage-law-change", + "priority_revision": 8, + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "original_card": { + "id": "coverage-law-change", + "question": "Can a completed call earn more independent productive target credit without an offsetting paid bill?", + "starting_points": [ + "docs/research/current-priorities.md", + "docs/research/research-family-status.md", + "certificates/selected-result.json", + "docs/research/pr-intake-evidence/pr5599-completion/PROOF-REVIEW.md" + ], + "methods": [ + "Construct and independently check one source-bound instance of the stated first experiment.", + "Seek an exact counterexample or target-specific complete-budget obstruction to that same proposed change." + ], + "acceptance_gate": "A source-bound arbitrary-input identity and legal producer/consumer boundary with the complete paid and productive target invoice, including restoration, ownership, native alignment and extra charges. Price under the actual current model; historical ceiling.py assumptions must be established before use. A favorable optimistic relaxation keeps a route open but is not a completed supplier. A scoped local result remains useful; expansion requires the family-level budget gate.", + "first_step": { + "command": [ + "python3", + "-B", + "scripts/research_selected_baseline.py" + ], + "expected": "PASS_RESEARCH_BASELINE_BINDINGS_ONLY", + "inspect": "Read revision 8, the selected review and live exact-source handoffs. Then follow this card's bounded first_experiment.", + "scope": "Source-bound orientation only, not a supplier replay or theorem proof." + }, + "first_experiment": "Use #5599 as a completed positive control, then choose one uncovered cut/module beyond an applicable frozen exclusion. Derive independence, saturation and chronological availability rather than counting rational rank alone. Price target credits and all new jobs together, then check compiler and actual caller compatibility. Stop on a nonphysical credit or an unfavorable complete relaxation.", + "bottleneck_link": "Judge the actual current supplier contract and complete signed target/paid bill; frozen-profile ceilings require an applicability proof.", + "allowed_variations": [ + "One exact source head, helper/cut region or quantified proposition and changed hypothesis; check live handoffs first. Different seeds are not different scopes." + ], + "scope_change_triggers": [ + "Changing source head, helper/cut domain, operation alphabet or caller boundary without recording the new scope.", + "Treating an archived proposal or local numerical pass as complete supplier admission." + ], + "overlap_terms": [ + "target credit", + "helper split", + "coverage law" + ], + "existing_checks": [ + { + "scope": "Selected PR5599: complete helper-subspace construction and independent caller replay; five framework assumptions remain.", + "evidence": "docs/research/pr-intake-evidence/pr5599-completion/PROOF-REVIEW.md", + "remaining": "The next experiment must identify uncovered source-specific work. Successor archive intake does not transfer this admission.", + "status": "reviewed", + "source_commit": "09dd0965711ca7eeb169057a420abab1c9052137", + "selected_record_sha256": "2a0220e866417774606e0f991e41b9c1d26b1f43b97857238cf478dbc7d330b5" + } + ] + }, + "scope_status": "changed", + "actual_scope": "Determine the exact relaxed column-error and normalized-Frobenius-error optimum for norm-bounded rectangular Gaussian tensor fusion with a column-sparse bypass.", + "scope_change_reason": "The selected card asks for a completed productive-credit change. This contribution instead proves a sharp approximate-interface obstruction extending the exact boundary of ToikY #7166, without a physical supplier or its invoice.", + "bottleneck_link": "A higher-rank child would reduce the concave paid moment only after its adapters and returned outputs are legal. The positive approximation floor rules out fixed norm bounds and sublinear bypass support as an approximate escape in this declared normalization.", + "budget_minutes": 60, + "stop_rule": "Stop at the first proved sharp local error law and exact finite corroboration; leave physical fusion and other norms as open questions.", + "outcome": "negative-result", + "evidence": "PROOF.md proves the universal lower bound and equality construction. verify.py checks literal finite matrices and emits a computed hash-bound receipt. Predecessor proof URL is pinned in PROOF.md; its bytes observed at head 6efb5d028b3212fba68edfb725608413622d6ab6 have SHA256 fbf91c955c997b9b55eb10ce3b7e925933b4e23a99544c18e9cd2417bc29e3b7. No external input is used by the new checker.", + "author": "Nick Petalas", + "ai_assistance": "Independent human and formal proof-kernel review are unclaimed.", + "open_questions": [ + { + "question": "What is the exact spectral-norm optimum under the same adapter and sparse-bypass constraints?", + "why_it_matters": "A uniform Euclidean-input error contract requires a spectral bound; equality for basis inputs does not establish it.", + "first_step": "At f=1 and h=1 compare the spectral errors for distinct bypass support patterns.", + "blocked_by": "Control of correlated residual columns for arbitrary adapters." + }, + { + "question": "What approximation is achievable with charged bank expansion strictly below two?", + "why_it_matters": "The sharp relaxed attainer has exponential bank expansion and is not an affordable physical fusion.", + "first_step": "Specify one exact rectangular source/consumer layout and charge all bank stock and bypass work.", + "blocked_by": "A complete source-bound physical contract, restoration proof and recursive invoice." + } + ] +} diff --git a/research/sharp-approximate-native-fusion/VERIFY.json b/research/sharp-approximate-native-fusion/VERIFY.json new file mode 100644 index 0000000000..455f8ce84d --- /dev/null +++ b/research/sharp-approximate-native-fusion/VERIFY.json @@ -0,0 +1,34 @@ +{ + "schema_version": 1, + "status": "ready", + "python": "3.12", + "requirements": [], + "inputs": [], + "commands": [ + { + "argv": [ + "{python}", + "-I", + "-W", + "error", + "-B", + "{package}/verify.py" + ], + "timeout_seconds": 120, + "checks": "Exact sharp attainers, independent tensor entries, arbitrary mixed-lane finite adapters and semantic/capacity controls." + }, + { + "argv": [ + "{python}", + "-I", + "-O", + "-W", + "error", + "-B", + "{package}/verify.py" + ], + "timeout_seconds": 120, + "checks": "The same scientific checks with assertions disabled; all gates use explicit exceptions." + } + ] +} diff --git a/research/sharp-approximate-native-fusion/verify.py b/research/sharp-approximate-native-fusion/verify.py new file mode 100644 index 0000000000..0bf139ffd5 --- /dev/null +++ b/research/sharp-approximate-native-fusion/verify.py @@ -0,0 +1,251 @@ +"""Exact finite corroboration of the sharp relaxed native-fusion error law.""" +from __future__ import annotations + +import argparse +import hashlib +import json +import platform +import random +from fractions import Fraction as F +from pathlib import Path + +G = tuple[F, F] +Matrix = list[list[G]] +ZERO: G = (F(0), F(0)) +ONE: G = (F(1), F(0)) +A: G = (F(1, 2), F(1, 2)) +B: G = (F(1, 2), F(-1, 2)) +MAX_DIM = 128 + + +def require(condition: bool, message: str) -> None: + if not condition: + raise ValueError(message) + + +def add(x: G, y: G) -> G: + return x[0] + y[0], x[1] + y[1] + + +def mul(x: G, y: G) -> G: + return x[0] * y[0] - x[1] * y[1], x[0] * y[1] + x[1] * y[0] + + +def scale(x: G, q: F) -> G: + return q * x[0], q * x[1] + + +def norm2(x: G) -> F: + return x[0] ** 2 + x[1] ** 2 + + +def power(x: G, n: int) -> G: + require(0 <= n <= 6, "power exponent outside finite-check domain") + out = ONE + for _ in range(n): + out = mul(out, x) + return out + + +def zeros(rows: int, cols: int) -> Matrix: + require(1 <= rows <= MAX_DIM and 1 <= cols <= MAX_DIM, "matrix capacity") + return [[ZERO for _ in range(cols)] for _ in range(rows)] + + +def matmul(x: Matrix, y: Matrix) -> Matrix: + require(bool(x) and bool(y) and len(x[0]) == len(y), "matrix dimensions") + out = zeros(len(x), len(y[0])) + for i, row in enumerate(x): + for k, value in enumerate(row): + if value == ZERO: + continue + for j, other in enumerate(y[k]): + if other != ZERO: + out[i][j] = add(out[i][j], mul(value, other)) + return out + + +def tensor(n: int) -> Matrix: + require(0 <= n <= 6, "tensor exponent outside finite-check domain") + out = [[ONE]] + for _ in range(n): + size = len(out) + new = zeros(2 * size, 2 * size) + for i in range(2 * size): + for j in range(2 * size): + base = A if i // size == j // size else B + new[i][j] = mul(base, out[i % size][j % size]) + out = new + return out + + +def duplicate(x: Matrix) -> Matrix: + size = len(x) + out = zeros(2 * size, 2 * size) + for lane in range(2): + for i in range(size): + for j in range(size): + out[lane * size + i][lane * size + j] = x[i][j] + return out + + +def column_errors(x: Matrix, target: Matrix) -> list[F]: + require(len(x) == len(target) and len(x[0]) == len(target[0]), "error shapes") + errors = [F(0) for _ in target[0]] + for i, row in enumerate(target): + for j, value in enumerate(row): + errors[j] += norm2(add(x[i][j], scale(value, F(-1)))) + return errors + + +def bypass(target: Matrix, gain: F, h: int) -> Matrix: + d = len(target) // 2 + require(0 <= h <= d, "bypass support") + out = zeros(len(target), len(target)) + for j in range(len(target)): + start = (j // d) * d + for i in range(start, start + h): + out[i][j] = scale(target[i][j], 1 - gain) + return out + + +def plus(x: Matrix, y: Matrix) -> Matrix: + require(len(x) == len(y) and len(x[0]) == len(y[0]), "sum shapes") + return [[add(a, b) for a, b in zip(row, other, strict=True)] + for row, other in zip(x, y, strict=True)] + + +def attainer(f: int, r: int, gain: F) -> tuple[Matrix, Matrix, Matrix, Matrix]: + require(1 <= f <= 3 and 2 <= r <= 4 and r * f <= 6, "attainer domain") + require(0 <= gain <= 1, "attainer gain") + d, n = 2 ** f, 2 ** (r * f) + child, target = duplicate(tensor(r * f)), duplicate(tensor(f)) + encode, read = zeros(2 * n, 2 * d), zeros(2 * d, 2 * n) + factor = power(A, (r - 1) * f) + reciprocal = scale((factor[0], -factor[1]), gain / norm2(factor)) + for lane in range(2): + for j in range(d): + encode[lane * n + j][lane * d + j] = ONE + read[lane * d + j][lane * n + j] = reciprocal + require(norm2(reciprocal) == gain ** 2 * n / d, "adapter norm product") + return child, target, encode, read + + +def check_attainers() -> dict[str, int]: + cases = columns = tensor_entries = 0 + shapes = ((1, 2), (1, 3), (1, 4), (2, 2), (2, 3), (3, 2)) + for f, r in shapes: + child, target, encode, read = attainer(f, r, F(1)) + raw = matmul(child, encode) + require(matmul(read, raw) == target, "exact projected identity") + d, n = 2 ** f, 2 ** (r * f) + for i in range(n): + for j in range(n): + weight = (i ^ j).bit_count() + direct = mul(power(A, r * f - weight), power(B, weight)) + require(child[i][j] == direct, "independent tensor entry") + require(norm2(direct) == F(1, n), "flat child modulus") + tensor_entries += 1 + for gain in (F(0), F(1, 4), F(1, 2), F(3, 4), F(1)): + scaled_read = [[scale(x, gain) for x in row] for row in read] + projected = matmul(scaled_read, raw) + for h in range(d + 1): + output = plus(projected, bypass(target, gain, h)) + errors = column_errors(output, target) + expected = F(d - h, d) * (1 - gain) ** 2 + require(all(e == expected for e in errors), "sharp error equality") + cases += 1 + columns += len(errors) + return {"attainers": cases, "attainer_columns": columns, + "independent_tensor_entries": tensor_entries} + + +def axis_abs(x: G) -> F: + require(x[0] == 0 or x[1] == 0, "axis-only random adapter coefficient") + return abs(x[0]) + abs(x[1]) + + +def random_adapter(rng: random.Random, rows: int, cols: int) -> Matrix: + out = zeros(rows, cols) + values = ((F(1, 4), F(0)), (F(-1, 4), F(0)), + (F(0), F(1, 4)), (F(0), F(-1, 4))) + for j in range(cols): + for i in rng.sample(range(rows), min(2, rows)): + out[i][j] = rng.choice(values) + return out + + +def check_general_adapters() -> dict[str, int]: + rng = random.Random(7166) + cases = columns = 0 + for f, r in ((2, 2), (2, 3)): + d, n = 2 ** f, 2 ** (r * f) + child, target = duplicate(tensor(r * f)), duplicate(tensor(f)) + alpha = F(1, 2 ** ((r - 1) * f // 2)) + for _ in range(4): + encode = random_adapter(rng, 2 * n, 2 * d) + transposed = random_adapter(rng, 2 * n, 2 * d) + read = [list(row) for row in zip(*transposed, strict=True)] + a_norm = max(sum(axis_abs(row[j]) for row in encode) + for j in range(2 * d)) + b_norm = max(sum(axis_abs(value) for value in row) for row in read) + product = a_norm * b_norm + projected = matmul(read, matmul(child, encode)) + for h in range(d + 1): + shortcut = zeros(2 * d, 2 * d) + for j in range(2 * d): + for i in rng.sample(range(2 * d), h): + shortcut[i][j] = rng.choice((A, B, ONE)) + errors = column_errors(plus(projected, shortcut), target) + bound = F(d - h, d) * max(F(0), 1 - product * alpha) ** 2 + require(all(e >= bound for e in errors), "general lower bound") + cases += 1 + columns += len(errors) + return {"general_adapters": cases, "general_columns": columns} + + +def check_controls() -> dict[str, int]: + child, target, encode, read = attainer(2, 2, F(1, 2)) + projected = matmul(read, matmul(child, encode)) + expected = F(3, 16) + require(all(e == expected for e in column_errors( + plus(projected, bypass(target, F(1, 2), 1)), target)), "control baseline") + wrong_phase = [[mul(x, (F(0), F(1))) for x in row] for row in projected] + require(any(e != expected for e in column_errors( + plus(wrong_phase, bypass(target, F(1, 2), 1)), target)), "phase rejection") + require(any(e != expected for e in column_errors(projected, target)), + "missing bypass rejection") + require(expected < F(1, 4), "wrong support-count rejection") + threshold = [h for h in range(257) if F(256 - h, 256) * F(15, 16) ** 2 <= F(1, 4)] + require(min(threshold) == 184, "exact bypass threshold") + rejected = 0 + for rows, cols in ((0, 1), (1, 0), (129, 1), (1, 129)): + try: + zeros(rows, cols) + except ValueError: + rejected += 1 + require(rejected == 4, "matrix-capacity rejections") + return {"semantic_controls": 3, "capacity_rejections": rejected, + "threshold_supports_enumerated": 257, "half_error_minimum_bypass": 184} + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--receipt", type=Path, help="create a hash-bound receipt; refuse overwrite") + args = parser.parse_args() + counts = check_attainers() | check_general_adapters() | check_controls() + package = Path(__file__).resolve().parent + names = ("verify.py", "README.md", "PROOF.md", "TASK.json", "SOURCES.json", "VERIFY.json") + hashes = {name: hashlib.sha256((package / name).read_bytes()).hexdigest() for name in names} + report = {"status": "PASS_SHARP_APPROXIMATE_NATIVE_FUSION", "counts": counts, + "python": platform.python_version(), "sha256": hashes} + payload = json.dumps(report, indent=2, sort_keys=True) + "\n" + if args.receipt is not None: + with args.receipt.open("x", encoding="utf-8") as stream: + written = stream.write(payload) + require(written == len(payload), "complete receipt write") + print(payload, end="") + + +if __name__ == "__main__": + main()