From b709a6adb6a9543247260900b108166a4d469f6f Mon Sep 17 00:00:00 2001 From: Nick Petalas Date: Tue, 27 Oct 2026 14:43:15 +0000 Subject: [PATCH] feat(research): sharpen conditioned matching-layer interpolation --- .../conditioned-matching-sublayers/README.md | 262 +++++++++++++++ .../SOURCES.json | 36 ++ .../conditioned-matching-sublayers/TASK.json | 80 +++++ .../VERIFY.json | 34 ++ .../conditioned-matching-sublayers/verify.py | 318 ++++++++++++++++++ 5 files changed, 730 insertions(+) create mode 100644 research/conditioned-matching-sublayers/README.md create mode 100644 research/conditioned-matching-sublayers/SOURCES.json create mode 100644 research/conditioned-matching-sublayers/TASK.json create mode 100644 research/conditioned-matching-sublayers/VERIFY.json create mode 100644 research/conditioned-matching-sublayers/verify.py diff --git a/research/conditioned-matching-sublayers/README.md b/research/conditioned-matching-sublayers/README.md new file mode 100644 index 0000000000..52ad64f7d0 --- /dev/null +++ b/research/conditioned-matching-sublayers/README.md @@ -0,0 +1,262 @@ +# Sharp interpolation for conditioned matching layers + +This contribution was produced by Nick Petalas. Apache-2.0. + +## Result and scope + +This resolves a conditioned version of the primitive-alphabet question in Brian / JoyboyBrian's +[PR #4976](https://github.com/CrocSwap/integer-mult-bounds/pull/4976), +[Open next questions](../matching-sublayer-norm/README.md#open-next-questions). +That package supplies the matching-cut identities and the unrestricted +`sqrt(2)` bound. We add a two-sided local gate bound and prove the smaller, +sharp factor + +```text +rho(K) = sqrt(2 K^2 / (1 + K^2)), K >= 1. +``` + +Here K bounds the Euclidean operator norm of every complete gate and its +inverse. The factor is one for unitary layers and strictly below sqrt(2) for +any finite K. The claim type is a scoped written mathematical proof, with exact +finite corroboration. It is neither a finite census theorem nor a complete +multiplication theorem. No supplier admission, new kappa or selected-frontier +change is claimed. + +The sharpness statement concerns an individual adjacent-boundary norm +implication, with arbitrary invertible surrounding operators. We prove all +four implications below. Optimality under additional simultaneous constraints +coupling all four surrounding operators is not claimed. + +## Weighted Gram theorem + +Work over a finite-dimensional complex Hilbert space. Let G be invertible, +let E be an orthogonal projection commuting with G, and put + +```text +H = E G + (I-E), q = K^2, +q^(-1) I <= G* G <= q I, c = q/(1+q). +``` + +For a matching layer, E selects the supports of complete gates. Unused +coordinates carry the identity. The two-sided bound holds for the whole +layer because its gates act on disjoint orthogonal supports. + +Commutation with E also holds for G* and G*G. The following identity proves +the theorem: + +```text +c (I + G*G) - H*H + = [ E (q I - G*G) + (I-E) (q G*G - I) ] / (1+q) + >= 0. (1) +``` + +Each bracketed term is positive semidefinite on its own orthogonal support. +For every matrix A of compatible size, congruence by A and evaluation on a +unit vector therefore give + +```text +||H A||^2 <= c (||A||^2 + ||G A||^2). (2) +``` + +The same proof applied to G* and then adjointed gives + +```text +||A H||^2 <= c (||A||^2 + ||A G||^2). (3) +``` + +In particular, two adjacent bounds at most F imply a partial-layer bound +`rho(K) F`. More generally adjacent bounds a,b imply +`sqrt(q/(1+q)) sqrt(a^2+b^2)`. This improves the corresponding generic +adjacent-boundary sum-of-squares estimate under the added gate hypothesis. + +The proof uses no dimension bound, invertibility of A, rationality condition +or restriction to real coefficients. The finite checker below uses rational +matrices, including realifications of complex matrices. + +## All four matching-cut operators + +Use the predecessor's column convention and complete boundaries + +```text +P1 = G P0, S0 = S1 G. +``` + +At a partial layer let `J = (I-E)G + E`. Since `G=JH=HJ`, the four operators +and applications of (2)-(3) are + +```text +P = H P0: use (2) with G, E, A=P0 +P^-1 = P0^-1 H^-1: use (3) with G^-1, E, A=P0^-1 +S = S1 J: use (3) with G, I-E, A=S1 +S^-1 = J^-1 S1^-1: use (2) with G^-1, I-E, A=S1^-1. +``` + +G^-1 and G* have the same two-sided cap K as G. The two complete neighbors +in each application are exactly the corresponding prefix, suffix or inverse +neighbors. Thus if each pair has a common bound F, all four partial operators +have bound `rho(K) F`. No commutation between E and P0 or S1 is assumed. + +For arbitrary segments whose two endpoints independently have bound +`rho(K) F`, submultiplicativity gives `rho(K)^2 F^2`. +This is an exact-operator implication. It does not count rounding events or +change a stored-component width or fractional grid. + +## Sharpness of the factor + +Fix any real K>=1. In dimension two take + +```text +G = diag(K,1/K), E = diag(1,0), H = diag(K,1), +A_epsilon = [[1,0],[K,epsilon]], epsilon > 0. +``` + +A_epsilon is invertible. Both adjacent norms tend to `sqrt(1+K^2)` as +epsilon tends to zero, while `||H A_epsilon e0|| = sqrt(2) K`. +Consequently no smaller uniform factor than rho(K) can replace it in the +common-F implication, even with invertible surrounding operators and two +scalar matching gates. Adjointing the construction and replacing G by its +inverse gives the same optimal constant in the other three individual +implications. At K=1, equality already follows from the identity layer. + +The finite checker does not approximate singular values. For rational K and +epsilon it upper-bounds both adjacent squared norms by their squared +Frobenius norms and lower-bounds the partial norm on e0. This gives the exact +lower bound + +```text +2 K^2 / (1+K^2+epsilon^2), +``` + +which converges to rho(K)^2. The written limit proves sharpness for every K; +finite witnesses only corroborate it. + +## Unitary and shear alphabets + +For a unitary matching layer, any subset of its whole gates is unitary. +All four partial norms equal their respective neighboring norms. Thus the +unitary butterfly part of the retained alphabet has no interpolation loss. +This statement is about whole gates, including their complex phases. + +For a shear `S_t = [[1,t],[0,1]]`, set u=|t|. Its Gram eigenvalues have +product one and sum `2+u^2`, so its norm and inverse norm both equal + +```text +K_t = (sqrt(u^2+4)+u)/2. +``` + +For any matching of such shears with |t|<=u, the new bound becomes + +```text +rho_t^2 = 2 K_t^2/(1+K_t^2) = 1 + u/sqrt(u^2+4). (4) +``` + +It is sharp even for two copies of the same shear at magnitude u. For u>0, +let v+ and v- be unit right singular vectors of S_u with singular values +K_t and K_t^-1. For `G=S_u direct-sum S_u`, selecting only its first gate, +take `x=(v+, K_t v-)`. The norms of x and Gx both equal `sqrt(1+K_t^2)`; +the partial image has norm `sqrt(2) K_t`. Extend this rank-one input map to +invertible matrices tending to it, as in the preceding construction. +A complex phase of t is removed by diagonal unitary conjugation, so the +same statement holds for complex shears. The u=0 case is the identity. + +For unit shears, (4) is `1+1/sqrt(5)`, strictly below two. An explicit +limiting vector is `(1,phi,phi^2,-phi)`, where `phi=(1+sqrt(5))/2`. +The rational checker uses Fibonacci ratios tending to phi and invertible +extensions. Its gate-cap fixtures use the rational enclosure +`K_t^2 < 21/8` at u=1, rather than claiming floating-point certification of +the irrational endpoint. + +## Evidence and reproduction + +From the repository root, use CPython 3.12 and only the standard library: + +```sh +/Users/nick/git/integer-mult-bounds/.venv/bin/python3.12 -I -W error -B research/conditioned-matching-sublayers/verify.py +/Users/nick/git/integer-mult-bounds/.venv/bin/python3.12 -I -O -W error -B research/conditioned-matching-sublayers/verify.py +/Users/nick/git/integer-mult-bounds/.venv/bin/python3.12 -B scripts/research_package.py --package research/conditioned-matching-sublayers +/Users/nick/git/integer-mult-bounds/.venv/bin/python3.12 -B scripts/check_research_commit.py --package research/conditioned-matching-sublayers --check-source-history +``` + +The direct checker prints a generated JSON receipt binding all five package +files by SHA256. It writes no output files and imports no predecessor code. +Local normal and optimized checks pass 64 matching cases, 512 Gram checks, +512 four-way context checks, 55 diagonal and 13 unit-shear invertible +sharpness witnesses, and 15 rejection controls. These are executed cases, +not a count of distinct equivalence classes. Both registered checks pass. +Its exact Schur-complement PSD check includes zero-pivot rejection. It checks +both sides of (1), PSD, both gate caps, inverse/adjoint/complement variants, +and four-way congruences in dense noncommuting contexts. Fixtures include +rational unitary rotations, real unit shears, and realified complex unit +shears, with whole-gate selections and coordinate permutations. The receipt +enumerates every executed fixture, inequality, witness and rejection control. + +Controls reject malformed inputs, split gates and invalid upper/inverse caps. +They also exhibit a split-unitary failure, a missing-inverse-cap failure, +a false no-loss bound and an undercut sharp factor. These tests corroborate +the new lemma; they do not replay #4976's scientific certificate. + +The missing-inverse-cap example has `G=diag(2,1/4)`, +`H=diag(2,1)` and `A=[[1,0],[7/4,1/100]]`. Its first-column lower bound, +divided by the larger adjacent squared Frobenius norm, exceeds `8/5`. +Thus even an invertible context can violate the proposed K=2 factor when +only the upper gate cap is assumed. + +The implementation bounds matrix dimensions at eight, fixture families at +three, masks at four, contexts at two and witness loops at thirteen. Every +loop has a finite bound. Python/Fraction dynamic allocation is a managed-runtime +deviation from fixed storage. The finite dimensions and fixed rational fixture +generators bound live data. The ten-entry rejection table uses fixed pure +validation callables, a limited indirect-call deviation. All invariant checks +use explicit exceptions and remain active under -O. Warning-strict normal and +optimized commands are registered. No shared configuration is changed. + +## Limitations + +E must commute with G and select complete orthogonal gate supports. Cutting +inside a two-wire gate can violate even the unitary no-loss conclusion. +The inverse cap is needed for (1) and for the sharp common-F claim at general +K. The checker includes counterexamples to dropping these hypotheses. + +No coefficient preparation, multiply/add/round kernel, temporary width, +physical tape execution, supplier invoice or universal multiplier is supplied. +The written proof is not a formal proof-kernel artifact. Independent human +and formal proof-kernel review are unclaimed. Hosted CI is pending at initial +publication. The selected construction and all predecessor files are unchanged. + +## Open next questions + +Can one actual compensated-shear layer use its exact two-sided gate cap to +reduce a complete precision allocation? First extract that layer's coefficients, +compute a certified cap and substitute rho(K) into the same complete caller +budget. The remaining blockers are rounding-event accounting, temporary widths +and source-specific physical costs. A smaller exact operator envelope alone +does not establish a smaller valid production grid. No further construction +search is justified by this lemma alone. + +## Provenance and overlap + +Base `19fdb086ea96af9a9f87936a2b888e10af4ed810`, priority revision 8. +The selected baseline command returned `PASS_RESEARCH_BASELINE_BINDINGS_ONLY`; +no selected scientific replay was run. The original coverage-law-change card +is retained verbatim in TASK.json. Scope changed to a numerical matching-boundary +side result because #4976 poses this precise missing primitive-alphabet step. +It can reduce a precision envelope, without changing productive target credit. + +Credit Brian / JoyboyBrian for #4976, its four matching-cut identities and +explicit open question; Jose Manuel / jmbarrancoml for the retained rational +FFT/Full numerical contracts; Vlado Vojdanovski for matching scheduling; and +Chafik Boukhalfa for phase construction. The Gram-order argument and shear +singular-value calculation use elementary linear algebra. We claim this scoped +refinement and its sharp witnesses, not priority for those background methods. +Source pins are provenance-only. No predecessor implementation is imported. +Armin Pourshafeie / apoursh's #5240 already gives the split-unitary row-splice +warning; it is used here only as a rejection control. Nick Petalas's #4829 +gives absolute cut norms for a particular dirty Toeplitz circuit. The new +quantity here is a conditioned adjacent-boundary interpolation factor; that +earlier circuit theorem and its open caller questions are not extended. + +[Advance CLAIM](https://github.com/CrocSwap/integer-mult-bounds/discussions/1166#discussioncomment-19218968). +Live open PRs, recent account work, the latest handoff comments and active +Discussions were checked before claiming. Searches of merged work and main +used matching/sublayer, the factor's shape and conditioning terms. Coverage is +advisory; unpublished work and every historical diff were not exhausted. diff --git a/research/conditioned-matching-sublayers/SOURCES.json b/research/conditioned-matching-sublayers/SOURCES.json new file mode 100644 index 0000000000..cb611e4e56 --- /dev/null +++ b/research/conditioned-matching-sublayers/SOURCES.json @@ -0,0 +1,36 @@ +{ + "schema_version": 1, + "base_commit": "19fdb086ea96af9a9f87936a2b888e10af4ed810", + "files": [ + { + "path": "certificates/selected-result.json", + "usage": "provenance", + "git_blob": "581f8d87008354eb5b869f7ed9de1317ad837ce8", + "sha256": "2a0220e866417774606e0f991e41b9c1d26b1f43b97857238cf478dbc7d330b5" + }, + { + "path": "docs/research/agent-task-catalog.json", + "usage": "provenance", + "git_blob": "3404fbdd5e7529a0674eef26114b5071e4586cec", + "sha256": "ead6cdc9d0af6d58e8a49744d8ec8c7c15e13d2ba93c276c434bcf9b51b93a81" + }, + { + "path": "research/matching-sublayer-norm/README.md", + "usage": "provenance", + "git_blob": "eb7b8be250b6f23ae30e7e611e651a8fe300ac3e", + "sha256": "ba6754f00779874ec981563101114cf18c03026c18338f37a813abd3fae59d21" + }, + { + "path": "research/matching-sublayer-norm/TASK.json", + "usage": "provenance", + "git_blob": "aebf90f027bd0f30a5782fff63d036ba01c035c8", + "sha256": "1ab1955cc4117fdbb01a3f1b765edf326a1b95b0bf7c2c48004dc117211fe01c" + }, + { + "path": "research/matching-layer-rounding/README.md", + "usage": "provenance", + "git_blob": "99f648abd626c91312ae03dffc41bf307a33176a", + "sha256": "ba0225a7af7aa7547d719831f3122c02af09bd56ae32eb45aecccb2e66d8cbdb" + } + ] +} diff --git a/research/conditioned-matching-sublayers/TASK.json b/research/conditioned-matching-sublayers/TASK.json new file mode 100644 index 0000000000..17e68729ba --- /dev/null +++ b/research/conditioned-matching-sublayers/TASK.json @@ -0,0 +1,80 @@ +{ + "schema_version": 1, + "task_id": "coverage-law-change", + "priority_revision": 8, + "base_commit": "19fdb086ea96af9a9f87936a2b888e10af4ed810", + "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": "Sharp conditioned interpolation at complete-gate matching cuts, with unitary and bounded-shear specializations.", + "scope_change_reason": "The picked target-credit card is changed to a numerical boundary side result posed explicitly in PR #4976. A sharper operator envelope can reduce a precision allowance but earns no productive target credit.", + "bottleneck_link": "A source-motivated precision-interface lemma for matching layers; physical implementation and complete supplier accounting remain separate.", + "budget_minutes": 60, + "stop_rule": "Stop after the first proved strict interpolation improvement and its finite exact corroboration; do not implement a wider caller.", + "outcome": "completed", + "evidence": "Written weighted Gram proof; exact checker passes 64 matching cases, 512 Gram checks, 512 four-way context checks, 55 diagonal and 13 unit-shear invertible witnesses, and 15 rejection controls. Generated stdout receipt binds all five package files.", + "author": "Nick Petalas", + "ai_assistance": "Independent human and formal proof-kernel review are unclaimed.", + "open_questions": [ + { + "question": "Can an actual compensated-shear layer use its certified two-sided gate cap to reduce a complete precision allocation?", + "why_it_matters": "The factor is strictly smaller than sqrt(2) at every finite gate cap.", + "first_step": "Extract one actual layer, certify its gate cap, and substitute rho(K) into the same complete caller budget.", + "blocked_by": "Rounding-event accounting, local temporary widths and source-specific physical costs remain unsupplied." + } + ], + "coordination": { + "claim_url": "https://github.com/CrocSwap/integer-mult-bounds/discussions/1166#discussioncomment-19218968", + "source_pr": 4976, + "source_author": "JoyboyBrian", + "source_head": "8a7e0e9b4a085f4fb47a76700dfe135412b9c4ef", + "upstream_checked_at": "2026-10-27T14:43:15.436386+00:00" + } +} diff --git a/research/conditioned-matching-sublayers/VERIFY.json b/research/conditioned-matching-sublayers/VERIFY.json new file mode 100644 index 0000000000..dd4e76c25b --- /dev/null +++ b/research/conditioned-matching-sublayers/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 weighted Gram identities and PSD, four-way dense contexts, rational sharpness witnesses and hypothesis rejection controls; receipt enumerates counts and hashes all five package files." + }, + { + "argv": [ + "{python}", + "-I", + "-O", + "-W", + "error", + "-B", + "{package}/verify.py" + ], + "timeout_seconds": 120, + "checks": "Exact weighted Gram identities and PSD, four-way dense contexts, rational sharpness witnesses and hypothesis rejection controls; receipt enumerates counts and hashes all five package files." + } + ] +} diff --git a/research/conditioned-matching-sublayers/verify.py b/research/conditioned-matching-sublayers/verify.py new file mode 100644 index 0000000000..f266d1ca5c --- /dev/null +++ b/research/conditioned-matching-sublayers/verify.py @@ -0,0 +1,318 @@ +"""Exact finite corroboration for conditioned matching interpolation. + +The quantified theorem is proved in README.md. This program uses only the +standard library and writes its hash-bound receipt to stdout. +""" + +from fractions import Fraction as F +from hashlib import sha256 +import json +from pathlib import Path +import platform + + +Matrix = tuple[tuple[F, ...], ...] +MAX_DIM = 8 + + +def require(condition: bool, message: str) -> None: + if not condition: + raise ValueError(message) + + +def matrix(rows: list[list[int | F]]) -> Matrix: + n = len(rows) + require(1 <= n <= MAX_DIM, "dimension outside 1..8") + require(all(len(row) == n for row in rows), "matrix must be square") + require(all(type(x) in (int, F) for row in rows for x in row), "nonrational entry") + return tuple(tuple(F(x) for x in row) for row in rows) + + +def identity(n: int) -> Matrix: + require(1 <= n <= MAX_DIM, "dimension outside 1..8") + return tuple(tuple(F(i == j) for j in range(n)) for i in range(n)) + + +def add(a: Matrix, b: Matrix, scale: F = F(1)) -> Matrix: + require(len(a) == len(b), "dimension mismatch") + n = len(a) + return tuple(tuple(a[i][j] + scale * b[i][j] for j in range(n)) for i in range(n)) + + +def scaled(a: Matrix, scale: F) -> Matrix: + return tuple(tuple(scale * x for x in row) for row in a) + + +def transpose(a: Matrix) -> Matrix: + n = len(a) + return tuple(tuple(a[j][i] for j in range(n)) for i in range(n)) + + +def product(a: Matrix, b: Matrix) -> Matrix: + require(len(a) == len(b), "dimension mismatch") + n = len(a) + return tuple(tuple(sum((a[i][k] * b[k][j] for k in range(n)), F(0)) + for j in range(n)) for i in range(n)) + + +def inverse(a: Matrix) -> Matrix: + n = len(a) + unit = identity(n) + rows = [list(a[i] + unit[i]) for i in range(n)] + for col in range(n): + candidates = [i for i in range(col, n) if rows[i][col]] + require(bool(candidates), "singular matrix") + pivot = candidates[0] + rows[col], rows[pivot] = rows[pivot], rows[col] + divisor = rows[col][col] + rows[col] = [x / divisor for x in rows[col]] + for i in range(n): + if i != col: + factor = rows[i][col] + rows[i] = [rows[i][j] - factor * rows[col][j] for j in range(2 * n)] + result = tuple(tuple(row[n:]) for row in rows) + require(product(a, result) == unit, "inverse postcondition") + return result + + +def positive_semidefinite(a: Matrix) -> bool: + """Exact symmetric Schur elimination, including zero pivots.""" + if a != transpose(a): + return False + n = len(a) + rows = [list(row) for row in a] + for k in range(n): + pivot = rows[k][k] + if pivot < 0: + return False + if pivot == 0: + if any(rows[k][j] != 0 for j in range(k + 1, n)): + return False + else: + for i in range(k + 1, n): + for j in range(k + 1, n): + rows[i][j] -= rows[i][k] * rows[k][j] / pivot + return True + + +def gram(a: Matrix) -> Matrix: + return product(transpose(a), a) + + +def projection(n: int, selected: tuple[int, ...]) -> Matrix: + require(len(set(selected)) == len(selected), "duplicate selected coordinate") + require(all(0 <= i < n for i in selected), "selected coordinate outside matrix") + return tuple(tuple(F(i == j and i in selected) for j in range(n)) for i in range(n)) + + +def validate(g: Matrix, e: Matrix, q: F) -> None: + require(type(q) is F and q >= 1, "squared gate cap must be rational and >=1") + require(len(g) == len(e), "dimension mismatch") + unit = identity(len(g)) + require(e == transpose(e) and product(e, e) == e, "not an orthogonal projection") + require(product(g, e) == product(e, g), "projection splits a gate") + require(positive_semidefinite(add(scaled(unit, q), gram(g), F(-1))), "upper cap fails") + require(positive_semidefinite(add(scaled(gram(g), q), unit, F(-1))), "inverse cap fails") + + +def check_gram_bound(g: Matrix, e: Matrix, q: F) -> None: + validate(g, e, q) + unit = identity(len(g)) + other = add(unit, e, F(-1)) + h = add(product(e, g), other) + gg = gram(g) + c = q / (1 + q) + slack = add(scaled(add(unit, gg), c), gram(h), F(-1)) + selected = product(e, add(scaled(unit, q), gg, F(-1))) + unselected = product(other, add(scaled(gg, q), unit, F(-1))) + require(slack == scaled(add(selected, unselected), 1 / (1 + q)), "slack identity fails") + require(positive_semidefinite(slack), "conditioned Gram bound fails") + + +def block_diagonal(blocks: tuple[Matrix, ...]) -> Matrix: + n = sum(len(block) for block in blocks) + require(1 <= n <= MAX_DIM, "block dimension outside 1..8") + rows = [[F(0) for _ in range(n)] for _ in range(n)] + start = 0 + for block in blocks: + for i in range(len(block)): + for j in range(len(block)): + rows[start + i][start + j] = block[i][j] + start += len(block) + return tuple(tuple(row) for row in rows) + + +def rotate_coordinates(a: Matrix, shift: int) -> Matrix: + n = len(a) + order = tuple((i + shift) % n for i in range(n)) + return tuple(tuple(a[i][j] for j in order) for i in order) + + +def dense_context(n: int, seed: int) -> Matrix: + """An explicit invertible context, unrelated to the gate decomposition.""" + rows = [list(row) for row in identity(n)] + for i in range(n): + j = (i + 1) % n + if i != j: + coefficient = F((-1) ** (i + seed), i + seed + 2) + rows[i] = [rows[i][k] + coefficient * rows[j][k] for k in range(n)] + return tuple(tuple(row) for row in rows) + + +def check_contexts(g: Matrix, e: Matrix, q: F) -> int: + unit = identity(len(g)) + h = add(product(e, g), add(unit, e, F(-1))) + hi = inverse(h) + complement = product(g, hi) + complement_inverse = inverse(complement) + c = q / (1 + q) + checks = 0 + for seed in range(2): + p0, s1 = dense_context(len(g), seed), dense_context(len(g), seed + 2) + p1, s0 = product(g, p0), product(s1, g) + triples = ((p0, p1, product(h, p0)), + (transpose(inverse(p0)), transpose(inverse(p1)), + transpose(product(inverse(p0), hi))), + (transpose(s1), transpose(s0), transpose(product(s1, complement))), + (inverse(s1), inverse(s0), product(complement_inverse, inverse(s1)))) + for left, right, partial in triples: + slack = add(scaled(add(gram(left), gram(right)), c), gram(partial), F(-1)) + require(positive_semidefinite(slack), "four-way context bound fails") + checks += 1 + return checks + + +def finite_fixtures() -> dict[str, int]: + rotation = matrix([[F(3, 5), F(-4, 5)], [F(4, 5), F(3, 5)]]) + shear = matrix([[1, 1], [0, 1]]) + # Realification of the complex shear [[1, 3/5+4i/5], [0,1]]. + complex_shear = matrix([[1, 0, F(3, 5), F(-4, 5)], + [0, 1, F(4, 5), F(3, 5)], + [0, 0, 1, 0], [0, 0, 0, 1]]) + families = ((rotation, F(1)), (shear, F(21, 8)), (complex_shear, F(21, 8))) + fixtures = gram_checks = context_checks = 0 + for block, q in families: + g0 = block_diagonal((block, block)) + width, n = len(block), 2 * len(block) + for shift in range(n): + g = rotate_coordinates(g0, shift) + for mask in range(4): + selected = tuple(i for b in range(2) if mask & (1 << b) + for i in range(b * width, (b + 1) * width)) + e = rotate_coordinates(projection(n, selected), shift) + other = add(identity(n), e, F(-1)) + for operator in (g, inverse(g), transpose(g), transpose(inverse(g))): + for projector in (e, other): + check_gram_bound(operator, projector, q) + gram_checks += 1 + context_checks += check_contexts(g, e, q) + fixtures += 1 + return {"matching_fixtures": fixtures, "gram_checks": gram_checks, + "four_way_context_checks": context_checks} + + +def frobenius_squared(a: Matrix) -> F: + return sum((x * x for row in a for x in row), F(0)) + + +def witness_ratio(a: Matrix, g: Matrix, h: Matrix) -> F: + """Lower bound using the first input and upper Frobenius endpoint bounds.""" + partial = product(h, a) + numerator = sum((row[0] ** 2 for row in partial), F(0)) + denominator = max(frobenius_squared(a), frobenius_squared(product(g, a))) + require(denominator > 0, "zero witness") + return numerator / denominator + + +def sharp_witnesses() -> dict[str, object]: + diagonal_checks = 0 + for k in (F(1), F(3, 2), F(2), F(3), F(5)): + q = k * k + target = 2 * q / (1 + q) + previous = F(0) + for power in range(2, 13): + epsilon = F(1, 2 ** power) + a = matrix([[1, 0], [k, epsilon]]) + g = matrix([[k, 0], [0, 1 / k]]) + h = matrix([[k, 0], [0, 1]]) + ratio = witness_ratio(a, g, h) + require(previous < ratio < target, "diagonal witness convergence fails") + require(target - ratio < epsilon * epsilon, "diagonal witness gap fails") + require(product(a, inverse(a)) == identity(2), "witness is not invertible") + previous = ratio + diagonal_checks += 1 + r0, r1 = 1, 1 + shear_checks = 0 + final_ratio = F(0) + g = block_diagonal((matrix([[1, 1], [0, 1]]),) * 2) + h = block_diagonal((matrix([[1, 1], [0, 1]]), identity(2))) + for power in range(2, 15): + r0, r1 = r1, r0 + r1 + r = F(r1, r0) + x = (F(1), r, r * r, -r) + epsilon = F(1, 2 ** power) + a = tuple(tuple(x[i] if j == 0 else epsilon * (i == j) + for j in range(4)) for i in range(4)) + final_ratio = witness_ratio(a, g, h) + require(product(a, inverse(a)) == identity(4), "shear witness is not invertible") + require(final_ratio <= 1 or 5 * (final_ratio - 1) ** 2 < 1, + "unit-shear witness exceeds the exact sharp constant") + shear_checks += 1 + require(final_ratio > F(1447, 1000), "unit-shear sharpness witness too weak") + return {"diagonal_invertible_witnesses": diagonal_checks, + "unit_shear_invertible_witnesses": shear_checks, + "unit_shear_final_ratio_squared_lower_bound": str(final_ratio)} + + +def rejection_controls() -> int: + unit = identity(2) + e = projection(2, (0,)) + swap = matrix([[0, 1], [1, 0]]) + cases = (("cap", lambda: validate(unit, e, F(1, 2))), + ("square", lambda: matrix([[1, 0]])), + ("type", lambda: matrix([[True]])), + ("orthogonal", lambda: validate(unit, matrix([[1, 1], [0, 0]]), F(1))), + ("split gate", lambda: validate(swap, e, F(1))), + ("upper", lambda: validate(matrix([[2, 0], [0, 1]]), e, F(1))), + ("inverse", lambda: validate(matrix([[1, 0], [0, F(1, 2)]]), e, F(1))), + ("singular", lambda: inverse(matrix([[1, 0], [0, 0]]))), + ("duplicate", lambda: projection(2, (0, 0))), + ("outside", lambda: projection(2, (2,)))) + for name, operation in cases: + try: + operation() + except ValueError: + continue + raise ValueError("control accepted: " + name) + require(not positive_semidefinite(matrix([[0, 1], [1, 0]])), "zero-pivot control") + # Splitting a unitary two-wire gate can duplicate a row and cost sqrt(2). + partial = add(product(e, swap), add(unit, e, F(-1))) + require(not positive_semidefinite(add(unit, gram(partial), F(-1))), "split-unitary control") + # An upper cap alone does not justify the new factor at K=2. + a = matrix([[1, 0], [F(7, 4), F(1, 100)]]) + g = matrix([[2, 0], [0, F(1, 4)]]) + h = matrix([[2, 0], [0, 1]]) + require(witness_ratio(a, g, h) > F(8, 5), "missing inverse-cap control") + a = matrix([[1, 0], [2, F(1, 100)]]) + g = matrix([[2, 0], [0, F(1, 2)]]) + require(witness_ratio(a, g, h) > F(159, 100), "undercut constant control") + require(not positive_semidefinite(add(gram(a), gram(product(h, a)), F(-1))), + "zero-loss control") + return len(cases) + 5 + + +def receipt() -> dict[str, object]: + counts = finite_fixtures() + counts.update(sharp_witnesses()) + counts["rejection_controls"] = rejection_controls() + package = Path(__file__).resolve().parent + names = ("README.md", "TASK.json", "SOURCES.json", "VERIFY.json", "verify.py") + hashes = {name: sha256((package / name).read_bytes()).hexdigest() for name in names} + return {"status": "PASS_CONDITIONED_MATCHING_SUBLAYERS", "counts": counts, + "squared_factor": "2*K^2/(1+K^2)", "python": platform.python_version(), + "package_sha256": hashes, + "claim_type": "scoped written proof with exact finite corroboration"} + + +if __name__ == "__main__": + print(json.dumps(receipt(), indent=2, sort_keys=True))