From 13561dbdf4971a7ae0901d2f43df8de3981e94a5 Mon Sep 17 00:00:00 2001 From: Jerry Jiaheng Chen <80299683+CubeJerry@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:07:01 +1100 Subject: [PATCH 1/7] Prove source-bound circulant precision with independent literal-word and cache review --- .../EVIDENCE.json | 93 +++++ .../LICENSE | 201 ++++++++++ .../NOTICE.md | 19 + .../ORIGINS.json | 60 +++ .../PROOF.md | 254 ++++++++++++ .../README.md | 183 +++++++++ .../ROOT-REVIEW.md | 100 +++++ .../SOURCES.json | 54 +++ .../TASK.json | 89 +++++ .../VERIFY.json | 43 ++ .../check_precision.py | 349 ++++++++++++++++ .../evidence/registered-replay.txt | 233 +++++++++++ .../precision.py | 39 ++ .../retained/compiler-engine.py | 258 ++++++++++++ .../retained/compiler-full.py | 243 ++++++++++++ .../retained/product.py | 163 ++++++++ .../retained/root_gate_plan.py | 151 +++++++ .../retained/spectral.py | 97 +++++ .../retained/tensor_word.py | 168 ++++++++ .../review/CROSS-REVIEW.md | 273 +++++++++++++ .../review/FINAL-BOUNDARY.json | 91 +++++ .../review/READ-BOUNDARY.json | 90 +++++ .../review/REVIEW-EVIDENCE.txt | 65 +++ .../review/REVIEW-RECEIPT.json | 18 + .../review/UPSTREAM-PINS.json | 29 ++ .../review/check_review.py | 277 +++++++++++++ .../review/refs/pr7849/COMPOSITE-OUTER.md | 107 +++++ .../review/refs/pr7849/PROOF.md | 54 +++ .../review/refs/pr7849/ROOT-CIRCUIT.md | 51 +++ .../rational-unitary-fft/FULL-PROOF.md | 374 ++++++++++++++++++ 30 files changed, 4226 insertions(+) create mode 100644 research/direct-circulant-production-precision/EVIDENCE.json create mode 100644 research/direct-circulant-production-precision/LICENSE create mode 100644 research/direct-circulant-production-precision/NOTICE.md create mode 100644 research/direct-circulant-production-precision/ORIGINS.json create mode 100644 research/direct-circulant-production-precision/PROOF.md create mode 100644 research/direct-circulant-production-precision/README.md create mode 100644 research/direct-circulant-production-precision/ROOT-REVIEW.md create mode 100644 research/direct-circulant-production-precision/SOURCES.json create mode 100644 research/direct-circulant-production-precision/TASK.json create mode 100644 research/direct-circulant-production-precision/VERIFY.json create mode 100644 research/direct-circulant-production-precision/check_precision.py create mode 100644 research/direct-circulant-production-precision/evidence/registered-replay.txt create mode 100644 research/direct-circulant-production-precision/precision.py create mode 100644 research/direct-circulant-production-precision/retained/compiler-engine.py create mode 100644 research/direct-circulant-production-precision/retained/compiler-full.py create mode 100644 research/direct-circulant-production-precision/retained/product.py create mode 100644 research/direct-circulant-production-precision/retained/root_gate_plan.py create mode 100644 research/direct-circulant-production-precision/retained/spectral.py create mode 100644 research/direct-circulant-production-precision/retained/tensor_word.py create mode 100644 research/direct-circulant-production-precision/review/CROSS-REVIEW.md create mode 100644 research/direct-circulant-production-precision/review/FINAL-BOUNDARY.json create mode 100644 research/direct-circulant-production-precision/review/READ-BOUNDARY.json create mode 100644 research/direct-circulant-production-precision/review/REVIEW-EVIDENCE.txt create mode 100644 research/direct-circulant-production-precision/review/REVIEW-RECEIPT.json create mode 100644 research/direct-circulant-production-precision/review/UPSTREAM-PINS.json create mode 100644 research/direct-circulant-production-precision/review/check_review.py create mode 100644 research/direct-circulant-production-precision/review/refs/pr7849/COMPOSITE-OUTER.md create mode 100644 research/direct-circulant-production-precision/review/refs/pr7849/PROOF.md create mode 100644 research/direct-circulant-production-precision/review/refs/pr7849/ROOT-CIRCUIT.md create mode 100644 research/direct-circulant-production-precision/review/refs/research/rational-unitary-fft/FULL-PROOF.md diff --git a/research/direct-circulant-production-precision/EVIDENCE.json b/research/direct-circulant-production-precision/EVIDENCE.json new file mode 100644 index 0000000000..3430e9c870 --- /dev/null +++ b/research/direct-circulant-production-precision/EVIDENCE.json @@ -0,0 +1,93 @@ +{ + "exact_two_wire_packets": 203, + "odometer": { + "packets": 120, + "records": 2448 + }, + "polynomial_certificate": { + "D_coefficients": [ + 1, + 288, + 584, + 256, + 32 + ], + "stage_difference_coefficients": [ + 1279954, + 3827280, + 4760480, + 3160704, + 1186304, + 238464, + 20000 + ] + }, + "scope": "Exact finite controls and universal written numerical theorem; no full assumption discharge or new kappa.", + "selector": { + "cases": 53, + "examples": [ + { + "address_bits": 1, + "axes": 1, + "new_fractional_bits": 6257, + "old_fractional_bits": 229664, + "public_bits": 30, + "ratio": "229664/6257" + }, + { + "address_bits": 9, + "axes": 2, + "new_fractional_bits": 22068, + "old_fractional_bits": 688620, + "public_bits": 72, + "ratio": "57385/1839" + }, + { + "address_bits": 2048, + "axes": 16, + "new_fractional_bits": 2912487, + "old_fractional_bits": 70304068, + "public_bits": 12288, + "ratio": "70304068/2912487" + }, + { + "address_bits": 1000000, + "axes": 10, + "new_fractional_bits": 1385047587, + "old_fractional_bits": 32793966628, + "public_bits": 6000000, + "ratio": "32793966628/1385047587" + }, + { + "address_bits": 10000000000000000000000000000000000000000, + "axes": 1, + "new_fractional_bits": 13850000000000000000000000000000000000005563, + "old_fractional_bits": 327920000000000000000000000000000000000199928, + "public_bits": 60000000000000000000000000000000000000000, + "ratio": "327920000000000000000000000000000000000199928/13850000000000000000000000000000000000005563" + } + ] + }, + "source_allocator_cases": 60, + "source_hashes": { + "compiler-engine.py": "9e36aee0835e6b1b62997433581f88b5a434ccab8ae43e5c25d1deaaf1ebf653", + "compiler-full.py": "1f42d5f2858564ffb320e54ba6aa29651025491569823e25006bf5862457b803", + "product.py": "29ab6c60f937b7cce58666f5ddd7a921c3197cf72abf91ecca0ff7ad9486850e", + "root_gate_plan.py": "379ca05625076824ac9c2399eac03c1c64c13fecee45ea17f78b8898df57cd2d", + "spectral.py": "ede9c48d34280c9c1c5c332b9434ff666fd321f4a18ffbf1f61b3339339e8ab6", + "tensor_word.py": "36c5a9a0082c9aa3c6cb2d04a9196af8debce0d551a0525975b710018ea02cac" + }, + "status": "PASS_DIRECT_CIRCULANT_PRODUCTION_PRECISION", + "commands": [ + "python3 -I -B research/direct-circulant-production-precision/check_precision.py", + "python3 -I -O -B research/direct-circulant-production-precision/check_precision.py" + ], + "executed_at_utc": "2026-11-23T07:34:49.667200+00:00", + "python": "3.12.14 (main, Aug 25 2026, 14:00:49) [Clang 22.1.3 ]", + "independent_review": "Pending", + "generic_registered_runner": "Not yet executed; this package is staged outside the canonical checkout for parent review and publication.", + "executed_code_sha256": { + "check_precision.py": "61bdeb7adca6d6f90034385eccb972ffde81f4bb9b411faa2076d5a0310d27e7", + "precision.py": "c5a82b4143a951bee14ced731ece4ad1458172d018ec79ba347e119aa33c0fa2" + } +} diff --git a/research/direct-circulant-production-precision/LICENSE b/research/direct-circulant-production-precision/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/research/direct-circulant-production-precision/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/research/direct-circulant-production-precision/NOTICE.md b/research/direct-circulant-production-precision/NOTICE.md new file mode 100644 index 0000000000..fa260ac8ff --- /dev/null +++ b/research/direct-circulant-production-precision/NOTICE.md @@ -0,0 +1,19 @@ +# Attribution and retained source notice + +The six files in `retained/` are byte-identical source excerpts at file level, +with original paths and exact hashes listed in `ORIGINS.json`. They are retained +to authenticate the physical gate layout, phase/grid selector, full allocator +and cached coefficient schedule used by this audit. The sources are provided +under the repository's Apache-2.0 license. + +Ali Romman, with substantial OpenAI Codex assistance, supplied the original +direct circulant Fourier word and coefficient generator in PR #7849. +Jose Manuel (`jmbarrancoml`), with substantial OpenAI Codex assistance, supplied +the retained rational full compiler and phase interface. Chafik Boukhalfa's +certified phase work and Vlado Vojdanovski's compiler and routing work retain +their predecessor credit. Cinna Davis and the native/mixed-rank contributors +remain credited for the separate supplier and recovery interfaces. + +The new precision proof, selector and exact audit were prepared for +Jerry Chen / @CubeJerry with substantial OpenAI assistance. They do not +reassign predecessor credit or assert independent human acceptance. diff --git a/research/direct-circulant-production-precision/ORIGINS.json b/research/direct-circulant-production-precision/ORIGINS.json new file mode 100644 index 0000000000..5f53c8e9e4 --- /dev/null +++ b/research/direct-circulant-production-precision/ORIGINS.json @@ -0,0 +1,60 @@ +{ + "schema_version": 1, + "note": "Frozen exact-source inputs retrieved at the listed commit refs; the checker verifies local Git blob and SHA-256 identities. These copies do not assert predecessor scientific acceptance.", + "files": [ + { + "file": "product.py", + "repository": "aliromman/integer-mult-bounds", + "commit": "3615fd982f2f4dc7172bef6f0dc9a4f77d5ab6dd", + "path": "research/direct-circulant-fourier/product.py", + "git_blob": "6059b6e2cecd125f741d148ba91d32637ef41ac1", + "url": "https://github.com/aliromman/integer-mult-bounds/blob/3615fd982f2f4dc7172bef6f0dc9a4f77d5ab6dd/research/direct-circulant-fourier/product.py", + "sha256": "29ab6c60f937b7cce58666f5ddd7a921c3197cf72abf91ecca0ff7ad9486850e" + }, + { + "file": "root_gate_plan.py", + "repository": "aliromman/integer-mult-bounds", + "commit": "3615fd982f2f4dc7172bef6f0dc9a4f77d5ab6dd", + "path": "research/direct-circulant-fourier/root_gate_plan.py", + "git_blob": "f306aa7fa8e1161caec399ae7f44a8af6a3db486", + "url": "https://github.com/aliromman/integer-mult-bounds/blob/3615fd982f2f4dc7172bef6f0dc9a4f77d5ab6dd/research/direct-circulant-fourier/root_gate_plan.py", + "sha256": "379ca05625076824ac9c2399eac03c1c64c13fecee45ea17f78b8898df57cd2d" + }, + { + "file": "spectral.py", + "repository": "aliromman/integer-mult-bounds", + "commit": "3615fd982f2f4dc7172bef6f0dc9a4f77d5ab6dd", + "path": "research/direct-circulant-fourier/spectral.py", + "git_blob": "57d84e16559f6d2b235a41b6b13abb8a2e076ac6", + "url": "https://github.com/aliromman/integer-mult-bounds/blob/3615fd982f2f4dc7172bef6f0dc9a4f77d5ab6dd/research/direct-circulant-fourier/spectral.py", + "sha256": "ede9c48d34280c9c1c5c332b9434ff666fd321f4a18ffbf1f61b3339339e8ab6" + }, + { + "file": "tensor_word.py", + "repository": "aliromman/integer-mult-bounds", + "commit": "3615fd982f2f4dc7172bef6f0dc9a4f77d5ab6dd", + "path": "research/direct-circulant-fourier/tensor_word.py", + "git_blob": "8bc7bc59957c1d56ae5cfeeec329e60fce02b998", + "url": "https://github.com/aliromman/integer-mult-bounds/blob/3615fd982f2f4dc7172bef6f0dc9a4f77d5ab6dd/research/direct-circulant-fourier/tensor_word.py", + "sha256": "36c5a9a0082c9aa3c6cb2d04a9196af8debce0d551a0525975b710018ea02cac" + }, + { + "file": "compiler-full.py", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/rational-unitary-fft/full.py", + "git_blob": "7f85ad1a89e81b7dfc6b54e7bd9547120e86d5d3", + "url": "https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/rational-unitary-fft/full.py", + "sha256": "1f42d5f2858564ffb320e54ba6aa29651025491569823e25006bf5862457b803" + }, + { + "file": "compiler-engine.py", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/rational-unitary-fft/engine.py", + "git_blob": "e9f2f2b08dc2bc4c646e47dca92059351ca89384", + "url": "https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/rational-unitary-fft/engine.py", + "sha256": "9e36aee0835e6b1b62997433581f88b5a434ccab8ae43e5c25d1deaaf1ebf653" + } + ] +} diff --git a/research/direct-circulant-production-precision/PROOF.md b/research/direct-circulant-production-precision/PROOF.md new file mode 100644 index 0000000000..76e89b74b3 --- /dev/null +++ b/research/direct-circulant-production-precision/PROOF.md @@ -0,0 +1,254 @@ +# A source-bound production precision theorem for direct circulant Fourier words + +**Status: author derivation, awaiting independent cross-review.** This is a local numerical interface theorem. It assumes the retained rational compiler's explicit operator, fragment and layer estimates and the exact represented-input native Hadamard contract. It does not prove the global tape tariff, ownership, compiler closure, or the multiplication theorem. There is no new kappa. + +Canonical base: `e54523517d0f03e58352e647c403a5af3e525a57`. +Primary source: CrocSwap/integer-mult-bounds#7849, Ali Romman's head +`3615fd982f2f4dc7172bef6f0dc9a4f77d5ab6dd`, package `research/direct-circulant-fourier`. +The retained full compiler is Jose Manuel's `research/rational-unitary-fft` at the canonical base. + +## 1. Quantified result + +Let there be `d >= 1` true cyclic axes of orders `2 <= r_i <= t_i = 2^ell_i`, with every `ell_i >= 1`. Put `L = sum ell_i`, and let `p >= 1` be the desired public precision parameter. The two signs use the same precision. Define the following integers: + +``` +E = ceil(1257*L/2) + 2154*d +A = 104*L + 438*d +J = 20000*(d+1)*(max(ell_i)+2)^6 +C = 4*J*(d+1)^2 + d+1 +P = 4*p + A + 2*E + bit_length(C). +``` + +Use `P` in the source's external `Grid`, hence `P+8` as the argument `bits` of `fourier_axis`. Retain the source's certified phase routine, unchanged exact rational root compiler and sixteen-H gate lowering. On represented inputs of maximum complex modulus at most one half, the computed transform differs from the exact original-coordinate Fourier mean, with identity on each local padded block, by strictly less than `2^(-4p)` in each coordinate. + +This includes both private coefficient synthesis and external coefficient/data rounding. The theorem concerns the actual full padded array. It does not infer the theorem from a small diagnostic replay. + +The source's original selector is + +``` +P_old = 4*p + 32768*(L+6*d) + + 4*bit_length(J*(d+1)) + 64. +``` + +Our sufficient selector has linear part +`4*p + 1361*L + 4746*d + (L mod 2)`. +This comparison concerns a sufficient fractional precision, not the minimum precision required by the numerical algorithm, a measured tape speedup, or an exponent improvement. + +The original selector is sufficient as a corollary. Put `q = J*(d+1)` and +`m = bit_length(q)`. Since `q >= d+1`, +`C = (d+1)*(4*q+1) <= 5*q^2 < 2^(2*m+3)`, so +`bit_length(C) <= 2*m+3`. The old selector exceeds the proposed selector by +at least `31407*L + 191862*d + 2*m + 61 - (L mod 2) > 0`. +The argument below also applies to every larger `P`, because all conditioning +and layout envelopes are uniform for `P >= 1` and every charged defect decreases +with `2^(-P)`. + +### Named source contracts + +| Contract used here | Exact source binding | Scope retained | +| --- | --- | --- | +| Fourier/CRT identity and public-grid recovery | PR7849 head above, `PROOF.md` and `COMPOSITE-OUTER.md` | Arbitrary supported composite cyclic orders, correct character and no-wrap hypotheses | +| Root adapter and emitted layout | PR7849 head above, `spectral.py`, `root_gate_plan.py`, `tensor_word.py` | Actual coefficient guard, leading-section admission, pivoted sixteen-H words and odometer | +| Full rational compiler estimates | Canonical base above, `research/rational-unitary-fft/FULL-PROOF.md`, especially (6), (11), (14), (15), and `full.allocation` | Compiler applicability, source-ordered fragments, prefix/inverse-prefix and exact-word defect bounds remain assumptions of this application | +| Certified rational unit phases | Canonical base above, `research/rational-unitary-fft/engine.py`, `Phases.phase` | Every returned phase is unit and lies within its certified target error; the oracle's all-size correctness is inherited | +| Exact native H action | PR7849's inherited represented-input native service | Exactness on sufficiently widened private grids; tariff, storage and private instruction cuts are outside this lemma | + +`ORIGINS.json` authenticates the executable fixtures; `SOURCES.json` pins +the canonical compiler proof and provenance. This proof instantiates the named +contracts rather than treating their implementation assertions as independent +proofs of those contracts. + +## 2. The actual Fourier coefficient producer + +Set `h = bit_length(2*r)` for one axis. In the pinned code, `cap = 1`, `gap_scale = 2*r` and the internal first-column grid is + +``` +b = P + 28 + 4*h, u = 2^(-b). +``` + +The exact-unit rational phase routine receives `b+4` bits and certifies complex phase error at most `u/16`. The lower square root of radius one is exactly one. The rounded circulant column differs from its ideal root column by at most `4*u` per entry (a deliberately weaker version of the direct phase-plus-rounding bound). Thus its operator error is at most `4*r*u`. Since `2^h > 2*r`, + +``` +4*r*u < 2^(-P-30)/r^3 <= 2^(-P-8). +``` + +The ideal root has real part at least `1/(2*r)`. The same inequality gives `4*r*u < 1/(4*r)`, so the actual stored column satisfies strict accretivity at the adapter's declared margin `mu = 1/(4*r)`. The exact Hermitian admission therefore accepts, independently of rounding cancellation. Identity padding has no error. + +Every leading principal section `A_k` of the padded stored root inherits +`Re(A_k) > mu*I`. For any vector `x`, Cauchy–Schwarz gives +`||A_k*x||*||x|| >= Re(x* A_k x) >= mu*||x||^2`. +Thus `||inverse(A_k)||_2 <= 1/mu`. Converting to maximum component +row/column sums costs at most `sqrt(2*k) <= 2*t`. This proves the exact +adapter's uniform leading-section allowance `Q = 2*t/mu = 8*t*r <= 8*t^2`; +it does not infer that allowance merely from invertibility of the full root. + +Every returned phase is exactly unit. Let `delta = u/16`. The rounded entry chirp has error at most `delta+u < 2*u`. The averaged Gauss scalar has error at most `delta`; multiplying by the correction phase and then the chirp gives error at most `3*delta`, because both exact and approximate averaged Gauss scalars have modulus at most one. Its final component rounding adds less than `u`. Hence the exit diagonal also has error less than `2*u`. + +The ideal entry has unit modulus. The ideal exit has modulus `1/sqrt(r)` on the true block and one on the holes. Since `2*u < 1/(2*r)`, every stored entry and exit diagonal and its inverse has norm at most `2*t`. + +The retained full compiler at target `P+8` supplies an exact stored gate word with operator defect at most `2^(-P-8)` against the stored rational root. Its radius argument is `2*t`; no data rounding is included in this exact-word endpoint estimate. Combining with first-column error gives a root-word defect at most `2^(-P-7)` against the ideal unitary root. + +Write the exact stored axis word as `Khat Rhat Rhat Ehat`, and its ideal target as `K R R E`. The ideal factors have norm at most one. The stored root and diagonal factors have norm at most two. The four-term product difference is therefore bounded by + +``` +9*entry_exit_error + 6*root_error + <= (9/256 + 6/128)*2^(-P) + = (21/256)*2^(-P) < 2^(-P). +``` + +Here the common upper bound `entry_exit_error <= 2^(-P-8)` follows immediately from `b = P+28+4*h`. This proves a dimension-independent local exact-word endpoint error; the source's `t^O(1)` envelope is more conservative. + +## 3. Explicit source compiler envelopes + +The source adapter's component bounds obey `lambda <= 4*t` and `Q <= 8*t^2`. For the first bound, the stored root has spectral norm at most `1+4*r*u < 2`, and a component row/column sum is at most `sqrt(2*t)` times that norm. The second is the adapter's literal `2*t/mu = 8*t*r`. + +Consequently `chi = lambda*Q <= 32*t^3`. For `ell >= 1`, induction gives `2^ell >= 2*ell`, so the source displacement allowance satisfies + +``` +r_star = 2*ell+8 <= 5*t. +``` + +Substitute these bounds into the full compiler's equations (6), (11), (14) and (15), as implemented by `full.allocation`: + +``` +B = 256*t^3*chi^12 <= 2^68*t^39 +alpha = 8*r_star*t^2*chi <= 1280*t^6 +K_G = 2*t+64*t^2*chi <= 2050*t^5 +H_star <= (4102*t^5)*(9230*t^6) < 2^26*t^11 +U+1 = lambda+lambda^2*Q+1 <= 133*t^4 +2*Q <= 16*t^2. +``` + +Thus the fragment bound `H = max(H_star,U+1,2*Q)` is at most `2^26*t^11`. Since `max(1,lambda,Q) <= 8*t^2`, the source physical-cut bound is + +``` +K = 2*max(1,lambda,Q)*B*H <= 2^98*t^52. +``` + +The inequality `4102*9230 = 37,861,460 < 2^26` is exact. All the other comparisons use nonnegative monomials and `t >= 2`; they are universal inequalities, not extrapolations of sampled dimensions. + +This also independently validates the source's looser `(64t)^40`, `(64t)^16` and `(64t)^64` bounds for completed approximate prefixes, fragments and physical prefixes respectively. + +## 4. Literal sixteen-H lowering and routing + +An original two-coordinate gate is the ratio of adjacent source prefixes, so the gate and its inverse have norm at most + +``` +L_gate = K^2 <= 2^196*t^104. +``` + +The largest-modulus pivot choice makes both shear ratios have modulus at most one. The two parameters supplied to each three-H identity are `-3` and `3+z` with `|z| <= 1`. Their moduli therefore lie between two and four. Every non-pivot diagonal and its inverse is bounded by 64. A raw H or its inverse is also bounded by 64. The middle pivot and its inverse are bounded by `2*L_gate`. + +Fully expanding both `upper_six` words before joining neighboring diagonals gives 23 diagonal factors and 16 H factors. Exactly one diagonal is the pivot. Therefore every partial product and its inverse, including cuts after a joined diagonal, is bounded by + +``` +64^40 * (2*L_gate). +``` + +This uses a conservative count of 40 ordinary factors; the fully expanded count is 38. Simultaneous pair words are a direct sum, so their norm is the maximum of the pair bounds, with no factor for the number of pairs. + +Completed Beneš switch rows are permutations. A partial switch and its inverse have norm at most four; all earlier completed rows contribute norm one. At a routed matching cut, combine that factor, the current pair-word prefix, and a source compiler prefix. Each lowered root prefix and inverse prefix is bounded by + +``` +4*K*64^40*(2*K^2) <= 2^537*t^156. +``` + +Across two roots and both external diagonals, every exact one-axis prefix and inverse prefix is therefore bounded by + +``` +(2*t)^2 * (2^537*t^156)^2 = 2^1076*t^314. +``` + +The axis programs may finish at different times. Exact tensor factors on distinct axes commute, so any global external prefix is the tensor product of one prefix for each axis. Sequential width classes and complete packs do not multiply the number of prefixes for an axis. To retain a conservative allowance for a partially completed tensor-H pack, permit one additional factor `2^d` at each end of an interval. This concerns cuts in the external H schedule; the literal native service's private arithmetic remains governed by its inherited exact represented-input contract. + +The two-norm of a global interval is at most + +``` +2^(2154*d + 628*L). +``` + +For a `T = 2^L` coordinate array, a matrix's infinity operator norm is at most `sqrt(T)` times its spectral norm. Hence every external exact-word interval is Lipschitz with constant `2^E`, where + +``` +E = ceil(1257*L/2) + 2154*d. +``` + +## 5. Coefficient odometers and local data errors + +Every single exact scalar factor of an axis's joined diagonal is bounded by the partial-word estimate without the preceding source prefix: + +``` +b_i = 2^437*t_i^104 >= 1. +``` + +This also bounds the entry and exit scalars and all routing scalars. Put `F = product b_i = 2^(437*d+104*L)` and external grid step `v = 2^(-P)`. + +Each individual rounded complex factor differs by at most `v` and has modulus at most `2*b_i`. The difference of products, together with at most `d-1` rounded suffix multiplications, bounds the error in any computed coefficient by `2*d*2^d*F*v`. This estimate permits zero factors and uses no division by a prior table entry. + +The odometer does not accumulate this error over the length of a tensor scan. At every write, suffix `k` is the rounded product of the current factors with indices at least `k`; a carry changes indices `0,...,j`, recomputes suffixes `j,...,1`, and leaves every higher suffix with its unchanged arguments. Induction on carries proves that each retained suffix is built from at most `d` factors and at most `d-1` multiplications, irrespective of how many records were already visited. + +The final multiplication by a represented data value adds at most `v` absolute complex error. Since `2*d+1 <= (d+1)^2`, its local defect is bounded by + +``` +epsilon*(1 + ||z||_infinity), +epsilon = (d+1)^2 * 2^(-P+A), +A = 104*L + 438*d. +``` + +A native H is exact on represented words under the inherited service contract. Any charged return conversion with one component rounding is also covered by this local envelope. Widening its private exact grid to cover the known integer radius is a separate retained service premise, not an uncharged assumption of this proof. + +## 6. Source-specific stage count + +At width `ell`, the full compiler has at most + +``` +D(ell) = 1 + 2*ell*(2*ell+8)*(8*ell^2+32*ell+18) + = 32*ell^4+256*ell^3+584*ell^2+288*ell+1 +``` + +matching layers. `local_schedule` emits 17 diagonal/H entries for a lowered matching plus two directions of `2*ell-1` switches, each with three entries: at most `12*ell+11` external entries per matching. Count each entry's diagonal and optional exact H as **separate mathematical steps**, so a pre-H rounding error is propagated by the interval bound. There are at most two steps per entry, two root passes, at most `d` nonempty packs, and one entry and one exit diagonal. Therefore + +``` +J_actual <= 2 + 4*d*D(ell_max)*(12*ell_max+11) + <= 20000*(d+1)*(ell_max+2)^6 = J. +``` + +The last inequality follows by coefficient comparison of polynomials with nonnegative coefficients. This bound counts the literal schedule's diagonals and H calls separately, including the no-H diagonal entries. H steps have zero local defect under the retained native contract; charging them the same envelope only increases the budget. This is not the sharper polylogarithmic time count used by the outer complexity proof. + +## 7. Endpoint bias and closing the bootstrap + +Section 2 gives local exact-word endpoint error below `2^(-P)`. Every ideal local endpoint has spectral norm at most one and every stored endpoint norm at most two. The tensor product difference is bounded by `d*2^(d-1)*2^(-P)` in spectral norm. On a maximum-norm half-disk input, the coordinate error is at most that quantity times `sqrt(T)/2`. Thus the exact stored tensor word has endpoint synthesis bias at most + +``` +beta = (d+1)*2^(-P+E). +``` + +For external execution use the retained bootstrap theorem with `M = R = 2^E`, local defect `epsilon` from Section 5, and at most `J` stages. Its budget and total raw error are bounded by + +``` +J*M*epsilon = J*(d+1)^2*2^(-P+A+E), + +J*M*epsilon*(2+2*R) + beta + <= [4*J*(d+1)^2 + d+1]*2^(-P+A+2*E) + = C*2^(-P+A+2*E). +``` + +For the proposed `P`, the last expression is strictly below `2^(-4p)` because `C < 2^bit_length(C)`. The bootstrap spend is strictly below `2^(-4p-E)/4 <= 1/4`, since `4*J*(d+1)^2 < C`. In particular it is below one half, so the bootstrap is valid without circularly assuming a bound on the computed state. + +Conjugating the word and its input gives the opposite sign with identical norms and errors. No symmetry of the component tie-breaking rule is needed. + +## 8. Exact product recovery and limits + +If the remaining source hypotheses hold — pairwise coprime true sides, true volume `S <= B`, no cyclic wrap, radix digit scale `4B`, `p = 6*log2(B)`, `B >= 32`, correct CRT character, and the public toward-zero conversions — the proved raw bound is exactly the input to the source's public-grid recovery theorem. Its final integer error is at most `144/B^2 < 1/2`. This corollary uses the source recovery theorem and exact native contracts; it is not an independent complete multiplier proof. + +All five canonical assumptions retain their selected status. This package provides a source-specific numerical lemma and a smaller sufficient fractional-grid selector. It does not change selected source files, admit pending suppliers, assert a practical crossover, or claim proof-kernel verification. + +## Open next questions + +1. Independently cross-review the literal source-to-constant bindings and the odometer induction. A wrong stage or omitted factor invalidates this application even if the scalar bootstrap arithmetic passes. +2. Join the improved selector to a source-specific all-size private-grid/owned-arena theorem. The external error bound alone is not the literal tape storage proof. +3. Tighten or formally certify the inherited full compiler's source physical-cut estimates. This contribution uses those exact estimates rather than re-proving the full compiler. + +## Credit + +Ali Romman supplied the direct circulant construction, its all-moduli Fourier/CRT and grid interfaces, coefficient generator and original precision selector. Jose Manuel (`jmbarrancoml`) supplied the rational unitary/full compiler and polynomial physical-cut estimates. Vlado Vojdanovski supplied the displacement and tensor matching compiler; Chafik Boukhalfa supplied the certified phase routine. Cinna Davis and the credited mixed-rank/native contributors supplied the inherited supplier and recovery chain. Prepared for Jerry Chen / `@CubeJerry` with substantial OpenAI assistance. Separate model-assisted review, when recorded, is not human or proof-kernel acceptance. diff --git a/research/direct-circulant-production-precision/README.md b/research/direct-circulant-production-precision/README.md new file mode 100644 index 0000000000..b0a122a5dd --- /dev/null +++ b/research/direct-circulant-production-precision/README.md @@ -0,0 +1,183 @@ +# An explicit production precision bound for the direct circulant Fourier word + +This package derives a smaller sufficient external precision for the exact +source word in [#7849](https://github.com/CrocSwap/integer-mult-bounds/pull/7849). +It connects the retained compiler's physical prefix and inverse-prefix bounds, +the actual sixteen-H lowering and cached diagonal implementation, and the +state-relative rounding bootstrap. The result is a **local analytic interface +theorem under named source contracts**, with exact finite controls. No full +framework assumption is removed, and there is **no new kappa**. + +## Result + +For public precision `p`, `d` axes, binary widths `ell_i >= 1`, and +`L = sum ell_i`, define + +``` +E = ceil(1257 L / 2) + 2154 d +A = 104 L + 438 d +J = 20000 (d+1) (max ell_i+2)^6 +C = 4 J (d+1)^2 + d+1 +P = 4p + A + 2E + bit_length(C). +``` + +Using `P` fractional bits in the source external grid, and its unchanged +`P+8` coefficient-construction call, gives raw transform error strictly below +`2^(-4p)` on every represented half-disk input. The two signs and the entire +padded tensor are covered. The corollary to the source public-grid theorem +retains its final integer error bound `144/B^2 < 1/2` for `B >= 32`. + +The proof supplies three separate interfaces: + +1. **Actual source intervals.** The full compiler's explicit constants give + physical prefixes and inverses at most `2^98 t^52`. The routed sixteen-H + word raises this to `2^537 t^156` per root, and both roots and diagonals + to `2^1076 t^314` per axis. Complete-factor norms alone are not used to + control a partial interval. +2. **Local rounding.** Each diagonal coefficient comes from at most `d` + current-coordinate factors. An odometer induction prevents rounding error + from accumulating with the number of tensor records. Its state-relative + defect is at most `(d+1)^2 2^(-P+A)(1+norm(z))`. +3. **Strict numerical budget.** The displayed selector makes both the + noncircular bootstrap spend and the final raw-error inequality strict. + +The exact stored one-axis word also has synthesis error below `2^(-P)`, +instead of needing a dimension-dependent polynomial envelope for that step. +See [PROOF.md](PROOF.md) for quantifiers, all constants and inherited premises. + +The old source selector has leading term `4p+32768(L+6d)`. The new selector +has leading term `4p+1361L+4746d+(L mod 2)`. For example: + +| Public bits | Axis widths | Old sufficient fractional bits | New sufficient fractional bits | +| ---: | --- | ---: | ---: | +| 72 | 4, 5 | 688,620 | 22,068 | +| 12,288 | sixteen widths of 128 | 70,304,068 | 2,912,487 | +| 6,000,000 | ten widths of 100,000 | 32,793,966,628 | 1,385,047,587 | + +These are exact precision-selector comparisons, not full transform executions, +measured memory or runtime gains, or minimum-precision claims. +The original source selector is larger for every supported input, by an explicit +integer comparison in the proof, so the same theorem also validates its numerical +budget under the named contracts. + +## Reproduction and evidence + +From the repository root: + +```sh +python3 -B scripts/research_package.py --package research/direct-circulant-production-precision +``` + +For a source export without Git: + +```sh +python3 -I -B research/direct-circulant-production-precision/check_precision.py +python3 -I -O -B research/direct-circulant-production-precision/check_precision.py +``` + +Both direct commands finish with `PASS_DIRECT_CIRCULANT_PRODUCTION_PRECISION` +and produce identical evidence. They check an exact positive-coefficient +polynomial certificate for the full schedule count; 60 bindings to the pinned +allocator; 203 exact two-wire words through a separate rational matrix +interpreter; 120 odometer packets containing 2,448 records against fresh +current-coordinate evaluation; and 53 selector inputs, including address +widths too large to materialize. Negative controls cover corrupted source +bytes, a middle-diagonal phase, omitted inverse-prefix reasoning, a stale +cached suffix, a missing column guard, and undercharged precision envelopes. + +The universal theorem uses the written inequalities. The finite packets are +not an exhaustive verification of arbitrary matrices, widths, inputs or the +complete multiplier. `EVIDENCE.json` records executed checks and review status. + +## Source pins, scope and novelty + +Canonical base is `e54523517d0f03e58352e647c403a5af3e525a57`. +The direct-circulant source is frozen at +`3615fd982f2f4dc7172bef6f0dc9a4f77d5ab6dd` in +`aliromman/integer-mult-bounds`. The six small code copies in `retained/` +are exact scientific inputs, not another copy of the predecessor package. +`ORIGINS.json` lists their repository paths, exact commits, Git blob IDs and +SHA-256 digests. The standalone verifier authenticates those bytes before +extracting named functions. `SOURCES.json` separately preserves the canonical +task and selected-result provenance. The result concerns these frozen words; +later compiler or phase changes need a new applicability check. + +The predecessor supplied the construction, its original generous selector, +the public-grid recovery theorem and diagnostic product checks. This package +adds a source-specific independent constant derivation, a sharper local endpoint +bound, the resulting smaller selector, and independent failure-sensitive +checks of the emitted word and coefficient-cache semantics. It does not repeat +the previously reported failure of a low diagnostic precision as a failure of +the production selector. + +The scope is historical and source-specific. Later +[#7981](https://github.com/CrocSwap/integer-mult-bounds/pull/7981), pinned at +`9585c1fa2ed5f2316ac09e04b357cb720badfcb8`, changes the chronology by completing +and normalizing each pack, and weakens the intermediate raw target from +`2^(-4p)` to `2^(-p)/8`. Its +[numerical proof](https://github.com/aliromman/integer-mult-bounds/blob/9585c1fa2ed5f2316ac09e04b357cb720badfcb8/research/triangular-native-supplier/NUMERICAL-STORAGE.md) +therefore gives a different and asymptotically smaller precision selector. The +present selector is not an improvement over that successor. That successor still +cites #7849 for local root and interval estimates; the sharper source binding here +is reusable evidence for that inherited interface, subject to a separate check of +the changed pack schedule and caller. Searches of PR bodies for `7849` and +`circulant precision` also inspected #7868, #7914 and #8030. This is a bounded +overlap check, not proof that no unpublished or unindexed duplicate exists. + +The retained full compiler estimates, certified phase service, exact native +Hadamard action on widened represented grids, outer CRT geometry and recovery +theorem remain named dependencies. No all-size private-tape storage proof, +native tariff, ownership implementation, selected-certificate edit, full +assumption removal, practical crossover or proof-kernel acceptance is claimed. +`precision.py` provides the candidate replacement selector without modifying +the frozen predecessor. + +## Open next questions + +1. Obtain external mathematical assessment of the source gate/layout bindings + and coefficient-cache induction. The included separate task-agent review + accepts the frozen corrected proof; adoption remains an upstream decision. +2. Join this external grid to a source-specific all-size private-grid and arena + theorem. That requires the exact native representation and ownership + contracts; a numerical endpoint estimate alone does not supply them. +3. Independently review or formalize the retained full compiler's physical-cut + estimates used here. The present proof instantiates those estimates rather + than re-proving the whole compiler. + +The structured first steps and blockers are in `TASK.json`. + +## Credit + +Prepared for Jerry Chen / @CubeJerry with substantial OpenAI assistance. +Ali Romman supplied [#7849](https://github.com/CrocSwap/integer-mult-bounds/pull/7849) +and its [#7846](https://github.com/CrocSwap/integer-mult-bounds/pull/7846) +native/recovery integration. Jose Manuel (`jmbarrancoml`) supplied the retained +rational full compiler and conditioning estimates; Vlado Vojdanovski supplied +the displacement and tensor matching compiler; Chafik Boukhalfa supplied the +certified phase routine; Cinna Davis and the credited mixed-rank/native +contributors supplied the inherited supplier and recovery chain. Source notices +are preserved. Model-assisted cross-review, when recorded, is distinct from +human peer review and proof-kernel verification. Apache-2.0. + +## Completed separate review + +[review/CROSS-REVIEW.md](review/CROSS-REVIEW.md) accepts the local conditional +numerical theorem at proof SHA256 +`26e4e214f0a5785c1d1414561465bb49a3248f9e6f59f6b514eb95a887bdfe2f`. +The author proof retains its original pre-review label for byte identity; +this later review and ROOT-REVIEW.md record the completed disposition. +A fully expanded lowering contains 23 diagonals and 16 H factors, with 38 +non-pivot factors. This corrects two prose counts; the conservative 64^40 +envelope and every selector constant were unchanged. + +The independent reviewer uses a new Gaussian-rational matrix interpreter for +600 words across all four pivots, and noncommutative expression trees for +1,214 coefficient-cache records. Two mutation controls reject a wrong sign +and a stale carried suffix. The author checker is not reused as independent +evidence. The registered third command runs this separate oracle. + +Scientific source copies and frozen proofs are self-contained. Top-level +SOURCES.json pins canonical provenance; ORIGINS.json authenticates the six +executable fixtures. Review source citations, read hashes and receipts are +retained under review/. No complete multiplier or private-tape proof is +claimed by this publication. diff --git a/research/direct-circulant-production-precision/ROOT-REVIEW.md b/research/direct-circulant-production-precision/ROOT-REVIEW.md new file mode 100644 index 0000000000..beca86cb7b --- /dev/null +++ b/research/direct-circulant-production-precision/ROOT-REVIEW.md @@ -0,0 +1,100 @@ +# Orchestrator review of the local precision theorem + +Accept the stated source-specific numerical implication under its named +compiler, phase and exact native-service contracts. The proof does not +discharge any whole canonical assumption and does not improve kappa. + +The frozen accepted proof has SHA256 +`26e4e214f0a5785c1d1414561465bb49a3248f9e6f59f6b514eb95a887bdfe2f`. +Its original pre-review status is retained for byte identity. The later +separate acceptance is in `review/CROSS-REVIEW.md`. + +## Critical boundaries + +I checked the complete proof and separate review. The leading-section bound +comes from strict accretivity of the actual rounded stored root, not just +invertibility of its full matrix. The full compiler's fragment and inverse +estimates remain explicit premises. An interval is controlled using both +its prefix and inverse prefix; endpoint conditioning alone would not suffice. + +The literal lowering has 23 diagonal factors and 16 H factors, including +38 non-pivot factors. The corrected count remains inside the conservative +`64^40` allowance. The data-error recurrence treats the diagonal and H of +an emitted entry as separate steps, so a newly rounded diagonal error is +propagated through the subsequent H. An H itself is exact only under the +stated widened-grid native-service premise. + +At each odometer write, the cached suffix is an expression in the current +coordinate factors. A carry rebuilds the changed suffix and retains only +suffixes with unchanged arguments. Thus the number of rounded operations +behind one coefficient depends on the number of axes, not the number of +previously visited tensor records. The independent noncommutative oracle +tests this dependency directly rather than relying on numerical cancellation. + +With `M=R=2^E` and +`epsilon=(d+1)^2 2^(-P+A)`, the proposed selector gives both the strict +bootstrap spend and +`C 2^(-P+A+2E) < 2^(-4p)`, since `C < 2^bit_length(C)`. +The computed-state bound is consequently a conclusion of the bootstrap. +The exact tensor endpoint bias is separately charged. Opposite-sign +execution uses input/output conjugation, an isometry; it does not require +the component-rounding rule to be odd. + +The recovery corollary retains the true volume, CRT character, no-wrap, +digit scaling, public-grid conversions and native-service hypotheses. +The final scalar inequality `144/B^2 < 1/2` alone would not establish those +interfaces. In particular, this package is not an independent proof of the +full direct-circulant multiplier. + +## Executed publication checks + +The orchestrator ran the registered three-command replay with CPython 3.12. +The normal and optimized author executions passed, as did the separately +authored Gaussian-rational and noncommutative lineage checks. The complete +registered output is retained in `evidence/registered-replay.txt`. + +```sh +python3 -B scripts/research_package.py --package research/direct-circulant-production-precision +``` + +Expected final marker: +`PASS_REGISTERED_RESEARCH_PACKAGE research/direct-circulant-production-precision outcome=completed`. + +The author evidence includes 203 two-wire words, 2,448 odometer records, +60 allocator bindings and 53 selector inputs. The independent reviewer +checks 600 words across all pivots and 1,214 noncommutative records. Both +paths contain meaningful rejection controls; rerunning the author's checker +is not relabelled as independent reasoning. The universal inequalities are +the written proof, not an extrapolation from these finite examples. + +The source export preserves six exact executable fixtures with Git blob and +SHA256 pins, canonical provenance, source-proof citations and review hashes. +The main proof, compiler estimates and source artifacts are unchanged by +publication integration. Strict source-history preflight is not claimed +from the shallow checkout. No complete selected replay, production-sized +transform, private-tape proof or full multiplier kernel proof was run. + +## Novelty and remaining work + +Ali Romman's #7849 supplies the direct construction and original generous +selector. This package gives a smaller sufficient selector for that same +chronology and the same strict raw error target, while proving the old +selector sufficient as a corollary. #7981 changes the chronology and target +and has an asymptotically smaller selector. This is explicitly not an +improvement over that successor. The source-local root and interval bounds +remain reusable evidence only after checking a successor's changed caller. + +The outstanding substantive step is to connect the external error/radius +contract to all-size private-grid storage, backing and native tariffs. +The retained full compiler estimates and exact phase service also remain +named hypotheses. No selected certificate or accepted bound is changed. + +Hosted CI success is not claimed: the unchanged canonical base has a +preflight documentation mismatch between #6030 in `docs/ci.md` and #7000 +in the selected record, observed on #8091 before research package selection. +The local registered replay is the executed scientific evidence. + +Prepared for Jerry Chen / @CubeJerry with substantial OpenAI assistance. +The author, reviewer and orchestrator were separate model task roles; +this is not independent human peer review. All predecessor credit in +README.md, the proof and source notices is retained. diff --git a/research/direct-circulant-production-precision/SOURCES.json b/research/direct-circulant-production-precision/SOURCES.json new file mode 100644 index 0000000000..035f4892cf --- /dev/null +++ b/research/direct-circulant-production-precision/SOURCES.json @@ -0,0 +1,54 @@ +{ + "schema_version": 1, + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "files": [ + { + "path": "AGENTS.md", + "usage": "provenance", + "git_blob": "ff81117fca368042f6092964d1f54eb4e6e08fb9", + "sha256": "fece32cdec9c1572ddce354a0b623459cb2c4ca162125d36d36262a92e3caa83" + }, + { + "path": "autoresearch.md", + "usage": "provenance", + "git_blob": "2fe84a7b30b1e26e60ce0ec4775894eb1831c5d6", + "sha256": "d16f0d3bb4d4b213d06c128db6d6460b0fe9ec1ac5a6c1ea1febf1db40e7b60d" + }, + { + "path": "CONTRIBUTING.md", + "usage": "provenance", + "git_blob": "5185786f2ec00f215019fb5777d70979429690a9", + "sha256": "fcd1a8d0e52342a23b8ffa9e905e85ccc539fb084145ef016dfc93cedfb3d924" + }, + { + "path": "docs/research/agent-task-catalog.json", + "usage": "provenance", + "git_blob": "3404fbdd5e7529a0674eef26114b5071e4586cec", + "sha256": "ead6cdc9d0af6d58e8a49744d8ec8c7c15e13d2ba93c276c434bcf9b51b93a81" + }, + { + "path": "certificates/selected-result.json", + "usage": "provenance", + "git_blob": "75d77b328ea02ded535e7f23aee5b1e55d0bb1a8", + "sha256": "154c3d30455d778fd3343b6b4851f0fa4665f0f7625b0adb3675e2bafbbf6bf1" + }, + { + "path": "research/rational-unitary-fft/FULL-PROOF.md", + "usage": "provenance", + "git_blob": "e650f46863115f810e27b403f916dd7f79b37786", + "sha256": "acf8c596d91b5efd35a286735d6867ff8afce64354a13f680c2fae3dab824410" + }, + { + "path": "research/rational-unitary-fft/full.py", + "usage": "provenance", + "git_blob": "7f85ad1a89e81b7dfc6b54e7bd9547120e86d5d3", + "sha256": "1f42d5f2858564ffb320e54ba6aa29651025491569823e25006bf5862457b803" + }, + { + "path": "research/rational-unitary-fft/engine.py", + "usage": "provenance", + "git_blob": "e9f2f2b08dc2bc4c646e47dca92059351ca89384", + "sha256": "9e36aee0835e6b1b62997433581f88b5a434ccab8ae43e5c25d1deaaf1ebf653" + } + ] +} diff --git a/research/direct-circulant-production-precision/TASK.json b/research/direct-circulant-production-precision/TASK.json new file mode 100644 index 0000000000..c881512623 --- /dev/null +++ b/research/direct-circulant-production-precision/TASK.json @@ -0,0 +1,89 @@ +{ + "schema_version": 1, + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "task_id": "uniform-transfer-audit", + "original_card": { + "id": "uniform-transfer-audit", + "question": "Can one of the selected record's five inherited assumptions be proved at its actual caller?", + "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": "Identify the proposition and what would change downstream; do not equate a finite replay with a universal proof.", + "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": "Choose one assumption ID (native_all_columns, owned_erasure, compiler, precision_tape, analytic_recovery), one quantified implication and exact dependency closure. Check current handoffs, including #5625 row reentry and #5707 root-prefix lowering, without treating their partial scope as the whole theorem. Prove or falsify that implication with a caller-bound argument; stop at the chosen obligation. Finite tests or root digits do not discharge an all-size statement.", + "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": [ + "native_all_columns", + "owned_erasure", + "compiler", + "precision_tape", + "analytic_recovery" + ], + "existing_checks": [ + { + "scope": "PR #4100: proposed unconditional construction and finite checks, without independent acceptance.", + "evidence": "research/unconditional-batched-crt/README.md", + "remaining": "Independent proof audit of one caller-bound all-size implication; all other premises remain explicit.", + "status": "author-checked", + "source_commit": "337d04939571a637aeab54a0f58f54fde811663a", + "selected_record_sha256": "bb2eaa58647b353f88d0aec2eafb9d30df1be53589231b23e12ceef3e4bad129" + }, + { + "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": "refined", + "scope_change_reason": "The assigned exact source is pending PR7849 rather than the selected supplier. The chosen analytic_recovery implication is the production fractional-grid bound for its emitted circulant word; no full canonical assumption is discharged.", + "actual_scope": "Prove a source-bound sufficient production precision for PR7849 on arbitrary supported composite cyclic axes, including rounded accretivity, partial routed gate words, coefficient odometer defects and the strict raw-error recovery threshold.", + "bottleneck_link": "The numerical contract connects the actual direct-circulant source word to its public-grid integer-recovery theorem. The complete compiler, native service and tape/ownership contracts remain dependencies.", + "stop_rule": "Stop after a reusable exact lemma and failure-sensitive controls, or after 65 minutes without a new discriminating idea. Do not expand into compiler closure or native tape storage.", + "outcome": "completed", + "evidence": "PROOF.md; accepted separate review/CROSS-REVIEW.md; normal and optimized exact author checks; independent literal-word and noncommutative cache-lineage checks.", + "author": "Jerry Chen / @CubeJerry", + "ai_assistance": "Substantial OpenAI ChatGPT assistance in derivation, code, verification and writing; model-assisted review is distinct from human or proof-kernel acceptance.", + "open_questions": [ + { + "question": "Does the improved external grid fit a source-specific all-size private-grid and owned-arena theorem?", + "why_it_matters": "A numerical error bound alone does not prove the native tape tariff or ownership contract.", + "first_step": "Bind the external interval and radius bounds to the exact native caller and its widened represented-input grid.", + "blocked_by": "The inherited native/private-grid implementation and ownership contracts require a separate proof audit." + }, + { + "question": "Can the retained full compiler physical-cut and inverse-cut estimates be independently certified or tightened?", + "why_it_matters": "They are the strongest inherited analytic premise of this local application.", + "first_step": "Review FULL-PROOF.md equations (6), (11), (14) and (15), preserving source-ordered active fragments and inverse prefixes.", + "blocked_by": "This contribution intentionally does not re-prove the full rational compiler." + } + ], + "priority_revision": 8, + "budget_minutes": 65 +} diff --git a/research/direct-circulant-production-precision/VERIFY.json b/research/direct-circulant-production-precision/VERIFY.json new file mode 100644 index 0000000000..2924a6c166 --- /dev/null +++ b/research/direct-circulant-production-precision/VERIFY.json @@ -0,0 +1,43 @@ +{ + "schema_version": 1, + "status": "ready", + "python": "3.12", + "requirements": [], + "inputs": [], + "commands": [ + { + "argv": [ + "{python}", + "-I", + "-B", + "{package}/check_precision.py" + ], + "timeout_seconds": 60, + "checks": "Authenticate retained source; exact polynomial/allocator, two-wire, odometer and selector controls including negative mutations." + }, + { + "argv": [ + "{python}", + "-I", + "-O", + "-B", + "{package}/check_precision.py" + ], + "timeout_seconds": 60, + "checks": "Repeat the same mathematical and rejection controls with assertions disabled." + }, + { + "argv": [ + "{python}", + "-I", + "-W", + "error", + "-B", + "{package}/review/check_review.py", + "{package}" + ], + "timeout_seconds": 90, + "checks": "Separate Gaussian-rational literal-word and noncommutative cache-lineage oracle; universal schedule polynomial and meaningful sign/stale-cache controls." + } + ] +} diff --git a/research/direct-circulant-production-precision/check_precision.py b/research/direct-circulant-production-precision/check_precision.py new file mode 100644 index 0000000000..24b86fdd59 --- /dev/null +++ b/research/direct-circulant-production-precision/check_precision.py @@ -0,0 +1,349 @@ +#!/usr/bin/env python3 +"""Exact checks for the explicit production-precision proof. + +Universal conclusions use PROOF.md. The finite controls bind that proof to the +source word, exercise a separate rational matrix interpreter, and expose omitted +inverse cuts, stale odometer suffixes and undercharged error envelopes. +""" + +import ast +from dataclasses import asdict, dataclass +from fractions import Fraction as Q +from hashlib import sha1, sha256 +from itertools import product +import json +from math import comb, prod +from pathlib import Path +from random import Random +import sys + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from precision import precision_budget + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def git_blob(data): + return sha1(b"blob " + str(len(data)).encode() + b"\0" + data).hexdigest() + + +def authenticate(): + manifest = json.loads((HERE / "ORIGINS.json").read_text()) + hashes = {} + for row in manifest["files"]: + data = (HERE / "retained" / row["file"]).read_bytes() + require(git_blob(data) == row["git_blob"], "Source Git blob drift: " + row["file"]) + if "sha256" in row: + require(sha256(data).hexdigest() == row["sha256"], "Source SHA-256 drift") + require(git_blob(data + b"\n") != row["git_blob"], "Source mutation was not rejected") + hashes[row["file"]] = sha256(data).hexdigest() + return hashes + + +def load_nodes(file, names, context): + tree = ast.parse((HERE / "retained" / file).read_text(), filename=file) + nodes = [n for n in tree.body if isinstance(n, (ast.FunctionDef, ast.ClassDef)) and n.name in names] + require({n.name for n in nodes} == set(names), "Requested source functions missing") + namespace = dict(context) + exec(compile(ast.Module(body=nodes, type_ignores=[]), "", "exec"), namespace) + return namespace + + +def poly_add(a, b): + return [sum(x) for x in zip(a + [0]*max(0, len(b)-len(a)), b + [0]*max(0, len(a)-len(b)))] + + +def poly_multiply(a, b): + out = [0]*(len(a)+len(b)-1) + for i, x in enumerate(a): + for j, y in enumerate(b): + out[i+j] += x*y + return out + + +def polynomial_certificate(): + # D(l) is taken from the documented exact expression, expanded independently. + depth = poly_add([1], poly_multiply([0, 2], poly_multiply([8, 2], [18, 32, 8]))) + require(depth == [1, 288, 584, 256, 32], "Layer polynomial expansion") + # A source entry contains a diagonal and an optional H: count both, so + # each rounding event is propagated across the following exact H. + stages = poly_add(poly_multiply([44, 48], depth), [2]) + upper = [20000*comb(6, j)*2**(6-j) for j in range(7)] + difference = [upper[j]-(stages[j] if j < len(stages) else 0) for j in range(7)] + require(all(c > 0 for c in difference), "Stage bound lacks a positive coefficient certificate") + require(4102*9230 == 37861460 < 2**26, "Generator constant") + require(8+12*5 == 68, "Completed prefix coefficient") + require(1+3+68+26 == 98 and 2+39+11 == 52, "Physical-cut exponents") + require(2+240+1+3*98 == 537 and 3*52 == 156, "Routed sixteen-H exponents") + require(2+2*537 == 1076 and 2+2*156 == 314, "Two-root prefixes") + require(2*1076+2 == 2154 and 2*314 == 628, "Tensor interval exponents") + require(240+1+2*98 == 437 and 2*52 == 104, "Joined scalar exponents") + require(Q(9, 256)+Q(6, 128) == Q(21, 256) < 1, "Synthesis error sum") + require(32768-1361 == 31407 and 6*32768-4746 == 191862, + "Original selector coefficient dominance") + return {"D_coefficients": depth, "stage_difference_coefficients": difference} + + +def ceil_log2(value): + value = Q(value) + require(value > 0, "Positive logarithm") + e = value.numerator.bit_length()-value.denominator.bit_length() + if e >= 0: + return e + (value.numerator > value.denominator*(1 << e)) + return e + (value.numerator*(1 << (-e)) > value.denominator) + + +def source_allocations(): + original = load_nodes("compiler-full.py", ["allocation"], {"Q": Q, "need": require, "ceil_log2": ceil_log2})["allocation"] + count = 0 + for ell in range(1, 21): + t = 1 << ell + for target in (1, 17, 53): + row = original(t, 4*t, 8*t*t, 2*t, target, 0) + require(row["conditioning"] <= 32*t**3, "Conditioning") + require(row["completed_prefix_bound"] <= 2**68*t**39, "Completed prefixes") + require(row["fragment_bound"] <= 2**26*t**11, "Active fragments") + require(row["execution_bound"] <= 2**98*t**52, "Physical cuts") + require(row["coefficient_error"] <= Q(1, 1 << target), "Exact-word defect") + require(row["layer_bound"] == 32*ell**4+256*ell**3+584*ell**2+288*ell+1, "Actual layer formula") + count += 1 + return count + + +@dataclass(frozen=True, eq=False) +class Z: + """Independent exact complex arithmetic for the emitted two-wire oracle.""" + re: Q = Q(0) + im: Q = Q(0) + + def __post_init__(self): + object.__setattr__(self, "re", Q(self.re)) + object.__setattr__(self, "im", Q(self.im)) + + @staticmethod + def coerce(x): + return x if isinstance(x, Z) else Z(x) + + def __add__(self, other): + other = self.coerce(other) + return Z(self.re+other.re, self.im+other.im) + + __radd__ = __add__ + + def __neg__(self): + return Z(-self.re, -self.im) + + def __sub__(self, other): + return self + -self.coerce(other) + + def __rsub__(self, other): + return self.coerce(other) + -self + + def __mul__(self, other): + other = self.coerce(other) + return Z(self.re*other.re-self.im*other.im, self.re*other.im+self.im*other.re) + + __rmul__ = __mul__ + + def __truediv__(self, other): + other = self.coerce(other) + denominator = other.norm2() + require(denominator != 0, "Division by zero in oracle") + return self*Z(other.re/denominator, -other.im/denominator) + + def __rtruediv__(self, other): + return self.coerce(other)/self + + def norm2(self): + return self.re*self.re+self.im*self.im + + def __eq__(self, other): + try: + other = self.coerce(other) + except (TypeError, ValueError): + return False + return self.re == other.re and self.im == other.im + + +def matrix_multiply(a, b): + return [[sum((a[i][k]*b[k][j] for k in range(2)), Z()) for j in range(2)] for i in range(2)] + + +IDENTITY = [[Z(1), Z()], [Z(), Z(1)]] +HADAMARD = [[Z(1), Z(1)], [Z(1), Z(-1)]] + + +def apply_word(word): + result = IDENTITY + for j, diagonal in enumerate(word): + matrix = [[Z.coerce(diagonal[0]), Z()], [Z(), Z.coerce(diagonal[1])]] + result = matrix_multiply(matrix, result) + if j+1 < len(word): + result = matrix_multiply(HADAMARD, result) + return result + + +def word_controls(): + names = ["diagonal_product", "chain", "swap_word", "upper_three", "upper_six", "lower_pair"] + source = load_nodes("root_gate_plan.py", names, {"Fraction": Q}) + rng = Random(7849) + fixtures = [ + [[Z(), Z(1)], [Z(1), Z()]], + [[Z(1), Z()], [Z(), Z(1)]], + [[Z(0, 1), Z()], [Z(), Z(0, -1)]], + ] + for q in (1, 8, 32, 128): + tiny = Q(1, 1 << q) + fixtures.extend(([[Z(tiny), Z()], [Z(), Z(1)]], + [[Z(1), Z(1)], [Z(1), Z(1+tiny)]])) + for _ in range(192): + fixtures.append([[Z(Q(rng.randint(-9, 9), rng.randint(1, 7)), + Q(rng.randint(-9, 9), rng.randint(1, 7))) for _ in range(2)] for _ in range(2)]) + passed = 0 + for gate in fixtures: + det = gate[0][0]*gate[1][1]-gate[0][1]*gate[1][0] + if det == 0: + continue + word = source["lower_pair"](gate) + require(len(word) == 17, "Sixteen-H lowering changed length") + require(apply_word(word) == gate, "Independent exact two-wire oracle disagrees") + # The selected pivot provides the uniform unit bound for both shear ratios. + i, j = max(product(range(2), repeat=2), key=lambda ij: gate[ij[0]][ij[1]].norm2()) + a, b, c = gate[i][j], gate[i][1-j], gate[1-i][j] + for z in (b/a, c/a): + require(z.norm2() <= 1, "Pivoted ratio leaves unit disk") + require(4 <= (z+3).norm2() <= 16, "Three-H parameter leaves annulus") + passed += 1 + # A phase/order mutation must change the actual matrix. + gate = [[Z(1, 1), Z(2)], [Z(0, 1), Z(3, -1)]] + word = source["lower_pair"](gate) + corrupted = list(word) + corrupted[8] = (word[8][0], -word[8][1]) + require(apply_word(corrupted) != gate, "Middle-diagonal phase mutation was not detected") + # Prefix norm alone cannot certify an interval. Inverses are indispensable. + for q in (1, 7, 31): + prefixes = (Q(1), Q(1, 1 << q), Q(1)) + require(max(prefixes) == 1 and prefixes[2]/prefixes[1] > 1, + "Inverse-cut negative control disappeared") + return passed + + +def fresh_diagonal_reference(data, tables, grid): + result = [] + for index, value in enumerate(data): + address, current = [], index + for row in tables: + current, position = divmod(current, len(row)) + address.append(position) + coefficient = grid.one + for k in range(len(tables)-1, 0, -1): + coefficient = grid.multiply(tables[k][address[k]], coefficient) + coefficient = grid.multiply(tables[0][address[0]], coefficient) + result.append(grid.multiply(coefficient, value)) + return result + + +def odometer_controls(): + source = load_nodes("tensor_word.py", ["Grid", "product_diagonal"], + {"Fraction": Q, "prod": prod, "word_product": lambda a, b: a*b}) + rng = Random(7849001) + packets = 0 + records = 0 + for sides in ((2,), (2, 2), (4, 2, 4), (2, 4, 2, 2), (2, 2, 2, 2, 2)): + for bits in (3, 7, 17): + grid = source["Grid"](bits) + for _ in range(8): + tables = [tuple((rng.randint(-2*grid.unit, 2*grid.unit), + rng.randint(-2*grid.unit, 2*grid.unit)) for _ in range(n)) for n in sides] + data = [(rng.randint(-grid.unit, grid.unit), rng.randint(-grid.unit, grid.unit)) + for _ in range(prod(sides))] + # Include exact zero and identity factors; no ratio update is valid there. + tables[0] = ((0, 0), grid.one) + tables[0][2:] + expected = fresh_diagonal_reference(data, tables, grid) + actual = list(data) + source["product_diagonal"](actual, tables, grid) + require(actual == expected, "Cached suffix differs from fresh current-coordinate evaluation") + packets += 1 + records += len(data) + # An actual stale-suffix mutant must fail, independently of a coarse norm budget. + text = (HERE / "retained" / "tensor_word.py").read_text() + changed = text.replace("for k in range(j, 0, -1):", "for k in range(j-1, 0, -1):") + require(changed != text, "Odometer mutation site missing") + node = next(n for n in ast.parse(changed).body if isinstance(n, ast.FunctionDef) and n.name == "product_diagonal") + namespace = {"prod": prod} + exec(compile(ast.Module(body=[node], type_ignores=[]), "", "exec"), namespace) + grid = source["Grid"](7) + tables = [((128, 0), (64, 32)), ((32, 64), (96, -32))] + data = [(128, 0)]*4 + expected = fresh_diagonal_reference(data, tables, grid) + namespace["product_diagonal"](data, tables, grid) + require(data != expected, "Stale suffix mutant was not rejected") + return {"packets": packets, "records": records} + + +def selector_controls(): + original = load_nodes("product.py", ["production_precision"], {})["production_precision"] + count = 0 + comparisons = [] + cases = [(30, (1,)), (72, (4, 5)), (12288, (128,)*16), + (6000000, (100000,)*10), (6*10**40, (10**40,))] + for d in range(1, 9): + for max_width in (1, 2, 3, 8, 17, 64): + widths = tuple(1+(i*7)%max_width for i in range(d)) + cases.append((6*(sum(widths)+3), widths)) + for p, widths in cases: + budget = precision_budget(p, widths) + k = budget.envelope_coefficient.bit_length() + upper_ratio = Q(budget.envelope_coefficient, 1 << k) + require(0 < upper_ratio < 1, "Strict raw error margin missing") + require(budget.fractional_bits == 4*p+budget.local_error_exponent+2*budget.interval_exponent+k, + "Selector identity") + # Dimension-free: this bounds the actual spend after division by the target. + require(Q(budget.stage_bound*(budget.axes+1)**2, 1 << k) < Q(1, 4), + "Bootstrap budget does not follow without circularity") + old = original(p, widths) + require(budget.fractional_bits < old, "New selector fails to improve original sufficient width") + require(2*upper_ratio >= 1, "One-bit undercharge should lose this envelope certificate") + count += 1 + if (p, widths) in cases[:5]: + comparisons.append({"public_bits": p, "axes": len(widths), "address_bits": sum(widths), + "old_fractional_bits": old, "new_fractional_bits": budget.fractional_bits, + "ratio": str(Q(old, budget.fractional_bits))}) + # A seriously undercharged selector violates even the exact scalar bootstrap expression. + q = precision_budget(30, (1,)) + exponent = q.envelope_coefficient.bit_length()-5 + exact_leading_ratio = Q(2*q.stage_bound*(q.axes+1)**2, 1 << exponent) + require(exact_leading_ratio > 1, "Five-bit undercharge did not violate the raw-bound expression") + for p, widths in ((0, (1,)), (1, ()), (1, (0,)), (True, (1,)), (1, (True,))): + try: + precision_budget(p, widths) + except ValueError: + pass + else: + raise ValueError("Malformed precision input accepted") + # With b=P+8 instead of the producer's paid phase/column guard, r=8 fails admission's error envelope. + require(Q(4*8, 1 << 9) >= Q(1, 4*8), "Missing column-guard negative control") + return {"cases": count, "examples": comparisons} + + +def main(): + result = { + "source_hashes": authenticate(), + "polynomial_certificate": polynomial_certificate(), + "source_allocator_cases": source_allocations(), + "exact_two_wire_packets": word_controls(), + "odometer": odometer_controls(), + "selector": selector_controls(), + "status": "PASS_DIRECT_CIRCULANT_PRODUCTION_PRECISION", + "scope": "Exact finite controls and universal written numerical theorem; no full assumption discharge or new kappa.", + } + print(json.dumps(result, sort_keys=True, indent=2)) + print(result["status"]) + + +if __name__ == "__main__": + main() diff --git a/research/direct-circulant-production-precision/evidence/registered-replay.txt b/research/direct-circulant-production-precision/evidence/registered-replay.txt new file mode 100644 index 0000000000..d36a8f4bec --- /dev/null +++ b/research/direct-circulant-production-precision/evidence/registered-replay.txt @@ -0,0 +1,233 @@ +CHECK Authenticate retained source; exact polynomial/allocator, two-wire, odometer and selector controls including negative mutations. +{ + "exact_two_wire_packets": 203, + "odometer": { + "packets": 120, + "records": 2448 + }, + "polynomial_certificate": { + "D_coefficients": [ + 1, + 288, + 584, + 256, + 32 + ], + "stage_difference_coefficients": [ + 1279954, + 3827280, + 4760480, + 3160704, + 1186304, + 238464, + 20000 + ] + }, + "scope": "Exact finite controls and universal written numerical theorem; no full assumption discharge or new kappa.", + "selector": { + "cases": 53, + "examples": [ + { + "address_bits": 1, + "axes": 1, + "new_fractional_bits": 6257, + "old_fractional_bits": 229664, + "public_bits": 30, + "ratio": "229664/6257" + }, + { + "address_bits": 9, + "axes": 2, + "new_fractional_bits": 22068, + "old_fractional_bits": 688620, + "public_bits": 72, + "ratio": "57385/1839" + }, + { + "address_bits": 2048, + "axes": 16, + "new_fractional_bits": 2912487, + "old_fractional_bits": 70304068, + "public_bits": 12288, + "ratio": "70304068/2912487" + }, + { + "address_bits": 1000000, + "axes": 10, + "new_fractional_bits": 1385047587, + "old_fractional_bits": 32793966628, + "public_bits": 6000000, + "ratio": "32793966628/1385047587" + }, + { + "address_bits": 10000000000000000000000000000000000000000, + "axes": 1, + "new_fractional_bits": 13850000000000000000000000000000000000005563, + "old_fractional_bits": 327920000000000000000000000000000000000199928, + "public_bits": 60000000000000000000000000000000000000000, + "ratio": "327920000000000000000000000000000000000199928/13850000000000000000000000000000000000005563" + } + ] + }, + "source_allocator_cases": 60, + "source_hashes": { + "compiler-engine.py": "9e36aee0835e6b1b62997433581f88b5a434ccab8ae43e5c25d1deaaf1ebf653", + "compiler-full.py": "1f42d5f2858564ffb320e54ba6aa29651025491569823e25006bf5862457b803", + "product.py": "29ab6c60f937b7cce58666f5ddd7a921c3197cf72abf91ecca0ff7ad9486850e", + "root_gate_plan.py": "379ca05625076824ac9c2399eac03c1c64c13fecee45ea17f78b8898df57cd2d", + "spectral.py": "ede9c48d34280c9c1c5c332b9434ff666fd321f4a18ffbf1f61b3339339e8ab6", + "tensor_word.py": "36c5a9a0082c9aa3c6cb2d04a9196af8debce0d551a0525975b710018ea02cac" + }, + "status": "PASS_DIRECT_CIRCULANT_PRODUCTION_PRECISION" +} +PASS_DIRECT_CIRCULANT_PRODUCTION_PRECISION +CHECK Repeat the same mathematical and rejection controls with assertions disabled. +{ + "exact_two_wire_packets": 203, + "odometer": { + "packets": 120, + "records": 2448 + }, + "polynomial_certificate": { + "D_coefficients": [ + 1, + 288, + 584, + 256, + 32 + ], + "stage_difference_coefficients": [ + 1279954, + 3827280, + 4760480, + 3160704, + 1186304, + 238464, + 20000 + ] + }, + "scope": "Exact finite controls and universal written numerical theorem; no full assumption discharge or new kappa.", + "selector": { + "cases": 53, + "examples": [ + { + "address_bits": 1, + "axes": 1, + "new_fractional_bits": 6257, + "old_fractional_bits": 229664, + "public_bits": 30, + "ratio": "229664/6257" + }, + { + "address_bits": 9, + "axes": 2, + "new_fractional_bits": 22068, + "old_fractional_bits": 688620, + "public_bits": 72, + "ratio": "57385/1839" + }, + { + "address_bits": 2048, + "axes": 16, + "new_fractional_bits": 2912487, + "old_fractional_bits": 70304068, + "public_bits": 12288, + "ratio": "70304068/2912487" + }, + { + "address_bits": 1000000, + "axes": 10, + "new_fractional_bits": 1385047587, + "old_fractional_bits": 32793966628, + "public_bits": 6000000, + "ratio": "32793966628/1385047587" + }, + { + "address_bits": 10000000000000000000000000000000000000000, + "axes": 1, + "new_fractional_bits": 13850000000000000000000000000000000000005563, + "old_fractional_bits": 327920000000000000000000000000000000000199928, + "public_bits": 60000000000000000000000000000000000000000, + "ratio": "327920000000000000000000000000000000000199928/13850000000000000000000000000000000000005563" + } + ] + }, + "source_allocator_cases": 60, + "source_hashes": { + "compiler-engine.py": "9e36aee0835e6b1b62997433581f88b5a434ccab8ae43e5c25d1deaaf1ebf653", + "compiler-full.py": "1f42d5f2858564ffb320e54ba6aa29651025491569823e25006bf5862457b803", + "product.py": "29ab6c60f937b7cce58666f5ddd7a921c3197cf72abf91ecca0ff7ad9486850e", + "root_gate_plan.py": "379ca05625076824ac9c2399eac03c1c64c13fecee45ea17f78b8898df57cd2d", + "spectral.py": "ede9c48d34280c9c1c5c332b9434ff666fd321f4a18ffbf1f61b3339339e8ab6", + "tensor_word.py": "36c5a9a0082c9aa3c6cb2d04a9196af8debce0d551a0525975b710018ea02cac" + }, + "status": "PASS_DIRECT_CIRCULANT_PRODUCTION_PRECISION" +} +PASS_DIRECT_CIRCULANT_PRODUCTION_PRECISION +CHECK Separate Gaussian-rational literal-word and noncommutative cache-lineage oracle; universal schedule polynomial and meaningful sign/stale-cache controls. +{ + "literal_word": { + "cases": 600, + "pivot_locations": [ + [ + 0, + 0 + ], + [ + 0, + 1 + ], + [ + 1, + 0 + ], + [ + 1, + 1 + ] + ], + "fully_expanded_diagonals": 23, + "H_factors": 16, + "nonpivot_factors": 38, + "retained_nonpivot_envelope": 40, + "negative_control": "sign in upper_three final diagonal changes endpoint" + }, + "odometer_lineage": { + "cases": 12, + "records": 1214, + "oracle": "exact current-coordinate right-associated expression tree, no numeric cancellation", + "negative_control": "skip newly changed suffix at a carry" + }, + "literal_stage_count": { + "actual_steps_per_matching": "20*ell+23", + "literal_two_root_depth_coefficients": [ + 46, + 13288, + 38384, + 35136, + 11712, + 1280 + ], + "J_minus_actual_constant_coefficients": [ + 1279998, + 3840000, + 4800000, + 3200000, + 1200000, + 240000, + 20000 + ], + "J_minus_actual_d_coefficients": [ + 1279954, + 3826712, + 4761616, + 3164864, + 1188288, + 238720, + 20000 + ] + }, + "scope": "Independent source/schema checks; universal inequalities are in CROSS-REVIEW.md" +} +PASS_INDEPENDENT_PRECISION_CROSS_REVIEW +PASS_REGISTERED_RESEARCH_PACKAGE research/direct-circulant-production-precision outcome=completed diff --git a/research/direct-circulant-production-precision/precision.py b/research/direct-circulant-production-precision/precision.py new file mode 100644 index 0000000000..ac7bbe28be --- /dev/null +++ b/research/direct-circulant-production-precision/precision.py @@ -0,0 +1,39 @@ +"""Source-bound sufficient external precision for PR7849's Fourier word. + +This selector assumes the exact source contracts in PROOF-DRAFT.md. It does not +estimate the minimum precision required by a numerical execution. +""" + +from dataclasses import dataclass + + +@dataclass(frozen=True) +class Budget: + public_bits: int + axes: int + address_bits: int + interval_exponent: int + local_error_exponent: int + stage_bound: int + envelope_coefficient: int + fractional_bits: int + + +def precision_budget(public_bits: int, side_widths: tuple[int, ...]) -> Budget: + if type(public_bits) is not int or public_bits < 1: + raise ValueError("Public precision must be a positive integer") + if not side_widths or any(type(w) is not int or w < 1 for w in side_widths): + raise ValueError("Supply at least one positive binary side width") + d = len(side_widths) + length = sum(side_widths) + interval = (1257 * length + 1) // 2 + 2154 * d + local = 104 * length + 438 * d + stages = 20000 * (d + 1) * (max(side_widths) + 2) ** 6 + coefficient = 4 * stages * (d + 1) ** 2 + d + 1 + bits = 4 * public_bits + local + 2 * interval + coefficient.bit_length() + return Budget(public_bits, d, length, interval, local, stages, coefficient, bits) + + +def production_precision(public_bits: int, side_widths: tuple[int, ...]) -> int: + """Return the fractional bits certified by the explicit source envelope.""" + return precision_budget(public_bits, side_widths).fractional_bits diff --git a/research/direct-circulant-production-precision/retained/compiler-engine.py b/research/direct-circulant-production-precision/retained/compiler-engine.py new file mode 100644 index 0000000000..e9f2f2b08d --- /dev/null +++ b/research/direct-circulant-production-precision/retained/compiler-engine.py @@ -0,0 +1,258 @@ +"""Certified phases and an authenticated rational adaptation of the FFT child. + +Jose Manuel (jmbarrancoml), with substantial OpenAI Codex assistance. +Apache-2.0. Phase projection follows Chafik/PR628; the schedule is Vlado/PR1673. +""" +import ast +import copy +from fractions import Fraction as Q +from hashlib import sha256 +from math import gcd, isqrt +from types import SimpleNamespace + +from exact import (C, Mat, Vec, adjoint, ceil_log2, component_l1, inverse_gate, + need, qheight, round_q, rounded) + + +class Phases: + def __init__(self, bits, source): + need(type(bits) is int and bits >= 1, "positive phase precision") + self.bits, self.nu = bits, Q(1, 1 << bits) + self.working_bits = 2 * (bits + 32) + self.oracle = {"__name__": "_authenticated_phase_oracle"} + exec(compile(source, "", "exec", optimize=0), self.oracle) + need(self.oracle["pi_interval"].cache_info().currsize == 0 + and self.oracle["kernel"].cache_info().currsize == 0, "fresh precision namespace") + self.oracle["BITS"] = self.working_bits + self.oracle["SCALE"] = 1 << self.working_bits + self.values, self.boxes, self.certificates = {}, {}, {} + + @staticmethod + def key(denominator, numerator): + need(type(denominator) is int and denominator > 0 and type(numerator) is int, + "integer phase description") + numerator %= denominator + divisor = gcd(denominator, numerator) + return denominator // divisor, numerator // divisor + + def box(self, denominator, numerator): + key = self.key(denominator, numerator) + if key not in self.boxes: + exact = {(1, 0): C(1), (2, 1): C(-1), (4, 1): C(0, 1), (4, 3): C(0, -1)} + if key in exact: + z = exact[key] + self.boxes[key] = ((z.re, z.re), (z.im, z.im)) + else: + self.boxes[key] = self.oracle["root_interval"](*key) + return self.boxes[key] + + def phase(self, denominator, numerator): + key = self.key(denominator, numerator) + if key in self.values: + return self.values[key] + box = self.box(*key) + if box[0][0] == box[0][1] and box[1][0] == box[1][1]: + sigma, error, parameter = C(box[0][0], box[1][0]), Q(0), None + else: + choices = [] + for center in (C(1), C(-1), C(0, 1), C(0, -1)): + conjugate = center.conjugate() + point = self.oracle["point"] + rotated = self.oracle["cmul"](box, (point(conjugate.re), point(conjugate.im))) + choices.append((rotated[0][0], center, rotated)) + _, center, rotated = max(choices, key=lambda item: item[0]) + need(rotated[0][0] >= Q(1, 2), "certified unit-phase chart") + parameters = [imag / (1 + real) for imag in rotated[1] for real in rotated[0]] + parameter = round_q((min(parameters) + max(parameters)) / 2, self.bits + 4) + need(abs(parameter) < 1, "bounded stereographic parameter") + sigma = center * C((1 - parameter ** 2) / (1 + parameter ** 2), + 2 * parameter / (1 + parameter ** 2)) + # Maximum endpoint distance, not minimum distance to a rectangle. + error = sum(max(abs(endpoint - value) for endpoint in interval) + for interval, value in zip(box, (sigma.re, sigma.im))) + need(sigma.norm2() == 1 and error <= self.nu, "certified exact rational unit phase") + need(max(qheight(sigma.re), qheight(sigma.im)) <= 2 * self.bits + 12, + "unit-phase representation bound") + self.values[key] = sigma + self.certificates[key] = {"denominator": key[0], "numerator": key[1], + "unit": sigma.record(), "error_bound": str(error), + "parameter": None if parameter is None else str(parameter)} + return sigma + + def record(self): + return {"phase_bits": self.bits, "oracle_bits": self.working_bits, + "certificates": [self.certificates[key] for key in sorted(self.certificates)]} + + +def split_kernel(matrix): + n = len(matrix) + need(n > 0 and n & (n - 1) == 0 and matrix.shape == (n, n), "square dyadic tile") + column, row = matrix[:, 0], matrix[0, :] + need(all(matrix[i][j] == (column[i - j] if i >= j else row[j - i]) + for i in range(n) for j in range(n)), "Toeplitz input") + g, h = Vec([0] * n), Vec([0] * n) + g[0] = h[0] = column[0] / 2 + for j in range(1, n): + g[j] = (column[j] + row[n - j]) / 2 + h[j] = (column[j] - row[n - j]) / 2 + return g, h + + +def budget(matrix, radius, target, input_fractional_bits=0): + g, h = split_kernel(matrix) + n, depth = len(matrix), len(matrix).bit_length() - 1 + mg, mh = component_l1(g), component_l1(h) + total = mg + mh + need(type(target) is int and target >= 1 and type(radius) in (int, Q) and radius >= 1, + "target and exact input radius") + need(type(input_fractional_bits) is int and input_fractional_bits >= 0, + "declared incoming fractional precision") + layers = 4 * depth + 8 + phase_bits = target + ceil_log2(16 * (depth + 1) * (total + 1) * (radius + 1)) + multiplier_bits = target + ceil_log2(8 * (radius + 1)) + data_bits = max(input_fractional_bits, target + ceil_log2(2 * layers * n * (total + 2))) + return certificate(n, mg, mh, radius, target, phase_bits, multiplier_bits, data_bits, + input_fractional_bits) + + +def certificate(n, mg, mh, radius, target, phase_bits, multiplier_bits, data_bits, + input_fractional_bits=0): + need(type(n) is int and n > 0 and n & (n - 1) == 0, "dyadic certificate dimension") + need(all(type(x) is int for x in (target, phase_bits, multiplier_bits, data_bits)) + and all(type(x) in (int, Q) for x in (mg, mh, radius)), "exact budget fields") + need(type(input_fractional_bits) is int and 0 <= input_fractional_bits <= data_bits, + "preserve incoming data grid") + need(min(phase_bits, multiplier_bits, data_bits, target) >= 1 and min(mg, mh) >= 0 + and radius >= 1, "positive precisions and valid envelopes") + depth, layers = n.bit_length() - 1, 4 * (n.bit_length() - 1) + 8 + nu, v, u = (Q(1, 1 << b) for b in (phase_bits, multiplier_bits, data_bits)) + total = mg + mh + coefficient_error = 4 * (depth + 1) * total * nu + 2 * v + prefix_bound = 1 + total + 2 * v + rounding_error = layers * prefix_bound * n * u + error = coefficient_error * radius + rounding_error + need(error <= Q(1, 1 << target), "complete target error budget") + need(layers * n * u <= 1, "bounded rounding accumulation") + amplitude = prefix_bound * (radius + layers * n * u) + integer_bits = max(1, ceil_log2(max(Q(1), amplitude))) + 2 + coefficient_height = max(4 * phase_bits + 24, + multiplier_bits + ceil_log2(total + 2) + 2) + temporary_bits = 2 * data_bits + 8 * coefficient_height + 2 * integer_bits + 32 + return dict(n=n, depth=depth, layer_bound=layers, mg=mg, mh=mh, radius=radius, + target_bits=target, phase_bits=phase_bits, multiplier_bits=multiplier_bits, + data_bits=data_bits, input_fractional_bits=input_fractional_bits, + coefficient_error=coefficient_error, prefix_bound=prefix_bound, + rounding_error=rounding_error, total_error=error, amplitude_bound=amplitude, + integer_bits=integer_bits, coefficient_height_bound=coefficient_height, + temporary_bits=temporary_bits) + + +class Adapt(ast.NodeTransformer): + def __init__(self): + self.function = None + self.changes = [] + + def visit_FunctionDef(self, node): + old = self.function + self.function = node.name + result = self.generic_visit(node) + self.function = old + return result + + def visit_Assign(self, node): + if len(node.targets) == 1 and isinstance(node.targets[0], ast.Name): + name = node.targets[0].id + if self.function == "fft" and name == "w": + self.changes.append("fft-twiddle") + node.value = ast.Call(func=ast.Name(id="phase", ctx=ast.Load()), + args=[ast.Name(id="size", ctx=ast.Load()), + ast.UnaryOp(op=ast.USub(), operand=ast.Name(id="j", ctx=ast.Load()))], + keywords=[]) + return node + if self.function == "toeplitz_shear" and name == "gamma": + self.changes.append("independent-twist-coefficients") + return ast.Pass() + if self.function == "toeplitz_shear" and name == "d": + self.changes.append("twist-vector") + node.value = ast.Call(func=ast.Name(id="certified_twist_vector", ctx=ast.Load()), + args=[ast.Name(id="n", ctx=ast.Load())], keywords=[]) + return node + return self.generic_visit(node) + + def visit_BinOp(self, node): + if (self.function == "fft" and isinstance(node.op, ast.Div) + and isinstance(node.right, ast.Call) and isinstance(node.right.func, ast.Attribute) + and node.right.func.attr == "sqrt"): + self.changes.append("unitary-splitter") + return ast.Call(func=ast.Name(id="butterfly", ctx=ast.Load()), + args=[ast.Name(id="w", ctx=ast.Load())], keywords=[]) + return self.generic_visit(node) + + +class Builder: + def __init__(self, phase_oracle, multiplier_bits, circuit_source): + self.phases, self.multiplier_bits = phase_oracle, multiplier_bits + self.spectra, self.twist_vectors, self.bounds = [], [], [] + selected = {"diag", "inverse", "parallel", "fft", "circ_shear", "toeplitz_shear"} + tree = ast.parse(circuit_source) + tree.body = [copy.deepcopy(n) for n in tree.body + if isinstance(n, ast.FunctionDef) and n.name in selected] + need({node.name for node in tree.body} == selected, "complete source function set") + self.original_ast = sha256(ast.dump(tree).encode()).hexdigest() + adapter = Adapt() + tree = ast.fix_missing_locations(adapter.visit(tree)) + need(adapter.changes == ["fft-twiddle", "unitary-splitter", + "independent-twist-coefficients", "twist-vector"], + "exact declared coefficient adaptation") + self.adapted_ast = sha256(ast.dump(tree).encode()).hexdigest() + self.np = SimpleNamespace(array=lambda rows, dtype=None: Mat(rows), + zeros=lambda n, dtype=None: Vec([0] * n), + fft=SimpleNamespace(fft=self.spectrum), + linalg=SimpleNamespace(inv=inverse_gate)) + self.namespace = {"np": self.np, "phase": self.phases.phase, + "butterfly": self.butterfly, "certified_twist_vector": self.twists} + exec(compile(tree, "", "exec", optimize=0), self.namespace) + + def butterfly(self, w): + splitter = self.phases.phase(8, 1) + a, b = splitter.re, splitter.im + return Mat([[a, b * w], [b, -a * w]]) + + def twists(self, n): + result = Vec(self.phases.phase(2 * n, j) for j in range(n)) + self.twist_vectors.append(result) + return result + + def spectrum(self, kernel): + n = len(kernel) + bound = self.bounds[len(self.spectra)] + exact = Vec(sum((kernel[j] * self.phases.phase(n, -i * j) for j in range(n)), C()) + for i in range(n)) + result = Vec(rounded(value, self.multiplier_bits) for value in exact) + v = Q(1, 1 << self.multiplier_bits) + need(all(value.norm2() <= bound ** 2 for value in exact), "unit-root multiplier bound") + need(all(value.norm2() <= (bound + v) ** 2 for value in result), "rounded multiplier bound") + need(all((x - y).norm2() <= v ** 2 for x, y in zip(result, exact)), "multiplier rounding") + self.spectra.append({"kernel": Vec(kernel), "multipliers": result, "bound": bound}) + return result + + def plan(self, matrix): + g, h = split_kernel(matrix) + n = len(matrix) + self.bounds = [component_l1(g), component_l1(h)] + self.spectra, self.twist_vectors = [], [] + result = self.namespace["toeplitz_shear"](list(range(n, 2 * n)), list(range(n)), matrix) + need(len(self.spectra) == 2 and len(self.twist_vectors) == 1, "two circulants and one twist table") + need(self.spectra[0]["kernel"] == g, "first source kernel") + need(self.spectra[1]["kernel"] == self.twist_vectors[0] * h, "twisted second source kernel") + need(all(a.norm2() == b.norm2() for a, b in zip(self.spectra[1]["kernel"], h)), + "twisting preserves kernel magnitudes") + return result + + +def inverse_sqrt_box(n, bits): + scale = 1 << bits + lower = isqrt((1 << (2 * bits)) // n) + if lower * lower * n == 1 << (2 * bits): + return Q(lower, scale), Q(lower, scale) + return Q(lower, scale), Q(lower + 1, scale) diff --git a/research/direct-circulant-production-precision/retained/compiler-full.py b/research/direct-circulant-production-precision/retained/compiler-full.py new file mode 100644 index 0000000000..7f85ad1a89 --- /dev/null +++ b/research/direct-circulant-production-precision/retained/compiler-full.py @@ -0,0 +1,243 @@ +"""Retained full Toeplitz recursion under leading-section conditioning. + +Jose Manuel (jmbarrancoml), with substantial OpenAI Codex assistance. +Apache-2.0. Recursive source and displacement identities: Vlado/PR1673. +""" +import ast +import copy +from fractions import Fraction as Q +from hashlib import sha256 +from types import SimpleNamespace + +from exact import (C, Mat, Vec, ceil_log2, component_l1, eye, inverse_gate, + multiply, need, rounded) +from engine import Phases +from generator import (ORACLE, SOURCE, Program, allocation as generator_allocation, + load_producer, prepare) + + +class Matrix(Mat): + @property + def T(self): + return Matrix(zip(*self)) + + def __getitem__(self, key): + value = super().__getitem__(key) + return Matrix(value) if isinstance(value, Mat) else value + + def __sub__(self, other): + need(self.shape == other.shape, "full matrix subtraction shape") + return Matrix([[x - y for x, y in zip(a, b)] for a, b in zip(self, other)]) + + def __matmul__(self, other): + return Matrix(multiply(self, other)) + + +def solve(left, right): + n = len(left) + need(left.shape == (n, n) and len(right) == n, "exact solve shapes") + width = len(right[0]) + rows = [list(a) + list(b) for a, b in zip(left, right)] + for j in range(n): + pivot = next((i for i in range(j, n) if rows[i][j] != 0), None) + need(pivot is not None, "singular leading/Schur section") + rows[j], rows[pivot] = rows[pivot], rows[j] + divisor = rows[j][j] + rows[j] = [x / divisor for x in rows[j]] + for i in range(n): + if i != j: + factor = rows[i][j] + rows[i] = [x - factor * y for x, y in zip(rows[i], rows[j])] + need(all(rows[i][j] == int(i == j) for i in range(n) for j in range(n)), + "exact solve elimination") + return Matrix([row[n:n + width] for row in rows]) + + +def norm_upper(matrix): + return max(max(component_l1(row) for row in matrix), + max(component_l1(column) for column in zip(*matrix))) + + +def admission(matrix): + matrix = Matrix(matrix) + n = len(matrix) + need(n > 0 and n & (n - 1) == 0 and matrix.shape == (n, n), "dyadic full Toeplitz shape") + need(all(matrix[i][j] == (matrix[i - j][0] if i >= j else matrix[0][j - i]) + for i in range(n) for j in range(n)), "exact full Toeplitz admission") + leading = [] + for b in range(1, n + 1): + inverse = solve(matrix[:b, :b], Matrix(eye(b))) + leading.append((b, norm_upper(inverse))) + return max(Q(1), norm_upper(matrix)), max(Q(1), *(v for _, v in leading)), leading + + +def allocation(n, lam, inverse_bound, radius, target, incoming): + need(type(n) is int and n > 0 and n & (n - 1) == 0, "full dyadic dimension") + need(all(type(x) in (int, Q) and x >= 1 for x in (lam, inverse_bound, radius)), + "exact full conditioning and radius bounds") + need(type(target) is int and target >= 1 and type(incoming) is int and incoming >= 0, + "full target and incoming precision") + lam, inverse_bound, radius = (Q(x) for x in (lam, inverse_bound, radius)) + d, chi = n.bit_length() - 1, lam * inverse_bound + descendant = lam + lam ** 2 * inverse_bound + b = 256 * n ** 3 * chi ** 12 + calls, rank = 3 * n - 2, 2 * d + 8 + alpha, kg = 8 * rank * n ** 2 * chi, 2 * n + 64 * n ** 2 * chi + generator = max(Q(3200 * n ** 3), 2 + 2 * kg) * (10 + 4 * alpha + 2 * kg) + fragment = max(generator, descendant + 1, 2 * inverse_bound) + execution = 2 * max(Q(1), lam, inverse_bound) * b * fragment + layers = 1 + 2 * d * rank * (8 * d * d + 32 * d + 18) + gates = n * (1 + d * rank * (4 * d * d + 24 * d + 22)) + s = target + ceil_log2(4 * calls * b ** 3 * (radius + 1)) + eta = Q(1, 1 << s) + theta = calls * b ** 2 * eta + data = max(incoming, target + ceil_log2(2 * layers * execution * n)) + coefficient = 2 * calls * b ** 3 * eta + rounding = layers * execution * n * Q(1, 1 << data) + need(theta <= Q(1, 4) and eta <= 1 / (2 * inverse_bound) + and coefficient * radius + rounding <= Q(1, 1 << target), "complete full precision budget") + amplitude = execution * radius + layers * execution ** 2 * n * Q(1, 1 << data) + integer = max(1, ceil_log2(max(Q(1), amplitude))) + 2 + scalar_height = 2 * s + 2 * ceil_log2(descendant + 2) + 8 + return dict(n=n, lam=lam, inverse_bound=inverse_bound, radius=radius, + target_bits=target, incoming_bits=incoming, conditioning=chi, + descendant_bound=descendant, completed_prefix_bound=b, + atomic_calls=calls, rank_bound=rank, displacement_bound=4 * n * chi, + generator_fragment_bound=generator, fragment_bound=fragment, + execution_bound=execution, segment_bound=execution ** 2, + layer_bound=layers, gate_bound=gates, child_target_bits=s, eta=eta, + theta=theta, data_bits=data, coefficient_error=coefficient, + rounding_error=rounding, total_error=coefficient * radius + rounding, + amplitude_bound=amplitude, integer_bits=integer, + scalar_height_bound=scalar_height, coefficient_height_bound=scalar_height) + + +class Plan(list): + def __init__(self, layers, atoms): + super().__init__(layers) + self.atoms = atoms + + def __add__(self, other): + need(isinstance(other, Plan), "typed full-plan composition") + return Plan(list(self) + list(other), [dict(a) for a in self.atoms] + + [dict(a, start=a["start"] + len(self), stop=a["stop"] + len(self)) + for a in other.atoms]) + + +class Full: + def __init__(self, bound, raw): + self.bound, self.raw = dict(bound), raw + self.producer = load_producer(raw) + self.phase_pool, self.nodes = {}, {} + selected = {"full_plan", "parallel", "inverse"} + tree = ast.parse(raw[SOURCE + "check_circuits.py"]) + tree.body = [copy.deepcopy(node) for node in tree.body + if isinstance(node, ast.FunctionDef) and node.name in selected] + need({node.name for node in tree.body} == selected, "complete full source function set") + self.source_ast = sha256(ast.dump(tree).encode()).hexdigest() + self.stats = {"full_nodes": 0} + self.namespace = dict(STATS=self.stats, + np=SimpleNamespace(linalg=SimpleNamespace(solve=solve, inv=inverse_gate)), + lowdisp_shear=self.shear, diag=self.leaf) + exec(compile(tree, "", "exec", optimize=0), + self.namespace) + self.source_full = self.namespace["full_plan"] + self.source_parallel = self.namespace["parallel"] + self.source_inverse = self.namespace["inverse"] + self.namespace["parallel"] = self.parallel + self.namespace["full_plan"] = self.node + + def interval(self, indices): + positions = [self.positions[i] for i in indices] + a, b = min(positions), max(positions) + 1 + need(positions == list(range(a, b)), "ordered contiguous logical interval") + return a, b + + def node(self, indices, matrix): + interval = self.interval(indices) + need(interval not in self.nodes, "one exact Schur reference per node") + self.nodes[interval] = dict(indices=list(indices), matrix=Matrix(matrix)) + need(norm_upper(matrix) <= self.bound["descendant_bound"], "component descendant bound") + result = self.source_full(indices, matrix) + self.nodes[interval]["layers"] = len(result) + return result + + def leaf(self, indices, values): + need(len(indices) == len(values) == 1, "scalar full leaf") + intended = values[0] + need(intended.norm2() >= 1 / self.bound["inverse_bound"] ** 2 + and intended.norm2() <= self.bound["descendant_bound"] ** 2, "full pivot margins") + stored = rounded(intended, self.bound["child_target_bits"]) + need((stored - intended).norm2() <= self.bound["eta"] ** 2 + and stored.norm2() >= 1 / (4 * self.bound["inverse_bound"] ** 2), "stored full pivot margin") + gate = Mat([[stored]]) + need(stored * inverse_gate(gate)[0][0] == 1, "same stored full scalar inverse") + a, b = self.interval(indices) + atom = dict(id=f"D:{a}", kind="leaf", interval=(a, b), indices=list(indices), + start=0, stop=1, ideal=Mat([[intended]]), + local_plan=[[((0,), gate)]], error=self.bound["eta"], + coefficient_height=self.bound["scalar_height_bound"]) + return Plan([[(tuple(indices), gate)]], [atom]) + + def shear(self, target, source, matrix): + m = len(source) + positions = sorted(self.positions[i] for i in source + target) + a, b = min(positions), max(positions) + 1 + need(positions == list(range(a, b)) and b - a == 2 * m, "owned full shear interval") + upper = self.positions[target[0]] < self.positions[source[0]] + need([self.positions[i] for i in target] == list(range(a if upper else a + m, + a + m if upper else b)) + and [self.positions[i] for i in source] == list(range(a + m if upper else a, + b if upper else a + m)), + "source full shear orientation") + need(norm_upper(matrix) <= self.bound["conditioning"], "full K/L conditioning") + items, displacement, be, heights = prepare(matrix, self.producer) + need(len(items) <= self.bound["rank_bound"] and be <= self.bound["displacement_bound"], + "retained displacement rank and envelope") + child, triangle = generator_allocation(m, len(items), be, 1, + self.bound["child_target_bits"], 0) + need(child["coefficient_error"] <= self.bound["eta"] + and child["execution_bound"] <= self.bound["generator_fragment_bound"], + "full atomic generator contract") + p = child["phase_bits"] + if p not in self.phase_pool: + self.phase_pool[p] = Phases(p, self.raw[ORACLE]) + program = Program(child, triangle, self.raw, self.phase_pool[p]) + local = program.plan(items) + mapping = source + target + plan = [[(tuple(mapping[i] for i in ids), gate) for ids, gate in layer] for layer in local] + kind = "upper" if upper else "lower" + atom = dict(id=f"{'R' if upper else 'L'}:{a}:{b}", kind=kind, + interval=(a, b), indices=list(mapping), start=0, stop=len(plan), + ideal=Mat(matrix), local_plan=local, error=child["coefficient_error"], + coefficient_height=child["coefficient_height_bound"], + program=program, generator_items=items, displacement=displacement, + producer_heights=heights) + return Plan(plan, [atom]) + + def parallel(self, left, right): + left_ids = {i for a in left.atoms for i in a["indices"]} + right_ids = {i for a in right.atoms for i in a["indices"]} + need(not left_ids.intersection(right_ids), "disjoint full sibling supports") + return Plan(self.source_parallel(left, right), + [dict(a) for a in left.atoms] + [dict(a) for a in right.atoms]) + + def plan(self, matrix, indices=None): + n = len(matrix) + need(n == self.bound["n"], "allocated full dimension") + indices = list(range(n)) if indices is None else list(indices) + need(all(type(i) is int for i in indices) and sorted(indices) == list(range(n)), + "full root wire permutation") + self.positions = {wire: pos for pos, wire in enumerate(indices)} + result = self.node(indices, Matrix(matrix)) + need(self.stats["full_nodes"] == 2 * n - 1 and len(result.atoms) == 3 * n - 2 + and len({a["id"] for a in result.atoms}) == len(result.atoms), "complete full recursion") + need(len(result) <= self.bound["layer_bound"] + and sum(map(len, result)) <= self.bound["gate_bound"], "full source schedule bounds") + self.bound["coefficient_height_bound"] = max(a["coefficient_height"] for a in result.atoms) + self.bound["temporary_bits"] = (2 * self.bound["data_bits"] + + 8 * self.bound["coefficient_height_bound"] + 2 * self.bound["integer_bits"] + 32) + return result + + def inverse(self, plan): + return self.source_inverse(plan) diff --git a/research/direct-circulant-production-precision/retained/product.py b/research/direct-circulant-production-precision/retained/product.py new file mode 100644 index 0000000000..6059b6e2ce --- /dev/null +++ b/research/direct-circulant-production-precision/retained/product.py @@ -0,0 +1,163 @@ +"""Evaluate a complete small multiplication with the compiled two-root word.""" + +from math import gcd, prod +from pathlib import Path +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from root_gate_plan import load_compiler +from spectral import fourier_axis +from tensor_word import Grid, TensorWord, load_routes +from word_product import word_product +from square_geometry import controller_shape, select_squares, production_widths +from heterogeneous_crt import HeterogeneousCRT + + +def digits(index, radices): + result = [] + for radix in radices: + index, remainder = divmod(index, radix) + result.append(remainder) + if index: + raise ValueError("The index exceeds the rectangle") + return tuple(result) + + +def ordinal(pos, widths): + acc = 0 + for j, side in reversed(tuple(zip(pos, widths, strict=True))): + if not 0 <= j < side: + raise ValueError("Coordinate outside the rectangle") + acc = acc*side + j + return acc + + +def rounded_ratio(x, scale): + return (2*x+scale)//(2*scale) + + +class Multiplier: + def __init__(self, sides, digit_bits=8, work_bits=136, source_root=None): + self.sides = tuple(sides) + d = len(sides) + if not d or d & (d-1) or any(r < 2 or gcd(r,prod(sides[:i])) != 1 + for i,r in enumerate(sides)): + raise ValueError("Use a power-of-two count of pairwise coprime cyclic sides") + self.size = prod(sides) + self.base = 1 << digit_bits + self.public_bits = 6*digit_bits + if self.size > self.base or digit_bits < 5 or work_bits < self.public_bits: + raise ValueError("Insufficient public digit or work precision") + root = Path(source_root) if source_root is not None else Path(__file__).resolve().parents[2] + compiler = load_compiler(root) + self.routes = load_routes(root) + self.widths = tuple(1 << (r-1).bit_length() for r in sides) + self.router = HeterogeneousCRT(sides, [(t-1).bit_length() for t in self.widths], + self.routes.benes) + self.grid = Grid(work_bits) + # The final grid pays for each table and arithmetic conversion. + axes = [fourier_axis(compiler, r, t, -1, work_bits+8) + for r,t in zip(self.sides, self.widths, strict=True)] + self.transform = TensorWord(axes, compiler, self.routes, self.grid, self.public_bits) + + def public(self, x): + shift = self.grid.bits-self.public_bits + return tuple((1 if u >= 0 else -1)*((abs(u) >> shift) << shift) for u in x) + + def public_product(self, x, y): + """Multiply the two represented words, then truncate once on the public grid.""" + a, b = x + c, d = y + re = word_product(a,c)-word_product(b,d) + im = word_product(a,d)+word_product(b,c) + shift = self.grid.bits-self.public_bits + return tuple((1 if u >= 0 else -1)*((abs(u) >> (self.grid.bits+shift)) << shift) + for u in (re, im)) + + def crt(self, field, reverse=False): + out = [None]*len(field) + for i, x in enumerate(field): + pos = digits(i, self.widths) + dest = self.router.route(pos, reverse=reverse) + j = ordinal(dest, self.widths) + if out[j] is not None: + raise ValueError("CRT collision in padded coordinates") + out[j] = x + return out + + def operand(self, value): + if value < 0: + raise ValueError("The magnitude must be nonnegative") + z = [(0,0)] * prod(self.widths) + used = 0 + while value: + if used == self.size: + raise ValueError("Too many input digits for this transform") + value, digit = divmod(value, self.base) + z[ordinal(digits(used, self.sides), self.widths)] = ( + digit * (self.grid.unit//(4*self.base)), 0) + used += 1 + return self.crt(z), used + + def convolution_grid(self, a, b): + a = list(map(self.public, self.transform.apply(a))) + b = list(map(self.public, self.transform.apply(b))) + products = [self.public_product(x,y) for x,y in zip(a,b,strict=True)] + return list(map(self.public, self.transform.apply(products, opposite=True))) + + def multiply(self, left, right): + a, la = self.operand(abs(left)) + b, lb = self.operand(abs(right)) + if max(0, la+lb-1) > self.size: + raise ValueError("Linear convolution would wrap on this geometry") + recovered = self.convolution_grid(a, b) + gain = (4*self.base*self.size)**2 + physical = [rounded_ratio(word_product(gain, z[0]), self.grid.unit) for z in recovered] + original = self.crt(physical, reverse=True) + coeffs = [original[ordinal(digits(i,self.sides),self.widths)] for i in range(self.size)] + carry = 0 + result_digits = [] + for value in coeffs: + carry, digit = divmod(value+carry, self.base) + result_digits.append(digit) + value = carry + for digit in reversed(result_digits): + value = (value << (self.public_bits//6)) + digit + return (-value if (left<0) != (right<0) else value), coeffs + + +def production_precision(public_bits, side_widths): + """Budget the physical intervals, table products and final public error.""" + intervals = 4096*sum(ell+6 for ell in side_widths) + stages = 20000*(len(side_widths)+1)*(max(side_widths)+2)**6 + return 4*public_bits + 8*intervals + 4*(stages*(len(side_widths)+1)).bit_length() + 64 + + +def multiply_uniform(left, right): + n = max(abs(left).bit_length(), abs(right).bit_length()) + p, length, count, _ = controller_shape(n) + if not count: + return word_product(left, right) + ws = production_widths(length, count) + sides = select_squares(ws) + if sides is None: + return word_product(left, right) + machine = Multiplier(sides, digit_bits=p//6, work_bits=production_precision(p, ws)) + return machine.multiply(left, right)[0] + + +if __name__ == "__main__": + import argparse + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("left", type=int) + parser.add_argument("right", type=int) + parser.add_argument("--sides", type=int, nargs="+", help="run the gate path on a diagnostic geometry") + args = parser.parse_args() + if args.sides is None: + print(multiply_uniform(args.left, args.right)) + else: + machine = Multiplier(args.sides) + result, coefficients = machine.multiply(args.left, args.right) + print(result) + print("coefficients", coefficients) + print("complete H calls per transform", machine.transform.h_calls) diff --git a/research/direct-circulant-production-precision/retained/root_gate_plan.py b/research/direct-circulant-production-precision/retained/root_gate_plan.py new file mode 100644 index 0000000000..f306aa7fa8 --- /dev/null +++ b/research/direct-circulant-production-precision/retained/root_gate_plan.py @@ -0,0 +1,151 @@ +"""Compile a padded circulant root into source-bound one- and two-wire layers.""" + +from fractions import Fraction +from hashlib import sha256 +from importlib import import_module +from pathlib import Path +from types import SimpleNamespace +import sys + + +SOURCES = { + "research/rational-unitary-fft/exact.py": "c9b89d7357210af69865690ba12e695366961f8b501a8fab9d0fefe3fb30c479", + "research/rational-unitary-fft/engine.py": "9e36aee0835e6b1b62997433581f88b5a434ccab8ae43e5c25d1deaaf1ebf653", + "research/rational-unitary-fft/triangular.py": "46780d95ddebfed22e8f0c18565fe2e768250afa5beeb31f450292cc06f7ec11", + "research/rational-unitary-fft/generator.py": "827ef9fe1bd664859995892b59843c390f7969c938fb7e1e6dc585c31a54b555", + "research/rational-unitary-fft/full.py": "1f42d5f2858564ffb320e54ba6aa29651025491569823e25006bf5862457b803", + "research/rational-unitary-fft/vendor/stein_rational.py": "3065fc5d6d22ec44de533b08fb0c639603449456383668e561dc46629e641502", + "research/rational-unitary-fft/vendor/STEIN-PROVENANCE.json": "e7f0e8dc517387e302b1e8bf5dff7e12b29da8aa91abc6ea597f33c1ac08ba62", + "research/cubic-cyclic-inverse/vendor/interval_kernel.py": "9b7bb24640a9a7d3f83c7951dfef483ec933db4c50de6c0130b85f450eeddfbe", + "research/capped-phase-fusion/evidence/inplace_algebra_ultra/check_circuits.py": "06d1861bfe8af543908e26557ffda7e451ff176bceb9bacfaf0f04f234b336d5" +} + + +def load_compiler(root): + """Authenticate the retained modules and the four inputs used by the builder.""" + root = Path(root).resolve() + raw = {} + for relative, expected in SOURCES.items(): + data = (root / relative).read_bytes() + if sha256(data).hexdigest() != expected: + raise ValueError(f"Source differs at {relative}") + raw[relative] = data + package = root / "research/rational-unitary-fft" + sys.path.insert(0, str(package)) + try: + modules = {} + for name in ("exact", "engine", "triangular", "generator", "full"): + module = import_module(name) + if Path(module.__file__).resolve() != package / (name + ".py"): + raise ValueError(f"Foreign compiler module {name}") + modules[name] = module + finally: + sys.path.remove(str(package)) + return SimpleNamespace(raw=raw, **modules) + + +def certify_accretivity(column, margin): + """Certify strict accretivity of the stored circulant at a named margin.""" + if type(margin) not in (int, Fraction) or margin <= 0: + raise ValueError("The accretivity margin must be a positive rational") + n = len(column) + hermitian = [(column[i] + column[-i % n].conjugate()) / 2 + - margin * int(i == 0) for i in range(n)] + matrix = [[hermitian[(i-j) % n] for j in range(n)] for i in range(n)] + for j in range(n): + pivot = matrix[j][j] + if pivot.im != 0 or pivot.re <= 0: + raise ValueError("Circulant root fails the strict accretivity test") + for i in range(j+1, n): + multiplier = matrix[i][j] / pivot + for k in range(j+1, n): + matrix[i][k] = matrix[i][k] - multiplier * matrix[j][k] + + +def padded_matrix(compiler, column, n): + r = len(column) + if not 1 <= r <= n or n & (n-1): + raise ValueError("The dyadic wire count must contain the source") + C = compiler.exact.C + col = [C(real, imag) for real, imag in column] + if any(part.denominator & (part.denominator - 1) + for z in col for part in (z.re, z.im)): + raise ValueError("A column entry is outside the dyadic grid") + return col, compiler.full.Matrix([ + [col[(i-j) % r] if i < r and j < r else C(int(i == j)) for j in range(n)] + for i in range(n) + ]) + + +def compile_padded_root(compiler, column, target_width, grid_bits, radius=1, incoming=0, + margin=Fraction(1, 4)): + """Compile a rational column. The plan acts on all target_width data wires.""" + col, matrix = padded_matrix(compiler, column, target_width) + certify_accretivity(col, margin) + size_bound = max(Fraction(1), compiler.full.norm_upper(matrix)) + inverse_bound = Fraction(2 * target_width) / min(Fraction(1), margin) + budget = compiler.full.allocation(target_width, size_bound, inverse_bound, + radius, grid_bits, incoming) + builder = compiler.full.Full(budget, compiler.raw) + return builder.plan(matrix), builder + + +def diagonal_product(left, right): + return left[0] * right[0], left[1] * right[1] + + +def chain(first, second): + """Join two alternating diagonal-H words in execution order.""" + return first[:-1] + [diagonal_product(first[-1], second[0])] + second[1:] + + +def swap_word(active): + return [(1, 1), (1, -1 if active else 1), (Fraction(1, 2), Fraction(1, 2))] + + +def upper_three(t): + a = 4 * t / 5 + return [(1/a, 1), (-3, 1), (2, 1), (-a/8, Fraction(-1, 6))] + + +def upper_six(t): + # In the pivoted matrix each shear multiplier has modulus at most one. + return chain(upper_three(Fraction(-3)), upper_three(t+3)) + + +def lower_pair(gate): + """Express an invertible rational two-wire gate with exactly sixteen H gates.""" + i, j = max(((i, j) for i in range(2) for j in range(2)), + key=lambda ij: gate[ij[0]][ij[1]].norm2()) + a, b = gate[i][j], gate[i][1-j] + c, d = gate[1-i][j], gate[1-i][1-j] + if a == 0 or a*d == b*c: + raise ValueError("Singular two-wire gate") + result = chain(swap_word(j != 0), upper_six(b/a)) + result = chain(result, [(a, d-c*b/a)]) + result = chain(result, list(reversed(upper_six(c/a)))) + return chain(result, swap_word(i != 0)) + + +def paired_layer(layer, n, exact): + """Keep the original pairs and pair each remaining scalar or idle wire.""" + if n < 2 or n & 1: + raise ValueError("Pair lowering requires a positive even number of wires") + occupied = set() + singles = {} + pairs = [] + for ids, gate in layer: + if len(ids) not in (1, 2) or len(set(ids)) != len(ids): + raise ValueError("Bad matching gate") + if any(i in occupied or not 0 <= i < n for i in ids): + raise ValueError("Matching overlap or wire outside the array") + occupied.update(ids) + if len(ids) == 2: + pairs.append((tuple(ids), gate)) + else: + singles[ids[0]] = gate[0][0] + reserved = {i for ids, _ in pairs for i in ids} + rest = [i for i in range(n) if i not in reserved] + for a, b in zip(rest[::2], rest[1::2], strict=True): + pairs.append(((a, b), exact.Mat([[singles.get(a, 1), 0], [0, singles.get(b, 1)]]))) + return pairs diff --git a/research/direct-circulant-production-precision/retained/spectral.py b/research/direct-circulant-production-precision/retained/spectral.py new file mode 100644 index 0000000000..57d84e1655 --- /dev/null +++ b/research/direct-circulant-production-precision/retained/spectral.py @@ -0,0 +1,97 @@ +"""Generate bounded circulant roots and the diagonals of a signed Fourier mean.""" + +from dataclasses import dataclass +from fractions import Fraction +from math import isqrt + + +def centered(turn): + """Represent a rational number of turns in (-1/2, 1/2].""" + turn %= 1 + return turn if 2 * turn <= 1 else turn - 1 + + +def phase_value(phases, turns): + return phases.phase(turns.denominator, turns.numerator) + + +def cut_rotation(turns): + """Put the negative real axis in the middle of a largest empty arc.""" + ordered = sorted(q % 1 for q in turns) + ends = ordered[1:] + [ordered[0] + 1] + gap, left = max((b-a, a) for a, b in zip(ordered, ends, strict=True)) + return (left + gap/2 - Fraction(1, 2)) % 1 + + +def lower_sqrt(value, bits): + scale = 1 << bits + return Fraction(isqrt((value.numerator * scale**2) // value.denominator), scale) + + +@dataclass +class RootColumn: + column: list + rotation: Fraction + accretivity: Fraction + phase_bits: int + + +def polar_root(compiler, radii, turns, bits, phase_grid=None): + """Generate one dyadic circulant for the two-pass factorization.""" + if not turns or len(radii) != len(turns) or bits < 1: + raise ValueError("Expected one modulus and phase per frequency") + if any(not isinstance(q, Fraction) for q in (*radii, *turns)) or min(radii) <= 0: + raise ValueError("Expected positive rational moduli and rational phase turns") + r = len(turns) + condition = max(Fraction(1), max(radii), 1/min(radii)) + cap = -(-condition.numerator // condition.denominator) + if phase_grid is None: + rotation = cut_rotation(turns) + gap_scale = r + else: + if phase_grid < 1 or any((phase_grid*q).denominator != 1 for q in turns): + raise ValueError("The declared phase grid misses a frequency") + rotation = Fraction(-1, 2*phase_grid) if phase_grid % 2 == 0 else Fraction(0) + gap_scale = phase_grid + b = bits + 4*max(r, gap_scale).bit_length() + 4*cap.bit_length() + 16 + phases = compiler.engine.Phases(b+4, compiler.raw[compiler.generator.ORACLE]) + angles = [centered(q-rotation)/2 for q in turns] + magnitudes = [lower_sqrt(q, b) for q in radii] + column = [] + for j in range(r): + total = compiler.exact.C() + for k, (radius, angle) in enumerate(zip(magnitudes, angles, strict=True)): + phase = phase_value(phases, angle + Fraction(j*k, r)) + total += phase * radius + q = compiler.exact.rounded(total/r, b) + column.append((q.re, q.im)) + return RootColumn(column, rotation, Fraction(1, 2*max(2, gap_scale)*cap), b), phases + + +@dataclass +class Axis: + size: int + width: int + entrance: tuple + exit: tuple + layers: list + + +def fourier_axis(compiler, r, t, direction, bits): + """Compile the signed mean on r original positions and identity on the holes.""" + from root_gate_plan import compile_padded_root + + if r < 2 or t < r or t & (t-1) or direction not in (-1, 1): + raise ValueError("Invalid cyclic order, dyadic container or Fourier sign") + turns = [Fraction(direction*j*(j+r), 2*r) for j in range(r)] + root, phases = polar_root(compiler, [Fraction(1)]*r, turns, bits, phase_grid=2*r) + plan, _ = compile_padded_root(compiler, root.column, t, bits, radius=2*t, + margin=root.accretivity) + chirps = [phase_value(phases, q) for q in turns] + gauss_mean = sum((z.conjugate() for z in chirps), compiler.exact.C()) / r + compensation = phase_value(phases, root.rotation) * gauss_mean + rounded = compiler.exact.rounded + entrance = [rounded(z, root.phase_bits) for z in chirps] + exit_diag = [rounded(compensation*z, root.phase_bits) for z in chirps] + holes = [compiler.exact.C(1)] * (t-r) + return Axis(r, t, tuple(entrance+holes), tuple(exit_diag+holes), plan) diff --git a/research/direct-circulant-production-precision/retained/tensor_word.py b/research/direct-circulant-production-precision/retained/tensor_word.py new file mode 100644 index 0000000000..8bc7bc5995 --- /dev/null +++ b/research/direct-circulant-production-precision/retained/tensor_word.py @@ -0,0 +1,168 @@ +"""Execute the simultaneous diagonal and Hadamard word on a full dyadic tensor.""" + +from fractions import Fraction +from hashlib import sha256 +from importlib.util import module_from_spec, spec_from_file_location +from math import prod + +from root_gate_plan import lower_pair, paired_layer +from word_product import word_product + + +def load_routes(root): + source = root / "research/unconditional-batched-crt/check_batched_crt.py" + if sha256(source.read_bytes()).hexdigest() != "681e2e3d71fa74c8b9b326f3860104fd9d89590a222e26ae6ee718d1fd40ff2e": + raise ValueError("Retained CRT and Beneš source differs") + spec = spec_from_file_location("retained_balanced_crt", source) + module = module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class Grid: + """Use a common denominator for real and imaginary component words.""" + + def __init__(self, bits): + if bits < 1: + raise ValueError("The grid must have at least one fractional bit") + self.bits = bits + self.unit = 1 << bits + self.one = (self.unit, 0) + + def word(self, z): + a, b = (z.re, z.im) if hasattr(z, "re") else (Fraction(z), 0) + return round(a*self.unit), round(b*self.unit) + + def multiply(self, u, v): + if u == self.one: + return v + if v == self.one: + return u + a, b = u + c, d = v + half = self.unit >> 1 + return ((word_product(a,c)-word_product(b,d)+half) >> self.bits, + (word_product(a,d)+word_product(b,c)+half) >> self.bits) + + +def local_schedule(axis, layers, compiler, routes, grid): + n = axis.width + ones = tuple([grid.one] * n) + halves = tuple([(grid.unit//2, 0)] * n) + words = {} + route_cache = {} + emitted = [] + for i in range(layers): + gates = axis.layers[i] if i < len(axis.layers) else () + pairs = paired_layer(gates, n, compiler.exact) + permutation = [0] * n + tables = [[] for _ in range(17)] + for j, ((x, y), gate) in enumerate(pairs): + permutation[x], permutation[y] = 2*j, 2*j+1 + key = tuple((z.re, z.im) for row in gate for z in row) + if key not in words: + words[key] = tuple(tuple(map(grid.word, diag)) for diag in lower_pair(gate)) + for table, diag in zip(tables, words[key], strict=True): + table.extend(diag) + perm = tuple(permutation) + if perm not in route_cache: + switches = [] + for bit, mask in routes.benes(perm): + signs = tuple((-grid.unit if mask[k] and (k >> bit) & 1 else grid.unit, 0) + for k in range(n)) + switches.append(((bit, ones), (bit, signs), (None, halves))) + route_cache[perm] = switches + switches = route_cache[perm] + for switch in switches: + emitted.extend(switch) + emitted.extend((0 if j < 16 else None, tuple(table)) + for j, table in enumerate(tables)) + for switch in reversed(switches): + emitted.extend(switch) + return emitted + + +def product_diagonal(data, tables, grid): + """Apply a tensor diagonal with suffix products and a mixed-radix counter.""" + sides = [len(row) for row in tables] + if prod(sides) != len(data): + raise ValueError("The diagonal must cover the whole field") + position = [0] * len(sides) + suffix = [grid.one] * (len(sides)+1) + for j in range(len(sides)-1, 0, -1): + suffix[j] = grid.multiply(tables[j][0], suffix[j+1]) + for index, x in enumerate(data): + diagonal = grid.multiply(tables[0][position[0]], suffix[1]) + data[index] = grid.multiply(diagonal, x) + if index+1 == len(data): + break + j = 0 + while position[j]+1 == sides[j]: + position[j] = 0 + j += 1 + position[j] += 1 + for k in range(j, 0, -1): + suffix[k] = grid.multiply(tables[k][position[k]], suffix[k+1]) + + +def hadamard(data, strides): + """Elementary exact realization of one simultaneous public H call.""" + for stride in strides: + for start in range(0, len(data), 2*stride): + for lo in range(start, start+stride): + hi = lo+stride + a, b = data[lo] + c, d = data[hi] + data[lo], data[hi] = (a+c, b+d), (a-c, b-d) + + +def axis_packs(sides, public_bits): + """Keep an untouched reservoir for a large simultaneous H.""" + d = len(sides) + s = (public_bits+1).bit_length() + limit = d if d <= s*s else max(1, d//s) + for width in sorted(set(sides)): + indices = [i for i, t in enumerate(sides) if t == width] + for start in range(0, len(indices), limit): + yield indices[start:start+limit] + + +class TensorWord: + def __init__(self, axes, compiler, routes, grid, public_bits=None): + self.grid = grid + self.sides = tuple(a.width for a in axes) + self.entrance = [tuple(map(grid.word, a.entrance)) for a in axes] + self.exit = [tuple(map(grid.word, a.exit)) for a in axes] + self.jobs = [] + self.h_calls = 0 + self.idles = [tuple([grid.one]*t) for t in self.sides] + strides = [prod(self.sides[:j]) for j in range(len(axes))] + for active in axis_packs(self.sides, public_bits or grid.bits): + depth = max(len(axes[i].layers) for i in active) + programs = [local_schedule(axes[i], depth, compiler, routes, grid) for i in active] + schedule = [] + for stage in zip(*programs, strict=True): + bit = stage[0][0] + if any(other_bit != bit for other_bit, _ in stage): + raise ValueError("Different local H targets in one physical call") + tables = self.idles.copy() + for i, (_, table) in zip(active, stage, strict=True): + tables[i] = table + target = () if bit is None else tuple(strides[i] << bit for i in active) + schedule.append((tables, target)) + self.h_calls += 2*bool(target) + self.jobs.append(schedule) + + def apply(self, values, opposite=False): + if len(values) != prod(self.sides): + raise ValueError("The signal must contain every physical record") + data = [(a,-b) for a,b in values] if opposite else list(values) + product_diagonal(data, self.entrance, self.grid) + for schedule in self.jobs: + for _ in range(2): + for tables, target in schedule: + product_diagonal(data, tables, self.grid) + if target: + hadamard(data, target) + product_diagonal(data, self.exit, self.grid) + return [(a,-b) for a,b in data] if opposite else data diff --git a/research/direct-circulant-production-precision/review/CROSS-REVIEW.md b/research/direct-circulant-production-precision/review/CROSS-REVIEW.md new file mode 100644 index 0000000000..4ad58763b1 --- /dev/null +++ b/research/direct-circulant-production-precision/review/CROSS-REVIEW.md @@ -0,0 +1,273 @@ +# Independent review of the direct-circulant precision selector + +**Verdict: accept the stated local numerical theorem under its named source +contracts, after the factor-count clarification below.** No blocking error +was found in the selector, interval estimates, odometer induction, bootstrap +or stated recovery corollary. This model-assisted review is not human peer +review, formal-kernel acceptance or admission of the complete multiplier. + +Review scope: wave 2, track 77, canonical base +`e54523517d0f03e58352e647c403a5af3e525a57`, package +`research/direct-circulant-production-precision`, and Ali Romman's #7849 at +`3615fd982f2f4dc7172bef6f0dc9a4f77d5ab6dd`. + +Initial proof SHA256: +`46b6651555dde18253c3f20220e455767acb970a0c459bdc09a3bd1f15a3698a`. +Accepted proof SHA256: +`26e4e214f0a5785c1d1414561465bb49a3248f9e6f59f6b514eb95a887bdfe2f`. +Only the two prose sentences giving the fully expanded factor census changed. +The selector, exponent envelopes and checker were unchanged. + +## 1. Accepted quantifiers and retained premises + +For every d>=1, true sides 2<=r_i<=t_i=2^ell_i, ell_i>=1, integer p>=1, +and represented complete padded tensor x with max |x_j|<=1/2, put + +\[ +L=\sum_i\ell_i,\quad E=\lceil1257L/2\rceil+2154d, +\quad A=104L+438d, +\] +\[ +J=20000(d+1)(\max_i\ell_i+2)^6,\quad +C=4J(d+1)^2+d+1,\quad P=4p+A+2E+\operatorname{bitlength}(C). +\] + +Using P in the external Grid and P+8 in fourier_axis gives error strictly +below 2^(-4p) against the tensor Fourier mean, with identity on each local +hole block, for both source signs. The following contracts remain premises: + +- The exact-unit rational phase oracle has its certified error at every + requested precision. +- The padded-root rank/conditioning adapter is in the full compiler's + applicability class, and the retained compiler has its explicit exact-word, + fragment, prefix/inverse-prefix and layer estimates. The precision package + instantiates those estimates; it does not re-prove that entire compiler. +- The native H service is exact on represented words on a sufficiently + widened private grid, with its complete-field restoration contract. +- The pinned lowering and coefficient/data arithmetic are the actual source + execution. They are not an arbitrary dense transform at unit cost. + +The recovery corollary additionally retains the source CRT character, true +volume S<=B, no-wrap condition, radix scale 4B, p=6 log_2 B, B>=32, and +public toward-zero conversions. The actual Multiplier wrapper further +restricts its geometry, including a power-of-two axis count; the local +TensorWord numerical theorem does not claim that wrapper accepts every d. + +## 2. Exact source boundary and independent method + +I read all six vendored scientific files, the new proof and selector, and +canonical FULL-PROOF.md. I independently fetched #7849's PROOF.md, +ROOT-CIRCUIT.md and COMPOSITE-OUTER.md at the exact head. Their bytes agree +with the author's reference copies; API Git blobs and SHA256 hashes are in +UPSTREAM-PINS.json. The canonical full compiler proof SHA256 is +`acf8c596d91b5efd35a286735d6867ff8afce64354a13f680c2fae3dab824410`. +Its (12), (13), (14) and (15) explicitly provide the coefficient defect, +physical-cut decomposition, prefix/suffix and inverse estimates, and depth. + +I did not run check_precision.py as independent evidence. The separate +check_review.py extracts named literal source functions, uses a new +Gaussian-rational matrix interpreter, and uses noncommutative expression +trees for the odometer. It imports neither the author's precision engine nor +the compiler matrix class. READ-BOUNDARY.json and FINAL-BOUNDARY.json preserve +initial and final review hashes. + +## 3. Column guard, leading sections and endpoint synthesis + +The source bit binding is correct: fourier_axis receives P+8; cap=1 and +gap_scale=2r in polar_root. Thus b=P+28+4h, h=bit_length(2r), and the phase +routine receives b+4. With u=2^-b its error is at most u/16. The lower +square root of radius one is exactly one. Consequently 4u per column entry +and 4ru for the operator are conservative. Since 2^h>2r, + +\[ +4ru<2^{-P-30}/r^3<1/(4r). +\] + +The centered roots of the even 2r-grid have real part at least +sin(pi/(4r))>=1/(2r). The stored root therefore has real part strictly +larger than the declared margin mu=1/(4r). Compression to any leading +section, including one that cuts the cyclic block, preserves this lower +bound. Cauchy–Schwarz implies inverse spectral norm at most 4r; converting +component row/column sums with sqrt(2k)<=2t yields the literal Q=8tr<=8t². +This is a real-part proof for every section, not an inference from full +matrix invertibility. The padded matrix is not incorrectly called globally +Toeplitz; its separate rank applicability remains a named source input. + +The approximate Gauss mean is an average of exact unit phases and hence has +modulus at most one. The exit's three phase replacements cost at most +3u/16, and final rounding adds less than u. Thus both outer diagonals have +error <2u. Their inverse bounds correctly use the ideal exit magnitude +1/sqrt(r); 2t covers both directions and identity holes. + +The compiler exact-word root defect is at most 2^(-P-8) against the stored +column; after the column error it is at most 2^(-P-7) against the ideal root. +Telescoping the four axis factors, with approximate norms <=2 and ideal +norms <=1, gives + +\[ +9\epsilon_{\rm diag}+6\epsilon_{\rm root} +\le(9/256+6/128)2^{-P}=21\,2^{-P}/256<2^{-P}. +\] + +The bias is incurred once per axis, not once per emitted gate. + +## 4. Prefixes, inverses, literal factors and partial H calls + +The universal substitutions lambda<=4t, Q<=8t², chi<=32t³ and +r_star<=5t give B<=2^68 t^39, alpha<=1280t^6 and K_G<=2050t^5. +The exact product 4102*9230=37,861,460<2^26 bounds H_star by 2^26 t^11; +the other fragment terms 133t^4 and 16t² fit that envelope. Source (14) +then gives K_phys<=2^98 t^52. These inequalities hold for every t>=2. + +An original matching gate is a ratio of adjacent source prefixes. The +inverse-prefix estimate therefore gives L_gate=K_phys² for both gate and +inverse. Largest-entry pivoting gives |b/a|,|c/a|<=1. The middle diagonal +diag(a,det(G)/a) and its inverse are bounded by 2 L_gate: the first +reciprocal follows from the largest-entry inequality, and the second is +an entry of the permuted inverse matrix. + +I independently multiplied the three-H identity. For a=4t/5, + +\[ +\operatorname{diag}(-a/8,-1/6)H\operatorname{diag}(2,1)H +\operatorname{diag}(-3,1)H\operatorname{diag}(1/a,1) +=\begin{pmatrix}1&t\\0&1\end{pmatrix}. +\] + +The two arguments -3 and 3+z have moduli between two and four when +|z|<=1. Every non-pivot primitive diagonal and inverse is bounded by 64. +Two switch words, four three-H words and one pivot fully expand to +**23 diagonals and 16 H factors**, hence **38 non-pivot factors**. +The original 21/36 count had already joined internal upper_six boundaries. +Both fit 64^40, but the expanded count makes the primitive bound immediate. +The author accepted this two-sentence repair without changing any constant. + +The independent literal interpreter checks 600 Gaussian-rational matrices, +all four pivot positions, large/small scales and near-singular Schur +diagonals. It verifies the endpoint, primitive/inverse factor bounds and +the census. A sign mutation fails. The universal justification is the +algebra above; finite samples corroborate the source binding. + +Completed routing rows are permutations. A partial switch adds at most +four; completed rows add norm one. Thus each lowered root prefix and its +inverse is bounded by + +\[ +4K\,64^{40}(2K^2)\le2^{537}t^{156}. +\] + +Two roots and both external diagonals give 2^1076 t^314 per one-axis +prefix/inverse. Each axis contributes exactly one such prefix even when +axes finish at different times. Serial width classes and packs do not +multiply that number. An extra 2^d at each interval end permits partial +external H packs. The resulting interval 2-norm is at most +2^(2154d+628L). A single sqrt(T)=2^(L/2) conversion gives exactly E. +The native service's private arithmetic cuts remain outside this external +interval theorem, as its named exactness premise requires. + +## 5. Literal stage count and coefficient-cache invariant + +A matching has 17 diagonal entries and 16 H calls. Each of its +2(2ell-1) route switches has three diagonal entries and two H calls. +Counting diagonals and H separately gives the sharper literal bound + +\[ +33+10(2\ell-1)=20\ell+23. +\] + +The paper's 24ell+22 bound is larger for ell>=1. Two roots and at most +d packs give J_actual<=2+2d D(ell_max)(20ell_max+23). The independent +polynomial certificate proves J minus this expression has positive +coefficients in both its constant and d-linear parts. The exact two-root +depth coefficients, in increasing degree, are +`[46,13288,38384,35136,11712,1280]`; the available degree-six polynomial +dominates each strictly. This covers unbounded widths. Separating the H +step is essential because a pre-H diagonal error must propagate through H. + +For coefficient arithmetic, b_i=2^437 t_i^104 bounds every exact scalar +of an emitted axis diagonal, including fused pivot boundaries. Each +rounded factor is at most 2b_i, and each complex multiplication has error +<=v=2^-P. Factor telescoping plus at most d-1 rounded multiplications +gives the stated 2d 2^d product(b_i) v bound. Final multiplication by data +adds at most v, yielding epsilon(1+||z||∞) with the declared A. + +The odometer invariant concerns the actual rounded expression tree. +At current indices i_0,...,i_(d-1), suffix k is the fixed right-associated +rounded product of the current factors with index at least k. A carry +through j changes only coordinates 0,...,j. Recomputing j down to 1 +restores the invariant; higher suffixes already have unchanged arguments. +No retained suffix contains more than d factors, regardless of scan length. + +My oracle distinguishes every (axis,index) factor and input datum with +noncommutative trees, so numerical cancellation cannot hide a stale cache. +Twelve shapes, including heterogeneous dyadic sides and carries through +eight axes, cover 1,214 records. Every output tree equals fresh +current-coordinate evaluation. Skipping the newly changed suffix fails +at the first relevant carry. This independently tests the no-drift +invariant rather than repeating the author's numeric packets. + +## 6. Bootstrap, signs and recovery + +The bootstrap comparison word is the exact rational word before external +table/data rounding. Rounded tensor coefficients need not factor as exact +tensors; their deviation is a local defect. This distinction is respected. + +Let a=JM epsilon and R=2^E. Variation of constants bounds each computed +prefix error by a(1+R+maximum_previous_error). The finite bootstrap gives +error <=2a(1+R) when a<=1/2. Here the selector establishes the stronger + +\[ +a<2^{-4p-E}/4<1/4, +\qquad \text{raw error}\le C2^{-P+A+2E}<2^{-4p}, +\] + +because C<2^bit_length(C). Thus no desired computed-state bound is assumed +in advance. If the native interface requires unit-disk inputs, the derived +radius 2R+1 permits the predetermined shift 2^(E+2), with corresponding +extra fractional bits, under the widened exact-native contract. + +The source opposite-sign path conjugates the input and output of the same +forward program. Conjugation is an isometry; no oddness of the component +tie-breaking rule is required. + +For recovery, the Fourier means are maximum-norm contractions on the whole +true/hole tensor. Forward error in a zero-filled hole is below +2^-4p<2^-p, so the actual public toward-zero conversion returns zero. +Pointwise public products stay in the next half-disk input domain. +The inherited source theorem bounds normalized final error by 3e, e=3/B^6. +Scaling by (4BS)^2 includes both digit scales and the two net source-size +factors. Therefore, with S<=B, + +\[ +(4BS)^2(3e)\le144/B^2<1/2\quad(B\ge32). +\] + +The correct direct character is u=sum_i(S/r_i) mu_i² mod S. At each +true side its own summand is a unit and every other summand vanishes, +so u is a unit modulo S. Reusing the old Gaussian character's extra +t_i would be a different and generally invalid application. This review +retains the precise CRT/recovery theorem; the scalar inequality alone +would not prove that application. + +## 7. Result, limits and reproduction + +The selector is sufficient, not minimum. The old-minus-new positivity +calculation is sound, so the result also validates #7849's larger original +selector under the named contracts. #7981 changes chronology and weakens +the intermediate target; the package correctly disclaims an asymptotic +improvement over that successor. No complete-framework assumption is +removed and no physical tape or owned-arena theorem is supplied here. + +Run the independent evidence with: + +```sh +python3 -I -W error -B check_review.py PATH/TO/direct-circulant-production-precision +``` + +It finishes with PASS_INDEPENDENT_PRECISION_CROSS_REVIEW. +REVIEW-EVIDENCE.txt contains the actual counts and polynomial certificate; +REVIEW-RECEIPT.json pins the checker, result and accepted proof. The +universal acceptance rests on the written conditional argument reviewed +above, not extrapolation from finite examples. No blocking objections +remain after the factor-count correction. The next substantive obligation +is the already disclosed private-grid and owned-arena interface. diff --git a/research/direct-circulant-production-precision/review/FINAL-BOUNDARY.json b/research/direct-circulant-production-precision/review/FINAL-BOUNDARY.json new file mode 100644 index 0000000000..4d02a6c487 --- /dev/null +++ b/research/direct-circulant-production-precision/review/FINAL-BOUNDARY.json @@ -0,0 +1,91 @@ +{ + "package": "/workspace/scratch/5b0914ccc34e/work-analytic/research/direct-circulant-production-precision", + "accepted_proof_sha256": "26e4e214f0a5785c1d1414561465bb49a3248f9e6f59f6b514eb95a887bdfe2f", + "files": [ + { + "file": "EVIDENCE.json", + "sha256": "5a02524187cc6b0dfadfe242fa0911253fabd66650b660c7eec13532b7489e4a", + "bytes": 3184 + }, + { + "file": "LICENSE", + "sha256": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4", + "bytes": 11357 + }, + { + "file": "NOTICE.md", + "sha256": "639ac4453a39ea5231b6bcf26014faee43b3815f4ea69937560eeae02d731979", + "bytes": 1134 + }, + { + "file": "ORIGINS.json", + "sha256": "35fee83e133468cc03ca82fb5f241e06b89027d11683a0f6b90bef221847f017", + "bytes": 3366 + }, + { + "file": "PROOF.md", + "sha256": "26e4e214f0a5785c1d1414561465bb49a3248f9e6f59f6b514eb95a887bdfe2f", + "bytes": 17479 + }, + { + "file": "README.md", + "sha256": "3337bc3238c9c62264eaec40a9ee51ea933abdcf4519dd1b0270bd565392d581", + "bytes": 8503 + }, + { + "file": "SOURCES.json", + "sha256": "355d3e022fcc4e0db3561e64b2bf768594d07231378aca0c8b34f9e6c74d9112", + "bytes": 1972 + }, + { + "file": "TASK.json", + "sha256": "b5519057617cb8a009bdb3f050e6a5a2b72bbdbe4580953f37185e566be15727", + "bytes": 6808 + }, + { + "file": "VERIFY.json", + "sha256": "0efbaef10c6d0ead93b6672f233cde540908a28d377fbb720893bb712e76a045", + "bytes": 690 + }, + { + "file": "check_precision.py", + "sha256": "61bdeb7adca6d6f90034385eccb972ffde81f4bb9b411faa2076d5a0310d27e7", + "bytes": 14873 + }, + { + "file": "precision.py", + "sha256": "c5a82b4143a951bee14ced731ece4ad1458172d018ec79ba347e119aa33c0fa2", + "bytes": 1503 + }, + { + "file": "retained/compiler-engine.py", + "sha256": "9e36aee0835e6b1b62997433581f88b5a434ccab8ae43e5c25d1deaaf1ebf653", + "bytes": 13174 + }, + { + "file": "retained/compiler-full.py", + "sha256": "1f42d5f2858564ffb320e54ba6aa29651025491569823e25006bf5862457b803", + "bytes": 12561 + }, + { + "file": "retained/product.py", + "sha256": "29ab6c60f937b7cce58666f5ddd7a921c3197cf72abf91ecca0ff7ad9486850e", + "bytes": 6733 + }, + { + "file": "retained/root_gate_plan.py", + "sha256": "379ca05625076824ac9c2399eac03c1c64c13fecee45ea17f78b8898df57cd2d", + "bytes": 6607 + }, + { + "file": "retained/spectral.py", + "sha256": "ede9c48d34280c9c1c5c332b9434ff666fd321f4a18ffbf1f61b3339339e8ab6", + "bytes": 3836 + }, + { + "file": "retained/tensor_word.py", + "sha256": "36c5a9a0082c9aa3c6cb2d04a9196af8debce0d551a0525975b710018ea02cac", + "bytes": 6815 + } + ] +} diff --git a/research/direct-circulant-production-precision/review/READ-BOUNDARY.json b/research/direct-circulant-production-precision/review/READ-BOUNDARY.json new file mode 100644 index 0000000000..54253769dd --- /dev/null +++ b/research/direct-circulant-production-precision/review/READ-BOUNDARY.json @@ -0,0 +1,90 @@ +{ + "package": "/workspace/scratch/5b0914ccc34e/work-analytic/research/direct-circulant-production-precision", + "files": [ + { + "file": "EVIDENCE.json", + "sha256": "5a02524187cc6b0dfadfe242fa0911253fabd66650b660c7eec13532b7489e4a", + "bytes": 3184 + }, + { + "file": "LICENSE", + "sha256": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4", + "bytes": 11357 + }, + { + "file": "NOTICE.md", + "sha256": "639ac4453a39ea5231b6bcf26014faee43b3815f4ea69937560eeae02d731979", + "bytes": 1134 + }, + { + "file": "ORIGINS.json", + "sha256": "35fee83e133468cc03ca82fb5f241e06b89027d11683a0f6b90bef221847f017", + "bytes": 3366 + }, + { + "file": "PROOF.md", + "sha256": "46b6651555dde18253c3f20220e455767acb970a0c459bdc09a3bd1f15a3698a", + "bytes": 17447 + }, + { + "file": "README.md", + "sha256": "3337bc3238c9c62264eaec40a9ee51ea933abdcf4519dd1b0270bd565392d581", + "bytes": 8503 + }, + { + "file": "SOURCES.json", + "sha256": "355d3e022fcc4e0db3561e64b2bf768594d07231378aca0c8b34f9e6c74d9112", + "bytes": 1972 + }, + { + "file": "TASK.json", + "sha256": "b5519057617cb8a009bdb3f050e6a5a2b72bbdbe4580953f37185e566be15727", + "bytes": 6808 + }, + { + "file": "VERIFY.json", + "sha256": "0efbaef10c6d0ead93b6672f233cde540908a28d377fbb720893bb712e76a045", + "bytes": 690 + }, + { + "file": "check_precision.py", + "sha256": "61bdeb7adca6d6f90034385eccb972ffde81f4bb9b411faa2076d5a0310d27e7", + "bytes": 14873 + }, + { + "file": "precision.py", + "sha256": "c5a82b4143a951bee14ced731ece4ad1458172d018ec79ba347e119aa33c0fa2", + "bytes": 1503 + }, + { + "file": "retained/compiler-engine.py", + "sha256": "9e36aee0835e6b1b62997433581f88b5a434ccab8ae43e5c25d1deaaf1ebf653", + "bytes": 13174 + }, + { + "file": "retained/compiler-full.py", + "sha256": "1f42d5f2858564ffb320e54ba6aa29651025491569823e25006bf5862457b803", + "bytes": 12561 + }, + { + "file": "retained/product.py", + "sha256": "29ab6c60f937b7cce58666f5ddd7a921c3197cf72abf91ecca0ff7ad9486850e", + "bytes": 6733 + }, + { + "file": "retained/root_gate_plan.py", + "sha256": "379ca05625076824ac9c2399eac03c1c64c13fecee45ea17f78b8898df57cd2d", + "bytes": 6607 + }, + { + "file": "retained/spectral.py", + "sha256": "ede9c48d34280c9c1c5c332b9434ff666fd321f4a18ffbf1f61b3339339e8ab6", + "bytes": 3836 + }, + { + "file": "retained/tensor_word.py", + "sha256": "36c5a9a0082c9aa3c6cb2d04a9196af8debce0d551a0525975b710018ea02cac", + "bytes": 6815 + } + ] +} diff --git a/research/direct-circulant-production-precision/review/REVIEW-EVIDENCE.txt b/research/direct-circulant-production-precision/review/REVIEW-EVIDENCE.txt new file mode 100644 index 0000000000..5e89dc7f47 --- /dev/null +++ b/research/direct-circulant-production-precision/review/REVIEW-EVIDENCE.txt @@ -0,0 +1,65 @@ +{ + "literal_word": { + "cases": 600, + "pivot_locations": [ + [ + 0, + 0 + ], + [ + 0, + 1 + ], + [ + 1, + 0 + ], + [ + 1, + 1 + ] + ], + "fully_expanded_diagonals": 23, + "H_factors": 16, + "nonpivot_factors": 38, + "retained_nonpivot_envelope": 40, + "negative_control": "sign in upper_three final diagonal changes endpoint" + }, + "odometer_lineage": { + "cases": 12, + "records": 1214, + "oracle": "exact current-coordinate right-associated expression tree, no numeric cancellation", + "negative_control": "skip newly changed suffix at a carry" + }, + "literal_stage_count": { + "actual_steps_per_matching": "20*ell+23", + "literal_two_root_depth_coefficients": [ + 46, + 13288, + 38384, + 35136, + 11712, + 1280 + ], + "J_minus_actual_constant_coefficients": [ + 1279998, + 3840000, + 4800000, + 3200000, + 1200000, + 240000, + 20000 + ], + "J_minus_actual_d_coefficients": [ + 1279954, + 3826712, + 4761616, + 3164864, + 1188288, + 238720, + 20000 + ] + }, + "scope": "Independent source/schema checks; universal inequalities are in CROSS-REVIEW.md" +} +PASS_INDEPENDENT_PRECISION_CROSS_REVIEW diff --git a/research/direct-circulant-production-precision/review/REVIEW-RECEIPT.json b/research/direct-circulant-production-precision/review/REVIEW-RECEIPT.json new file mode 100644 index 0000000000..18ca178144 --- /dev/null +++ b/research/direct-circulant-production-precision/review/REVIEW-RECEIPT.json @@ -0,0 +1,18 @@ +{ + "accepted_proof_sha256": "26e4e214f0a5785c1d1414561465bb49a3248f9e6f59f6b514eb95a887bdfe2f", + "review_sha256": "2c032c534efd1e6ee261c1b4733a756fb2dc5b2c6115cce810113b7c2b2fd25c", + "checker_sha256": "18e9494d9995684f819b3e8e20bc4d1fa6a5919d99d44494cdaabc0b4e9f5cf6", + "evidence_sha256": "f5fa5883db2a2418a2809e34b0466d4804a027b042572a7972cc6a1e58c363e1", + "command": [ + "python3", + "-I", + "-W", + "error", + "-B", + "check_review.py", + "/workspace/scratch/5b0914ccc34e/work-analytic/research/direct-circulant-production-precision" + ], + "exit_code": 0, + "author_verifier_run": false, + "status": "ACCEPT_CONDITIONAL_LOCAL_NUMERICAL_THEOREM_AFTER_FACTOR_COUNT_CLARIFICATION" +} diff --git a/research/direct-circulant-production-precision/review/UPSTREAM-PINS.json b/research/direct-circulant-production-precision/review/UPSTREAM-PINS.json new file mode 100644 index 0000000000..062ed561a9 --- /dev/null +++ b/research/direct-circulant-production-precision/review/UPSTREAM-PINS.json @@ -0,0 +1,29 @@ +[ + { + "local": "refs/pr7849/PROOF.md", + "repository": "aliromman/integer-mult-bounds", + "commit": "3615fd982f2f4dc7172bef6f0dc9a4f77d5ab6dd", + "path": "research/direct-circulant-fourier/PROOF.md", + "git_blob": "4425f80b38d64e2d5714fcd5c1582e84bc21eda5", + "sha256": "2c34a896932e7be813a87ef0fe420c8cf86cd13a44c92942073f83ba721c10af", + "matches_author_reference_copy": true + }, + { + "local": "refs/pr7849/ROOT-CIRCUIT.md", + "repository": "aliromman/integer-mult-bounds", + "commit": "3615fd982f2f4dc7172bef6f0dc9a4f77d5ab6dd", + "path": "research/direct-circulant-fourier/ROOT-CIRCUIT.md", + "git_blob": "6c2e924edad16a2b95fb285f88e4029ef0c6e776", + "sha256": "9e2990c215bef84722ea083d383b23bf4eaca1255cdaee6e311a7e2781eb8d78", + "matches_author_reference_copy": true + }, + { + "local": "refs/pr7849/COMPOSITE-OUTER.md", + "repository": "aliromman/integer-mult-bounds", + "commit": "3615fd982f2f4dc7172bef6f0dc9a4f77d5ab6dd", + "path": "research/direct-circulant-fourier/COMPOSITE-OUTER.md", + "git_blob": "32587da2cc622f7dccec69c2df2dd5cb055db0ea", + "sha256": "baa8e61912664afd656752d414bf5e55a23e037637251e17cbb1458a27942c76", + "matches_author_reference_copy": true + } +] diff --git a/research/direct-circulant-production-precision/review/check_review.py b/research/direct-circulant-production-precision/review/check_review.py new file mode 100644 index 0000000000..3e5d58f986 --- /dev/null +++ b/research/direct-circulant-production-precision/review/check_review.py @@ -0,0 +1,277 @@ +"""Independent literal-word and cache-lineage audit for the precision theorem. + +No author verifier, precision selector or compiler matrix class is imported. +Only the small exact functions under review are extracted from pinned source. +The independent matrix interpreter uses Gaussian rationals; the odometer oracle +uses noncommutative expression trees, so cancellations cannot hide stale data. +""" +import ast +from dataclasses import dataclass +from fractions import Fraction as Q +from hashlib import sha256 +from itertools import product +import json +from math import prod, comb +from pathlib import Path +import sys + +PACKAGE = Path('research/direct-circulant-production-precision') +HERE = Path(__file__).resolve().parent + + +def need(value, message): + if not value: + raise ValueError(message) + + +@dataclass(frozen=True) +class Z: + re: Q = Q(0) + im: Q = Q(0) + + def __post_init__(self): + object.__setattr__(self, 're', Q(self.re)) + object.__setattr__(self, 'im', Q(self.im)) + + @staticmethod + def lift(z): + return z if isinstance(z, Z) else Z(Q(z)) + + def __add__(self, other): + other = Z.lift(other) + return Z(self.re + other.re, self.im + other.im) + + __radd__ = __add__ + + def __neg__(self): + return Z(-self.re, -self.im) + + def __sub__(self, other): + return self + (-Z.lift(other)) + + def __rsub__(self, other): + return Z.lift(other) - self + + def __mul__(self, other): + other = Z.lift(other) + return Z(self.re * other.re - self.im * other.im, + self.re * other.im + self.im * other.re) + + __rmul__ = __mul__ + + def __truediv__(self, other): + other = Z.lift(other) + denominator = other.norm2() + return Z((self.re * other.re + self.im * other.im) / denominator, + (self.im * other.re - self.re * other.im) / denominator) + + def __rtruediv__(self, other): + return Z.lift(other) / self + + def norm2(self): + return self.re ** 2 + self.im ** 2 + + def component_norm(self): + return abs(self.re) + abs(self.im) + + +ZERO, ONE = Z(), Z(Q(1)) +IDENTITY = ((ONE, ZERO), (ZERO, ONE)) +H = ((ONE, ONE), (ONE, -ONE)) +SWAP = ((ZERO, ONE), (ONE, ZERO)) + + +def matmul(a, b): + return tuple(tuple(sum((a[i][k] * b[k][j] for k in range(2)), ZERO) + for j in range(2)) for i in range(2)) + + +def inverse(a): + d = a[0][0] * a[1][1] - a[0][1] * a[1][0] + return ((a[1][1] / d, -a[0][1] / d), (-a[1][0] / d, a[0][0] / d)) + + +def bound(a): + return max(sum(z.component_norm() for z in row) for row in (*a, *zip(*a))) + + +def authenticated(name): + pins = json.loads((PACKAGE / 'ORIGINS.json').read_text())['files'] + pin = next(p for p in pins if p['file'] == name) + raw = (PACKAGE / 'retained' / name).read_bytes() + need(sha256(raw).hexdigest() == pin['sha256'], 'source differs: ' + name) + return raw + + +def functions(raw, names, namespace): + module = ast.parse(raw) + body = [node for node in module.body if isinstance(node, ast.FunctionDef) and node.name in names] + need({node.name for node in body} == set(names), 'missing literal source function') + exec(compile(ast.Module(body=body, type_ignores=[]), '', 'exec'), namespace) + return namespace + + +class Diagonal(tuple): + def __new__(cls, value, primitive): + result = tuple.__new__(cls, value) + result.primitive = primitive + return result + + +def source_word_namespace(fault=False): + names = ('diagonal_product', 'chain', 'swap_word', 'upper_three', 'upper_six', 'lower_pair') + raw = authenticated('root_gate_plan.py') + if fault: + raw = raw.replace(b'Fraction(-1, 6)', b'Fraction(1, 6)') + env = functions(raw, names, {'Fraction': Q}) + for name, label in [('upper_three', 'three-H diagonal'), ('swap_word', 'switch diagonal')]: + original = env[name] + def wrap(value, original=original, label=label): + return [Diagonal(d, [(label, d)]) for d in original(value)] + env[name] = wrap + + def join(a, b): + origins_a = a.primitive if isinstance(a, Diagonal) else [('pivot', a)] + origins_b = b.primitive if isinstance(b, Diagonal) else [('pivot', b)] + return Diagonal((a[0] * b[0], a[1] * b[1]), origins_a + origins_b) + env['diagonal_product'] = join + return env + + +def execute(diagonals): + value = IDENTITY + for i, diagonal in enumerate(diagonals): + d = ((Z.lift(diagonal[0]), ZERO), (ZERO, Z.lift(diagonal[1]))) + value = matmul(d, value) + if i + 1 != len(diagonals): + value = matmul(H, value) + return value + + +def literal_word_check(): + env = source_word_namespace() + ratios = [ZERO, Z(Q(1, 2)), Z(Q(-1, 2)), Z(Q(0), Q(1, 2)), Z(Q(0), Q(-1, 2))] + cases = 0 + pivot_locations = set() + for x, y, scale, schur_ratio, left_swap, right_swap in product( + ratios, ratios, [Q(1), Q(1, 2**20), Q(2**20)], + [Q(1, 4), Q(1, 2**24)], [False, True], [False, True]): + a, s = Z(scale), Z(scale * schur_ratio) + gate = ((a, a * x), (a * y, a * y * x + s)) + if left_swap: + gate = matmul(SWAP, gate) + if right_swap: + gate = matmul(gate, SWAP) + pivot_locations.add(max(product(range(2), repeat=2), key=lambda ij: gate[ij[0]][ij[1]].norm2())) + word = env['lower_pair'](gate) + need(len(word) == 17 and execute(word) == gate, 'literal sixteen-H identity') + primitive = [item for diag in word for item in diag.primitive] + need(len(primitive) == 23, 'fully expanded primitive diagonal count') + need(sum(label == 'pivot' for label, _ in primitive) == 1, 'one pivot factor') + L = max(Q(1), bound(gate), bound(inverse(gate))) + for label, diagonal in primitive: + cap = 2 * L if label == 'pivot' else Q(64) + for entry in diagonal: + z = Z.lift(entry) + need(z.norm2() != 0 and z.norm2() <= cap**2 and (ONE / z).norm2() <= cap**2, + 'primitive and inverse factor bound') + cases += 1 + mutated = source_word_namespace(fault=True)['lower_pair'](((Z(3), Z(1)), (Z(1), Z(2)))) + need(execute(mutated) != ((Z(3), Z(1)), (Z(1), Z(2))), 'middle-phase mutation escaped') + return {'cases': cases, 'pivot_locations': sorted(pivot_locations), + 'fully_expanded_diagonals': 23, 'H_factors': 16, + 'nonpivot_factors': 38, 'retained_nonpivot_envelope': 40, + 'negative_control': 'sign in upper_three final diagonal changes endpoint'} + + +IDENTITY_TREE = ('identity',) + + +class TreeGrid: + one = IDENTITY_TREE + + def multiply(self, x, y): + if x == self.one: + return y + if y == self.one: + return x + return ('multiply', x, y) + + +def expected_tree(sides, ordinal): + coefficient = IDENTITY_TREE + indices = [] + for size in sides: + ordinal, digit = divmod(ordinal, size) + indices.append(digit) + for axis in reversed(range(len(sides))): + coefficient = TreeGrid().multiply(('factor', axis, indices[axis]), coefficient) + return coefficient + + +def lineage_case(sides, function): + tables = [[('factor', axis, digit) for digit in range(size)] for axis, size in enumerate(sides)] + data = [('data', i) for i in range(prod(sides))] + function(data, tables, TreeGrid()) + for i, actual in enumerate(data): + expected = ('multiply', expected_tree(sides, i), ('data', i)) + need(actual == expected, 'odometer uses a stale/noncurrent coefficient subtree') + return len(data) + + +def lineage_check(): + raw = authenticated('tensor_word.py') + good = functions(raw, ['product_diagonal'], {'prod': prod})['product_diagonal'] + shapes = [(2,) * d for d in range(1, 9)] + [(2, 4, 8), (8, 2, 4, 2), (4, 4, 2, 8), (2, 8, 2, 4, 2)] + records = sum(lineage_case(shape, good) for shape in shapes) + mutant = raw.replace(b'for k in range(j, 0, -1):', b'for k in range(j-1, 0, -1):') + bad = functions(mutant, ['product_diagonal'], {'prod': prod})['product_diagonal'] + try: + lineage_case((2, 2), bad) + except ValueError as error: + need('stale/noncurrent' in str(error), 'wrong lineage mutation gate') + else: + raise ValueError('stale cache mutation survived') + return {'cases': len(shapes), 'records': records, + 'oracle': 'exact current-coordinate right-associated expression tree, no numeric cancellation', + 'negative_control': 'skip newly changed suffix at a carry'} + + +def mul_poly(a, b): + out = [0] * (len(a) + len(b) - 1) + for i, x in enumerate(a): + for j, y in enumerate(b): + out[i + j] += x * y + return out + + +def source_stage_bound(): + D = [1, 288, 584, 256, 32] + # Literal matching: 17 diagonals + 16 H; 2*(2ell-1) switches, + # each with three diagonals + two H. Therefore 20ell+23 steps. + literal_two_roots = [2 * x for x in mul_poly(D, [23, 20])] + J = [20000 * comb(6, i) * 2**(6-i) for i in range(7)] + constant = J.copy() + constant[0] -= 2 + d_coefficient = [J[i] - (literal_two_roots[i] if i < len(literal_two_roots) else 0) + for i in range(len(J))] + need(all(x > 0 for x in constant + d_coefficient), 'literal stage-count polynomial') + return {'actual_steps_per_matching': '20*ell+23', + 'literal_two_root_depth_coefficients': literal_two_roots, + 'J_minus_actual_constant_coefficients': constant, + 'J_minus_actual_d_coefficients': d_coefficient} + + +def main(): + global PACKAGE + need(len(sys.argv) <= 2, 'usage: check_review.py [package-directory]') + PACKAGE = Path(sys.argv[1]).resolve() if len(sys.argv) == 2 else PACKAGE.resolve() + result = {'literal_word': literal_word_check(), + 'odometer_lineage': lineage_check(), 'literal_stage_count': source_stage_bound(), + 'scope': 'Independent source/schema checks; universal inequalities are in CROSS-REVIEW.md'} + print(json.dumps(result, indent=2)) + print('PASS_INDEPENDENT_PRECISION_CROSS_REVIEW') + + +if __name__ == '__main__': + main() diff --git a/research/direct-circulant-production-precision/review/refs/pr7849/COMPOSITE-OUTER.md b/research/direct-circulant-production-precision/review/refs/pr7849/COMPOSITE-OUTER.md new file mode 100644 index 0000000000..32587da2cc --- /dev/null +++ b/research/direct-circulant-production-precision/review/refs/pr7849/COMPOSITE-OUTER.md @@ -0,0 +1,107 @@ +# Composite outer geometry and complete caller + +## Statement and physical addresses + +Let the binary input lengths be at most n. Let b = ceil(log₂ n), B = 2ᵇ and p = 6b. Let T be the unique power of two in [4n/b,8n/b). Write L = log₂ T and V = Tp. Thus 24n ≤ V < 48n. All asymptotic statements concern n beyond a fixed finite cutoff. Handle the finite initial range by elementary binary multiplication. The fast branch uses radix-B digits and the original CRT permutation from the complete mixed-rank caller. Its new outer transform acts on the true physical coordinates of each axis. + +The local circuit to which this proof applies has the following explicit requirements. Each true odd side rᵢ sits inside a dyadic side tᵢ = 2^ℓᵢ. For either sign, the exact target is the true Fourier mean on [0,rᵢ) extended by the identity. The generated rational gate word approximates this target on arbitrary signals with operator error ≤ 2^(−P) tᵢ^O(1). It uses a polynomial in ℓᵢ matching layers. Each pair map and its inverse have 2-norm bounded by a fixed power of tᵢ. At complete matching-layer boundaries the norm of every prefix and its inverse are bounded by a fixed power of tᵢ. Tables, routings, control words and dyadic coefficients to P fractional bits can be constructed in poly(tᵢ,P) time and space on sequential tapes. Constants and polynomial degrees are uniform in i,n. A single-axis table must include dummy rows. The direct spectral-root construction in this package supplies these requirements for the original-coordinate Fourier transform. They also describe other circuits that can use the same multidimensional tensor executor. Only circuits that realize the stated Fourier mean give the integer-product conclusion here. + +## Construct a family of odd square sides + +Set s = ceil(log₂(p+2)), w = 2¹⁶s³ and let d be the greatest power of two ≤ L/w. Start with widths floor(L/d) or ceil(L/d), placing the larger widths first. Write h₀ = floor(L/d), a = floor(h₀/8) and H = d/2 for d ≥ 2. For i = 0,…,H−1 transfer eᵢ = a−(i mod (a+1)) actual address bits from axis H+i to axis i. Call the resulting declared widths ℓᵢ. The sum is still L. Axis zero has maximum width; the minimum is at least 7h₀/8 and the maximum at most 9h₀/8+1. Thus max ℓᵢ ≤ 2 min ℓᵢ, d = Θ(p/s³), and every ℓᵢ = Θ(s³). Eventually H ≥ a+1. The widths of the first a+1 axes are strictly decreasing because their initial widths are nonincreasing and their respective transfers decrease by one. Hence there are Θ(s³) distinct binary widths. The difference between the first and its paired target is at least 2a−1, so their padded *side lengths* can differ by a factor at least 2^(2a−1). For d = 1 retain its unique width. [Executable controller](square_geometry.py) + +For each target tᵢ choose an odd square rᵢ = xᵢ² in its own relative-deficit interval. For an even i use + + 1/(8d) ≤ 1 − rᵢ/tᵢ ≤ 1/(4d). + +For an odd i use + + 1/(32d) ≤ 1 − rᵢ/tᵢ ≤ 1/(16d). + +In increasing i order, scan the corresponding consecutive possible x ≥ 3. Choose the first odd x coprime to twice the product of the previously chosen bases. Use integer square roots, exact divisions with specified floor or ceiling, and the Euclidean algorithm. The controller code makes each choice deterministic. Its bounds depend only on operand length. + +Here is an elementary count that proves every scan succeeds eventually, uniformly over the previous choices. Put M = 2∏_{j m. The finite Bonferroni inequalities put A between Aₖ = Σ_{v≤k}(−1)ᵛ Eᵥ and Aₖ+Eₖ₊₁. One way to see the signs is to select independent Bernoulli coordinates with probabilities 1/qⱼ. On an outcome with h ≥ 1 selected coordinates the truncated alternating binomial sum is (−1)ᵏ binom(h−1,k). For h = 0 the sum is 1. Also + + Eₖ₊₁ ≤ μ^(k+1)/(k+1)! ≤ (e μ/(k+1))^(k+1) ≤ 2^(−k−1). + +The first inequality counts tuples with distinct indices in the full expansion. The second follows by integrating log x on [1,k+1]. The last follows from μ ≤ s ln 2 and e ln 2 < 4. Hence Aₖ ≥ 1/(2(m+1)). In X consecutive integers the count divisible by any square-free product of these primes differs from X divided by that product by less than one. The number of terms through degree k is at most (m+1)^k, by padding the increasing tuple of indices with null symbols. Apply the same odd binomial bound to each integer. The count coprime to M is at least + + X/(2(m+1)) − (m+1)^k. + +It is positive for X > 2(m+1)^(k+1). The narrower square band has real base width at least √tᵢ/(64d), by taking the difference of the square roots and bounding the sum of their roots by 2√tᵢ. Rounding the two endpoints loses at most two. More explicitly, m+1 ≤ p+2 ≤ 2ˢ, d ≤ 2ˢ and ℓᵢ ≥ 2¹⁵s³. The required X is at most 2^(1+s(8s+2)); the available count is at least 2^(2¹⁴s³−6−s)−2, which is larger for every s ≥ 1. Thus a square is available whenever the nonempty width rule and the stated size bounds hold. Establishing the count requires no result on the distribution of primes in intervals. + +The chosen sides are pairwise coprime composites. Put S = ∏ᵢ rᵢ. The product inequality ∏(1−δᵢ) ≥ 1−Σδᵢ for 0 ≤ δᵢ ≤ 1 gives S ≥ 3T/4. Each individual tᵢ/rᵢ ≤ 1/(1−1/(4d)) and the full storage expansion T/S is at most 4/3. Each operand has at most l = ceil(n/b) digits. Thus 2l−2 < 2n/b ≤ T/2 < S. Also S < T ≤ B for b ≥ 8. Each cyclic coefficient equals its linear coefficient and is less than B³. For this controller every axis lies outside the previous upper-deficit bound 1/(2p²) eventually. Adjacent even and odd fields lie in disjoint relative-gap bands. The same complete executor below works for *any* pairwise coprime odd rᵢ strictly within its matching dyadic bounds, with ∏rᵢ ≥ 3T/4, axis zero widest, all ℓᵢ = Θ(s³) and max ℓᵢ ≤ 2 min ℓᵢ. The square scan realizes these conditions from every large input length. + +Generate all one-axis tables and the full list of square sides once in d·2^O(max ℓᵢ) poly(p) = 2^O(s³) = o(n) bit operations. This allows a bounded-degree polynomial in tᵢ and P. The same bound covers the largest interval ever visited on the private tapes, including erasure. These table sizes may exceed a polynomial in p. No full tensor is used at this private precision. + +## Tensor stages on a complete field + +Run one width class at a time. There are O(s³) classes. Within a class all axes use the same significance at each stage. Complete shorter local programs with identity pairs. For any invertible two-coordinate gate G exchange rows and columns to place its largest entry by modulus in the leading pivot. Its modulus is at least 1/(√2 ‖G⁻¹‖₂), both triangular shear ratios have modulus at most one, and the reciprocal of the second pivot is an entry of the inverse of the permuted matrix. The emitted fixed word uses two optional two-H exchanges, two six-H shears and the pivot diagonal, with exactly sixteen H factors. It therefore also covers the stored rational numerical FFT butterflies that need not factor as H times a diagonal. The forward and reverse Beneš programs for the matching each use 2(2ℓᵢ−1) H factors. The total per layer is 8ℓᵢ+12. Thus O(ℓᵢ⁴) matching depth costs O(ℓᵢ⁵) H calls per class, before pack division. All private controls and coefficient tables are generated in polynomial time in tᵢ and P, with both permutations included. [Tensor compiler and fixed words](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/unconditional-batched-crt/vendor/TENSOR-COMPILER.md) · [Gate lowering used by the executable word](root_gate_plan.py) + +Each such H acts on one bit of each active axis across the *complete padded tensor*, including all spectators and holes. Take P = C p for fixed sufficiently large C. Let s' = ceil(log₂(P+2)), G = 4s'+6 and K = 128G. For significance j on a width-ℓᵢ axis take common offset ρ = min(j,K−1) and start the K-bit window at j−ρ. Its highest index is < ℓᵢ because ℓᵢ ≥ K eventually. This includes the most significant bit, which a window that always starts at j would miss. + +Split a class into packs of at most max(1,floor(d/s)) bits. There are O(s) packs within any class and O(s³+s) packs summed over classes for a common local depth. The corresponding tensor factors commute and leave every other bit a spectator. For h bits of a pack, gathering and restoring the real neighborhoods moves k ≤ 2hK = O(hs) positions. The complete short-record suffix of (s')² untouched bits exists away from these moves because + + (k+1)(s')² = O_F((d/s)s³ + s²) = O_F(p/s) = o(L). + +Reserve and place the suffix first. Take the additional three O(kG)-bit reservoirs in its complement. Their sizes satisfy kG = o(L) as well. The source re-computes the control positions and colors after physical placement and removes the suffix after inverse exposure. A coarse-label-dependent diagonal is applied only when the full original stream has returned. Such a suffix on a fixed-label subarray would not give the same resource. + +For clarity, the row bound in this application is the proved stock for the actual fixed mixed-rank frames. The logarithms of all simultaneous ordinary and complex row stocks add. Their product requires at most O_F(log(h+1) + h^(1/250)(s')³ + 1) further complete chunks. The two front fields and the back field use at most 3h/128+O(1) chunks. For h larger than a fixed multiple of (1+s')⁵, the sum is ≤ h/16, since 5(1−1/250)>3. Defer the selected bits in these chunks. Execute the current native word on every other selected bit, restore every dirty borrowed coordinate, remove temporary whole-row padding, then process the deferred bits. The positive powers of the shrinking widths have a convergent geometric sum. Below this threshold perform each selected kernel separately in O(V polylog p). The exact common dyadic grid for a complete pack has fractional precision P+O(h), magnitude exponent O(p)+O(h), and O(p) temporary width. Converting the normalized H to raw H costs a full shift scan by 2ʰ. Every intervening displacement, row encoding, materialization, return and cleanup is priced. The proof uses h ≤ d and the displayed physical-space inequalities directly. A power saving h = O(p^(1−ε)) with a fixed ε > 0 would fail for this controller. [Complete mixed-rank Hadamard price and stock](https://github.com/CrocSwap/integer-mult-bounds/blob/343f7b1817e26ad3f89d2ddad313b12741d53602/research/mixed-rank-uniform-composition/COMPLEX-LAYER.md) · [Whole-field placement and suffix proof](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/capped-phase-fusion/SUPPLIER-SUPPORT-AUDIT.md) · [Active-packet widths and physical retirement](https://github.com/CrocSwap/integer-mult-bounds/blob/343f7b1817e26ad3f89d2ddad313b12741d53602/research/mixed-rank-uniform-composition/FRAMES.md) + +Stream each complete tensor diagonal, with a value 1 for inactive axes. Store all axis tables in physical order. Maintain suffix products in a mixed-radix odometer, taking axis zero fastest. A carry through at least k axes occurs at most T/(t₀⋯tₖ₋₁) times for k ≥ 1. It takes O(k) coefficient operations to rebuild affected suffixes and O(kt₀) records to move the coefficient head out and back, because t₀ is the largest side. Since t₀⋯tₖ₋₁ ≥ t₀·2^(k−1), all carry travel is at most O(T Σ_{k≥1} k/2^(k−1)) = O(T). The arithmetic and normal head movement add O(T) more records per diagonal. The first table load of O(d t₀) records fits the private budget. This covers the large ratio between dyadic side lengths in the constructed family. Each cached product comes from at most d factors in the current index, including at the first coordinates after a carry. Thus the number of tensor records scanned does not increase multiplicative error through a reused ratio. The exact and rounded suffixes remain bounded by products of the same local factor bounds. [Predecessor odometer for equal side lengths](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/unconditional-batched-crt/vendor/TENSOR-COMPILER.md#L112-L133) + +## Original-coordinate recovery and uniform error + +The physical address of cyclic index j is Φ(j)ᵢ = μᵢj mod rᵢ, where μᵢ = (∏_{k