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..115113617d --- /dev/null +++ b/research/direct-circulant-production-precision/README.md @@ -0,0 +1,333 @@ +# 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. + +## Completed source-ordered complete-gate supplement + +[compiler-cuts/INTEGRATION.md](compiler-cuts/INTEGRATION.md) and its separate +[review](compiler-cuts/review/CROSS-REVIEW.md) now establish a scoped fragment +lemma for the exact retained Builder, Triangle, Program and Full factories. +Their same sufficient four-way envelopes cover every cut after a subset of +complete one- or two-wire gates in a matching. For the primitive word, the two +cross-bank shears have the same direction and all bank-local gates are unitary; +this controls every prefix, suffix and inverse without an additional generic +matching-interpolation factor. The Full bound remains `2 L0 B H`, with +`B = 256 N^3 (lambda Q)^12`, and an arbitrary interval is bounded by its square. +Both `lambda >= 1` and `Q >= 1` are required individually, as in the source. + +This is an extension of a sufficient source envelope, not a no-loss theorem +relative to the measured norms of neighboring full-layer cuts. It retains the +all-size conditioning, rank, phase-service and atom-error contracts. Intermediate +coordinate assignments, arithmetic temporaries, changed recursive atom services +and physical tape costs remain outside the result. The original precision proof, +selector and selected certificate are unchanged. + +The author checker and a separately written rational-realification/downset +checker both passed normally and with Python assertions disabled. The independent +review checked 760 primitive cuts, 3,040 four-way structural certificates, +100 arbitrary primitive intervals and 46 separate LDU downsets. The source's +individual conditioning lower bounds have an explicit failing control when +improperly weakened to their product alone. Source notices, frozen proof bytes, +receipts and the prior-work comparison are retained inside the supplement. + +This result builds on #4976 and credits the sharp conditioned interpolation +already proved in [#5940](https://github.com/CrocSwap/integer-mult-bounds/pull/5940). +The singular partial-write swap warning and rounded-event boundary were already +identified in [#5240](https://github.com/CrocSwap/integer-mult-bounds/pull/5240); +the new proof does not claim either precedent as a new result. + +## Nested-downset intervals and the smaller consumer selector + +The preceding `compiler-cuts/` subtree is preserved byte-for-byte from +`e040fedfd8fcc51480d2468f3fa07562c8bacbf0`, including its accepted proof, +review, receipts and attribution. The additions are separate: + +- [compiler-intervals/INTEGRATION.md](compiler-intervals/INTEGRATION.md) + introduces the relative-interval improvement. Its frozen proof also + contains an overlapping complete-gate derivation as source context; + that portion corroborates the preceding result and is not claimed again + as a new discovery. +- [spectral-downset/README.md](spectral-downset/README.md) propagates the + accepted interval result and sharper actual root/child bounds through + the complete consumer precision calculation. Its supplementary API is + `spectral-downset/precision.py`; the original parent API remains intact. + +For two nested completed downsets, one common legal linearization cancels +the shared normalized perturbation prefix. The interval and the inverse of +the same stored operator therefore obey + +``` +norm <= B^2*H^2/(1-theta) < 2*B^2*H^2, theta<=1/4, +``` + +improving the conservative `K_Full^2=4*L0^2*B^2*H^2` envelope. The argument +includes interleaved siblings, matching subsets, simultaneous active atoms +and zero-duration predecessors. It retains `lambda>=1` and `Q>=1` +individually, all conditioning/rank/phase/atom-error contracts, and the +complete-gate boundary. The separate interval review accepts the frozen +proof SHA256 `e942012e66adc2d696cde3fedd6ae9c73df98e77a71b16e5004f5a74ccdfaa07`. + +The consumer uses Nick Petalas's credited #4852 block-solve theorem and the +actual component envelope passed to each generator child, while preserving +the source's allocation and admission code. It charges complete lowering, +routing, padded spectral-to-infinity conversion, coefficient rounding, +odometer lineage and the strict computed-state bootstrap. With the same +`J` and `C` defined above, its sufficient precision is + +``` +P = 4p+277L+3011d+(L mod 2)+bit_length(C). +``` + +This saves exactly `1084L+1735d` bits against the original parent selector. +For `p=72` and widths `(4,5)`, the sufficient budgets are 688,620 bits for +the original source, 22,068 for the parent theorem and 8,842 for the new +supplement. These are sufficient budgets, with no minimum-precision, +measured runtime or physical-memory claim. At a fixed external precision, +the allocation and resulting word are unchanged; choosing another external +precision regenerates coefficients through the same source rules. + +The interval reviewer separately checks 149 primitive intervals, 475 nested +downset pairs and 1,404 cut intervals. The selector reviewer checks 113 +selector cases and 254 symbolic / 762 complex rational cache records, +including 507 zero-factor records. Their normal and optimized receipts +agree. The frozen selector proof remains at SHA256 +`0501a6a9a5f467fff4c998606965babc8157e74d98cf33b93f71fb10674d57bb`; +its pre-review filename is retained and its later separate review records +acceptance. + +The original seven verification methods remain registered. Four existing +compiler-cut commands now run through a path-only adapter in disposable +byte-identical package copies, preserving the published elapsed-time +receipts. One eighth command runs the added interval and selector methods, +including both independent optimized modes, in the same way. Exact original +commands and protected source identities are retained in `reconciliation/`. + +These additions do not claim the complete-gate theorem, #5940's conditioned +matching interpolation, or #5240's rounded-event and partial-write controls +as new work. All predecessor credit remains explicit. The useful remaining +consumer task is the source-specific all-size private arithmetic, owned +arena and tape-tariff interface. The selected five assumptions, coefficient +service contracts, Fourier/CRT recovery geometry and kappa remain unchanged. + +The canonical [integer-rounded-gate package](../integer-rounded-gate/README.md) +already supplies Nick Petalas's once-rounded arithmetic construction for +supplied rational coefficients, with word-width bound `W=B+4C+2`. It uses +shifts, additions and bounded binary multiplication/division while saving +inputs before output writes. We cite its pinned README for prior-work +orientation; its proof is not a new dependency or re-audited here. The open +task is to bind that existing kernel to the actual caller and charge +simultaneous live words, coefficient preparation/delivery, cleanup and the +complete instruction/tape cost. Our complete-gate restriction does not claim +that the supplied-coefficient arithmetic kernel remains unconstructed. + + +## Supplied dyadic arithmetic at the actual caller + +The separately accepted [grid-arithmetic supplement](grid-arithmetic/INTEGRATION.md) +binds a new common-denominator specialization to the literal `Grid.multiply` +calls. It preserves Nick Petalas's general rational-row kernel and its finite +diagnostic guards. For signed B-bit supplied inputs and 1<=P<=B, the new +shift/add schedule has arithmetic width W=2B+1 and simultaneous local data +storage at most 4B+7W bits plus logarithmic controls. Under the accepted +spectral-downset theorem, B=P+max(A,E)+3 covers the actual external table +entries, suffix caches and represented data. + +This is a local arithmetic result with an explicit quadratic charge: +O(J(d+1)T B^2) for at most J literal diagonal scans of T records. It does not +claim the accelerated native tariff, coefficient preparation, global movement +or ownership, private native-H storage, or reversible cleanup. The exact +coefficient conversion still uses ties to even, while multiplication uses +ties toward positive infinity; original Full gates are not substituted for +the externally lowered chronology. The review records a concrete source +counterexample to that substitution and an admissible constructor input that +exceeds the predecessor's finite diagnostic guard. + +The independent reviewer checked 39,220 arithmetic cases, including 18,716 +ties and 8,628 zero-multiplier cases, plus 1,020 literal odometer calls and +28 API bindings. Normal and optimized receipts agree. The extracted Grid +fixture supplies an exact `operator.mul` helper; it does not execute or price +the retained multiplication backend. The sides=(2,), digit_bits=5 example +is an admissible explicit constructor geometry, without asserting that the +uniform geometry selector chooses it. The eighth registered command preserves +all prior checks and appends both modes of the new author and independent +reviewer replays. The selected assumptions and kappa remain unchanged. 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..f551100ec3 --- /dev/null +++ b/research/direct-circulant-production-precision/SOURCES.json @@ -0,0 +1,126 @@ +{ + "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" + }, + { + "path": "research/rational-unitary-fft/GENERATOR-PROOF.md", + "usage": "provenance", + "git_blob": "8bef383eec887450e86f14365a6f7b07c1310e9d", + "sha256": "cddda1f944299a349c837808b349fa6e4499cbb1889f7dacc00ca8afac9b580c" + }, + { + "path": "research/rational-unitary-fft/PROOF.md", + "usage": "provenance", + "git_blob": "99a55596f67ae3b94ef02ebb159b313f33bf22af", + "sha256": "50e31e33e1275a133d10e87208ceb50dddce67d0678d2a89de9f7ba28d8380d9" + }, + { + "path": "research/rational-unitary-fft/SOURCES.json", + "usage": "provenance", + "git_blob": "7ee22e983f54dfb73e74d20ed1910a64d2abb6cd", + "sha256": "7324e22bcb202b5cc03b5f7ea713f6f0c7cd80ee60d320fb03b1e2f7b13b8c91" + }, + { + "path": "research/rational-unitary-fft/vendor/STEIN-PROVENANCE.json", + "usage": "provenance", + "git_blob": "c602fb5bb332dbe098950b14d55da05ce2cf4312", + "sha256": "e7f0e8dc517387e302b1e8bf5dff7e12b29da8aa91abc6ea597f33c1ac08ba62" + }, + { + "path": "research/rational-unitary-fft/TRIANGLE-PROOF.md", + "usage": "provenance", + "git_blob": "f923f4ff2dfe40401fa90d83727ade62b2ef5b5f", + "sha256": "abea26e3c86a9970225b070be034c47e7970e10fe1b5686f405e0b301acf3159" + }, + { + "path": "research/capped-phase-fusion/evidence/inplace_algebra_ultra/check_circuits.py", + "usage": "provenance", + "git_blob": "f80c141c8116b163c2bb5a028c28212077c8d5a9", + "sha256": "06d1861bfe8af543908e26557ffda7e451ff176bceb9bacfaf0f04f234b336d5" + }, + { + "path": "research/rational-unitary-fft/exact.py", + "usage": "provenance", + "git_blob": "aae41e6acfb2e5a4fafdd85727891eb746b57b42", + "sha256": "c9b89d7357210af69865690ba12e695366961f8b501a8fab9d0fefe3fb30c479" + }, + { + "path": "research/rational-unitary-fft/generator.py", + "usage": "provenance", + "git_blob": "d761d3c88b1685fb64d92d69f699b8218c9ec30f", + "sha256": "827ef9fe1bd664859995892b59843c390f7969c938fb7e1e6dc585c31a54b555" + }, + { + "path": "research/cubic-cyclic-inverse/vendor/interval_kernel.py", + "usage": "provenance", + "git_blob": "1182175a55cb871481de0f56ea9ae56e474705fe", + "sha256": "9b7bb24640a9a7d3f83c7951dfef483ec933db4c50de6c0130b85f450eeddfbe" + }, + { + "path": "research/rational-unitary-fft/vendor/stein_rational.py", + "usage": "provenance", + "git_blob": "71b240a460a185ee2fe926cd189b56aeac6f997f", + "sha256": "3065fc5d6d22ec44de533b08fb0c639603449456383668e561dc46629e641502" + }, + { + "path": "research/rational-unitary-fft/triangular.py", + "usage": "provenance", + "git_blob": "2bd8de01a7ac80de7e6b9f8252bc69d0e0a291e8", + "sha256": "46780d95ddebfed22e8f0c18565fe2e768250afa5beeb31f450292cc06f7ec11" + }, + { + "path": "research/integer-rounded-gate/README.md", + "usage": "provenance", + "git_blob": "80e8ae627ef8b35553f43a014c2a4b4686c84def", + "sha256": "8fbc9c0b34f5d9233664c9822034b3ab2e9725452c59227eb0b25f416b93951b" + } + ] +} diff --git a/research/direct-circulant-production-precision/TASK.json b/research/direct-circulant-production-precision/TASK.json new file mode 100644 index 0000000000..4cdff41d86 --- /dev/null +++ b/research/direct-circulant-production-precision/TASK.json @@ -0,0 +1,144 @@ +{ + "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. The completed follow-up addresses the exact retained Full compiler cut premise; its gate-level boundary is distinct from physical arithmetic or native storage.", + "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. A separately reviewed source-ordered complete-gate fragment theorem extends the retained four-way compiler envelopes under explicit individual conditioning, phase, rank and atom-error hypotheses.", + "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. compiler-cuts/PROOF.md and accepted compiler-cuts/review/CROSS-REVIEW.md; independent rational-realification, LDU-downset and order-sensitive negative controls, with normal/optimized parity.", + "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 complete-gate compiler bound be extended to intermediate physical arithmetic and changed recursive atom services?", + "why_it_matters": "The added four-way source envelope covers completed gates but leaves scratch registers, coefficient delivery and temporary widths unproved.", + "first_step": "Bind one actual lowered gate to a reversible enlarged state and prove forward/inverse fragment bounds with its exact scratch and rounding costs.", + "blocked_by": "Complete-gate invertibility does not control a singular coordinate splice or unexamined recursive service." + } + ], + "priority_revision": 8, + "budget_minutes": 65, + "sequential_supplements": [ + { + "id": "nested-downset-relative-intervals", + "scope": "Add a separately reviewed relative interval/inverse bound using one common legal order for nested source downsets; retain the complete-gate compiler result already published at 0a1c144 byte-for-byte.", + "outcome": "completed with separate model-assisted mathematical acceptance", + "proof": "compiler-intervals/PROOF.md", + "review": "compiler-intervals/review/REVIEW.md", + "evidence": "compiler-intervals/EVIDENCE.json; compiler-intervals/review/EVIDENCE.json; compiler-intervals/review/EVIDENCE-OPTIMIZED.json", + "downstream_consequence": "Original direct-circulant gate/inverse envelope improves to 2^189*t^100; original published selector and its complete error budget remain unchanged in this supplement.", + "retained_premises": "Ideal downset conditioning, generator rank, phase certification, coefficient-defect and native/recovery interfaces.", + "boundary": "Exact whole one/two-wire gate cuts; excludes a cut between output writes or a complete physical-storage theorem.", + "next_step": "Completed by the following spectral-downset precision supplement; private arithmetic and owned storage remain separate." + }, + { + "id": "spectral-downset-precision", + "scope": "Propagate sharper spectral downset and actual prepared-child fragment bounds through the unchanged full allocation, complete physical lowering, tensor schedule, coefficient odometer and raw-error bootstrap.", + "outcome": "completed with separate model-assisted mathematical acceptance", + "proof": "spectral-downset/PROOF-DRAFT.md", + "review": "spectral-downset/review/REVIEW.md", + "supplementary_api": "spectral-downset/precision.py", + "evidence": "spectral-downset/EVIDENCE.json; spectral-downset/review/EVIDENCE.json; spectral-downset/review/EVIDENCE-OPTIMIZED.json", + "downstream_consequence": "P=4p+277L+3011d+(L mod 2)+bit_length(C), saving exactly 1084L+1735d bits against the preserved parent selector with the same strict raw target and coefficient C.", + "retained_premises": "Source phase, displacement rank, exact represented-input native H, Fourier/CRT geometry and recovery; full allocation and component admission code remain unchanged.", + "boundary": "Source-bound sufficient external precision; no minimum-precision claim, practical speed/memory claim, complete private-tape theorem, selected assumption discharge or new multiplier exponent.", + "next_step": "Bind the existing supplied-coefficient arithmetic kernel to the exact Full/native caller and charge simultaneous live words, coefficient delivery, cleanup and instruction/tape cost; separately check applicability to changed successor pack chronology." + }, + { + "id": "supplied-grid-arithmetic", + "scope": "Bind actual external Grid.multiply events to a separate common-denominator shift/add program, retaining coefficient conversion and lowering chronology.", + "outcome": "completed with separate model-assisted acceptance", + "proof": "grid-arithmetic/PROOF.md", + "review": "grid-arithmetic/review/REVIEW.md", + "evidence": "grid-arithmetic/EVIDENCE.json; grid-arithmetic/EVIDENCE-OPTIMIZED.json; grid-arithmetic/review/EVIDENCE.json; grid-arithmetic/review/EVIDENCE-OPTIMIZED.json", + "downstream_consequence": "W=2B+1 and local live data 4B+7W plus logarithmic controls, with B=P+max(A,E)+3 under the frozen numerical theorem.", + "cost": "O(J(d+1)T B^2) local arithmetic; no accelerated tariff or outer recurrence repricing.", + "retained_premises": "Coefficient synthesis, global movement/ownership, native private storage, reversible cleanup and all selected assumptions.", + "boundary": "Supplied arithmetic; source fixture supplies operator.mul as exact helper, not a replay of the word_product backend; explicit admissible constructor geometry is not a selected uniform-production witness." + } + ], + "reconciliation": { + "remote_base": "e040fedfd8fcc51480d2468f3fa07562c8bacbf0", + "preserved_subtree": "compiler-cuts/", + "new_interval_dependency": "compiler-intervals/PROOF.md", + "novel_scope": "Nested-downset relative interval cancellation and complete spectral-downset consumer precision propagation. Existing complete-gate results, conditioned interpolation and partial-write boundary controls are retained predecessors.", + "preserved_incoming_history": [ + "0a1c14499407b103ae964f36551b0e9c11400197", + "e040fedfd8fcc51480d2468f3fa07562c8bacbf0" + ] + }, + "prior_arithmetic_kernel": { + "source": "research/integer-rounded-gate/README.md", + "git_blob": "80e8ae627ef8b35553f43a014c2a4b4686c84def", + "scope": "Nick Petalas supplies once-rounded supplied-coefficient arithmetic with word width W=B+4C+2; cited for prior-work orientation, not adopted or re-audited here.", + "remaining": "Actual Full caller binding, simultaneous live-word census, coefficient delivery, cleanup, instruction encoding and tape cost." + } +} diff --git a/research/direct-circulant-production-precision/VERIFY.json b/research/direct-circulant-production-precision/VERIFY.json new file mode 100644 index 0000000000..4c161622a1 --- /dev/null +++ b/research/direct-circulant-production-precision/VERIFY.json @@ -0,0 +1,111 @@ +{ + "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." + }, + { + "argv": [ + "{python}", + "-I", + "-W", + "error", + "-B", + "{package}/reconciliation/replay.py", + "--legacy", + "3" + ], + "timeout_seconds": 180, + "checks": "Authenticate 18 source files; exact source matching cuts, four-way envelopes, partial Full timestamps and order/alphabet rejection controls. Run the exact original command in an isolated byte-identical package copy; preserve published receipts." + }, + { + "argv": [ + "{python}", + "-I", + "-W", + "error", + "-B", + "{package}/reconciliation/replay.py", + "--legacy", + "4" + ], + "timeout_seconds": 180, + "checks": "Authenticate 18 source files; exact source matching cuts, four-way envelopes, partial Full timestamps and order/alphabet rejection controls. Run the exact original command in an isolated byte-identical package copy; preserve published receipts." + }, + { + "argv": [ + "{python}", + "-I", + "-W", + "error", + "-B", + "{package}/reconciliation/replay.py", + "--legacy", + "5" + ], + "timeout_seconds": 60, + "checks": "Independent rational realification, bank invariants, all matching subsets, primitive intervals, LDU downsets and conditioning/chronology controls; no author checker imported. Run the exact original command in an isolated byte-identical package copy; preserve published receipts." + }, + { + "argv": [ + "{python}", + "-I", + "-W", + "error", + "-B", + "{package}/reconciliation/replay.py", + "--legacy", + "6" + ], + "timeout_seconds": 60, + "checks": "Independent rational realification, bank invariants, all matching subsets, primitive intervals, LDU downsets and conditioning/chronology controls; no author checker imported. Run the exact original command in an isolated byte-identical package copy; preserve published receipts." + }, + { + "argv": [ + "{python}", + "-I", + "-W", + "error", + "-B", + "{package}/grid-arithmetic/run_registered.py" + ], + "timeout_seconds": 510, + "checks": "Authenticate preserved remote subtree and frozen new proofs; replay relative-interval author audit, separate normal/optimized interval oracle, sharp selector source checks and separate normal/optimized selector oracle in isolated copies. Preserve that entire prior replay, then authenticate frozen grid arithmetic and compare fresh normal/optimized author and independent reviewer receipts byte-for-byte in isolated copies." + } + ] +} 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/compiler-cuts/AUTHOR-RECEIPT.json b/research/direct-circulant-production-precision/compiler-cuts/AUTHOR-RECEIPT.json new file mode 100644 index 0000000000..fe77a0aa16 --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-cuts/AUTHOR-RECEIPT.json @@ -0,0 +1,32 @@ +{ + "status": "AUTHOR_NORMAL_AND_OPTIMIZED_REPLAYS_PASSED_SEPARATE_REVIEW_PENDING", + "base": "e54523517d0f03e58352e647c403a5af3e525a57", + "proof_sha256": "162dd4bb7a020dfb72dd3c80cb9a1de37212cc7f812f36fd4365d487d49b341b", + "checker_sha256": "e7756cc6fec1c789dcdb5ef5e7c828c3b4981c4ace681029c49e16607628b6a4", + "evidence_sha256": "aa1ada5b2e9f1275815c9780b3055874c21ff289cde859001d1a536ac903ca15", + "commands": [ + [ + "python3", + "-I", + "-B", + "audit.py" + ], + [ + "python3", + "-I", + "-O", + "-B", + "audit.py" + ] + ], + "expected_marker": "PASS_SOURCE_ORDERED_FOUR_WAY_CUT_AUDIT", + "suggested_package_subdir": "research/direct-circulant-production-precision/compiler-cuts", + "suggested_existing_pr": 8093, + "no_new_kappa": true, + "limits": [ + "whole one/two-wire gates only", + "no intermediate coordinate-write inverses", + "rank, phase, component-conditioning and atom-error contracts retained", + "no physical tape tariff or unconditional multiplier" + ] +} diff --git a/research/direct-circulant-production-precision/compiler-cuts/EVIDENCE.json b/research/direct-circulant-production-precision/compiler-cuts/EVIDENCE.json new file mode 100644 index 0000000000..6cf13661d6 --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-cuts/EVIDENCE.json @@ -0,0 +1,200 @@ +{ + "authenticated_origins": 18, + "boundary": "Exact stored one/two-wire gate cuts, including arbitrary matching subsets; no split-output inverse claim", + "checker_sha256": "e7756cc6fec1c789dcdb5ef5e7c828c3b4981c4ace681029c49e16607628b6a4", + "full_words": [ + { + "atoms": 4, + "child_target_bits": 111, + "coefficient_error": "1/8", + "cuts": 61, + "execution_bound": "50566979566069350400", + "gates": 30, + "global_frobenius_certificates": 244, + "label": "n2_nonzero_approximation", + "layers": 21, + "n": 2, + "noncommuting_prefix_controls": 30, + "normalized_suffix_identities": 5, + "proper_partial_cuts": 18, + "rejected_delayed_zero_atoms": 0, + "simultaneous_nonempty_fragments": 0, + "source_atom_timestamps": [ + [ + "R:0:2", + 0, + 10 + ], + [ + "D:0", + 10, + 11 + ], + [ + "D:1", + 10, + 11 + ], + [ + "L:0:2", + 11, + 21 + ] + ], + "theta": "1/549755813888", + "trace_equalities": 244, + "zero_duration_atoms": 0 + }, + { + "atoms": 10, + "child_target_bits": 154, + "coefficient_error": "10920822045372851498541422188282012939453125/89202980794122492566142873090593446023921664", + "cuts": 821, + "execution_bound": "78397326014400000000000000", + "gates": 318, + "global_frobenius_certificates": 3284, + "label": "n4_asymmetric_zero_atom", + "layers": 189, + "n": 4, + "noncommuting_prefix_controls": 453, + "normalized_suffix_identities": 11, + "proper_partial_cuts": 474, + "rejected_delayed_zero_atoms": 1, + "simultaneous_nonempty_fragments": 50, + "source_atom_timestamps": [ + [ + "R:0:4", + 0, + 84 + ], + [ + "R:0:2", + 84, + 94 + ], + [ + "D:0", + 94, + 95 + ], + [ + "D:1", + 94, + 95 + ], + [ + "L:0:2", + 95, + 105 + ], + [ + "R:2:4", + 84, + 84 + ], + [ + "D:2", + 84, + 85 + ], + [ + "D:3", + 84, + 85 + ], + [ + "L:2:4", + 85, + 95 + ], + [ + "L:0:4", + 105, + 189 + ] + ], + "theta": "84170560980141162872314453125/713623846352979940529142984724747568191373312", + "trace_equalities": 3284, + "zero_duration_atoms": 1 + }, + { + "atoms": 1, + "child_target_bits": 64, + "coefficient_error": "1/8", + "cuts": 3, + "execution_bound": "10495826329600", + "gates": 1, + "global_frobenius_certificates": 12, + "label": "n1_complex_scalar", + "layers": 1, + "n": 1, + "noncommuting_prefix_controls": 0, + "normalized_suffix_identities": 2, + "proper_partial_cuts": 0, + "rejected_delayed_zero_atoms": 0, + "simultaneous_nonempty_fragments": 0, + "source_atom_timestamps": [ + [ + "D:0", + 0, + 1 + ] + ], + "theta": "1/16777216", + "trace_equalities": 12, + "zero_duration_atoms": 0 + } + ], + "negative_controls": [ + "coordinate-write splice is singular; no inverse-cut contract", + "nonunitary compensated bank gates violate a near-one fragment cap", + "nonunitary scalar adjoint is not its stored inverse", + "generic no-loss interpolation rejected; source structure is necessary", + "opposite-direction sweeps violate the additive bank-triangular bound" + ], + "primitive_words": [ + { + "bank_invariant_certificates": 52, + "cap": "2049/2048", + "cuts": 13, + "gates": 6, + "label": "zero_side1", + "layers": 4, + "nonreal_twiddle_inverse_control": "wrong conjugated-twiddle replacement rejected", + "proper_partial_cuts": 4, + "psd_certificates": 52, + "side": 1, + "unitary_gates": 4 + }, + { + "bank_invariant_certificates": 244, + "cap": "14339/6144", + "cuts": 61, + "gates": 20, + "label": "dirty_side2", + "layers": 12, + "nonreal_twiddle_inverse_control": "wrong conjugated-twiddle replacement rejected", + "proper_partial_cuts": 40, + "psd_certificates": 244, + "side": 2, + "unitary_gates": 16 + }, + { + "bank_invariant_certificates": 244, + "cap": "85519/30720", + "cuts": 61, + "gates": 20, + "label": "complex_side2", + "layers": 12, + "nonreal_twiddle_inverse_control": "wrong conjugated-twiddle replacement rejected", + "proper_partial_cuts": 40, + "psd_certificates": 244, + "side": 2, + "unitary_gates": 16 + } + ], + "proof_sha256": "162dd4bb7a020dfb72dd3c80cb9a1de37212cc7f812f36fd4365d487d49b341b", + "python_version": "3.12.14", + "scope": "Finite evidence corroborates PROOF.md; phase, rank and conditioning premises remain explicit", + "status": "PASS_SOURCE_ORDERED_FOUR_WAY_CUT_AUDIT" +} diff --git a/research/direct-circulant-production-precision/compiler-cuts/INTEGRATION.md b/research/direct-circulant-production-precision/compiler-cuts/INTEGRATION.md new file mode 100644 index 0000000000..dd18a4152b --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-cuts/INTEGRATION.md @@ -0,0 +1,62 @@ +# Completion and application of the compiler-cut review + +The frozen proof SHA256 is +`162dd4bb7a020dfb72dd3c80cb9a1de37212cc7f812f36fd4365d487d49b341b`. +Its original pending-review text and AUTHOR-RECEIPT.json are preserved historical +records. The independent review in `review/CROSS-REVIEW.md` accepts that exact +proof with the scope clarification below. Neither the frozen proof nor the +parent precision theorem has been rewritten. + +## Scope at the actual source + +The source requires lambda >= 1 and Q >= 1 individually, in addition to every +retained all-size rank, phase-service, component-conditioning and per-atom error +premise. Their product being at least one is insufficient; the independent +checker supplies the unclamped scalar counterexample. The theorem concerns the +stored exact gate program. Its four operators are prefix, suffix, inverse prefix +and inverse suffix at any complete-gate cut. The Full sufficient envelope is +`K = 2 L0 B H`; arbitrary intervals have the conservative bound `K^2`. + +A matching may be partially completed only by selecting whole one- or two-wire +gates. Incomplete coordinate writes, arithmetic scratch, rounded assignment +states and altered recursive implementations require their own analysis. The +bound retains the predecessor's sufficient constant; it does not compare a cut +with the actual measured maximum of its adjacent completed-layer endpoints. + +## Prior work and attribution + +Brian / JoyboyBrian's #4976 gives unrestricted sharp sqrt(2) interpolation. +Nick Petalas's merged #5940, head +`b709a6adb6a9543247260900b108166a4d469f6f`, already gives sharp conditioned +interpolation and unitary no-loss. The present addition exploits the whole pinned +source word, including its two same-direction shears, and extends a sufficient +envelope through actual source timestamps. It does not sharpen that generic +interpolation formula or settle its four-way sharpness question. + +Armin Pourshafeie / apoursh's merged #5240, head +`6d0a6043120880c696d0850e9242a16e6fb980a5`, already identifies the singular +coordinate-write swap and audits rounded-event/component-width interfaces. +Those are credited boundary controls here, not new discoveries. The mathematical +inputs and inherited compiler contributors are listed in NOTICE.md and the +independent review. Full PR bodies were used for this bounded overlap comparison; +these two predecessor proofs were not independently re-audited by the cut reviewer. + +## Reproduction and result + +The parent VERIFY.json runs both author and independent methods normally and +under optimized Python. The reviewer never imports the author audit. Retained +source bytes are authenticated with SHA256, Git blob identifiers and lengths. +The written induction supplies the universal implication under its hypotheses; +finite checks discriminate source and order errors. No selected assumption, +physical tariff, integer-recovery contract or kappa improvement is claimed. + +Prepared for Jerry Chen / @CubeJerry with substantial OpenAI assistance. + +## Immutable review receipts + +The separate reviewer's original evidence files retain the exact bytes named +in review/RECEIPT.json. Registered reruns write their time-dependent evidence +to temporary output paths, leaving those frozen records unchanged. A root +normal/optimized replay of that output-path adjustment matched every scientific +receipt field after removing only elapsed time. This is a transport and +reproducibility correction, with no change to the reviewed theorem or checker. diff --git a/research/direct-circulant-production-precision/compiler-cuts/LICENSE b/research/direct-circulant-production-precision/compiler-cuts/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-cuts/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/compiler-cuts/NOTICE.md b/research/direct-circulant-production-precision/compiler-cuts/NOTICE.md new file mode 100644 index 0000000000..d236f8104d --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-cuts/NOTICE.md @@ -0,0 +1,32 @@ +# Source and assistance notice + +Prepared for Jerry Chen / CubeJerry with substantial OpenAI assistance. +The resumed research and checker are model-assisted mathematical work. + +- Jose Manuel / jmbarrancoml authored the rational-unitary FFT, parity, + generator and Full compiler, its exact source adapters, stored-coefficient + interpretation, polynomial conditioning estimates and allocations. +- Vlado Vojdanovski / #1673 supplied the original recursive compiler, + displacement identities, seven-statement generator macro and gate schedule. +- Chafik Boukhalfa / #628 supplied the interval phase-service lineage; + canonical `interval_kernel.py` is retained unchanged. +- The exact Stein producer's original author and source commit are recorded + in retained/STEIN-PROVENANCE.json and its source header. +- Brian / JoyboyBrian supplied #4755's full physical-cut trace audit, + #4976's sharp generic matching-subset bound and explicit alphabet question, + and #4977's separate improved downset allocation. +- Nick Petalas supplied #4852's separate block-solve bound; this supplement + does not import its improved constant. +- Ali Romman supplied the downstream direct-circulant construction whose + local numerical interface is studied in #8093. +- Cinna Davis and the source-credited native/recovery contributors retain + credit for their separate downstream interfaces. + +The files under retained/ are exact source bytes, not locally edited +replacements. Their repository, commit, path, byte count, SHA256 and Git +blob hashes are in ORIGINS.json. Source headers and licenses remain intact. +All new work is provided under the repository's Apache-2.0 license. + +The two-bank block-matrix estimate uses elementary operator-norm facts; +no literature-priority claim is made. The contribution is the quantified +application to the exact retained alphabet and its caller composition. diff --git a/research/direct-circulant-production-precision/compiler-cuts/ORIGINS.json b/research/direct-circulant-production-precision/compiler-cuts/ORIGINS.json new file mode 100644 index 0000000000..d3d018b180 --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-cuts/ORIGINS.json @@ -0,0 +1,167 @@ +{ + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "files": [ + { + "local": "retained/FULL-PROOF.md", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/rational-unitary-fft/FULL-PROOF.md", + "sha256": "acf8c596d91b5efd35a286735d6867ff8afce64354a13f680c2fae3dab824410", + "git_blob": "e650f46863115f810e27b403f916dd7f79b37786", + "bytes": 15002 + }, + { + "local": "retained/GENERATOR-PROOF.md", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/rational-unitary-fft/GENERATOR-PROOF.md", + "sha256": "cddda1f944299a349c837808b349fa6e4499cbb1889f7dacc00ca8afac9b580c", + "git_blob": "8bef383eec887450e86f14365a6f7b07c1310e9d", + "bytes": 9975 + }, + { + "local": "retained/PR4755-README.md", + "repository": "JoyboyBrian/integer-mult-bounds", + "commit": "653289c67733e1b0feb24ddac796003ebb827e55", + "path": "research/full-toeplitz-cut-audit/README.md", + "sha256": "5b514f93ab3b0a37a32978a599d74c545ed19122e235f9cccfff36faefb97a9b", + "git_blob": "f088efaaa828e415db6bb152a8cbeaea1dd68dd7", + "bytes": 10529 + }, + { + "local": "retained/PR4852-README.md", + "repository": "petalas/integer-mult-bounds", + "commit": "8acf04b4c42fe75894a87a3b2d37ddb68e96a798", + "path": "research/downset-block-solve-bound/README.md", + "sha256": "1e59ae73eb142ec3d4579ce98244295b733896afca0fec3693906fc6def26d3f", + "git_blob": "0b753c1b16f0a2977d3aad7242510ba55bec98a0", + "bytes": 11141 + }, + { + "local": "retained/PR4976-README.md", + "repository": "JoyboyBrian/integer-mult-bounds", + "commit": "8a7e0e9b4a085f4fb47a76700dfe135412b9c4ef", + "path": "research/matching-sublayer-norm/README.md", + "sha256": "ba6754f00779874ec981563101114cf18c03026c18338f37a813abd3fae59d21", + "git_blob": "eb7b8be250b6f23ae30e7e611e651a8fe300ac3e", + "bytes": 7062 + }, + { + "local": "retained/PR4977-README.md", + "repository": "JoyboyBrian/integer-mult-bounds", + "commit": "cd30004ff733d4acac45a47a74fc9b1e76ef35e4", + "path": "research/full-downset-allocation/README.md", + "sha256": "fd1f8cade22bc01f981f8855e6b4c0a62996875a007ff8391e258157ce80f56c", + "git_blob": "c5248440b72a566314aa1ba40647d706f2561f96", + "bytes": 8170 + }, + { + "local": "retained/PROOF.md", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/rational-unitary-fft/PROOF.md", + "sha256": "50e31e33e1275a133d10e87208ceb50dddce67d0678d2a89de9f7ba28d8380d9", + "git_blob": "99a55596f67ae3b94ef02ebb159b313f33bf22af", + "bytes": 14204 + }, + { + "local": "retained/SOURCES.json", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/rational-unitary-fft/SOURCES.json", + "sha256": "7324e22bcb202b5cc03b5f7ea713f6f0c7cd80ee60d320fb03b1e2f7b13b8c91", + "git_blob": "7ee22e983f54dfb73e74d20ed1910a64d2abb6cd", + "bytes": 7143 + }, + { + "local": "retained/STEIN-PROVENANCE.json", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/rational-unitary-fft/vendor/STEIN-PROVENANCE.json", + "sha256": "e7f0e8dc517387e302b1e8bf5dff7e12b29da8aa91abc6ea597f33c1ac08ba62", + "git_blob": "c602fb5bb332dbe098950b14d55da05ce2cf4312", + "bytes": 1366 + }, + { + "local": "retained/TRIANGLE-PROOF.md", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/rational-unitary-fft/TRIANGLE-PROOF.md", + "sha256": "abea26e3c86a9970225b070be034c47e7970e10fe1b5686f405e0b301acf3159", + "git_blob": "f923f4ff2dfe40401fa90d83727ade62b2ef5b5f", + "bytes": 10475 + }, + { + "local": "retained/check_circuits.py", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/capped-phase-fusion/evidence/inplace_algebra_ultra/check_circuits.py", + "sha256": "06d1861bfe8af543908e26557ffda7e451ff176bceb9bacfaf0f04f234b336d5", + "git_blob": "f80c141c8116b163c2bb5a028c28212077c8d5a9", + "bytes": 10774 + }, + { + "local": "retained/engine.py", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/rational-unitary-fft/engine.py", + "sha256": "9e36aee0835e6b1b62997433581f88b5a434ccab8ae43e5c25d1deaaf1ebf653", + "git_blob": "e9f2f2b08dc2bc4c646e47dca92059351ca89384", + "bytes": 13174 + }, + { + "local": "retained/exact.py", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/rational-unitary-fft/exact.py", + "sha256": "c9b89d7357210af69865690ba12e695366961f8b501a8fab9d0fefe3fb30c479", + "git_blob": "aae41e6acfb2e5a4fafdd85727891eb746b57b42", + "bytes": 7863 + }, + { + "local": "retained/full.py", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/rational-unitary-fft/full.py", + "sha256": "1f42d5f2858564ffb320e54ba6aa29651025491569823e25006bf5862457b803", + "git_blob": "7f85ad1a89e81b7dfc6b54e7bd9547120e86d5d3", + "bytes": 12561 + }, + { + "local": "retained/generator.py", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/rational-unitary-fft/generator.py", + "sha256": "827ef9fe1bd664859995892b59843c390f7969c938fb7e1e6dc585c31a54b555", + "git_blob": "d761d3c88b1685fb64d92d69f699b8218c9ec30f", + "bytes": 12562 + }, + { + "local": "retained/interval_kernel.py", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/cubic-cyclic-inverse/vendor/interval_kernel.py", + "sha256": "9b7bb24640a9a7d3f83c7951dfef483ec933db4c50de6c0130b85f450eeddfbe", + "git_blob": "1182175a55cb871481de0f56ea9ae56e474705fe", + "bytes": 2363 + }, + { + "local": "retained/stein_rational.py", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/rational-unitary-fft/vendor/stein_rational.py", + "sha256": "3065fc5d6d22ec44de533b08fb0c639603449456383668e561dc46629e641502", + "git_blob": "71b240a460a185ee2fe926cd189b56aeac6f997f", + "bytes": 6045 + }, + { + "local": "retained/triangular.py", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/rational-unitary-fft/triangular.py", + "sha256": "46780d95ddebfed22e8f0c18565fe2e768250afa5beeb31f450292cc06f7ec11", + "git_blob": "2bd8de01a7ac80de7e6b9f8252bc69d0e0a291e8", + "bytes": 10040 + } + ] +} diff --git a/research/direct-circulant-production-precision/compiler-cuts/PROOF.md b/research/direct-circulant-production-precision/compiler-cuts/PROOF.md new file mode 100644 index 0000000000..9c0aa70006 --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-cuts/PROOF.md @@ -0,0 +1,384 @@ +# Source-alphabet bounds at every complete-gate compiler cut + +Status: author proof; separate review pending. No new kappa or complete +canonical assumption discharge is claimed. + +## 1. Exact claim, novelty and premises + +This completes the interrupted audit of the literal rational compiler at +canonical commit `e54523517d0f03e58352e647c403a5af3e525a57`. The immutable +sources and predecessor reports are authenticated in `ORIGINS.json`. + +For the actual `engine.Builder` alphabet, the four bounds for prefixes, +suffixes, inverse prefixes and inverse suffixes extend to a cut after **any +subset of the complete one/two-wire gates in one matching layer**, with the +same constants as the complete-layer bounds. For the actual composed +`Triangle`, `Program` and `Full` factories, this preserves respectively + +\[ + K_\triangle=3200m^3,\qquad + K_G=\max(3200m^3,2+2k_G)(10+4\alpha+2k_G), +\] + +and the source `Full.allocation` constant + +\[ + K_{\rm Full}=2L_0\mathcal B\mathcal H,\quad + L_0=\max(1,\lambda,Q),\quad + \mathcal B=256N^3(\lambda Q)^{12}. \tag{1} +\] + +Here `k_G`, `alpha` and `H` have their existing source definitions, made +explicit below. An arbitrary segment is conservatively bounded by +`K_Full^2`; the numerical conclusion does not include an intermediate +coordinate assignment inside a two-wire gate. + +Brian/JoyboyBrian's #4755 supplies the exact source-timed trace identity. +His #4976 proves the sharp generic `sqrt(2)` extension from adjacent +matching-layer bounds and asks whether this particular alphabet avoids +that loss. The answer here is affirmative **for these stated source +envelopes**, by the same-direction two-bank invariant in section 2. It does +not assert zero-loss interpolation for arbitrary adjacent matrices, nor +that a partial cut is bounded by the measured maximum of adjacent cuts. +Jose Manuel/jmbarrancoml supplied the original compiler, allocation, +conditioning estimates and the underlying local bounds. We retain those +credits rather than present the complete compiler as a new construction. + +The following source premises are explicit. The complete leading-section +conditioning and component bounds must be valid for the unchanged root. +The exact rank/displacement producer, phase-service certificates and +per-atom operator-error estimates must satisfy their documented contracts. +The data interpretation is the exact stored-coefficient linear program. +The proof supplies the missing fragment extension and verifies its +composition; it does not independently derive the algebraic rank theorem, +certify an analytic mass estimate, price preparation/delivery or identify +online Python arithmetic with a multitape machine. + +## 2. The bank-triangular invariant + +Use the Euclidean operator norm and order coordinates as the complete source +bank followed by the complete target bank. Every non-crossing elementary +gate in `Builder` is unitary within one bank. The swaps are unitary. A +stored phase has modulus one. Its stored butterfly is + +\[ + \begin{pmatrix}a&bw\\b&-aw\end{pmatrix},\qquad + a,b\in\mathbb Q,\quad a^2+b^2=1,\quad |w|=1, +\] + +so its columns are orthonormal. This uses exact rational identities, not +closeness to a unitary gate. The inverse source uses the inverse of the +same stored matrix; conjugating only its twiddle would be incorrect. + +Every cross-bank layer is a complete matching of gates + +\[ + (x_j,y_j)\longmapsto(x_j,y_j+\ell_j x_j). +\] + +Selecting any subset replaces its diagonal multiplier `D` by a diagonal +matrix `D_E` with some entries zero. Hence `||D_E|| <= max_j |ell_j|`. +There are exactly two such layers: cyclic followed by negacyclic. Both +point from the same source bank into the same target bank. The retained +twists and transforms between them act separately within the two banks. + +More generally, a word consisting of bank-local unitaries and same-direction +shear matchings has an operator of the form + +\[ + A=\begin{pmatrix}U&0\\X&V\end{pmatrix},\qquad U,V\text{ unitary}. + \tag{2} +\] + +Initially `X=0`. A bank-local unitary multiplies `X` by a unitary and +preserves its norm. Left multiplication by a shear `S(D)` changes it to +`X+D U`; consequently each shear contributes at most `||D||`. Induction +gives `||X|| <= sum ||D||`. Moreover + +\[ + A^{-1}=\begin{pmatrix}U^{-1}&0\\-V^{-1}XU^{-1}&V^{-1}\end{pmatrix}. +\] + +The diagonal blocks of `A` and `A^-1` have norm one, while the off-diagonal +blocks have equal norms. Splitting each matrix into its diagonal and +off-diagonal parts proves + +\[ + \|A\|,\|A^{-1}\|\le1+\sum\|D\|. \tag{3} +\] + +A complete-gate cut inside any matching layer is legitimate because the +gates have disjoint supports and commute. A selected subset of a unitary +matching is unitary; a selected subset of a shear matching has the same +orientation and no larger coefficient bound. Apply (2)-(3) directly to +the prefix, suffix, or any chronological interval. Each meets at most the +two original spectral matchings. With the source kernel envelopes `M_g`, +`M_h` and multiplier error `v=2^-S`, all four cut operators obey + +\[ + \boxed{1+M_g+M_h+2v.} \tag{4} +\] + +This is exactly the existing primitive envelope. No interpolation factor +is required. Matrix multiplication order is retained throughout; two +noncommuting transforms on a common bank have not been interchanged. + +Both structural premises matter. Compensated nonunitary bank operations can +have arbitrarily large intermediate norms despite an identity endpoint. +Opposite-direction shears with coefficient two have product +`[[5,2],[2,1]]`, whose norm exceeds `1+2+2=5` since its first column has +squared norm 29. Thus the conclusion does not follow just from two +spectral sweeps or an invertible final map. + +## 3. Aligned parity-triangular children + +We retain the source component-l1 near-identity admission. Its Schur +argument gives ideal completed shears of norm and inverse norm at most +five, middle blocks at most two, and primitive envelopes at most seven. +For a recursive ideal prefix or inverse prefix the recurrence + +\[ + B(m)\le\max(7,5B(m/2),70),\qquad B(1)\le2 +\] + +is bounded by `B=100m^3`. Siblings act on disjoint supports. The source +explicitly checks equal sibling macro-boundary partitions in +`Triangle.parallel`, so there are `q=2 log2(m)+1` aligned macro layers. +The exact ideal endpoint and its inverse have norm at most two. + +Let `A_j` be ideal macros, `Ahat_j` their stored counterparts, and let +`||Ahat_j-A_j|| <= epsilon`. Write `Q_j=A_j...A_1`. Put + +\[ + G_j=Q_j^{-1}(\widehat A_j-A_j)Q_{j-1},\qquad + Z_j=Q_j^{-1}\widehat A_j\cdots\widehat A_1. +\] + +Then `Z_j=(I+G_j)Z_(j-1)` and `sum ||G_j|| <= theta=q B^2 epsilon <=1/4` +under the source allocation. Every consecutive product `W` of these +factors has both norm and inverse norm at most `(1-theta)^-1<2`: +use `prod(1+a_j)<=1/(1-sum a_j)` and +`prod(1-a_j)>=1-sum a_j`. Completed stored macro prefixes and their +inverses are therefore bounded by `2B`; suffixes and their inverses by +`4B`. In particular, the suffix is `Q_q W Q_j^-1`, where `W` is a single +consecutive product. Bounding two unrelated perturbation products would +lose a gratuitous factor and is not the argument used here. + +Inside one active macro, every disjoint primitive child has all four +fragment bounds at most seven by (4). A scalar leaf has stored modulus +between one quarter and three, so its complete or empty fragment and +inverse have norm at most four. Their direct sum contributes the maximum, +including a selection that finishes some scalar gates but not others. +Multiplying one completed-prefix/suffix bound by that maximum gives + +\[ + \boxed{K_\triangle=32B=3200m^3} \tag{5} +\] + +at arbitrary complete-gate subsets. The same statement holds for the +literal stored inverse word by exchanging prefixes with inverse suffixes. +This does not replace inverse macros by independently rounded forward +macros or use an adjoint for a nonunitary scalar. + +## 4. Compensated bounded-generator words + +Use the source exact generator decomposition and its fixed-scale bounds + +\[ + \alpha=2rmB_E,\qquad k_G=2m+16mB_E. +\] + +For one term, the exact stored chronology is +`p; S(h); p^-1; S(-h)`. The inverse uses the same stored triangular +transform, and the compensation negates the same stored multipliers while +retaining the original cyclic-then-negacyclic order. The endpoint is +`S(h(p-I))`. It restores the source bank exactly at the algebraic level. +Under the source defect allocation, preceding and remaining sums have +norm at most `a=alpha+1`; `||p||<=2`, `||p^-1||<=4`, `||h||<=k=k_G+1`. + +For `L(B,D)=[[B,0],[D,I]]`, the four checkpoint prefixes are + +\[ + L(p,A),\quad L(p,A+hp),\quad S(A+hp),\quad S(A+h(p-I)). +\] + +If `C` is the sum from the current term onward, their suffixes are + +\[ + L(p^{-1},Cp^{-1}),\quad L(p^{-1},Cp^{-1}-h),\quad + S(C-hp),\quad S(C-h(p-I)). +\] + +Use `L(B,D)^-1=L(B^-1,-DB^-1)` and +`||L(B,D)||<=max(||B||,1)+||D||`. All four checkpoint operators and +inverses are bounded by + +\[ + C_G=4+4a+2k=10+4\alpha+2k_G. \tag{6} +\] + +The triangular fragments have cap (5). Scaled positive and compensation +shears have cap `2+2k_G` by (4) and the source scaled-multiplier envelope. +The latter inequality retains its literal allowance: `k_G>=2` and the +source `v<=1/2` give `1+sqrt(2)k_G+2v<=2+2k_G`. +Only one child is active within a generator term. Thus all four +complete-gate fragment bounds are + +\[ + \boxed{H_G=\max(3200m^3,2+2k_G)C_G.} \tag{7} +\] + +For rank zero the source emits an empty identity word. For disjoint active +generator words in a parent, their direct sum uses the maximum of (7). +The argument uses completed-sum bounds, rather than multiplying one +shear amplification for every generator term. + +## 5. The chronological Full word + +Fix a valid unchanged Toeplitz root of dyadic size `N`, with complete leading +section bounds `||T||<=lambda`, `||T[0:b,0:b]^-1||<=Q`, and the source's +stronger component-envelope guards when calling its executable factories. +Write `chi=lambda Q>=1`. We recall the exact downset proof so that the +fragment composition's dependence is explicit. + +Every contiguous Schur descendant has norm at most +`U=lambda+lambda^2 Q` and inverse norm at most `Q`. Its scalar unit-LDU +factors have direct norm at most `W=3N chi^2` and inverse norm at most +`V=6N chi^4`. The row/column tails of scalar elimination are bounded by +`UQ<=2chi^2`; the Frobenius estimate gives `W`, and +`u^-1=M^-1 l delta`, `l^-1=delta u M^-1` give `V`. Partial pivot +diagonals and their inverses have norm at most `2chi^2`. + +The atom order is upper shear, both disjoint child programs, lower shear; +leaves are scalar pivots. For every ideal completed downset `I`, its product +is `L(I)D(I)U(I)` in that order. `L(I)` is a direct sum of full lower factors +on maximal completed subtrees. If `F` is the partition at the unvisited +upper frontier, `U(I)=U_F^-1 u_root`. These identities follow by tree +induction and never commute overlapping factors. Consequently the product +and inverse product have norm at most + +\[ + V(2\chi^2)(VW)=216N^3\chi^{12}<\mathcal B. \tag{8} +\] + +There are `J=3N-2` atoms. With per-atom stored defect at most `eta` and +`theta=J B^2 eta<=1/4`, the normalized-product argument in section 3 +applies in **any** topological atom order. Every ideal prefix is a downset, +so (8) controls its factors. Completed stored downsets and inverses have +cap `2B`; a remaining stored suffix after any downset and its inverse have +cap `2L_0 B`. For the suffix, cancellation gives the exact expression +`T W Q_j^-1` with one consecutive normalized factor product `W`. + +At a gate cut, use the actual source timestamps: completed atoms satisfy +`stop<=k`, active atoms satisfy `start<=k 0, 'Independent zero divisor') + numerator = self*other.bar() + return Z(numerator.re/norm, numerator.im/norm) + + def __bool__(self): + return bool(self.re or self.im) + + +def matrix(a): + return [[Z.get(x) for x in row] for row in a] + + +def ident(n): + return [[Z(Q(i == j)) for j in range(n)] for i in range(n)] + + +def adjoint(a): + return [[a[j][i].bar() for j in range(len(a))] for i in range(len(a[0]))] + + +def multiply(a, b): + need(len(a[0]) == len(b), 'Independent matrix dimensions') + out = [[Z() for _ in b[0]] for _ in a] + for i, row in enumerate(a): + for k, x in enumerate(row): + if x: + for j, y in enumerate(b[k]): + if y: + out[i][j] = out[i][j]+x*y + return out + + +def subtract(a, b): + return [[x-y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)] + + +def inverse(a): + n = len(a) + rows = [list(row)+unit for row, unit in zip(a, ident(n))] + for j in range(n): + pivot = next((k for k in range(j, n) if rows[k][j]), None) + need(pivot is not None, 'Independent singular matrix') + rows[j], rows[pivot] = rows[pivot], rows[j] + v = rows[j][j] + rows[j] = [x/v for x in rows[j]] + for i in range(n): + if i != j and rows[i][j]: + v = rows[i][j] + rows[i] = [x-v*y for x, y in zip(rows[i], rows[j])] + return [row[n:] for row in rows] + + +def psd(a): + need(a == adjoint(a), 'Hermitian PSD input') + a = [list(row) for row in a] + for k in range(len(a)): + diagonal = a[k][k] + if diagonal.im or diagonal.re < 0: + return False + if not diagonal: + if any(a[k][j] for j in range(k+1, len(a))): + return False + continue + for i in range(k+1, len(a)): + for j in range(k+1, len(a)): + a[i][j] = a[i][j]-a[i][k]*a[k][j]/diagonal + return True + + +def norm_at_most(a, cap): + gram = multiply(adjoint(a), a) + margin = [[Z(cap*cap if i == j else 0)-x for j, x in enumerate(row)] + for i, row in enumerate(gram)] + return psd(margin) + + +def frobenius2(a): + return sum((x.norm2() for row in a for x in row), Q(0)) + + +def embed(a, ids, n): + out = ident(n) + for i, old_i in enumerate(ids): + for j, old_j in enumerate(ids): + out[old_i][old_j] = a[i][j] + return out + + +def convert_plan(plan, n): + out = [] + for layer in plan: + used, row = set(), [] + for ids, gate in layer: + ids = tuple(ids) + need(len(set(ids)) == len(ids) and not used.intersection(ids), 'Actual matching supports') + need(all(0 <= i < n for i in ids), 'Actual gate wires') + used.update(ids) + row.append((ids, matrix(gate))) + out.append(row) + return out + + +def product(plan, n): + out = ident(n) + for layer in plan: + for ids, gate in layer: + out = multiply(embed(gate, ids, n), out) + return out + + +def boundaries(plan, n): + prefixes, prefix_inverses = [ident(n)], [ident(n)] + for layer in plan: + p, pi = prefixes[-1], prefix_inverses[-1] + for ids, gate in layer: + p = multiply(embed(gate, ids, n), p) + pi = multiply(pi, embed(inverse(gate), ids, n)) + prefixes.append(p) + prefix_inverses.append(pi) + suffixes, suffix_inverses = [None]*(len(plan)+1), [None]*(len(plan)+1) + suffixes[-1], suffix_inverses[-1] = ident(n), ident(n) + for k in range(len(plan)-1, -1, -1): + g = product([plan[k]], n) + gi = inverse(g) + suffixes[k] = multiply(suffixes[k+1], g) + suffix_inverses[k] = multiply(gi, suffix_inverses[k+1]) + return prefixes, prefix_inverses, suffixes, suffix_inverses + + +def cuts(plan, n): + pre, pri, suf, sui = boundaries(plan, n) + for k, layer in enumerate(plan): + for mask in range(1 << len(layer)): + yes = [gate for j, gate in enumerate(layer) if mask >> j & 1] + no = [gate for j, gate in enumerate(layer) if not mask >> j & 1] + h, rest = product([yes], n), product([no], n) + yield (k, mask, multiply(h, pre[k]), multiply(pri[k], inverse(h)), + multiply(suf[k+1], rest), multiply(inverse(rest), sui[k+1])) + yield len(plan), 0, pre[-1], pri[-1], ident(n), ident(n) + + +def load_source(): + origins = json.loads((HERE/'ORIGINS.json').read_text()) + for row in origins['files']: + data = (HERE/row['local']).read_bytes() + need(sha256(data).hexdigest() == row['sha256'], + 'Pinned source SHA-256: '+row['local']) + need(len(data) == row['bytes'] and + sha1(b'blob '+str(len(data)).encode()+b'\0'+data).hexdigest() == row['git_blob'], + 'Pinned source Git blob and byte count: '+row['local']) + modules = {} + for name in ('exact', 'engine', 'triangular', 'generator', 'full'): + m = types.ModuleType(name) + m.__file__ = str(RET/(name+'.py')) + sys.modules[name] = m + exec(compile((RET/(name+'.py')).read_bytes(), m.__file__, 'exec', optimize=0), m.__dict__) + modules[name] = m + gen = modules['generator'] + raw = {gen.SOURCE+'check_circuits.py': (RET/'check_circuits.py').read_bytes(), + gen.ORACLE: (RET/'interval_kernel.py').read_bytes(), + gen.PRODUCER: (RET/'stein_rational.py').read_bytes(), + gen.PROVENANCE: (RET/'STEIN-PROVENANCE.json').read_bytes()} + return modules, raw, len(origins['files']) + + +def source_value(z, source): + z = Z.get(z) + return source.C(z.re, z.im) + + +def primitive_fixture(values, modules, raw, label): + exact, engine, gen = (modules[n] for n in ('exact', 'engine', 'generator')) + values = matrix(values) + n = len(values) + source_matrix = exact.Mat([[source_value(x, exact) for x in row] for row in values]) + # These are actual certified source words at a bounded declared precision. + phases = engine.Phases(12, raw[gen.ORACLE]) + builder = engine.Builder(phases, 12, raw[gen.SOURCE+'check_circuits.py']) + plan = convert_plan(builder.plan(source_matrix), 2*n) + # Exercise the nonreal butterfly twiddle site directly, even when this + # bounded whole fixture only needs smaller FFTs. + w=phases.phase(8,1) + butterfly=matrix(builder.butterfly(w)) + wrong_inverse=matrix(builder.butterfly(w.conjugate())) + need(multiply(adjoint(butterfly),butterfly)==ident(2), 'Nonreal rational butterfly is unitary') + need(multiply(wrong_inverse,butterfly)!=ident(2), 'Conjugating only the twiddle is not inversion') + mg, mh = builder.bounds + cap = 1+mg+mh+Q(2, 1 << 12) + spectral_layers, unitary_gates = [], 0 + for k, layer in enumerate(plan): + crossings = [] + for ids, gate in layer: + crossing = len(ids) == 2 and ids[0] < n <= ids[1] + if crossing: + need(gate[0][0] == Z(Q(1)) and gate[1][1] == Z(Q(1)) and not gate[0][1], + 'Actual crossing is one oriented shear') + crossings.append((ids, gate)) + else: + need(all(i < n for i in ids) or all(i >= n for i in ids), 'Actual bank-local support') + need(multiply(adjoint(gate), gate) == ident(len(gate)), 'Exact unitary bank gate') + unitary_gates += 1 + if crossings: + need(len(crossings) == n and len(crossings) == len(layer), 'Complete one-to-one spectral matching') + spectral_layers.append(k) + need(len(spectral_layers) == 2, 'Exactly two spectral sweeps') + count, partial, norm_checks, invariant_checks = 0, 0, 0, 0 + endpoint = product(plan,2*n) + for k, mask, p, pi, s, si in cuts(plan, 2*n): + count += 1 + partial += k < len(plan) and mask not in (0, (1 << len(plan[k]))-1) + for a in (p, pi, s, si): + need(norm_at_most(a, cap), 'Actual primitive four-way cut bound') + norm_checks += 1 + upper = [row[:n] for row in a[:n]] + lower = [row[n:] for row in a[n:]] + cross = [row[:n] for row in a[n:]] + need(not any(x for row in a[:n] for x in row[n:]), + 'Source cut keeps the bank-triangular orientation') + need(multiply(adjoint(upper), upper) == ident(n) + and multiply(adjoint(lower), lower) == ident(n), + 'Source cut has unitary diagonal bank factors') + need(norm_at_most(cross, cap-1), 'Additive source spectral off-diagonal bound') + invariant_checks += 1 + need(multiply(pi, p) == ident(2*n) and multiply(s, p) == endpoint, + 'Independent primitive inverse and concatenation') + return dict(label=label,side=n,layers=len(plan),gates=sum(map(len,plan)),cuts=count, + proper_partial_cuts=partial,psd_certificates=norm_checks, + unitary_gates=unitary_gates,cap=str(cap),bank_invariant_certificates=invariant_checks, + nonreal_twiddle_inverse_control='wrong conjugated-twiddle replacement rejected') + + +def atom_ideal(atom, n): + ids = atom['indices'] + a = matrix(atom['ideal']) + if atom['kind'] == 'leaf': + return embed(a, ids, n) + m = len(a) + local = ident(2*m) + for i in range(m): + for j in range(m): + local[m+i][j] = a[i][j] + return embed(local, ids, n) + + +def atom_prefix(atom, k, selected, n): + local = atom['converted'] + j = k-atom['start'] + out = atom['prefixes'][j] + for ids, gate in selected: + if set(ids).issubset(atom['indices']): + # Global coordinates are retained in every atom's converted plan. + out = multiply(embed(gate, ids, n), out) + return out + + +def timing_predecessors(atoms,depth): + predecessors=[set() for _ in atoms] + for i,a in enumerate(atoms): + need(0<=a['start']<=a['stop']<=depth, 'Source timestamp domain') + lo,hi=a['interval'] + descendants=[j for j,b in enumerate(atoms) + if (lo,hi)!=tuple(b['interval']) and lo<=b['interval'][0]> j & 1] if k < len(plan) else [] + completed = [a for a in atoms if a['stop'] <= k] + active = [a for a in atoms if a['start'] <= k < a['stop']] + remaining = [a for a in atoms if a not in completed and a not in active] + completed_ids={j for j,a in enumerate(atoms) if a['stop']<=k} + for j,a in enumerate(atoms): + if a in completed or a in active: + need(predecessors[j].issubset(completed_ids), 'Completed/active source downset') + used = [i for a in active for i in a['indices']] + need(len(used)==len(set(used)), 'Active source atom supports are disjoint') + qhat, rem, fragments, tails = ident(n),ident(n),ident(n),ident(n) + for a in completed: + qhat = multiply(a['stored'],qhat) + for a in remaining: + rem = multiply(a['stored'],rem) + nonempty=0 + for a in active: + f = atom_prefix(a,k,selected,n) + t = multiply(a['stored'],inverse(f)) + fragments=multiply(f,fragments); tails=multiply(t,tails) + nonempty += f!=ident(n) and t!=ident(n) + need(multiply(fragments,qhat)==p, 'Exact active-prefix trace identity') + need(multiply(rem,tails)==s, 'Exact active-suffix trace identity') + need(multiply(inverse(qhat),inverse(fragments))==pi, 'Prefix inverse order') + need(multiply(inverse(tails),inverse(rem))==si, 'Suffix inverse order') + if multiply(qhat,fragments)!=p: + counts['noncommuting_prefix_controls']+=1 + for a in (p,pi,s,si): + need(frobenius2(a)<=kphys*kphys, 'Independent conservative Full spectral consequence') + counts['global_frobenius_certificates']+=1 + counts['cuts']+=1 + counts['proper_partial_cuts']+=k=2 + counts['trace_equalities']+=4 + need(norm_at_most(subtract(stored_endpoint,target),bound['coefficient_error']), 'Accumulated forward atom error') + need(norm_at_most(subtract(stored_inverse,inverse(target)),bound['coefficient_error']), 'Accumulated inverse atom error') + zero_controls=0 + for j,a in enumerate(atoms): + if a['start']!=a['stop']: + continue + mutated=[dict(row) for row in atoms] + mutated[j]['start']+=1;mutated[j]['stop']+=1 + try: + timing_predecessors(mutated,len(plan)) + except ValueError: + zero_controls+=1 + if any(a['start']==a['stop'] for a in atoms): + need(zero_controls>0, 'Delayed zero-duration source predecessor must reject') + return dict(label=label,n=n,layers=len(plan),gates=sum(map(len,plan)),atoms=len(atoms), + zero_duration_atoms=sum(a['start']==a['stop'] for a in atoms), + source_atom_timestamps=[(a['id'],a['start'],a['stop']) for a in atoms], + child_target_bits=bound['child_target_bits'],theta=str(bound['theta']), + coefficient_error=str(bound['coefficient_error']),execution_bound=str(kphys), + normalized_suffix_identities=normalized_suffix_checks, + rejected_delayed_zero_atoms=zero_controls,**counts) + + +def controls(): + out=[] + # A whole unitary gate can have a singular intermediate coordinate write. + swap=matrix([[0,1],[1,0]]) + partial=matrix([[0,1],[0,1]]) + need(norm_at_most(swap,1) and not norm_at_most(partial,1), 'Split-write norm control') + try: + inverse(partial) + except ValueError: + out.append('coordinate-write splice is singular; no inverse-cut contract') + else: + raise ValueError('Singular intermediate write accepted') + # Endpoint restoration alone cannot bound fragments. + shrink=matrix([[Q(1,2),0],[0,1]]) + need(multiply(inverse(shrink),shrink)==ident(2) and not norm_at_most(inverse(shrink),Q(3,2)), + 'Missing exact-unitarity control') + out.append('nonunitary compensated bank gates violate a near-one fragment cap') + # Reusing an adjoint instead of the stored inverse breaks a nonunit pivot. + scalar=matrix([[Q(3,2)]]) + need(multiply(inverse(scalar),scalar)==ident(1) and multiply(adjoint(scalar),scalar)!=ident(1), + 'Stored inverse versus adjoint') + out.append('nonunitary scalar adjoint is not its stored inverse') + # The generic zero-loss adjacent-boundary interpolation rule is false. + p0=matrix([[6,0],[1,Q(1,6)]]) + p1=multiply(matrix([[Q(1,6),0],[0,6]]),p0) + cut=multiply(matrix([[1,0],[0,6]]),p0) + need(norm_at_most(p0,8) and norm_at_most(p1,8) and not norm_at_most(cut,8), + 'Generic matching interpolation still needs a loss') + out.append('generic no-loss interpolation rejected; source structure is necessary') + opposite = multiply(matrix([[1,2],[0,1]]), matrix([[1,0],[2,1]])) + need(opposite == matrix([[5,2],[2,1]]) and not norm_at_most(opposite,5), + 'Opposite-direction spectral sweeps violate the additive bound') + out.append('opposite-direction sweeps violate the additive bank-triangular bound') + return out + + +def main(): + modules,raw,authenticated=load_source() + primitives=[primitive_fixture([[0]],modules,raw,'zero_side1'), + primitive_fixture([[1,Q(1,3)],[Q(-1,4),1]],modules,raw,'dirty_side2'), + primitive_fixture([[Z(Q(1),Q(1,4)),Z(Q(1,3),Q(-1,5))], + [Z(Q(-1,4),Q(1,7)),Z(Q(1),Q(1,4))]],modules,raw,'complex_side2')] + fulls=[full_fixture([[3,1],[1,3]],modules,raw,'n2_nonzero_approximation'), + full_fixture([[2,1,1,2],[1,2,1,1],[1,1,2,1],[0,1,1,2]],modules,raw, + 'n4_asymmetric_zero_atom',True), + full_fixture([[Z(Q(3,2),Q(1,2))]],modules,raw,'n1_complex_scalar')] + need(fulls[1]['zero_duration_atoms']>0 and fulls[1]['simultaneous_nonempty_fragments']>0, + 'Actual asymmetric fixture exercises the intended source risk') + need(sum(x['noncommuting_prefix_controls'] for x in fulls)>0, + 'Actual source distinguishes illegal factor order') + report=dict(status='PASS_SOURCE_ORDERED_FOUR_WAY_CUT_AUDIT',authenticated_origins=authenticated, + primitive_words=primitives,full_words=fulls,negative_controls=controls(), + proof_sha256=sha256((HERE/'PROOF.md').read_bytes()).hexdigest(), + checker_sha256=sha256(Path(__file__).read_bytes()).hexdigest(), + python_version=sys.version.split()[0], + boundary='Exact stored one/two-wire gate cuts, including arbitrary matching subsets; no split-output inverse claim', + scope='Finite evidence corroborates PROOF.md; phase, rank and conditioning premises remain explicit') + (HERE/'EVIDENCE.json').write_text(json.dumps(report,indent=2,sort_keys=True)+'\n') + print(json.dumps(dict(status=report['status'],primitive_cuts=sum(x['cuts'] for x in primitives), + primitive_psd=sum(x['psd_certificates'] for x in primitives), + full_cuts=sum(x['cuts'] for x in fulls), + full_trace_equalities=sum(x['trace_equalities'] for x in fulls)),sort_keys=True)) + + +if __name__=='__main__': + main() diff --git a/research/direct-circulant-production-precision/compiler-cuts/retained/FULL-PROOF.md b/research/direct-circulant-production-precision/compiler-cuts/retained/FULL-PROOF.md new file mode 100644 index 0000000000..e650f46863 --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-cuts/retained/FULL-PROOF.md @@ -0,0 +1,374 @@ +# Full Toeplitz recursion with a polynomial conditioning envelope + +Jose Manuel (`jmbarrancoml`), with substantial OpenAI Codex assistance. +Apache-2.0. + +## 1. Domain, result and predecessor scope + +Let \(N=2^d\), and let \(T\in\mathbb Q(i)^{N\times N}\) be Toeplitz. +Write \(T_b=T[0:b,0:b]\). I assume +\[ +\Lambda,Q\ge1,\qquad \|T\|_2\le\Lambda,\qquad +\|T_b^{-1}\|_2\le Q\quad(1\le b\le N). +\tag{1} +\] +The full inverse bound alone would not suffice: the Toeplitz matrix +\(\left[\begin{smallmatrix}0&1\\1&0\end{smallmatrix}\right]\) is invertible +but has a singular first section. I include it as an admission control. +I allow indefinite and non-Hermitian matrices satisfying (1). + +I execute the retained `full_plan` on exactly \(N\) logical complex wires, +using the completed generator circuit and the same stored gates in reverse +for inversion. For input norm at most \(R\ge1\), incoming grid +\(F_0\in\mathbb Z_{\ge0}\) and target \(2^{-t}\), \(t\in\mathbb Z_{\ge1}\), +I prove forward and inverse error at most \(2^{-t}\) +with online widths +\[ +O(F_0+t+\log N+\log\Lambda+\log Q+\log R). +\tag{2} +\] +The circuit has \(O(\log^4N)\) layers and \(O(N\log^4N)\) gates. +I give explicit constants below. + +Vlado/PR1673 supplied the recursive compiler and displacement identities. +The retained `GAUGEFREE-INTERIORS.md`, Theorem 4.1, supplies a +conditioning-dependent guard of +\(O(\log N\log(2+\Lambda/\mu))\) for its accretive domain. +I use the scalar unit-LDU factors of legal completed-call sets to obtain +a joint polynomial envelope in dimension and conditioning. This +sharpens the sufficient guard's conditioning dependence under (1). +I leave the selected multiplication exponent unchanged. + +ToikY's [PR4209](https://github.com/CrocSwap/integer-mult-bounds/pull/4209) +at `ccc33bfde8baadef7979fac81e28c0a6f6f278c4` supplies sharper local +Schur closure under a row/column near-identity majorant. I retain that +distinct credit. I do not infer its hypothesis from (1) or use its +sharper constants in the present allocation. + +### Executable admission + +`admission()` computes exact inverses of the same root's leading sections. +It returns \(\lambda_c,Q_c\), each at least one, using the maximum row +and column sums of \(|\Re z|+|\Im z|\). These bound the corresponding +operator norms and also support the executable component-envelope guards. +The verifier binds them to the unchanged root passed to `Full.plan()`. +That lower-level factory does not repeat the complete admission. + +If (1) is supplied as operator-norm information, then +\[ +\lambda_c\le\sqrt{2N}\Lambda,\qquad +Q_c\le\sqrt{2N}Q. +\tag{3} +\] +I use the executable envelopes in its explicit constants. The inflation +in (3) preserves (2). The written operator lemma below uses any valid +\(\Lambda,Q\); passing uninflated operator bounds directly to the +component-guarded factory need not satisfy its stronger guards. + +Exact admission and Schur preparation are offline rational computations. +I do not equate their denominators with online data words or claim a +complete physical preparation/delivery tariff. + +## 2. Contiguous descendants, shears and rank + +The node on logical interval \([a,b)\) has reference matrix +\[ +M_{a,b}=S(a,b)=T_b/T_a, +\] +with the empty prefix convention at \(a=0\). Its children are \(S(a,c)\) +and \(S(c,b)\), where \(c=(a+b)/2\), by the Schur quotient identity. +Consequently +\[ +\|M_{a,b}\|\le U:=\Lambda+\Lambda^2Q,\qquad +\|M_{a,b}^{-1}\|\le Q. +\tag{4} +\] +The inverse is a principal block of \(T_b^{-1}\); the direct bound follows +from the Schur formula and restrictions of the original \(T\). + +At a split, write \(M=\left[\begin{smallmatrix}A&B\\C&D\end{smallmatrix}\right]\), +\(K=A^{-1}B\), \(L=CA^{-1}\). Let \(R_a\) select the coordinates +\([a,c)\) from \([0,c)\). The block inverse identities give +\[ +K=R_aT_c^{-1}T[0:c,c:b],\qquad +L=T[c:b,0:c]T_c^{-1}R_a^T. +\] +Thus, with \(\chi=\Lambda Q\), +\[ +\|K\|,\|L\|\le\chi. +\tag{5} +\] +The component-envelope versions follow under the executable admission. +The source computes \(L\) as `solve(A.T, C.T).T`. I preserve ordinary +transpose in this complex identity. + +The retained `SHALLOW-TOEPLITZ.md`, Sections 4–6, gives commutator rank +at most \(2+\text{depth}\) for the Schur nodes. Its rectangular identities +bound the shear commutator ranks by \(2\,\text{depth}+5\) and +\(2\,\text{depth}+7\). Conversion to +\(E_X=X-ZXZ^T\) adds at most one rank. I use the uniform allowance +\[ +r_*=2d+8. +\tag{6} +\] +The exact rational producer retains that rank; I do not use the numerical +source's floating SVD threshold as a universal rank argument. +The executable also checks exact generator rank against separate +elimination in its finite fixtures. + +## 3. Uniform scalar-LDU bounds + +Write \(M_J=\ell_J\delta_Ju_J\) for the scalar unit-LDU factors of a +contiguous descendant. All its leading sections are further \(S(a,c)\), +so (4) also applies during scalar elimination. +For \(A_k=M_J[0:k,0:k]\), the last row of +\(A_k^{-1}M_J[0:k,k:]\) is the corresponding unit-upper row tail. +The last column of \(M_J[k:,0:k]A_k^{-1}\) is the unit-lower column tail. +Each therefore has norm at most +\[ +UQ=\chi+\chi^2\le2\chi^2. +\] +The Frobenius estimate therefore permits +\[ +\|\ell_J\|,\|u_J\|\le W:=3N\chi^2. +\] +The pivot diagonal has norm at most \(U\) and inverse norm at most \(Q\). +From +\[ +u_J^{-1}=M_J^{-1}\ell_J\delta_J,\qquad +\ell_J^{-1}=\delta_Ju_JM_J^{-1} +\] +I obtain +\[ +\|\ell_J^{-1}\|,\|u_J^{-1}\|\le V:=6N\chi^4, +\tag{7} +\] +using \(QU\le2\chi^2\). A diagonal containing some completed pivots +and otherwise ones has direct and inverse norms at most \(2\chi^2\). + +## 4. Exact downsets and the upper frontier + +At an internal node \(v\), denote the upper and lower atomic calls by +\[ +R_v=\begin{pmatrix}I&K_v\\0&I\end{pmatrix},\qquad +B_v=\begin{pmatrix}I&0\\L_v&I\end{pmatrix}. +\] +The source executes \(R_v\), its two child programs in parallel, then +\(B_v\). A leaf executes its scalar pivot. +The atomic partial order places \(R_v\) before both children and both +children before \(B_v\). Incomparable calls act on disjoint intervals +and commute. I count identity shears as calls even when they emit zero layers. + +For a downset \(I\), let \(Q(I)\) be its product in any legal linearization. +At a node, the restricted downset is empty; or it contains \(R_v\) and +child downsets \(I_0,I_1\) but not \(B_v\); or it contains the whole node. +For an empty node set all three factors to identity. At a completed leaf +set them to \(I,d_i,I\). Otherwise define +\[ +\begin{aligned} +\mathcal L(I)&=B_v^\epsilon + \operatorname{diag}(\mathcal L(I_0),\mathcal L(I_1)),\\ +\mathcal D(I)&=\operatorname{diag}(\mathcal D(I_0),\mathcal D(I_1)),\\ +\mathcal U(I)&=\operatorname{diag}(\mathcal U(I_0),\mathcal U(I_1))R_v, +\end{aligned} +\tag{8} +\] +where \(\epsilon=1\) exactly when the lower call has completed. +Then both children are complete. Substituting the child identities gives +\[ +\boxed{Q(I)=\mathcal L(I)\mathcal D(I)\mathcal U(I).} +\tag{9} +\] +This induction never commutes overlapping factors. + +Uniqueness of scalar unit-LDU gives +\[ +\ell_v=B_v\operatorname{diag}(\ell_{v0},\ell_{v1}),\quad +\delta_v=\operatorname{diag}(\delta_{v0},\delta_{v1}),\quad +u_v=\operatorname{diag}(u_{v0},u_{v1})R_v. +\] +Hence \(\mathcal L(I)\) is the direct sum of full lower factors on the +maximal completed subtrees, with identity elsewhere. The partial diagonal +contains completed pivots and otherwise ones. + +For the upper frontier, stop at a node whose upper call has not completed; +otherwise descend to its two children. Retain singleton leaves. +The resulting intervals partition the coordinates. With +\(U_{\mathcal F}=\bigoplus_{v\in\mathcal F}u_v\), induction gives +\[ +u_{\rm root}=U_{\mathcal F}\mathcal U(I),\qquad +\mathcal U(I)=U_{\mathcal F}^{-1}u_{\rm root}. +\tag{10} +\] +At an unvisited node the identity is \(u_v=u_vI\); at a visited node, +substitute the two child identities and multiply by \(R_v\). + +Equations (7)–(10) bound the lower factor and its inverse by \(V\), +the partial diagonal and its inverse by \(2\chi^2\), and the upper +factor and its inverse by \(VW\). Thus +\[ +\boxed{\|Q(I)\|,\|Q(I)^{-1}\| +\le216N^3\chi^{12}<\mathcal B:=256N^3\chi^{12}.} +\tag{11} +\] +I use a fixed number of polynomial factors, rather than multiplying +conditioning factors through the recursion depth. + +## 5. Approximate atomic calls and physical cuts + +There are \(J=3N-2\) atomic calls: two shears per internal node and one +scalar per leaf. Approximate each by operator error at most \(\eta\). +For any legal linearization, set +\[ +G_j=Q_j^{-1}(\widehat A_j-A_j)Q_{j-1},\qquad +\theta=J\mathcal B^2\eta. +\] +The downset bound (11) applies to its prefixes. +If \(\theta\le1/4\), the product of \(I+G_j\), or its inverse, has norm +below two and distance from identity at most \(2\theta\). +Using \(\Lambda,Q\le\mathcal B\), I obtain +\[ +\|\widehat T-T\|,\|\widehat T^{-1}-T^{-1}\| +\le e:=2J\mathcal B^3\eta. +\tag{12} +\] +Completed approximate prefixes and inverse prefixes have norm at most +\(2\mathcal B\). Remaining suffixes and inverse suffixes have norm at most +\(2L_0\mathcal B\), where \(L_0=\max(1,\Lambda,Q)\). +I apply the exact LDU identities to the ideal calls, not to the +approximate endpoints. + +At a physical gate cut, completed calls form a downset \(I\). +Started but unfinished calls form a pairwise incomparable set \(A\): +the source finishes an upper call before starting its descendants and +finishes those descendants before its lower call. Active supports are +therefore disjoint, even when sibling ranks and lengths differ. + +Write each active stored endpoint as \(\widehat A_a=T_aF_a\), with executed +prefix \(F_a\) and remaining suffix \(T_a\). A completed call executed +after an active call began must act on a disjoint subtree, so I may commute +only that disjoint work. I obtain the exact identities +\[ +C_{\rm prefix}=(\bigoplus_{a\in A}F_a\oplus I)\widehat Q(I),\qquad +C_{\rm suffix}=\widehat Q_{\rm remaining} + (\bigoplus_{a\in A}T_a\oplus I). +\tag{13} +\] +The set \(I\cup A\) is also a downset, so I may order \(I\), then \(A\), +then the remaining calls in the suffix argument. +A direct sum contributes the largest fragment norm. I do not require +aligned child macro boundaries. A zero-layer identity completes at its +position in the source schedule and contributes no active fragment. + +## 6. Child, scalar and data bounds + +The component envelope used by a shear's exact producer satisfies +\(B_E\le4N\chi\): its displacement norm is at most \(2\chi\), and a +component row/column sum is at most \(\sqrt{2m}\) times that norm. +Substituting \(m\le N\), \(r\le r_*\), \(B_E\le4N\chi\) in +[GENERATOR-PROOF.md](GENERATOR-PROOF.md), put +\[ +\alpha_*=8r_*N^2\chi,\quad K_{G,*}=2N+64N^2\chi, +\] +\[ +H_*=\max(3200N^3,2+2K_{G,*})(10+4\alpha_*+2K_{G,*}). +\] +The generator's radius-one allocation supplies an unrounded operator +defect. I discard its local data grid and execute the flattened full +program on one global grid. + +A scalar pivot has \(1/Q\le|a|\le U\). I round it at \(s\) bits, +with \(\eta=2^{-s}\le1/(2Q)\), and invert the same stored value. +Then \(|\widehat a|\ge1/(2Q)\), its direct norm is at most \(U+1\), +and its inverse norm is at most \(2Q\). +Consequently +\[ +\mathcal H=\max(H_*,U+1,2Q),\qquad +K_{\rm phys}=2L_0\mathcal B\mathcal H +\tag{14} +\] +bounds physical prefixes, suffixes and their inverses. +An arbitrary segment needs the conservative bound \(K_{\rm phys}^2\). + +The unchanged source schedule permits +\[ +D_*=1+2dr_*(8d^2+32d+18),\qquad +G_*=N[1+dr_*(4d^2+24d+22)]. +\tag{15} +\] +I sum two generator calls per level and the \(N\) scalar leaves; parallel +siblings contribute their maximum depth. +Choose +\[ +s=t+\lceil\log_2(4J\mathcal B^3(R+1))\rceil,\quad +F=\max(F_0,t+\lceil\log_2(2D_*K_{\rm phys}N)\rceil). +\tag{16} +\] +These choices ensure the perturbation and scalar margins above. +One layer's rounding error is at most \(N2^{-F}\). Thus either direction +has error at most +\[ +eR+D_*K_{\rm phys}N2^{-F}\le2^{-t}, +\tag{17} +\] +and intermediate amplitude at most +\[ +A=K_{\rm phys}R+D_*K_{\rm phys}^2N2^{-F}. +\tag{18} +\] +The inverse direction uses the exact stored inverse program on its own +input satisfying the same \(R,F_0\) contract. I claim no exact rounded +forward/inverse round trip. + +If \(\widehat a=(a+ib)/2^s\) is a scalar leaf, its reciprocal +\(2^s(a-ib)/(a^2+b^2)\) has component height at most +\(2s+2\lceil\log_2(U+2)\rceil+8\). +I take the maximum of this bound and the generator children's declared +coefficient bounds, all fixed before online execution. +With \(I=\max(1,\lceil\log_2\max(1,A)\rceil)+2\), signed grid words fit +\(F+I\) bits and constant-size gate temporaries fit +\[ +2F+8C_{\rm bits}+2I+32. +\] +The constants in (6), (11), (14) and (15) are polynomial in \(N,\Lambda,Q\). +The child precision formulas and (16) therefore give (2), including the +executable envelope inflation (3). + +## 7. Source binding, finite evidence and limits + +I authenticate and execute the unmodified `full_plan`, `parallel` and +`inverse` ASTs. I supply exact rational matrix slicing, ordinary transpose, +solve, subtraction and multiplication; wrap recursive calls only to +record their exact reference matrices; and bind `lowdisp_shear` to the +completed generator program. I preserve source assertions in its +dependencies under optimized Python. + +The verifier checks direct full matrices and separate inverse references, +exact stored inversion, leading-section bounds, scalar-LDU identities, +legal downsets and upper-frontier identities. It enumerates all downsets +through size four and checks source-timed downsets on larger fixtures. +Selected physical cuts compare both identities in (13), including +simultaneous nonempty active fragments. Timing checks explicitly cover +unequal sibling lengths and zero-layer calls. + +I test indefinite and half-shift Gaussian matrices, complex inputs, +small and large scalar pivots, reversed wire labels, a nonzero 512-bit +incoming fixture and a size-16 identity with zero-layer shear calls. +The finite Frobenius inequalities include the dimension factor \(N\); +they corroborate consequences of the written operator proof rather than +independently establish its sharper bounds. +Exact dense matrices remain checker oracles outside the online +representation claim. Observed heights describe completed rational +components rather than exhaustive `Fraction` internals. + +I preserve the earlier FFT, triangular and generator receipts and the +fixed-head scope of James Reed's finite budget/source-seal audit at +`fdcdc269`. That audit excludes gate replay and universal-proof acceptance. +I credit Vlado Vojdanovski/PR1673 and the retained gauge-free source lineage +for the original recursive, displacement and conditioning arguments; +Chafik Boukhalfa/PR628 for certified phases; Cinna Davis for the later caller; +ToikY for the distinct same-rho Schur theorem; and classical LU/Schur methods. +Internal agents belong to the author process. + +Complete Gaussian assembly, physical coefficient setup/delivery, fixed-tape +costs and independent mathematical acceptance remain open. diff --git a/research/direct-circulant-production-precision/compiler-cuts/retained/GENERATOR-PROOF.md b/research/direct-circulant-production-precision/compiler-cuts/retained/GENERATOR-PROOF.md new file mode 100644 index 0000000000..8bef383eec --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-cuts/retained/GENERATOR-PROOF.md @@ -0,0 +1,277 @@ +# Complete rounded bounded-generator circuits + +Jose Manuel (`jmbarrancoml`), with substantial OpenAI Codex assistance. +Apache-2.0. + +## 1. Input, output and inherited generator identity + +I consider a rational complex matrix \(T\) of dyadic size \(m=2^d\). +Let \(Z\) be the nilpotent lower shift and \(E=T-ZTZ^T\), with rank \(r\). +The target is the dirty shear +\[ +S(T)(x,y)=(x,y+Tx) +\] +on exactly \(2m\) existing complex wires. I require no zero bank. +The input lies on an \(F_0\)-bit dyadic grid and has norm at most \(R\ge1\); +the requested output error is \(2^{-t}\), with integer \(t\ge1\). +I use a rational bound \(B_E\ge\|E\|_2\). The executable takes the maximum +of the row and column component sums, which bounds both induced norms. + +I execute the frozen PR4198 rational producer. For each nonzero orthogonal +residual \(v_j\) of \(E\), it chooses a dyadic \(c_j\) with +\(\|v_j\|\le c_j<2\|v_j\|\), then emits +\[ +g_j=v_j/c_j,\qquad +a_j=\frac{c_j}{v_j^*v_j}v_j^*E. +\] +The orthogonal projectors sum to the identity on the column space of \(E\). +Thus +\[ +E=\sum_{j=1}^r g_ja_j,\quad +\|g_j\|\le1,\quad \|a_j\|<2B_E,\quad +T=\sum_{j=1}^r L(g_j)U(a_j). +\tag{1} +\] +The last identity follows by telescoping +\(T=\sum_{k=0}^{m-1}Z^kE(Z^T)^k\). The \(a_j\) are coefficient rows; +I apply no further conjugation. + +I retain the producer's scale +\[ +\Gamma_j=\min\{2^e:2^e\ge\max(1,2\ell(a_j))\},\quad +\ell(a)=\sum_k(|\Re a_k|+|\Im a_k|), +\] +and put \(P_j=I+U(a_j)/\Gamma_j\), \(G_j=\Gamma_jL(g_j)\). +Then \(P_j\) satisfies the component-l1 admission used in +[TRIANGLE-PROOF.md](TRIANGLE-PROOF.md), and +\(\|P_j\|\le3/2,\ \|P_j^{-1}\|\le2\). +The source realizes the upper triangular map by reversing its source wires. + +I use the rational bounds +\[ +\alpha=2rmB_E,\qquad K_G=2m+16mB_E. +\tag{2} +\] +Indeed \(\|L(g_j)U(a_j)\|\le2mB_E\), and +\[ +\Gamma_j\sqrt m + <2\sqrt m+8\sqrt2\,mB_E\le K_G. +\] +The scaled shear's coefficient component sum is at most +\(\sqrt2K_G<2K_G\). I budget the approximation of \(G_j\) itself; +approximating \(L(g_j)\) first and multiplying by an uncharged +\(\Gamma_j\) would not meet this contract. + +## 2. Paired compensation and additive defects + +I retain the source's four calls: +\[ +P_j;\quad S(G_j);\quad P_j^{-1};\quad S(-G_j). +\tag{3} +\] +I compile \(\widehat P_j\) and reuse its exact stored inverse. +For the positive shear I use the certified FFT construction. +For its compensation I reuse the same unitary tables and negate the +stored spectral multipliers, preserving the source's cyclic-then-negacyclic +order. The two unrounded shear endpoints are exactly +\(S(\widehat G_j)\) and \(S(-\widehat G_j)\). + +Negating a nearest-grid value gives a nearest-grid value of the negative +exact quantity, so this paired rule retains the same multiplier-error +bound. At half-grid ties it need not agree with independent rounding +toward positive infinity. The verifier includes that discrepancy as a +control. I do not replace the negative child with a reversed whole +positive-shear program. + +For \(\|\widehat P_j-P_j\|,\|\widehat G_j-G_j\|\le\eta\le1/4\), +the exact stored-coefficient program has endpoint +\[ +(x,y)\longmapsto(x,y+\widehat G_j(\widehat P_j-I)x). +\] +Write \(T_j=G_j(P_j-I)\) and +\(\widehat T_j=\widehat G_j(\widehat P_j-I)\). Then +\[ +\|\widehat T_j-T_j\| +\le K_G\eta+(1/2+\eta)\eta\le(K_G+1)\eta. +\] +The completed terms restore the same source bank, so their endpoints +compose to \(S(\sum_j\widehat T_j)\). Consequently +\[ +\boxed{\|\sum_j\widehat T_j-T\|\le +\Delta:=r(K_G+1)\eta.} +\tag{4} +\] +I need no generic product-of-perturbed-matrices bound across completed +generator terms. This additive estimate uses exact stored-coefficient +restoration; data-rounding errors receive a separate bound below. + +## 3. Checkpoint prefixes and suffixes + +Assume \(\Delta\le1\). Any preceding or remaining sum of approximate terms +has norm at most \(a_*=\alpha+1\). +For the current term write \(p=\widehat P_j\), \(h=\widehat G_j\), +\(A=\sum_{i=1`, such that + +``` +Λ,Q >= 1, ||T||₂ <= Λ, ||T_k^-1||₂ <= Q for 1<=k<=N, +T_k = T[0:k,0:k]. +``` + +Every leading section is invertible. Put `χ=ΛQ` and `S=Λ+Λ²Q`. +Choose any binary tree of contiguous coordinate intervals. At `[a,b)` split +at `s`, the reference matrix is the Schur descendant `T_b/T_a`, with the +empty-prefix convention. Execute the upper shear, both children in any +legal interleaving, then the lower shear. A leaf executes its scalar pivot. +Atoms are complete ideal shears and scalars, including identity atoms. + +For every downset of this atomic dependency order, let `P` be its endpoint +product. Form a partition by stopping at a fully finished subtree or a +subtree none of whose atoms has executed, and otherwise descending. Label +its intervals finished or untouched. If their counts are `c` and `u`, then + +``` +||P||₂² <= c S² + u(1+χ²), +||P^-1||₂² <= c Q² + u(1+χ²). +``` + +The partition has `1<=c+u<=N`. Since `S>=1+χ>=sqrt(1+χ²)` and +`Q<=χ`, this implies + +``` +||P||₂ <= sqrt(N) (Λ+Λ²Q), +||P^-1||₂ <= sqrt(N(1+χ²)), +``` + +and the common envelope `2 sqrt(N) χ²`. Neither Toeplitz structure, +positivity, equal splits nor a balanced tree is required. The theorem +concerns complete calls. Cuts inside a generator/FFT call, rounded arithmetic, +storage, native cost and the complete multiplication theorem are outside scope. + +## Proof + +### 1. Retain the global factorization and its order + +Write the unique scalar unit-LDU factorization as `T=L D U`. For an interval +`J=[a,b)`, write `M_J=T_b/T_a` and `U_J=U[J,J]`. The identities +`M_J=L[J,J] D[J,J] U_J` and the completed-downset/frontier factorization +are inherited from Jose Manuel's `rational-unitary-fft/FULL-PROOF.md`, +sections 2 and 4, and Brian's PR #4788, sections 2 and 3, head +`ddd98e28b1d6a674b1d6b93c5d7de8a9f9c86eec`. +The latter includes arbitrary contiguous interval trees. They are cited +inputs, not results audited here. + +Let `B` be the finished/untouched partition. Define + +``` +U_B = direct_sum over J in B of U_J, +E_B = direct_sum over J in B of (M_J if finished, I_J if untouched). +``` + +The inherited factorization gives, in this order, + +``` +P = E_B U_B^-1 U, (1) +P^-1 = U^-1 U_B E_B^-1. (2) +``` + +Indeed the usual upper frontier stops at untouched internal nodes and has +singleton leaves inside finished nodes. Replacing those singletons within a +finished `J` by `U_J` changes its left factor from `L_J D_J` to +`M_J=L_J D_J U_J`; the new right factor `U_J^-1` cancels that change. +Untouched blocks already have left factor identity and upper block `U_J`. +This gives (1) without commuting overlapping factors. Incomparable atoms +have disjoint intervals, so all legal linearizations give the same product. +Equivalently, contract each finished or untouched node to one block. At an +open internal node its lower atom is absent, so its product is +`diag(P_left,P_right) R`. Substituting the child formulas and +`U_node=diag(U_left,U_right) R` proves (1) inductively for every interval +tree. The two stopping cases are respectively `P=M_J` and `P=I_J`. + +### 2. Bound forward block rows + +For a finished `J=[a,b)`, equation (1) gives + +``` +P[J,:a] = 0, +P[J,a:N] = T[J,a:N] - T[J,:a] T_a^-1 T[:a,a:N]. (3) +``` + +Eliminate the leading `a` rows of `T=LDU` and restrict the resulting +rectangular Schur row to `J`. Each restriction of `T` has norm at most `Λ`. +Thus this whole block row has norm at most `S`. At `a=0` the second term +is absent and `Λ<=S` suffices. + +For an untouched `J`, its row is `U_J^-1 U[J,:]`. It is zero before `a`, +identity on `J`, and has tail + +``` +K_J = (T_b^-1 T[:b,b:N])[a:b,:]. (4) +``` + +To see this, cancel `L_b D_b` in `T_b^-1 T[:b,b:N]`. The last block rows +of the result are `U_J^-1 U[J,b:N]`. Hence `||K_J||<=QΛ=χ`. +The row `[I_J K_J]` has squared norm `1+||K_J||²<=1+χ²` by its Gram +product. For any `x`, sum the squared norms of the disjoint block-row +outputs of `Px`. This proves `||P||²<=cS²+u(1+χ²)`. + +### 3. Bound inverse block columns + +For every interval `J=[a,b)`, triangular block inversion gives + +``` +(U^-1[:,J] U_J)[0:b,:] = [-T_a^-1 T[:a,J]; I_J], (5) +(U^-1[:,J] U_J)[b:N,:] = 0. +``` + +At `a=0` the top block is empty. For the top identity, invert the upper +`2×2` blocks on `[:a,J]` and use +`T_a^-1 T[:a,J]=U[:a,:a]^-1 U[:a,J]`. + +An untouched block column in (2) equals (5). Its norm is at most +`sqrt(1+χ²)`, using the original leading solve at `a`, or is one if `a=0`. +For a finished block, multiply (5) on the right by `M_J^-1`. +The ordinary block inverse formula identifies the result as + +``` +P^-1[0:b,J] = T_b^-1[:,a:b], +P^-1[b:N,J] = 0. (6) +``` + +Its whole block-column norm is at most `Q`. This avoids multiplying +separate bounds for the two factors in (5). + +For disjoint input blocks, `P^-1 x=sum_J C_J x_J`. The triangle and +Cauchy-Schwarz inequalities give + +``` +||sum_J C_J x_J|| <= sum_J ||C_J|| ||x_J|| + <= sqrt(sum_J ||C_J||²) ||x||. +``` + +This proves the inverse inequality. Empty downsets, finished roots, +singletons and zero-width tails are included. Finally +`S=Λ(1+χ)<=2Λχ<=2χ²` proves the common envelope. + +## Exact evidence and reproduction + +`verify.py` is a self-contained standard-library checker. It constructs +literal upper/child/lower atomic programs and checks all binary contiguous +interval trees through five leaves and every downset of each tree, for one +real and one nonreal rational fixture per size. Complex matrices use faithful +interleaved rational realification. No predecessor verifier or unmerged Git +object is imported. + +For each downset it computes `P` by literal atomic multiplication and its +inverse by exact elimination, then checks (1), (3), (4), (5) and (6). +Exact rational positive-semidefinite tests certify block norms and both +assembled squared bounds. The printed receipt enumerates its checks and +binds them to hashes of the package files. Checks use explicit exceptions +and remain enabled under `-O`. Rejection controls cover wrong factor order, +omitted finished endpoints, wrong inverse signs, invalid partitions, invalid +spectral certificates and using only the whole-matrix inverse premise. +The complete finite replay passes 46 trees, 2,380 downsets, 9,520 matrix +identities, 9,372 partition blocks and 23,504 downset spectral certificates. +Eleven control groups pass, including 2,244 wrong-order, 2,160 omitted-endpoint +and 1,940 inverse-sign distinguishing states. These are finite coverage counts, +not claims about every complex matrix. + +From the worktree root: + +```sh +~/git/integer-mult-bounds/.venv/bin/python3.12 -I -W error -B research/downset-block-solve-bound/verify.py +~/git/integer-mult-bounds/.venv/bin/python3.12 -I -O -W error -B research/downset-block-solve-bound/verify.py +~/git/integer-mult-bounds/.venv/bin/python3.12 -B scripts/research_package.py --package research/downset-block-solve-bound +~/git/integer-mult-bounds/.venv/bin/python3.12 -B scripts/check_research_commit.py --package research/downset-block-solve-bound --check-source-history +``` + +The last command follows committing. The universal claim rests on the written +proof. A selected-baseline metadata control passed; the selected construction +was not replayed. Independent human and formal proof-kernel review are unclaimed. + +Checker resource limits: Python/Fraction arithmetic allocates managed objects. +The checker fixes at most five logical coordinates and ten real coordinates, +at most 16 tree shapes per size, and at most 256 downsets per tree. Loop +bounds follow these capacities or fixed package-file inventories. No recursion, +dynamic imports, code evaluation, subprocesses or external runtime dependencies are used. +The three negative-control callbacks have fixed local targets and no retained +state. AST syntax validation and warning-strict execution supplement the replay; +no unavailable standalone lint or type-check pass is claimed. A future +parameterized checker must add input/bit-size limits before lifting these +fixed-fixture resource bounds. + +## Open next questions + +1. Can this envelope replace the old one in the complete rounded Full factory? + First list every old-envelope dependency and prove the new allocation + inequalities. Unfinished generator fragments and scalar/data grids retain + their own obligations. No factory substitution is supplied here. +2. Is square-root growth in the number of frontier blocks necessary when + `Λ,Q` stay bounded? Seek an explicit growing family or a bound exploiting + shared block-solve geometry. No asymptotic sharpness claim is made. + +## Attribution and overlap + +Credit Brian (JoyboyBrian), PR #4788, for global-factor restrictions, +arbitrary interval trees and the previous `32 N^(3/2)χ^8` envelope; +Jose Manuel (jmbarrancoml), PR #4205, for the original scalar-LDU/frontier +proof and polynomial Full-recursion envelope; and Vlado Vojdanovski, +PR #1673, for the recursive compiler. Classical Schur and block inverse +identities are background. The new step is the mixed finished/untouched +partition and direct original-leading-solve block norm estimate. Predecessor +credit and disclosures remain unchanged in their own packages. + +The task changes `uniform-transfer-audit` into a new precision-interface +inequality. Brian's open package studies the same quantity and is the +nearest predecessor. Triangular parity-prefix/suffix and dirty FFT gate-cut +packages use different schedules and boundaries; this does not extend their +exact constants or audit their results. + +Canonical base is `624de9dc66858af0945e5f8a0942488d62280d43`, priority revision 7. +The [advance claim](https://github.com/CrocSwap/integer-mult-bounds/discussions/1166#discussioncomment-19133325) +records the scope. Main README searches, merged PR searches, live open PR +bodies, recent handoffs and local reservations were checked. Those searches +do not cover unpublished investigations or every historical diff. +Provenance pins are in `SOURCES.json`; runtime needs only this package. +The overlap helper covered 367 open PRs and 3,821 Discussion records at its +21:46–21:47 UTC snapshot. Its sparse local inventory covered 115 of 6,319 +HEAD notes; separate `git grep` searched all main package READMEs for the +distinctive terms. No complete local-note inventory or novelty certificate +is claimed. A canonical refresh after the first replay retained the same base. diff --git a/research/direct-circulant-production-precision/compiler-cuts/retained/PR4976-README.md b/research/direct-circulant-production-precision/compiler-cuts/retained/PR4976-README.md new file mode 100644 index 0000000000..eb7b8be250 --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-cuts/retained/PR4976-README.md @@ -0,0 +1,121 @@ +# Numerical bounds inside a matching layer + +Prepared by JoyboyBrian with substantial OpenAI Codex assistance. Apache-2.0. + +## Result and scope + +The physical-cut trace audit `full-toeplitz-cut-audit` explicitly leaves the +numerical contract at a proper subset of a matching layer open. This package +supplies a dimension-independent interpolation lemma for all four operators: +prefix, suffix, inverse prefix and inverse suffix. It binds the lemma to the +actual retained rational FFT and Toeplitz-shear gates. It changes no frozen +factory or selected exponent. + +Let the complete layer be an invertible block diagonal operator G on disjoint +coordinate supports. Choose any subset of its complete gates, let E be the +orthogonal coordinate projection onto their supports, and let H be their +product, identity elsewhere. Then + +``` +H = E G + (I-E), H^-1 = E G^-1 + (I-E), EG=GE. +``` + +For the adjacent complete-layer prefixes P0 and P1=G P0 and suffixes +S0=S1 G, the cut inside this layer has P=H P0 and S=S1 G H^-1. Exactly, + +``` +P = E P1 + (I-E) P0, +P^-1 = P1^-1 E + P0^-1 (I-E), +S = S0 (I-E) + S1 E, +S^-1 = (I-E) S0^-1 + E S1^-1. +``` + +The order matters; the projection need not commute with any prefix or suffix. +All products act on columns and the most recent gate multiplies on the left. + +## Quantified norm proof + +For orthogonal output projections, the two summands' squared output norms add. +For orthogonal input projections, use the triangle inequality followed by +Cauchy–Schwarz. Thus if the two neighboring operators of any one of the four +types have norm at most a and b, the partial-layer operator has norm at most +`sqrt(a*a+b*b)`. In particular a common complete-layer bound F becomes +`sqrt(2) F`. This proof holds over C for every dimension and every finite +matching, including identity gates, empty/full selected subsets, and unused +coordinates. It does not split an individual gate's internal arithmetic. + +There is no valid generic zero-loss interpolation rule. For integer m>=4 use + +``` +P0 = [[m,0],[1,1/m]], G = diag(1/m,m), +P1 = [[1,0],[m,1]], H = diag(1,m). +``` + +Every complete boundary of the two-layer program P0;G, including its prefix, +suffix and both inverses, has norm at most `m+2` (their squared Frobenius +norms suffice). But `H P0` maps e0 to `(m,m)`, of norm `sqrt(2)m`. +For m>=5 this exceeds m+2, and its ratio to that common valid envelope tends +to sqrt(2). Consequently the generic factor sqrt(2) is sharp, even when the +four complete-boundary contracts are provided together. The witness uses two +disjoint scalar gates, so the complete-layer matching premise is preserved. + +## Consequence for the retained generator and Full caller + +The retained `GENERATOR-PROOF.md` complete-layer fragment bounds and the exact +physical-cut trace remain explicit inputs, rather than results re-proved here. +Apply the lemma separately to each actual local microprogram. A child with +four complete-layer bounds H has four arbitrary-matching-subset bounds +`sqrt(2)H`, with rational safe envelope `2H`. Active atoms have disjoint +supports, so their direct sum contributes the maximum such bound, without +multiplying by the number of active atoms. + +In FULL-PROOF.md (14), complete-layer `K_phys=2 L0 B H` therefore becomes +`sqrt(2) K_phys` at these added sublayer cuts; `2 K_phys` is a rational safe +choice. Arbitrary segments between two added cuts have bound `2 K_phys^2` +(or rational safe `4 K_phys^2`). If one keeps the predecessor's data-rounding +count and only doubles the suffix propagation envelope, one extra data bit +preserves its rounding allowance. This is an implication, not an installed +precision change or a claim covering extra rounding events. Rounding inside a +gate, asynchronous overlapping gates and changed non-coordinate layouts need +separate contracts. + +## Verification and attribution + +The written proof establishes the quantified result. The standard-library +checker uses exact Gaussian-rational scalar representation from Jose Manuel's +retained implementation; its matrix multiplication, inverse, PSD tests and cut +oracle are local. It checks all four identities and independently certifies +norm bounds at actual FFT/shear cuts and at nonunitary complex synthetic cuts. +Wrong projection sides, overlapping supports and a missing interpolation loss +have discriminating controls. Counts and commands are reported after replay. + +Credit Jose Manuel/jmbarrancoml for rational FFT/Full and numerical fragment +contracts, Vlado Vojdanovski/PR1673 for the matching scheduler, Chafik +Boukhalfa/PR628 for certified phases, and Brian/JoyboyBrian's physical-cut +trace audit for the explicit sublayer question. Original source notices remain. +The orthogonal row/column mixing inequality is elementary background; this +contribution is its four-way source-bound application and quantified interface +consequence, without a literature-priority claim. + +## Open next questions + +Can the retained primitive alphabet improve the generic sqrt(2) loss? +Start with its unitary butterflies and compensated shear layers, retaining the +same actual neighboring operators. The sharp generic witness need not belong +to that alphabet. A better bound would reduce added sublayer headroom, but +physical preparation, storage, tape and full supplier admission remain open. + +## Reproduction and evidence + +Canonical claim: https://github.com/CrocSwap/integer-mult-bounds/discussions/4202#discussioncomment-19138297 + +The fixed replay covers 97 cuts, including 52 proper sublayer cuts, 388 exact four-way identities and 388 independently PSD-certified partial-cut norm inequalities. Actual retained FFTs at widths two/four and a complete dirty Toeplitz shear contribute 73 cuts; the other four fixtures cover sharp nonunitary and complex controls. Six controls distinguish missing loss, wrong projection sides, overlapping supports and a complex adjoint norm failure. All checks use explicit exceptions and remain enabled under -O. + +```sh +/opt/local/bin/python3.12 -B scripts/research_package.py --package research/matching-sublayer-norm +python3 -B scripts/check_research_commit.py --package research/matching-sublayer-norm --check-source-history +``` + +The registered normal and optimized commands require CPython 3.12 and only the standard library. The local interpreter path above is environment-specific; the registered hook resolves its declared Python version. The source-history command follows committing. Official committed exports can run verify.py directly with -I -W error -B, and separately -O, without Git or a network. Automated execution is not independent human or proof-kernel acceptance. Hosted CI is unverified at publication. + +Base b91956876e5b4122fd89179f1b57557ff8378f15, priority revision 7. Fresh entry overlap covered 317 open PRs, 4064 Discussion records and all 6636 current-base local notes at 04:46–04:47 UTC. The scoped searches found the named explicit predecessor obligation; unpublished work, arbitrary closed histories and every historical diff are not covered. This is advisory coverage, not a novelty certificate. diff --git a/research/direct-circulant-production-precision/compiler-cuts/retained/PR4977-README.md b/research/direct-circulant-production-precision/compiler-cuts/retained/PR4977-README.md new file mode 100644 index 0000000000..c5248440b7 --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-cuts/retained/PR4977-README.md @@ -0,0 +1,141 @@ +# Bind the block-solve envelope to the rounded Full allocation + +Prepared by JoyboyBrian with substantial OpenAI Codex assistance. Apache-2.0. + +## Result and exact boundary + +Nick Petalas's `downset-block-solve-bound` gives the ideal completed-call +common spectral envelope `2 sqrt(N) (Lambda Q)^2`, and explicitly leaves its +rounded Full-factory substitution open. This package performs that substitution +through a one-expression, source-authenticated allocation adapter. Frozen +`rational-unitary-fft/full.py`, its compiler and every predecessor remain intact. +The uniform implication below retains the stated block-solve theorem and the +predecessor generator's local fragment/rank contracts as dependencies. + +Let N=2^d, Lambda,Q,R>=1, target t>=1 and incoming precision F0>=0, under the +original component-guarded Full admission contract. Set chi=Lambda Q and + +``` +B = 2 * 2^ceil(d/2) * chi^2. +``` + +Then `2 sqrt(N) chi^2 <= B <= 2 sqrt(2N) chi^2`. Also B dominates 1, Lambda +and Q. Use this B in place of `256 N^3 chi^12` in the original allocation, +leaving every other expression and check unchanged. The resulting actual +factory has the same retained forward and stored-inverse error target `2^-t` +at complete matching-layer boundaries. No new selected kappa or physical +preparation/delivery bound is claimed. This is not the sublayer interpolation +contract being studied in the separate `matching-sublayer-norm` contribution. + +## Every affected implication + +Put J=3N-2, tau=2^-t, and take + +``` +s = t + ceil(log2(4 J B^3 (R+1))), eta=2^-s, +theta = J B^2 eta. +``` + +The ideal completed-downset theorem is valid for every legal atom ordering. +For its prefixes Q_j and the approximate atom errors E_j, conjugated defects +`G_j=Q_j^-1 E_j Q_(j-1)` have sum of norms at most theta. Thus + +``` +theta <= tau/(4 B (R+1)) <= 1/16 < 1/4, +eta <= 1/(2Q), +e = 2 J B^3 eta <= tau/(2(R+1)). +``` + +Products of `I+G_j` have norm at most exp(theta)<2, and inverse products +have norm at most `1/(1-theta)<2`. Their distance from identity is below +`2 theta`, using exp(theta)-1<=2theta and theta/(1-theta)<=2theta on this +interval. Apply the same estimates to a contiguous suffix of the normalized +interaction factors, rather than multiplying two independently bounded +prefixes. All approximate completed prefixes and their inverses have norm +at most 2B; remaining suffixes and their inverses have norm at most 2L0B, +where L0=max(1,Lambda,Q). Both endpoint operator errors are at most e. +The inverse reference is the mathematical inverse of the unchanged ideal T; +it is not an independently rounded inverse coefficient table. + +For U=Lambda+Lambda^2 Q, let H be the predecessor's maximum of its generator +fragment allowance, U+1 and 2Q. Generator parameters, exact displacement/rank +bounds and polynomial H are unchanged. Although their requested accuracy is +smaller, every child still receives its full requested coefficient accuracy; +the existing child allocation is recomputed from s. For a scalar leaf a, +`|a|>=1/Q` and `|ahat-a|<=eta<=1/(2Q)` imply `|ahat|>=1/(2Q)` and direct/inverse +fragment bounds U+1 and 2Q. Inversion always uses the same stored ahat. +The physical-cut trace therefore gives the same formula + +``` +K = 2 L0 B H, segment <= K^2. +``` + +Let D be the original layer bound and choose + +``` +F=max(F0, t+ceil(log2(2 D K N))). +``` + +Nearest component rounding contributes at most N 2^-F per layer. Its propagated +endpoint error is at most D K N 2^-F <= tau/2. The coefficient charge is +`e R <= tau R/(2(R+1)) < tau/2`, hence the total is strictly below tau. +The same proof applies to the reversed stored program on its own input; +no exact rounded forward/inverse round trip is asserted. Intermediate +amplitude is bounded by `A=K R+D K^2 N 2^-F`, using the segment bound. +Consequently the original integer-bit and temporary-bit formulas remain valid. + +For scalar height, the unchanged pivot upper bound U and precision s give +`2s+2ceil(log2(U+2))+8`; actual generator coefficient heights are still +maximized after building the plan. Their original phase/multiplier recipes +are used, not stale heights from the old allocation. All quantities remain +polynomial in N,Lambda,Q,R before logarithms, preserving the original +`O(F0+t+log N+log Lambda+log Q+log R)` online-width conclusion. + +## Executable adapter and independent checks + +`allocation.py` authenticates exactly the original AST assignment to B, +replaces only that assignment in a private function, and compiles it with the +original exact helpers. All validation, output fields and subsequent formulas +are retained byte-for-byte at the AST level. The live Full factory and frozen +source files are not edited. The verifier authenticates every declared source +before imports and constructs actual plans with the adapted allocation. +It independently derives every affected formula and checks actual exact and +rounded forward/stored-inverse endpoints, source grid and word widths. +The written proof establishes the uniform implication; finite execution +binds it to the actual source and exercises error controls. + +## Attribution and remaining scope + +Credit Nick Petalas for the block-solve `2 sqrt(N) chi^2` theorem, Brian's +PR4788 for the earlier leading-section/downset bridge, Jose Manuel/jmbarrancoml +for rational Full, its all-size allocation and rounding proof, Vlado/PR1673 +for the recursive/displacement compiler, Chafik/PR628 for certified phases, +and the retained Stein and interval source contributors. Orthogonal block +estimates, Schur formulas and perturbation inequalities are background. +Author-process checks do not constitute independent human or proof-kernel +acceptance. Tape cost, physical coefficient preparation/delivery and the +complete multiplication theorem remain separate. + +## Open next questions + +Can a downstream normalized/raw Gaussian caller use the smaller actual Full +word widths while preserving immutable reference and intermediate-radius +contracts? Begin by threading this exact allocation receipt through one +normalized `Gaussian` instance and auditing its requested child grid. The +present Full contract is complete at its own boundary; the outer wrapper and +physical cost claims require their own source-bound proof. + +## Reproduction and evidence + +Canonical claim: https://github.com/CrocSwap/integer-mult-bounds/discussions/4202#discussioncomment-19138298 + +The fixed replay checks 63 allocation contracts (N from 1 through 2^20), then six actual Full factories and 24 rounded forward/stored-inverse trajectories. Cases include a complex scalar, a 2^-30 pivot, non-Hermitian complex N=2/N=4, a nonzero 512-bit input grid and zero-duration shears. At complex N=4 the source emits 189 layers, child precision falls 72 to 26 bits and data precision 76 to 61 bits; at complex N=2 these fall 82 to 28 and 72 to 54. A 512-bit incoming grid remains 512. These are fixture measurements, not a universal constant saving. Seven controls cover source-expression drift, invalid types/dimension, a rounded-zero pivot, wrong inverse ordering and an underfunded actual data grid. + +```sh +/opt/local/bin/python3.12 -B scripts/research_package.py --package research/full-downset-allocation +python3 -B scripts/check_research_commit.py --package research/full-downset-allocation --check-source-history +``` + +The registered normal and optimized commands require CPython 3.12 and only the standard library. The local interpreter path above is environment-specific; the registered hook resolves its declared Python version. The source-history command follows committing. Official committed exports can run verify.py directly with -I -W error -B, and separately -O, without Git or a network. Automated execution is not independent human or proof-kernel acceptance. Hosted CI is unverified at publication. + +Base b91956876e5b4122fd89179f1b57557ff8378f15, priority revision 7. Fresh entry overlap covered 317 open PRs, 4064 Discussion records and all 6636 current-base local notes at 04:46–04:47 UTC. The scoped searches found the named explicit predecessor obligation; unpublished work, arbitrary closed histories and every historical diff are not covered. This is advisory coverage, not a novelty certificate. diff --git a/research/direct-circulant-production-precision/compiler-cuts/retained/PROOF.md b/research/direct-circulant-production-precision/compiler-cuts/retained/PROOF.md new file mode 100644 index 0000000000..99a55596f6 --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-cuts/retained/PROOF.md @@ -0,0 +1,349 @@ +# Certified rational unitary FFT and rounded Toeplitz shear + +Jose Manuel (`jmbarrancoml`), with substantial OpenAI Codex assistance. +Apache-2.0. + +I instantiate Chafik Boukhalfa/PR628's rational unit-phase construction +inside Vlado Vojdanovski/PR1673's retained FFT and Toeplitz-shear schedule. +PR3709 already supplies certified inward dyadic twiddles and rounded FFT +execution. I retain those credits. The result here concerns the unitary +child, its composed approximation and its fixed-grid dirty-data contract. + +## 1. Contract and precision allocation + +Let \(n=2^d\ge1\), and let \(T\in\mathbb Q(i)^{n\times n}\) be Toeplitz, +with first column \(c\) and first row \(r\). Define +\[ +g_0=h_0=c_0/2,\quad +g_j=(c_j+r_{n-j})/2,\quad h_j=(c_j-r_{n-j})/2\quad(1\le j2/3\), while the endpoint error is below \(1/6\). +For the true rotated phase \(v_0\), put +\[ +\tau=\Im(v_0)/(1+\Re(v_0)). +\] +The denominator is at least \(3/2\). Compute quotient extrema at the box +corners, round their midpoint to the nearest \((P+4)\)-grid value \(t_0\), +and form +\[ +\sigma=C\frac{1-t_0^2+2it_0}{1+t_0^2}. +\] +Then \(|\sigma|=1\) exactly, \(|t_0|<1\), and +\[ +|\sigma-e^{2\pi ik/n}|\le4E_B+2^{-P-4}. +\] +This follows from the quotient bound \(2E_B\) and the stereographic +derivative bound \(2/(1+t^2)\le2\). + +The executable checks the **maximum endpoint** component-\(\ell^1\) +distance from \(\sigma\) to the entire oracle box. That distance is at +most \(10E_B+2^{-P-3}<\nu\). A minimum distance to the box would not +certify the approximation. + +The parameter denominator is at most \(2^{P+4}\). Unit-phase components +therefore have numerator/denominator height at most \(2P+9\), with +slightly larger allowances in the code. The oracle's offline exact +Machin sums, factorials and phase-description arithmetic use polynomial +time and space in \(P\) and the input description length. A long external +phase numerator is an input cost, not a free oracle argument. + +## 3. Exactly unitary butterflies and FFT approximation + +Use the certified phase \(a+ib\) approximating \(e^{i\pi/4}\), and a +certified twiddle \(w\). Define +\[ +B(a,b,w)= +\begin{pmatrix}a&bw\\b&-aw\end{pmatrix} += +\begin{pmatrix}a&b\\b&-a\end{pmatrix}\operatorname{diag}(1,w). +\] +Since \(a^2+b^2=|w|^2=1\), this matrix is exactly unitary. +Its adjoint is +\(\operatorname{diag}(1,\bar w)\left[\begin{smallmatrix}a&b\\b&-a\end{smallmatrix}\right]\). +It is generally not the same expression with \(w\) merely conjugated. + +The splitter difference from the ideal \(1/\sqrt2\) splitter has norm +\(|(a+ib)-e^{i\pi/4}|\). Hence each butterfly differs from its ideal gate +by at most \(2\nu\). Disjoint gates give the same layer bound. I retain +the source's exact bit reversal and its \(d\) butterfly layers, so +\[ +\boxed{\|\widetilde F-F\|_2\le2d\nu,\qquad +F=\mathrm{DFT}_{-}/\sqrt n.} +\] +We telescope products of unitary layers, so no amplification factor +appears. Every exact FFT prefix and suffix is unitary. Reverse the layers +and adjoint the stored gates to obtain \(\widetilde F^*\); do not generate +a new approximate inverse phase table. + +## 4. Spectral preparation and Toeplitz approximation + +For a kernel \(k\), the ideal circulant eigenvalues are the +**unnormalized** DFT +\[ +\lambda_\ell=\sum_j k_j e^{-2\pi i\ell j/n}. +\] +I approximate each root independently by a certified rational unit, +sum exactly offline, and round each multiplier component once to the +nearest \(S\)-grid value. If \(\|k\|_1\le M_k\), then +\[ +\|\widehat\lambda-\lambda\|_\infty\le M_k\nu+v,\qquad +\|\widehat\lambda\|_\infty\le M_k+v. +\] +The second bound uses exact unit modulus before rounding. It does not +add a spurious phase-error magnitude factor. + +I store the rounded multipliers before online use. The exact offline +sum can have a denominator whose size grows with \(n\); carrying that +sum into data gates would violate the stated coefficient-width bound. + +The actual circulant child applies +\[ +\widetilde C_k=\widetilde F^*\operatorname{diag}(\widehat\lambda)\widetilde F, +\] +so +\[ +\|\widetilde C_k-C_k\|_2 +\le M_k\nu+v+2M_k\|\widetilde F-F\|_2. +\] +Exact unitarity alone does not make \(\widetilde F\) an exact diagonalizer. + +For \(D=\operatorname{diag}(e^{\pi ij/n})\), the source decomposition is +\[ +T=C_g+D^*C_{Dh}D. +\] +I generate each diagonal entry of \(\widetilde D\) independently. Thus +\(\|\widetilde D-D\|_2\le\nu\), without a powers' accumulated error or +an \(nP\)-bit phase representation. The actual schedule is the first +circulant shear, the common twist \(\widetilde D\) on both banks, the +circulant shear prepared from \(\widetilde D h\), and the inverse twist. + +Twisting preserves \(\|h\|_1\). Charge \(M_h\nu\) for changing the +second kernel and \(2M_h\nu\) for its two exterior twists. Combining +these terms with the two circulant estimates gives +\[ +\|\widetilde T-T\|_2 +\le(4d+1)M_g\nu+(4d+4)M_h\nu+2v +\le\boxed{\delta}. +\] +In exact rational arithmetic the complete map is +\((x,y)\mapsto(x,y+\widetilde T x)\). The input matrix may be zero +or singular because the pointwise shear gates remain invertible. + +## 5. Prefix bounds and rounded execution + +Every non-spectral gate stays within one bank and is unitary. +Each of the two spectral layers has orientation +\[ +S(A)=\begin{pmatrix}I&0\\A&I\end{pmatrix}. +\] +For a bank unitary \(U=\operatorname{diag}(U_x,U_y)\), +\[ +US(A)U^*=S(U_yAU_x^*). +\] +Move the bank unitaries to the ends of any contiguous gate segment. +The remaining shear matrix is a sum of at most two unitarily transformed +spectral matrices. Their norms are at most \(M_g+v\) and \(M_h+v\). +Consequently every segment, inverse segment, prefix and suffix has norm +at most +\[ +\boxed{H=1+M_g+M_h+2v.} +\] +Masked partial spectral layers satisfy the same estimate. +I do not multiply a shear bound once per stage. + +Nearest component rounding has error at most \(u/2\); a complex output +has error at most \(u/\sqrt2\). A disjoint layer updates at most \(2n\) +complex wires, so its error vector has norm at most \(\sqrt n\,u\). +The source schedule has at most \(L=4d+8\) layers, including empty +bit-reversal layers. Transporting each local residual through its +remaining exact suffix gives +\[ +\|\widehat z-\widetilde S z_0\|_2 +\le LH\sqrt n\,u\le LHnu. +\] +Every pre-round and rounded state has amplitude at most +\[ +A=H(R+Lnu). +\] +The source-bank error receives no coefficient-approximation term, +because the unrounded rational circuit restores that bank exactly. +Fixed-grid execution can still have nonzero source-restoration error; +the verifier includes a small-grid witness. + +The precision choices in Section 1 close the requested budget: +\[ +4(d+1)M\nu R<2^{-t}/4,\quad 2vR<2^{-t}/4,\quad +LHnu<2^{-t}/2. +\] +Here \(v\le1/32\) and \(H= j else row[j-i] + for j in range(n)] for i in range(n)]) + + +def lower(c): + return toep(c) + + +def invseries(f): + n = len(f) + ans = np.zeros(n, complex) + ans[0] = 1 / f[0] + for j in range(1, n): + ans[j] = -sum(f[k] * ans[j-k] for k in range(1, j+1)) / f[0] + return ans + + +def conv(a, b, n): + return np.convolve(a, b)[:n] + + +def diag(indices, values): + return [[((int(i),), np.array([[v]], complex)) for i, v in zip(indices, values)]] + + +def inverse(plan): + return [[(ids, np.linalg.inv(g)) for ids, g in layer] + for layer in reversed(plan)] + + +def parallel(a, b): + return [(a[j] if j < len(a) else []) + (b[j] if j < len(b) else []) + for j in range(max(len(a), len(b)))] + + +def fft(indices): + n = len(indices) + if n <= 1: + return [] + assert n & (n - 1) == 0 + bits = n.bit_length() - 1 + rev = [int(f"{j:0{bits}b}"[::-1], 2) for j in range(n)] + plan = [[((indices[i], indices[j]), np.array([[0, 1], [1, 0]], complex)) + for i, j in enumerate(rev) if i < j]] + size = 2 + while size <= n: + layer = [] + for start in range(0, n, size): + for j in range(size // 2): + w = np.exp(-2j * np.pi * j / size) + layer.append(((indices[start+j], indices[start+j+size//2]), + np.array([[1, w], [1, -w]], complex) / math.sqrt(2))) + plan.append(layer) + size *= 2 + return plan + + +def circ_shear(target, source, kernel): + """target += circulant(kernel) source, using these wires only.""" + p = parallel(fft(target), fft(source)) + lams = np.fft.fft(kernel) + mid = [[((source[j], target[j]), np.array([[1, 0], [lams[j], 1]], complex)) + for j in range(len(source))]] + return p + mid + inverse(p) + + +def toeplitz_shear(target, source, T): + """Cyclic + negacyclic decomposition; source and target are disjoint.""" + n = len(source) + assert T.shape == (n, n) and len(target) == n + c, r = T[:, 0], T[0, :] + g = np.zeros(n, complex) + h = np.zeros(n, complex) + g[0] = h[0] = c[0] / 2 + for j in range(1, n): + g[j] = (c[j] + r[n-j]) / 2 + h[j] = (c[j] - r[n-j]) / 2 + gamma = np.exp(1j * np.pi / n) + d = gamma ** np.arange(n) + twists = parallel(diag(target, d), diag(source, d)) + return (circ_shear(target, source, g) + twists + + circ_shear(target, source, d * h) + inverse(twists)) + + +def triangle_plan(indices, f): + n = len(indices) + STATS["triangle_nodes"] += 1 + STATS["max_triangle_coefficient"] = max( + STATS["max_triangle_coefficient"], float(np.max(np.abs(f)))) + if n == 1: + return diag(indices, f) + assert n % 2 == 0 + m = n // 2 + ev, od = indices[::2], indices[1::2] + e, o = np.asarray(f[::2]), np.asarray(f[1::2]) + k = conv(o, invseries(e), m) + zk = np.r_[0, k[:-1]] + s = e - np.r_[0, conv(o, k, m)[:-1]] + right = toeplitz_shear(ev, od, lower(zk)) + middle = parallel(triangle_plan(ev, e), triangle_plan(od, s)) + left = toeplitz_shear(od, ev, lower(k)) + return right + middle + left + + +def lowdisp_shear(target, source, T): + n = len(source) + Z = np.eye(n, k=-1) + Delta = T - Z @ T @ Z.T + U, vals, Vh = np.linalg.svd(Delta) + cutoff = 1e-11 * max(1.0, vals[0]) + rank = int(np.sum(vals > cutoff)) + STATS["max_displacement_rank"] = max(STATS["max_displacement_rank"], rank) + STATS["generator_shears"] += 1 + result = [] + reconstructed = np.zeros_like(T) + for j in range(rank): + g = U[:, j] + h = vals[j] * Vh[j, :] + STATS["max_generator_entry"] = max( + STATS["max_generator_entry"], float(np.max(np.abs(g))), + float(np.max(np.abs(h)))) + reconstructed += lower(g) @ lower(h).T + gamma = max(1.0, 2 * float(np.sum(np.abs(h)))) + p = h / gamma + p[0] += 1 + # U(h)=J L(h) J. This is a genuinely invertible source transform. + transform = triangle_plan(source[::-1], p) + result += transform + result += toeplitz_shear(target, source, gamma * lower(g)) + result += inverse(transform) + result += toeplitz_shear(target, source, -gamma * lower(g)) + assert np.max(np.abs(T - reconstructed)) < 1e-9 + return result + + +def full_plan(indices, M): + n = len(indices) + STATS["full_nodes"] += 1 + if n == 1: + return diag(indices, [M[0, 0]]) + m = n // 2 + A, B, C, D = M[:m, :m], M[:m, m:], M[m:, :m], M[m:, m:] + K = np.linalg.solve(A, B) + L = np.linalg.solve(A.T, C.T).T + S = D - C @ K + right = lowdisp_shear(indices[:m], indices[m:], K) + mid = parallel(full_plan(indices[:m], A), full_plan(indices[m:], S)) + left = lowdisp_shear(indices[m:], indices[:m], L) + return right + mid + left + + +def replay(plan, n, track=True): + out = np.eye(n, dtype=complex) + peak = 1.0 + min_det = 1.0 + for layer in plan: + used = set() + for ids, g in layer: + assert not used.intersection(ids), "non-disjoint layer" + used.update(ids) + min_det = min(min_det, float(abs(np.linalg.det(g)))) + out[list(ids), :] = g @ out[list(ids), :] + if track: + peak = max(peak, float(np.linalg.norm(out, 2))) + STATS["min_gate_determinant"] = min(STATS["min_gate_determinant"], min_det) + return out, peak + + +def main(): + rng = np.random.default_rng(20261013) + rows = [] + for n in [2, 4, 8, 16]: + f = rng.normal(size=n) / (12 * n) + f[0] += 1 + p = triangle_plan(list(range(n)), f) + actual, peak = replay(p, n) + rows.append({"kind": "triangular", "n": n, "rounds": len(p), + "gates": sum(map(len, p)), + "max_error": float(np.max(np.abs(actual-lower(f)))), + "peak_prefix_norm_2": peak}) + + c = rng.normal(size=n) / (20 * n) + r = rng.normal(size=n) / (20 * n) + c[0] += 1 + H = toep(c, r) + p = full_plan(list(range(n)), H) + actual, peak = replay(p, n, track=n <= 8) + rows.append({"kind": "full_toeplitz", "n": n, "rounds": len(p), + "gates": sum(map(len, p)), + "max_error": float(np.max(np.abs(actual-H))), + "peak_prefix_norm_2": peak if n <= 8 else None, + "input_distance_from_I_2": float(np.linalg.norm(H-np.eye(n), 2))}) + # Destructive control: dropping the second subtraction computes the wrong map. + # Independent direct parity block algebra across a range of sizes. + identities = [] + for n in [2, 4, 8, 16, 32]: + f = rng.normal(size=n) / n + f[0] += 2 + m = n // 2 + e, o = f[::2], f[1::2] + k = conv(o, invseries(e), m) + s = e - np.r_[0, conv(o, k, m)[:-1]] + E, O, K = lower(e), lower(o), lower(k) + Z = np.eye(m, k=-1) + left = np.block([[np.eye(m), np.zeros((m,m))], [K, np.eye(m)]]) + diagblock = np.block([[E, np.zeros((m,m))], [np.zeros((m,m)), lower(s)]]) + right = np.block([[np.eye(m), Z@K], [np.zeros((m,m)), np.eye(m)]]) + order = list(range(0,n,2)) + list(range(1,n,2)) + exact = lower(f)[np.ix_(order,order)] + identities.append({"n": n, "error": float(np.max(np.abs(left@diagblock@right-exact)))}) + sylvester = [] + for b in [1, 2, 4, 8]: + f = np.array([1.0]) + g = np.array([1.0]) + for j in range(b): + f = np.convolve(f, [1.0, 256.0 ** (j-b+0.5)]) + g = np.convolve(g, [1.0, 256.0 ** (-j-0.5)]) + fp = np.r_[f, np.zeros(3*b+2-len(f))] + fi = invseries(fp) + def hc(k): + return sum(g[v]*fi[k+v] for v in range(b+1) if 0 <= k+v < len(fi)) + K = np.array([[hc(i-b-j) for j in range(b)] for i in range(b)]) + H = np.array([[hc(i-j) for j in range(b)] for i in range(b)]) + S = np.zeros((2*b, 2*b), complex) + for j in range(b): + for k in range(b+1): + if j+k < 2*b: + S[j+k, j] += f[k] + if 0 <= b+j-k < 2*b: + S[b+j-k, b+j] += g[k] + inds = list(range(2*b)) + p = toeplitz_shear(inds[:b], inds[b:], K) + p += full_plan(inds[b:], H) + p += triangle_plan(inds, np.r_[f, np.zeros(2*b-len(f))]) + actual, peak = replay(p, 2*b, track=b <= 4) + sylvester.append({"b": b, "total_wires": 2*b, "rounds": len(p), + "gates": sum(map(len, p)), + "max_error": float(np.max(np.abs(actual-S))), + "H_minus_I_norm_1": float(np.linalg.norm(H-np.eye(b), 1)), + "H_minus_I_norm_infinity": float(np.linalg.norm(H-np.eye(b), np.inf)), + "peak_prefix_norm_2": peak if b <= 4 else None}) + # Removing the compensating dirty subtraction must fail. + b = 4 + gi, hi = np.array([1, .02, .01, .005]), np.array([.1, .04, .02, .01]) + pi = hi.copy() + pi[0] += 1 + target = np.block([[np.eye(b), np.zeros((b,b))], [lower(gi)@lower(hi).T, np.eye(b)]]) + pp = triangle_plan(list(range(b))[::-1], pi) + correct = pp + toeplitz_shear(list(range(b, 2*b)), list(range(b)), lower(gi)) + inverse(pp) + broken_actual, _ = replay(correct, 2*b, track=False) + correct += toeplitz_shear(list(range(b, 2*b)), list(range(b)), -lower(gi)) + correct_actual, _ = replay(correct, 2*b, track=False) + omission = {"correct_error": float(np.max(np.abs(correct_actual-target))), + "omit_second_subtraction_error": float(np.max(np.abs(broken_actual-target)))} + result = {"seed": 20261013, "note": "Floating replay supports, does not replace, algebraic proof.", + "controls": rows, "polyphase_identity": identities, + "normalized_sylvester": sylvester, "omission_control": omission, "stats": STATS} + (ROOT / "CIRCUIT-REPLAY.json").write_text(json.dumps(result, indent=2)+"\n") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/research/direct-circulant-production-precision/compiler-cuts/retained/engine.py b/research/direct-circulant-production-precision/compiler-cuts/retained/engine.py new file mode 100644 index 0000000000..e9f2f2b08d --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-cuts/retained/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/compiler-cuts/retained/exact.py b/research/direct-circulant-production-precision/compiler-cuts/retained/exact.py new file mode 100644 index 0000000000..aae41e6acf --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-cuts/retained/exact.py @@ -0,0 +1,242 @@ +"""Exact complex rational arithmetic for coefficient and rounded-gate certificates. + +Jose Manuel (jmbarrancoml), with substantial OpenAI Codex assistance. +Apache-2.0. +""" +from fractions import Fraction as Q +from hashlib import sha256 + +TRACK = None + + +def need(ok, message): + if not ok: + raise ValueError(message) + + +def qheight(value): + return max(abs(value.numerator).bit_length(), value.denominator.bit_length()) + + +class C: + __slots__ = ("re", "im") + + def __init__(self, re=0, im=0): + need(type(re) in (int, Q) and type(im) in (int, Q), "exact rational components") + self.re, self.im = Q(re), Q(im) + if TRACK is not None: + TRACK["max_observed_height"] = max(TRACK["max_observed_height"], + qheight(self.re), qheight(self.im)) + + @staticmethod + def wrap(value): + return value if isinstance(value, C) else C(value) + + def __add__(self, other): + other = C.wrap(other) + return C(self.re + other.re, self.im + other.im) + + __radd__ = __add__ + + def __neg__(self): + return C(-self.re, -self.im) + + def __sub__(self, other): + return self + -C.wrap(other) + + def __rsub__(self, other): + return C.wrap(other) + -self + + def __mul__(self, other): + other = C.wrap(other) + return C(self.re * other.re - self.im * other.im, + self.re * other.im + self.im * other.re) + + __rmul__ = __mul__ + + def conjugate(self): + return C(self.re, -self.im) + + def norm2(self): + return self.re * self.re + self.im * self.im + + def __truediv__(self, other): + other = C.wrap(other) + denominator = other.norm2() + need(denominator > 0, "nonzero divisor") + product = self * other.conjugate() + return C(product.re / denominator, product.im / denominator) + + def __rtruediv__(self, other): + return C.wrap(other) / self + + def __eq__(self, other): + if not isinstance(other, C) and type(other) not in (int, Q): + return False + other = C.wrap(other) + return self.re == other.re and self.im == other.im + + def record(self): + return [str(self.re), str(self.im)] + + +class Vec(list): + def __init__(self, values): + super().__init__(C.wrap(x) for x in values) + + def __mul__(self, other): + if isinstance(other, C) or type(other) in (int, Q): + return Vec(x * other for x in self) + need(len(self) == len(other), "elementwise vector dimensions") + return Vec(x * y for x, y in zip(self, other)) + + __rmul__ = __mul__ + + def __sub__(self, other): + need(len(self) == len(other), "vector subtraction dimensions") + return Vec(x - y for x, y in zip(self, other)) + + def copy(self): + return Vec(self) + + def __truediv__(self, scalar): + return Vec(x / scalar for x in self) + + +class Mat(list): + def __init__(self, rows): + super().__init__([C.wrap(x) for x in row] for row in rows) + + def __rmul__(self, scalar): + return Mat([[scalar * x for x in row] for row in self]) + + @property + def shape(self): + return (len(self), len(list.__getitem__(self, 0)) if self else 0) + + def __getitem__(self, key): + if not isinstance(key, tuple): + return list.__getitem__(self, key) + row, column = key + if isinstance(row, slice): + rows = list.__getitem__(self, row) + return Mat([r[column] for r in rows]) if isinstance(column, slice) else Vec(r[column] for r in rows) + selected = list.__getitem__(self, row) + return Vec(selected[column]) if isinstance(column, slice) else selected[column] + + +def eye(n): + return Mat([[int(i == j) for j in range(n)] for i in range(n)]) + + +def adjoint(matrix): + return Mat([[matrix[j][i].conjugate() for j in range(len(matrix))] + for i in range(len(matrix[0]))]) + + +def multiply(left, right): + return Mat([[sum((x * right[k][j] for k, x in enumerate(row)), C()) + for j in range(len(right[0]))] for row in left]) + + +def unitary(matrix): + return multiply(adjoint(matrix), matrix) == eye(len(matrix)) + + +def inverse_gate(matrix): + if unitary(matrix): + return adjoint(matrix) + if matrix.shape == (1, 1): + return Mat([[1 / matrix[0][0]]]) + if matrix.shape == (2, 2) and matrix[0][0] == matrix[1][1] == 1 and matrix[0][1] == 0: + return Mat([[1, 0], [-matrix[1][0], 1]]) + raise ValueError("unsupported nonunitary inverse gate") + + +def round_q(value, bits): + scale = 1 << bits + shifted = value * scale + Q(1, 2) + return Q(shifted.numerator // shifted.denominator, scale) + + +def rounded(value, bits): + return C(round_q(value.re, bits), round_q(value.im, bits)) + + +def norm2(vector): + return sum((x.norm2() for x in vector), Q(0)) + + +def component_l1(vector): + return sum((abs(x.re) + abs(x.im) for x in vector), Q(0)) + + +def ceil_log2(value): + value = Q(value) + need(value > 0, "positive logarithm bound") + result = value.numerator.bit_length() - value.denominator.bit_length() + power = Q(1 << result) if result >= 0 else Q(1, 1 << -result) + while power < value: + result += 1 + power *= 2 + while power / 2 >= value: + result -= 1 + power /= 2 + return result + + +def upper(value, bits=160): + scale = 1 << bits + scaled = value * scale + return Q(-((-scaled.numerator) // scaled.denominator), scale) + + +def vector_hash(vector): + digest = sha256() + for entry in vector: + for value in (entry.re, entry.im): + for integer in (value.numerator, value.denominator): + raw = abs(integer).to_bytes(max(1, (abs(integer).bit_length() + 7) // 8), "big") + digest.update(bytes([integer < 0])) + digest.update(len(raw).to_bytes(8, "big")) + digest.update(raw) + return digest.hexdigest() + + +def apply(plan, vector, bits=None): + global TRACK + state = Vec(vector) + old_track = TRACK + stats = {"max_observed_height": 0, "max_grid_numerator_bits": 0, + "max_reduced_fractional_bits": 0, "rounded_outputs": 0} + if bits is not None: + need(bits >= 1, "positive data precision") + for entry in state: + for value in (entry.re, entry.im): + need((value * (1 << bits)).denominator == 1, "input already on data grid") + TRACK = stats + try: + for layer in plan: + used = set() + for ids, gate in layer: + need(len(ids) == len(gate) in (1, 2), "one- or two-wire gate") + need(not used.intersection(ids) and len(set(ids)) == len(ids), "disjoint layer") + need(all(0 <= i < len(state) for i in ids), "wire bounds") + used.update(ids) + before = [state[i] for i in ids] + outputs = [sum((a * x for a, x in zip(row, before)), C()) for row in gate] + for i, value in zip(ids, outputs): + if bits is not None: + value = rounded(value, bits) + stats["rounded_outputs"] += 1 + for part in (value.re, value.im): + grid_integer = part * (1 << bits) + need(grid_integer.denominator == 1, "rounded output grid") + stats["max_grid_numerator_bits"] = max(stats["max_grid_numerator_bits"], + abs(grid_integer.numerator).bit_length()) + stats["max_reduced_fractional_bits"] = max(stats["max_reduced_fractional_bits"], + part.denominator.bit_length() - 1) + state[i] = value + finally: + TRACK = old_track + return state, stats diff --git a/research/direct-circulant-production-precision/compiler-cuts/retained/full.py b/research/direct-circulant-production-precision/compiler-cuts/retained/full.py new file mode 100644 index 0000000000..7f85ad1a89 --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-cuts/retained/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/compiler-cuts/retained/generator.py b/research/direct-circulant-production-precision/compiler-cuts/retained/generator.py new file mode 100644 index 0000000000..d761d3c88b --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-cuts/retained/generator.py @@ -0,0 +1,233 @@ +"""Exact generators connected to the retained compensated gate program. + +Jose Manuel (jmbarrancoml), with substantial OpenAI Codex assistance. +Apache-2.0. Macro/compiler: Vlado/PR1673; certified phases: Chafik/PR628. +""" +import ast +import copy +from fractions import Fraction as Q +from hashlib import sha256 +import json + +from exact import C, Mat, Vec, ceil_log2, component_l1, inverse_gate, need, norm2 +from engine import Builder, Phases, split_kernel +from triangular import Triangle, allocation as triangle_allocation + +SOURCE = "research/capped-phase-fusion/evidence/inplace_algebra_ultra/" +PRODUCER = "research/rational-unitary-fft/vendor/stein_rational.py" +PROVENANCE = "research/rational-unitary-fft/vendor/STEIN-PROVENANCE.json" +ORACLE = "research/cubic-cyclic-inverse/vendor/interval_kernel.py" + + +def load_producer(raw): + record = json.loads(raw[PROVENANCE]) + need(record["source_commit"] == "e457d5e912a27307d725827aeca7198169320b84" + and record["source_git_blob"] == "71b240a460a185ee2fe926cd189b56aeac6f997f" + and sha256(raw[PRODUCER]).hexdigest() == record["sha256"], + "original producer identity and retained bytes") + namespace = {"__name__": "_frozen_rational_stein"} + exec(compile(raw[PRODUCER], "", "exec", optimize=0), namespace) + return namespace + + +def lower(vector): + return Mat([[vector[i - j] if i >= j else C() for j in range(len(vector))] + for i in range(len(vector))]) + + +def prepare(matrix, producer): + matrix = Mat(matrix) + m = len(matrix) + need(m > 0 and m & (m - 1) == 0 and matrix.shape == (m, m), "dyadic generator matrix") + displacement = Mat([[matrix[i][j] - (matrix[i - 1][j - 1] if i and j else C()) + for j in range(m)] for i in range(m)]) + old_c = producer["C"] + old_e = producer["Matrix"]([[old_c(x.re, x.im) for x in row] for row in displacement]) + old_items, heights = producer["generators"](old_e) + items = [dict(column=item["column"], gamma=item["gamma"], + scale=item["scale"], scale_exponent=item["scale_exponent"], + g=Vec(C(x.re, x.im) for x in item["g"]), + row=Vec(C(x.re, x.im) for x in item["row"])) for item in old_items] + bound_e = max(max(component_l1(row) for row in displacement), + max(component_l1(column) for column in zip(*displacement))) + need(all(norm2(item["g"]) <= 1 and norm2(item["row"]) < 4 * bound_e ** 2 + and 2 * component_l1(item["row"]) <= item["gamma"] for item in items), + "actual bounded rational generator output") + return items, displacement, bound_e, heights + + +def allocation(m, rank, bound_e, radius, target, incoming): + need(type(m) is int and m > 0 and m & (m - 1) == 0, "dyadic macro size") + need(type(rank) is int and 0 <= rank <= m and type(bound_e) in (int, Q) + and bound_e >= 0, "generator count and exact displacement bound") + need(type(radius) in (int, Q) and radius >= 1 and type(target) is int + and target >= 1 and type(incoming) is int and incoming >= 0, "global generator input") + d = m.bit_length() - 1 + kg, alpha = 2 * m + 16 * m * bound_e, 2 * rank * m * bound_e + checkpoint = 10 + 4 * alpha + 2 * kg + child = max(Q(3200 * m ** 3), 2 + 2 * kg) + execution = child * checkpoint + depth = rank * (8 * d * d + 32 * d + 18) + gates = rank * m * (4 * d * d + 24 * d + 22) + s = target + ceil_log2(4 * (rank + 1) * (kg + 1) * (radius + 1)) + eta = Q(1, 1 << s) + triangle = triangle_allocation(m, 1, s) + envelope = max(Q(6), 2 * kg) + p = max(triangle["phase_bits"], s + ceil_log2(32 * (d + 1) * (envelope + 1))) + mult = max(triangle["multiplier_bits"], s + 4) + triangle = dict(triangle, phase_bits=p, multiplier_bits=mult, + coefficient_height_bound=max(4 * p + 24, mult + 5, + 2 * triangle["leaf_bits"] + 16)) + data = max(incoming, target + ceil_log2(max(Q(1), 2 * depth * execution * m))) + u = Q(1, 1 << data) + defect = rank * (kg + 1) * eta + rounding = depth * execution * m * u + need(defect <= 1 and defect * radius + rounding <= Q(1, 1 << target), + "complete compensated-generator target budget") + amplitude = execution * radius + depth * execution ** 2 * m * u + integer = max(1, ceil_log2(max(Q(1), amplitude))) + 2 + height = max(4 * p + 24, mult + ceil_log2(envelope + 2) + 2, + 2 * triangle["leaf_bits"] + 16) + return dict(m=m, rank=rank, displacement_bound=bound_e, radius=radius, + target_bits=target, incoming_bits=incoming, kg=kg, alpha=alpha, + checkpoint_bound=checkpoint, child_bound=child, execution_bound=execution, + segment_bound=execution ** 2, layer_bound=depth, gate_bound=gates, + child_target_bits=s, eta=eta, phase_bits=p, multiplier_bits=mult, + leaf_bits=triangle["leaf_bits"], data_bits=data, + multiplier_envelope=envelope, coefficient_error=defect, + rounding_error=rounding, total_error=defect * radius + rounding, + amplitude_bound=amplitude, integer_bits=integer, + coefficient_height_bound=height, + temporary_bits=2 * data + 8 * height + 2 * integer + 32), triangle + + +def macro_template(source): + tree = ast.parse(source) + function = next(n for n in tree.body if isinstance(n, ast.FunctionDef) + and n.name == "lowdisp_shear") + loop = next(n for n in function.body if isinstance(n, ast.For)) + start = next(i for i, n in enumerate(loop.body) if isinstance(n, ast.Assign) + and isinstance(n.targets[0], ast.Name) and n.targets[0].id == "p") + tail = copy.deepcopy(loop.body[start:]) + need([type(n).__name__ for n in tail] == + ["Assign", "AugAssign", "Assign", "AugAssign", "AugAssign", "AugAssign", "AugAssign"], + "retained seven-statement macro") + identity = sha256(ast.dump(ast.Module(body=tail, type_ignores=[])).encode()).hexdigest() + need(identity == "2a2e0f16a779597fa555857307451831bace11e66861fdc3caf26d2373a21210", + "unchanged source macro identity") + function = ast.FunctionDef( + name="emit", args=ast.arguments(posonlyargs=[], args=[ast.arg(arg=n) for n in + ("target", "source", "g", "h", "gamma")], vararg=None, kwonlyargs=[], + kw_defaults=[], kwarg=None, defaults=[]), + body=[ast.Assign(targets=[ast.Name(id="result", ctx=ast.Store())], + value=ast.List(elts=[], ctx=ast.Load()))] + tail + + [ast.Return(value=ast.Name(id="result", ctx=ast.Load()))], + decorator_list=[], type_params=[]) + module = ast.fix_missing_locations(ast.Module(body=[function], type_ignores=[])) + return compile(module, "", "exec", optimize=0), identity + + +class PairedNegative(Builder): + def __init__(self, positive, source): + super().__init__(positive.phases, positive.multiplier_bits, source) + self.positive = positive + + def spectrum(self, kernel): + row = self.positive.spectra[len(self.spectra)] + need(Vec(kernel) == Vec(-x for x in row["kernel"]), "paired negative spectral kernel") + result = Vec(-x for x in row["multipliers"]) + bound = self.bounds[len(self.spectra)] + need(bound == row["bound"], "paired spectral envelope") + v = Q(1, 1 << self.multiplier_bits) + need(all(x.norm2() <= (bound + v) ** 2 for x in result), "negative stored multiplier bound") + self.spectra.append(dict(kernel=Vec(kernel), multipliers=result, bound=bound)) + return result + + +class Program: + def __init__(self, bound, triangle_bound, raw, phase_oracle=None): + self.bound, self.triangle_bound, self.raw = bound, triangle_bound, raw + self.phases = phase_oracle if phase_oracle is not None else Phases(bound["phase_bits"], raw[ORACLE]) + need(self.phases.bits == bound["phase_bits"], "common generator phase precision") + self.source = list(range(bound["m"])) + self.target = list(range(bound["m"], 2 * bound["m"])) + self.stages, self.position, self.calls = [], 0, [] + self.pending = None + self.last_triangle = None + self.triangles, self.shears = [], [] + code, self.macro_ast = macro_template(raw[SOURCE + "check_circuits.py"]) + namespace = dict(triangle_plan=self.triangle, toeplitz_shear=self.shear, + inverse=self.inverse, lower=lower) + exec(code, namespace) + self.emit = namespace["emit"] + + def record(self, kind, plan, **details): + self.calls.append(kind) + self.stages.append(dict(kind=kind, start=self.position, stop=self.position + len(plan), + **details)) + self.position += len(plan) + return plan + + def triangle(self, indices, coefficients): + builder = Triangle(self.triangle_bound, self.raw[SOURCE + "check_circuits.py"], + self.raw[ORACLE], self.phases) + local_indices = [self.source.index(i) for i in indices] + local = builder.plan(coefficients, local_indices) + plan = [[(tuple(self.source[i] for i in ids), gate) for ids, gate in layer] for layer in local] + need(builder.bound["coefficient_error"] <= self.bound["eta"], "triangle operator allowance") + self.last_triangle = plan + self.triangles.append(builder) + return self.record("triangle", plan, symbol=Vec(coefficients), indices=list(indices), + operator_error=builder.bound["coefficient_error"]) + + def inverse(self, plan): + need(plan is self.last_triangle, "inverse of the same stored triangle") + result = [[(ids, inverse_gate(gate)) for ids, gate in layer] for layer in reversed(plan)] + return self.record("inverse", result) + + def shear(self, target, source, matrix): + need(target == self.target and source == self.source, "literal complete dirty banks") + if self.pending is None: + builder = Builder(self.phases, self.bound["multiplier_bits"], + self.raw[SOURCE + "check_circuits.py"]) + local = builder.plan(matrix) + self.pending = (builder, matrix, local) + kind = "positive" + else: + positive, original, positive_plan = self.pending + need(matrix == -1 * original, "literal negative compensation matrix") + builder = PairedNegative(positive, self.raw[SOURCE + "check_circuits.py"]) + local = builder.plan(matrix) + m = len(source) + need(len(local) == len(positive_plan), "same compensation layer schedule") + for a, b in zip(positive_plan, local): + need(len(a) == len(b), "same compensation gate schedule") + for (ids, g), (other_ids, h) in zip(a, b): + crossing = len(ids) == 2 and ids[0] < m <= ids[1] + expected = Mat([[1, 0], [-g[1][0], 1]]) if crossing else g + need(ids == other_ids and h == expected, "paired coefficients preserve source order") + self.pending = None + kind = "compensation" + g, h = split_kernel(matrix) + envelope = component_l1(g) + component_l1(h) + defect = (4 * len(source).bit_length() * envelope * self.phases.nu + + Q(2, 1 << self.bound["multiplier_bits"])) + need(envelope <= self.bound["multiplier_envelope"] and defect <= self.bound["eta"], + "scaled shear absolute operator allowance") + self.shears.append(builder) + mapping = source + target + plan = [[(tuple(mapping[i] for i in ids), gate) for ids, gate in layer] for layer in local] + return self.record(kind, plan, matrix=matrix, operator_error=defect, envelope=envelope) + + def plan(self, items): + result = [] + for item in items: + before = Vec(item["row"]) + result += self.emit(self.target, self.source, item["g"], item["row"], item["gamma"]) + need(before == item["row"], "fresh division preserves generator row") + need(self.pending is None and self.calls == + ["triangle", "positive", "inverse", "compensation"] * len(items), + "complete retained compensated call sequence") + need(self.position == len(result) <= self.bound["layer_bound"] + and sum(map(len, result)) <= self.bound["gate_bound"], "full program gate/layer budget") + return result diff --git a/research/direct-circulant-production-precision/compiler-cuts/retained/interval_kernel.py b/research/direct-circulant-production-precision/compiler-cuts/retained/interval_kernel.py new file mode 100644 index 0000000000..1182175a55 --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-cuts/retained/interval_kernel.py @@ -0,0 +1,61 @@ +"""Outward-rounded rational enclosures for prime-power cyclic kernels.""" +from fractions import Fraction as F +import math +from functools import lru_cache + +BITS=1536 +SCALE=1<4:raise ValueError('angle bound') + itheta=(point(0),theta) + total=term=ONE + # Taylor remainder for complex exp: <=exp(4)*4^(N+1)/(N+1)! <128*... + n=0 + while True: + n+=1;term=cmul(term,itheta);term=(scale(term[0],F(1,n)),scale(term[1],F(1,n)));total=cadd(total,term) + remainder=F(128*4**(n+1),math.factorial(n+1)) + if remainder= 0 else Q(1, 1 << -exponent) + + +def norm_scale(squared): + need(squared > 0, "positive residual squared norm") + exponent = (squared.numerator.bit_length() - squared.denominator.bit_length()) // 2 + scale = pow2(exponent) + while scale * scale < squared: + exponent += 1 + scale *= 2 + while scale * scale / 4 >= squared: + exponent -= 1 + scale /= 2 + need(squared <= scale * scale < 4 * squared, "dyadic norm bracket") + observe(scale) + return scale, exponent + + +def upper_dyadic(value): + need(value > 0, "positive dyadic upper target") + exponent = value.numerator.bit_length() - value.denominator.bit_length() + result = pow2(exponent) + while result < value: + result *= 2 + while result / 2 >= value: + result /= 2 + return observe(result) + + +def height(matrix): + return max([1] + [max(abs(x.numerator).bit_length(), x.denominator.bit_length()) + for row in matrix for entry in row + for x in (C.wrap(entry).re, C.wrap(entry).im)]) + + +def generators(displacement): + """Return column g, explicit coefficient ROW r, and a dyadic admission scale.""" + global MAX_HEIGHT + displacement = Matrix(displacement) + size = len(displacement) + need(size > 0 and all(len(row) == size for row in displacement), "nonempty square displacement") + input_height = height(displacement) + MAX_HEIGHT = input_height + columns = [[displacement[i][j] for i in range(size)] for j in range(size)] + residuals, result = [], [] + for column_index, column in enumerate(columns): + residual = list(column) + for old, squared in residuals: + factor = inner(old, residual) / squared + residual = [x - factor * y for x, y in zip(residual, old)] + squared = norm2(residual) + if squared == 0: + continue + scale, exponent = norm_scale(squared) + g = Vector(x / scale for x in residual) + row = Vector(inner(residual, c) * (scale / squared) for c in columns) + gamma = upper_dyadic(max(Q(1), 2 * component_l1(row))) + need(norm2(g) <= 1 and 2 * component_l1(row) <= gamma, "bounded generator admission") + residuals.append((residual, squared)) + result.append({"column": column_index, "residual": residual, "squared_norm": squared, + "scale": scale, "scale_exponent": exponent, "g": g, "row": row, + "gamma": gamma}) + return result, {"input_height": input_height, "max_observed_height": MAX_HEIGHT} + + +def lower(vector): + return Matrix([[vector[i - j] if i >= j else C() for j in range(len(vector))] + for i in range(len(vector))]) + + +def transpose(matrix): + return Matrix(zip(*matrix)) + + +def frobenius2(matrix): + return observe(sum((C.wrap(x).norm2() for row in matrix for x in row), Q(0))) + + +def norm_bound(matrix): + """Rational upper bound for the induced 2-norm.""" + return max(max(component_l1(row) for row in matrix), + max(component_l1(column) for column in zip(*matrix))) + + +def exact_record(matrix): + return [[C.wrap(x).record() for x in row] for row in matrix] diff --git a/research/direct-circulant-production-precision/compiler-cuts/retained/triangular.py b/research/direct-circulant-production-precision/compiler-cuts/retained/triangular.py new file mode 100644 index 0000000000..2bd8de01a7 --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-cuts/retained/triangular.py @@ -0,0 +1,200 @@ +"""Source-bound rational parity recursion with a common precision allocation. + +Jose Manuel (jmbarrancoml), with substantial OpenAI Codex assistance. +Apache-2.0. Parity recursion and its stability premise: 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, inverse_gate, need, + rounded) +from engine import Builder, Phases, split_kernel + + +def allocation(n, radius, target, incoming=0): + need(type(n) is int and n > 0 and n & (n - 1) == 0, "dyadic triangle size") + need(type(radius) in (int, Q) and radius >= 1, "exact triangle radius") + need(type(target) is int and target >= 1, "positive triangle target") + need(type(incoming) is int and incoming >= 0, "incoming triangle grid") + d = n.bit_length() - 1 + q, depth, bound = 2 * d + 1, 4 * d * d + 12 * d + 1, 100 * n ** 3 + s = target + ceil_log2(4 * q * bound ** 3 * (radius + 1)) + p = s + ceil_log2(48 * (d + 1)) + multiplier = s + 2 + data = max(incoming, target + ceil_log2(64 * depth * bound * n)) + epsilon, u = Q(1, 1 << s), Q(1, 1 << data) + theta = q * bound ** 2 * epsilon + coefficient = 2 * q * bound ** 3 * epsilon + rounding = 32 * depth * bound * n * u + need(theta <= Q(1, 4) and coefficient * radius + rounding <= Q(1, 1 << target), + "complete triangular error allocation") + amplitude = 32 * bound * radius + 1024 * depth * bound ** 2 * n * u + integer = max(1, ceil_log2(max(Q(1), amplitude))) + 2 + height = max(4 * p + 24, multiplier + 5, 2 * s + 16) + return dict(n=n, radius=radius, target_bits=target, incoming_bits=incoming, + ideal_bound=bound, macro_layers=q, layer_bound=depth, + gate_bound=n * (2 * d * d + 8 * d + 1), + leaf_bits=s, phase_bits=p, multiplier_bits=multiplier, + data_bits=data, epsilon=epsilon, theta=theta, + coefficient_error=coefficient, rounding_error=rounding, + total_error=coefficient * radius + rounding, + physical_prefix_suffix_bound=32 * bound, + segment_bound=1024 * bound ** 2, amplitude_bound=amplitude, + integer_bits=integer, coefficient_height_bound=height, + temporary_bits=2 * data + 8 * height + 2 * integer + 32) + + +class Plan(list): + """Actual layers plus consecutive, disjoint-support macro partitions.""" + def __init__(self, layers, blocks): + super().__init__(layers) + self.blocks = blocks + + def __add__(self, other): + need(isinstance(other, Plan), "typed triangular composition") + offset = len(self) + blocks = [dict(block) for block in self.blocks] + blocks += [dict(start=b["start"] + offset, stop=b["stop"] + offset, + pieces=list(b["pieces"])) for b in other.blocks] + return Plan(list(self) + list(other), blocks) + + +class Concatenate: + def __getitem__(self, parts): + values = [] + for part in parts: + values.extend(part if isinstance(part, (list, tuple)) else [part]) + return Vec(values) + + +def convolution(a, b): + return Vec(sum((a[j] * b[k - j] for j in range(len(a)) + if 0 <= k - j < len(b)), C()) + for k in range(len(a) + len(b) - 1)) + + +class AdaptTriangle(ast.NodeTransformer): + def __init__(self): + self.changes = [] + + def visit_Assign(self, node): + if (len(node.targets) == 1 and isinstance(node.targets[0], ast.Subscript) + and isinstance(node.targets[0].slice, ast.Constant) + and node.targets[0].slice.value == "max_triangle_coefficient"): + self.changes.append("exact-component-diagnostic") + node.value = ast.parse( + "max(STATS['max_triangle_coefficient'], component_l1(f))", + mode="eval").body + return node + return self.generic_visit(node) + + def visit_Return(self, node): + if (isinstance(node.value, ast.Call) and isinstance(node.value.func, ast.Name) + and node.value.func.id == "diag"): + self.changes.append("stored-rounded-leaf") + node.value.func.id = "leaf_diag" + return self.generic_visit(node) + + +class Triangle: + def __init__(self, bound, circuit_source, oracle_source, phase_oracle=None): + self.bound, self.circuit_source = bound, circuit_source + self.phases = phase_oracle if phase_oracle is not None else Phases(bound["phase_bits"], oracle_source) + need(self.phases.bits == bound["phase_bits"], "common triangular phase precision") + base = Builder(self.phases, bound["multiplier_bits"], circuit_source) + self.source_parallel = base.namespace["parallel"] + self.source_inverse = base.namespace["inverse"] + self.children, self.leaves = [], [] + selected = {"toep", "lower", "invseries", "conv", "triangle_plan"} + tree = ast.parse(circuit_source) + 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 parity source") + self.original_ast = sha256(ast.dump(tree).encode()).hexdigest() + adapter = AdaptTriangle() + tree = ast.fix_missing_locations(adapter.visit(tree)) + need(adapter.changes == ["exact-component-diagnostic", "stored-rounded-leaf"], + "exact declared parity adaptations") + self.adapted_ast = sha256(ast.dump(tree).encode()).hexdigest() + facade = SimpleNamespace(asarray=lambda a, dtype=None: Vec(a), + array=lambda a, dtype=None: Mat(a), + zeros=lambda n, dtype=None: Vec([0] * n), + convolve=convolution, r_=Concatenate()) + self.stats = {"triangle_nodes": 0, "max_triangle_coefficient": Q(0)} + self.namespace = dict(np=facade, STATS=self.stats, component_l1=component_l1, + leaf_diag=self.leaf, parallel=self.parallel, + toeplitz_shear=self.shear) + exec(compile(tree, "", "exec", optimize=0), + self.namespace) + + def leaf(self, indices, values): + need(len(indices) == len(values) == 1, "scalar triangular leaf") + wanted = values[0] + stored = rounded(wanted, self.bound["leaf_bits"]) + epsilon = self.bound["epsilon"] + need(Q(1, 4) <= wanted.norm2() <= 4, "ideal scalar leaf margin") + need((stored - wanted).norm2() <= epsilon ** 2 + and stored.norm2() >= Q(1, 16), "stored scalar leaf margin") + gate = Mat([[stored]]) + inverse = inverse_gate(gate) + need(stored * inverse[0][0] == 1, "same stored scalar reciprocal") + piece = dict(kind="leaf", ids=list(indices), ideal=Mat([[wanted]]), + error=epsilon, stored=stored, reciprocal=inverse[0][0]) + self.leaves.append(piece) + return Plan([[(tuple(indices), gate)]], + [dict(start=0, stop=1, pieces=[piece])]) + + def shear(self, target, source, matrix): + n = len(source) + need(len(set(source + target)) == 2 * n, "owned disjoint parity banks") + child = Builder(self.phases, self.bound["multiplier_bits"], self.circuit_source) + local = child.plan(matrix) + g, h = split_kernel(matrix) + envelope = component_l1(g) + component_l1(h) + v = Q(1, 1 << self.bound["multiplier_bits"]) + defect = 4 * (n.bit_length()) * envelope * self.phases.nu + 2 * v + need(envelope + 2 * v <= 6 and defect <= self.bound["epsilon"], + "bounded parity child and allocated operator defect") + mapping = source + target + layers = [[(tuple(mapping[i] for i in ids), gate) for ids, gate in layer] + for layer in local] + piece = dict(kind="shear", ids=list(mapping), ideal=matrix, error=defect, + envelope=envelope, source_ast=child.original_ast, + adapted_ast=child.adapted_ast, local_layers=len(local)) + self.children.append(piece) + return Plan(layers, [dict(start=0, stop=len(layers), pieces=[piece])]) + + def parallel(self, left, right): + need([(b["start"], b["stop"]) for b in left.blocks] + == [(b["start"], b["stop"]) for b in right.blocks], + "equal sibling macro boundary partitions") + blocks = [] + for a, b in zip(left.blocks, right.blocks): + pieces = a["pieces"] + b["pieces"] + ids = [i for piece in pieces for i in piece["ids"]] + need(len(ids) == len(set(ids)), "disjoint sibling macro supports") + blocks.append(dict(start=a["start"], stop=a["stop"], pieces=pieces)) + return Plan(self.source_parallel(left, right), blocks) + + def plan(self, symbol, indices=None): + symbol = Vec(symbol) + n = len(symbol) + need(n == self.bound["n"], "allocated triangle dimension") + need(component_l1(symbol - Vec([1] + [0] * (n - 1))) <= Q(1, 2), + "component-l1 near-identity admission") + indices = list(range(n)) if indices is None else list(indices) + need(len(indices) == n and sorted(indices) == list(range(n)), "triangle wire permutation") + result = self.namespace["triangle_plan"](indices, symbol) + need(self.stats["triangle_nodes"] == 2 * n - 1, "complete parity recursion tree") + need(len(result.blocks) == self.bound["macro_layers"] + and len(result) <= self.bound["layer_bound"] + and sum(map(len, result)) <= self.bound["gate_bound"], "complete schedule bounds") + return result + + def inverse(self, plan): + # Forward pieces certify forward defects. Inverse endpoint bounds use + # the inverse-product proof, not relabelled forward macro certificates. + return self.source_inverse(plan) diff --git a/research/direct-circulant-production-precision/compiler-cuts/review/CROSS-REVIEW.md b/research/direct-circulant-production-precision/compiler-cuts/review/CROSS-REVIEW.md new file mode 100644 index 0000000000..044ede502e --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-cuts/review/CROSS-REVIEW.md @@ -0,0 +1,125 @@ +# Independent review: complete-gate compiler cuts + +**Decision:** accept the scoped mathematical result in the frozen author proof. No mathematical repair is required. Publication should include the overlap clarification below and preserve the stated source, conditioning, rank, phase-service and per-atom error premises. This is an independent model-assisted review, not independent human acceptance or a formal kernel proof. + +Reviewed proof SHA256: `162dd4bb7a020dfb72dd3c80cb9a1de37212cc7f812f36fd4365d487d49b341b`. + +Canonical source commit: `e54523517d0f03e58352e647c403a5af3e525a57`. The independent checker authenticates all 18 files in the author's `ORIGINS.json`, including their byte lengths, SHA256 values and Git blob identifiers, before execution. The proof is authenticated again after execution. The old author-proof status and interrupted receipt are historical; this dated separate review supplies the new review outcome without rewriting the frozen proof. + +## 1. Accepted theorem and its boundary + +For the literal pinned `Builder`, `Triangle`, `Program` and `Full` words, the existing sufficient four-way envelopes extend to cuts after any subset of **complete** one- or two-wire gates in a matching layer. The four operators are the prefix, suffix, inverse prefix and inverse suffix. The accepted envelopes are + +\[ +K_\triangle=3200m^3, +\qquad +H_G=\max(3200m^3,2+2k_G)(10+4\alpha+2k_G), +\] + +and + +\[ +K_{\rm Full}=2L_0\mathcal B\mathcal H, +\quad \mathcal B=256N^3(\lambda Q)^{12}. +\] + +The statement concerns the exact linear program with the stored coefficients. A Full interval has the conservative bound `K_Full^2`. It does not say that a partial cut is bounded by the measured maximum of its two neighboring whole-layer cuts. It does not cover an intermediate assignment of only one output of a two-wire gate, arbitrary alternative implementations having the same endpoint, or the internal states of an unexamined recursive replacement service. + +This supplies a source-specific supplement to the same Full word used in #8093. The finite-carrier construction in #8092 is a different implementation and receives no compiler, tape, ownership or analytic discharge from this result. The selected canonical constant remains `.00363005817`; no selected assumption is removed by this review. + +## 2. Why the primitive claim is sound + +I inspected the pinned coefficient factory and elementary-gate construction. Every non-crossing elementary gate acts within one bank and is exactly unitary: swaps, rational unit-modulus phases, and the stored butterfly with `a^2+b^2=1`. Its inverse is the inverse of those same stored coefficients. The cyclic and negacyclic diagonal shears both have the same source-to-target direction; their intervening transforms and twists preserve the two banks. + +Writing an arbitrary resulting fragment as + +\[ +A=\begin{pmatrix}U&0\\X&V\end{pmatrix}, +\] + +the diagonal blocks are unitary. A bank-local unitary preserves the norm of `X`; a shear updates it to `X+DU`, increasing its norm by at most `||D||`. Selecting complete gates from one matching changes a diagonal shear multiplier to a coordinate restriction and never increases its norm. A partial unitary matching remains unitary. Every chronological primitive interval encounters at most the two original shear matchings, so + +\[ +\|X\|\le M_g+M_h+2v, +\qquad +\|A\|,\|A^{-1}\|\le1+M_g+M_h+2v. +\] + +The inverse off-diagonal block is `-V^{-1}XU^{-1}` and has the same norm. This proves all four fragment bounds directly, without interpolation. Order is essential: no overlapping bank transformations are commuted. The exact checker verifies the bank blocks, orthogonality and inverse formula separately; it does not infer them merely from a correct final endpoint. + +Two adversarial cases explain the assumptions. Opposite-direction shears of coefficient two produce `[[5,2],[2,1]]`, whose first-column squared norm is 29, exceeding the square of the false additive cap 5. Compensated nonunitary scaling also permits intermediate amplification even when all whole-layer operators and inverses have a common cap. Neither case belongs to the pinned primitive alphabet. + +## 3. Triangle and generator composition + +`Triangle.parallel` checks the equality of sibling macro-boundary partitions, and siblings occupy disjoint supports. Therefore the active fragment is a direct sum of primitive fragments, rather than a product of arbitrarily staggered recursive subwords. The source near-identity admission and ideal-prefix bound `B=100m^3` remain hypotheses/results of the retained compiler proof. The fragment extension adds the local cap 7, or the scalar cap 4, to that existing argument. + +The perturbation algebra is correct in its stated order. With ideal prefixes `Q_j`, normalized errors `G_j=Q_j^{-1}E_j Q_{j-1}` and stored prefixes, a suffix is exactly + +\[ +Q_q\bigl((I+G_q)\cdots(I+G_{j+1})\bigr)Q_j^{-1}. +\] + +Only one consecutive product occurs. When the sum of error norms is at most one quarter, every consecutive product and its inverse have norm less than two. Using two separately bounded perturbation prefixes here would obscure the cancellation and unnecessarily enlarge the constant. The resulting completed-prefix and suffix caps, combined with the active primitive/scalar cap, fit inside the existing `32B` allowance. The literal inverse word exchanges prefixes with inverse suffixes; it must not be replaced with independently rounded forward macros or adjoints of nonunitary scalar leaves. + +The generator chronology `p; S(h); p^{-1}; S(-h)` is also correct. `p^{-1}` is the paired stored inverse, and compensation negates the same stored multipliers. The endpoint is `S(h(p-I))`. I rederived all four checkpoint prefixes, suffixes and inverse formulas in the proof. In particular, the second suffix is `L(p^{-1},Cp^{-1}-h)`, whose product with `L(p,A+hp)` cancels the intermediate `hp` term in the required order. The common cap `4+4a+2k=10+4alpha+2k_G` follows without multiplying a separate amplification for every generator term. The primitive allowance `2+2k_G` retains its source hypotheses `k_G>=2` and `v<=1/2`. + +## 4. Full downsets and actual cut chronology + +The source domain includes **`lambda>=1` and `Q>=1` individually**, as enforced by `full.allocation` and the clamped return of `admission`. The weaker condition `lambda*Q>=1` alone would not justify the retained pivot and completed-downset estimates. A scalar `1/1024` with unclamped `lambda=1/1024,Q=1024` has product one but inverse norm 1024, exceeding `B=256`. This is outside the source domain. Integration should preserve the individual lower bounds explicitly when summarizing the theorem. + +For the admitted domain, I checked the original downset derivation and source recursion. An internal node executes its upper shear, then both disjoint child programs, then its lower shear. An ideal downset has factorization `L(I)D(I)U(I)`; its lower factor is a direct sum over maximal completed subtrees, and its upper factor is `U_F^{-1}u_root` for the unvisited-upper frontier. Inverse factors occur in reverse order. The existing `W=3N chi^2`, `V=6N chi^4` and partial-pivot bound give `216N^3 chi^12 < B`. These estimates are inherited from the retained conditioning proof, not a new improvement to the predecessor's downset constant. + +Actual timestamps classify a zero-duration atom as complete at its source position. At an interior matching cut, the complete and active sets satisfy the legal downset requirements; active atoms are incomparable and disjoint. A selected complete last gate may already finish its active atom's fragment without changing the validity of the conservative timestamp classification. Unequal sibling durations preserve the disjoint-support argument. The prefix is `F Qhat(I)`, while the suffix is `Rhat T`, and inverse formulas preserve reversed multiplication order. Only disjoint incomparable atom work can be reordered. + +For the remaining whole-atom suffix, take a legal order `I,A,remaining`. The same normalized consecutive-product identity bounds the suffix after `I union A`; using the independent cap on active tails then gives `2L0 B H`. No factor proportional to the number of active atoms occurs because their direct sum takes the maximum norm. The root-scalar case and empty rank-zero identity atoms are included. An arbitrary interval is `P_b P_a^{-1}`, so its bound is `K_Full^2`, not the primitive interval cap and not an endpoint condition number. + +## 5. Independent executed checks + +`check_independent.py` was written for this review and never imports or executes the author's `audit.py`. It imports the authenticated retained `engine`/`exact` coefficient factory to obtain actual elementary gates. All reviewed gate multiplication, realification, inverse elimination, block checks and downset calculations use a separate standard-library Fraction implementation. Complex rational gates are realified into twice as many real coordinates; inverses use a separate last-available-pivot elimination. The downset fixtures are independently generated exact non-Hermitian Toeplitz LDU trees, not the author's instrumented Full traces. + +The normal and optimized receipts record these checks: + +- 760 primitive cuts at bank widths 1, 2 and 4, including 700 proper partial-matching selections and 3,040 four-way structural certificates. Every matching subset is enumerated in each fixture. +- 90 source gates independently classified by bank support and exact orthogonality or same-direction shear form. The two spectral layers and their multiplier bounds are checked explicitly. +- 726 source cut witnesses distinguish suffix-times-prefix order from its reversal. +- Additional chronological primitive intervals check the bank invariant, inverse formula and `P_b P_a^{-1}` identity. Exact counts are in the receipts. +- All 46 abstract downsets for three independent LDU trees: 2 at size one, 6 at size two and 38 at size four. These check factorization, unvisited frontier, inverse order and a rational Frobenius consequence of the old `B` envelope. +- Four generator checkpoints check prefix, suffix and both inverse identities. Missing the paired inverse, changing one compensation coefficient and reversing noncommuting chronology are rejected. +- Five normalized suffixes and five inverse suffixes check the single consecutive-product formula; three distinguish reversal of the normalized factors. +- The nonunitary-scale control has common whole-layer and inverse cap 10 but intermediate first-column squared norm 128; the opposite-direction shear control has squared column norm 29 against false cap squared 25; the split swap coordinate-write matrix is singular. +- The unclamped-conditioning scalar control has `lambda Q=1` but inverse norm 1024, violating the claimed completed-prefix cap 256 if the individual source bounds are improperly dropped. + +The primitive certificates are exact algebraic certificates of the bank invariant and coefficient bounds. They are not an independent numerical spectral optimization or a PSD-eigenvalue test. The universal norm inequality is the written argument in section 2; bounded enumeration corroborates its source binding. Similarly, the 46 independent LDU downsets are not the author's larger source-timestamp sweep. The author reports separate execution evidence in its own receipt; those counts are not claimed as independent reviewer executions. + +Run from this review directory, with `SOURCE` denoting the directory containing the frozen proof and `retained`: + +```sh +python3 -W error -I -B check_independent.py --source "$SOURCE" --output EVIDENCE.json +python3 -W error -I -O -B check_independent.py --source "$SOURCE" --output EVIDENCE-OPTIMIZED.json +``` + +All logical checks use explicit exceptions and remain active under `-O`. Proof-relevant receipt fields match after removing only the elapsed `seconds` field. These bounded checks do not independently establish all-size rank, phase or analytic hypotheses. + +## 6. Required overlap and credit clarification + +Brian/JoyboyBrian's [#4976](https://github.com/CrocSwap/integer-mult-bounds/pull/4976) provides the unrestricted sharp `sqrt(2)` matching interpolation and asks about compiler alphabets. It should not be described as wholly untouched until this work: Nick Petalas's merged [#5940](https://github.com/CrocSwap/integer-mult-bounds/pull/5940), head `b709a6adb6a9543247260900b108166a4d469f6f`, proves the sharp conditioned factor + +\[ +\sqrt{\frac{2K^2}{1+K^2}} +\] + +when a gate and its inverse have norm at most `K`, including no loss for a unitary layer. Its shear specialization has squared factor `1+u/sqrt(u^2+4)`. This author proof is different: it uses the structure of the **whole stored source word**, including both same-direction shear matchings, to retain a stated sufficient envelope. It does not improve the sharp generic conditioned interpolation formula, prove measured-adjacent no-loss, or claim the four-way coupled sharpness that #5940 itself leaves open. + +Armin Pourshafeie/apoursh's merged [#5240](https://github.com/CrocSwap/integer-mult-bounds/pull/5240), head `6d0a6043120880c696d0850e9242a16e6fb980a5`, already audits the actual `exact.py:apply` rounded-output semantics, one residual vector per layer, stored-coordinate splice and unchanged component-width implication. It also supplies the singular partial-write swap warning. The swap in this independent checker is an inherited boundary rejection control, not a new discovery. The present source-fragment result does not claim its rounded-event or component-width theorem as new work, and does not supply the outstanding local arithmetic temporary-width proof. + +The two preceding scope comparisons use the full downloaded PR bodies supplied by the coordinating reviewer. Their mathematical proofs were not independently audited here and are not inputs to the new bank-invariant proof. Exact PR heads identify the compared contributions; merge status was checked by the coordinating reviewer. Parent package integration should carry these credits in its README/overlap appendix without altering the reviewed proof bytes. + +Further inherited results are Brian/JoyboyBrian's #4755 source-timed trace and #4977 allocation adapter, Nick Petalas's #4852 sharper completed-downset bound, and Jose Manuel/jmbarrancoml's rational compiler, conditioning and allocation results. This proof deliberately retains the older `B=256N^3 chi^12` source allocation rather than importing #4852's smaller bound. Vlado Vojdanovski's recursive matching schedule, Chafik Boukhalfa's phase service and the retained exact Stein producer remain credited premises. + +## 7. Integration decision and remaining obligations + +Accept the complete-gate fragment extension and its propagation through the unchanged factories. Preserve the proof hash, attach this separate review and both independent receipts, and state the individual conditioning lower bounds in the integration appendix. No selected frontier update or new kappa is justified by this result. The author proof's historic “separate review pending” line should be explained by the current completion record, rather than treated as a missing execution. + +All-size conditioning and component guards, exact rank/displacement contracts, phase certificates and per-atom operator error must still be supplied by the caller. Physical arithmetic, scratch-register states, coefficient preparation and delivery, tape realization, temporary widths and analytic recovery remain outside this lemma. Any altered recursive gate implementation needs its own fragment and inverse bounds. The source-specific whole-word theorem should be published as that scoped addition, with the existing interpolation and rounding work credited distinctly. + +Review completed 2026-11-23 UTC by a separate OpenAI agent for Jerry Chen / @CubeJerry. No author checker was imported as independent evidence. diff --git a/research/direct-circulant-production-precision/compiler-cuts/review/EVIDENCE-OPTIMIZED.json b/research/direct-circulant-production-precision/compiler-cuts/review/EVIDENCE-OPTIMIZED.json new file mode 100644 index 0000000000..f6f6614046 --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-cuts/review/EVIDENCE-OPTIMIZED.json @@ -0,0 +1,113 @@ +{ + "status": "PASS_INDEPENDENT_SOURCE_ALPHABET_CUT_REVIEW", + "proof_sha256": "162dd4bb7a020dfb72dd3c80cb9a1de37212cc7f812f36fd4365d487d49b341b", + "source_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "source_files": [ + "retained/FULL-PROOF.md", + "retained/GENERATOR-PROOF.md", + "retained/PR4755-README.md", + "retained/PR4852-README.md", + "retained/PR4976-README.md", + "retained/PR4977-README.md", + "retained/PROOF.md", + "retained/SOURCES.json", + "retained/STEIN-PROVENANCE.json", + "retained/TRIANGLE-PROOF.md", + "retained/check_circuits.py", + "retained/engine.py", + "retained/exact.py", + "retained/full.py", + "retained/generator.py", + "retained/interval_kernel.py", + "retained/stein_rational.py", + "retained/triangular.py" + ], + "method": "Own Fraction realification, reverse-pivot inverses, gate-word multiplication, recursive LDU downsets; imports retained coefficient factory only; never imports audit.py.", + "primitive_cuts": { + "cases": [ + { + "bank_width": 1, + "layers": 4, + "cuts": 12, + "envelope": "3/2" + }, + { + "bank_width": 2, + "layers": 12, + "cuts": 60, + "envelope": "141/80" + }, + { + "bank_width": 4, + "layers": 16, + "cuts": 688, + "envelope": "3691/1680" + } + ], + "cuts": 760, + "proper_sublayer_cuts": 700, + "four_way_certificates": 3040, + "classified_source_gates": 90, + "wrong_order_witnesses": 726, + "arbitrary_intervals": 100 + }, + "compensated_generator": { + "checkpoint_identities": 16, + "missing_inverse_rejected": true, + "unpaired_compensation_rejected": true, + "wrong_order_rejected": true + }, + "normalized_suffixes": { + "suffix_identities": 5, + "inverse_suffix_identities": 5, + "reversed_product_witnesses": 3 + }, + "downsets": { + "cases": [ + { + "n": 1, + "atoms": 1, + "all_downsets": 2, + "lambda_envelope": "2", + "inverse_envelope": "1", + "old_B": "1048576" + }, + { + "n": 2, + "atoms": 4, + "all_downsets": 6, + "lambda_envelope": "19/9", + "inverse_envelope": "1", + "old_B": "4532868954247497728/282429536481" + }, + { + "n": 4, + "atoms": 10, + "all_downsets": 38, + "lambda_envelope": "2279/990", + "inverse_envelope": "1", + "old_B": "78522097759866167353707291250420812908164/216402556571320625160840087890625" + } + ], + "downsets": 46 + }, + "negative_controls": { + "unclamped_conditioning": { + "lambda": "1/1024", + "Q": "1024", + "chi": "1", + "invalid_B": "256", + "actual_inverse_norm": "1024" + }, + "unpaired_scale": { + "endpoint_cap": "10", + "intermediate_column_squared": "128" + }, + "opposite_direction_shear": { + "false_cap": 5, + "column_squared": "29" + }, + "coordinate_write_swap_singular": true + }, + "seconds": 12.162 +} diff --git a/research/direct-circulant-production-precision/compiler-cuts/review/EVIDENCE.json b/research/direct-circulant-production-precision/compiler-cuts/review/EVIDENCE.json new file mode 100644 index 0000000000..864edddad2 --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-cuts/review/EVIDENCE.json @@ -0,0 +1,113 @@ +{ + "status": "PASS_INDEPENDENT_SOURCE_ALPHABET_CUT_REVIEW", + "proof_sha256": "162dd4bb7a020dfb72dd3c80cb9a1de37212cc7f812f36fd4365d487d49b341b", + "source_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "source_files": [ + "retained/FULL-PROOF.md", + "retained/GENERATOR-PROOF.md", + "retained/PR4755-README.md", + "retained/PR4852-README.md", + "retained/PR4976-README.md", + "retained/PR4977-README.md", + "retained/PROOF.md", + "retained/SOURCES.json", + "retained/STEIN-PROVENANCE.json", + "retained/TRIANGLE-PROOF.md", + "retained/check_circuits.py", + "retained/engine.py", + "retained/exact.py", + "retained/full.py", + "retained/generator.py", + "retained/interval_kernel.py", + "retained/stein_rational.py", + "retained/triangular.py" + ], + "method": "Own Fraction realification, reverse-pivot inverses, gate-word multiplication, recursive LDU downsets; imports retained coefficient factory only; never imports audit.py.", + "primitive_cuts": { + "cases": [ + { + "bank_width": 1, + "layers": 4, + "cuts": 12, + "envelope": "3/2" + }, + { + "bank_width": 2, + "layers": 12, + "cuts": 60, + "envelope": "141/80" + }, + { + "bank_width": 4, + "layers": 16, + "cuts": 688, + "envelope": "3691/1680" + } + ], + "cuts": 760, + "proper_sublayer_cuts": 700, + "four_way_certificates": 3040, + "classified_source_gates": 90, + "wrong_order_witnesses": 726, + "arbitrary_intervals": 100 + }, + "compensated_generator": { + "checkpoint_identities": 16, + "missing_inverse_rejected": true, + "unpaired_compensation_rejected": true, + "wrong_order_rejected": true + }, + "normalized_suffixes": { + "suffix_identities": 5, + "inverse_suffix_identities": 5, + "reversed_product_witnesses": 3 + }, + "downsets": { + "cases": [ + { + "n": 1, + "atoms": 1, + "all_downsets": 2, + "lambda_envelope": "2", + "inverse_envelope": "1", + "old_B": "1048576" + }, + { + "n": 2, + "atoms": 4, + "all_downsets": 6, + "lambda_envelope": "19/9", + "inverse_envelope": "1", + "old_B": "4532868954247497728/282429536481" + }, + { + "n": 4, + "atoms": 10, + "all_downsets": 38, + "lambda_envelope": "2279/990", + "inverse_envelope": "1", + "old_B": "78522097759866167353707291250420812908164/216402556571320625160840087890625" + } + ], + "downsets": 46 + }, + "negative_controls": { + "unclamped_conditioning": { + "lambda": "1/1024", + "Q": "1024", + "chi": "1", + "invalid_B": "256", + "actual_inverse_norm": "1024" + }, + "unpaired_scale": { + "endpoint_cap": "10", + "intermediate_column_squared": "128" + }, + "opposite_direction_shear": { + "false_cap": 5, + "column_squared": "29" + }, + "coordinate_write_swap_singular": true + }, + "seconds": 11.737 +} diff --git a/research/direct-circulant-production-precision/compiler-cuts/review/RECEIPT.json b/research/direct-circulant-production-precision/compiler-cuts/review/RECEIPT.json new file mode 100644 index 0000000000..882635a606 --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-cuts/review/RECEIPT.json @@ -0,0 +1,22 @@ +{ + "status": "ACCEPT_SCOPED_COMPLETE_GATE_RESULT", + "proof_sha256": "162dd4bb7a020dfb72dd3c80cb9a1de37212cc7f812f36fd4365d487d49b341b", + "reviewer": "separate OpenAI agent; not human or formal-kernel acceptance", + "normal_optimized_parity": true, + "run_seconds": [ + 11.737, + 12.162 + ], + "arbitrary_primitive_intervals": 100, + "files": { + "check_independent.py": "d18064eb86ff9975d59446907cde80ef1c9665188c04409d9287f35b75040ddd", + "CROSS-REVIEW.md": "b9b2ff6ac1b4454c5a4b62489bb4b00ad0de89b37dfbe8f13da48db0a3ed45ae", + "EVIDENCE.json": "db6f12ffdb0909fef4f83e4e91d0f41090435191b6ca13da1a9be31dee7f7347", + "EVIDENCE-OPTIMIZED.json": "04a27e7865a42f0ad609010b30f67ff08e7ddd13093585834770f4419ea59561" + }, + "integration_requirements": [ + "Preserve lambda>=1 and Q>=1 individually", + "Credit #5940 conditioned interpolation and #5240 rounded/splice semantics", + "Do not transfer to #8092 finite-carrier compiler or internal coordinate-write states" + ] +} diff --git a/research/direct-circulant-production-precision/compiler-cuts/review/check_independent.py b/research/direct-circulant-production-precision/compiler-cuts/review/check_independent.py new file mode 100644 index 0000000000..1fae72e9d0 --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-cuts/review/check_independent.py @@ -0,0 +1,221 @@ +"""Independent rational realification; does not import author audit.py.""" +from fractions import Fraction as F +from hashlib import sha1, sha256 +from pathlib import Path +import argparse, importlib, json, sys, time +PROOF_SHA='162dd4bb7a020dfb72dd3c80cb9a1de37212cc7f812f36fd4365d487d49b341b' +def need(ok,why): + if not ok:raise ValueError(why) +def eye(n):return [[F(i==j) for j in range(n)] for i in range(n)] +def zero(n,m=None):return [[F(0)]*(n if m is None else m) for _ in range(n)] +def trans(a):return [list(r) for r in zip(*a)] +def add(a,b,s=1):return [[x+s*y for x,y in zip(r,t)] for r,t in zip(a,b)] +def scale(a,s):return [[s*x for x in r] for r in a] +def block(a,i,j,n,m):return [r[j:j+m] for r in a[i:i+n]] +def join(a,b,c,d):return [r+s for r,s in zip(a,b)]+[r+s for r,s in zip(c,d)] +def diag(a,b):return join(a,zero(len(a),len(b)),zero(len(b),len(a)),b) +def mm(a,b): + out=zero(len(a),len(b[0])) + for i,r in enumerate(a): + for k,x in enumerate(r): + if x: + for j,y in enumerate(b[k]): + if y:out[i][j]+=x*y + return out +def inv(a): + n=len(a);r=[list(map(F,row))+eye(n)[i] for i,row in enumerate(a)] + for k in range(n): + piv=[j for j in range(k,n) if r[j][k]];need(piv,'singular matrix rejected') + j=piv[-1];r[k],r[j]=r[j],r[k];s=r[k][k];r[k]=[x/s for x in r[k]] + for j in range(n): + if j!=k and r[j][k]: + s=r[j][k];r[j]=[x-s*y for x,y in zip(r[j],r[k])] + return [row[n:] for row in r] +def frob2(a):return sum(x*x for row in a for x in row) +def envelope(a):return max(max(sum(abs(x) for x in r) for r in a),max(sum(abs(x) for x in c) for c in zip(*a))) +def realify(a): + out=zero(2*len(a),2*len(a[0])) + for i,row in enumerate(a): + for j,z in enumerate(row): + x,y=(F(z.re),F(z.im)) if hasattr(z,'re') else (F(z),F(0)) + out[2*i][2*j]=x;out[2*i][2*j+1]=-y;out[2*i+1][2*j]=y;out[2*i+1][2*j+1]=x + return out +def gate_left(a,ids,g): + out=[r[:] for r in a];updated=mm(g,[a[i] for i in ids]) + for i,r in zip(ids,updated):out[i]=r + return out +def word(layers,n,reverse=False): + out=eye(n) + for layer in (reversed(layers) if reverse else layers): + for ids,g in (reversed(layer) if reverse else layer):out=gate_left(out,ids,inv(g) if reverse else g) + return out +def triangular_certificate(a,ai,m): + u=block(a,0,0,m,m);v=block(a,m,m,m,m);x=block(a,m,0,m,m) + need(block(a,0,m,m,m)==zero(m),'upper block not zero') + need(mm(trans(u),u)==eye(m) and mm(trans(v),v)==eye(m),'bank block not orthogonal') + need(ai==join(trans(u),zero(m),scale(mm(mm(trans(v),x),trans(u)),-1),trans(v)),'inverse bank formula failed') + +def primitives(retained): + sys.path.insert(0,str(retained));ex=importlib.import_module('exact');en=importlib.import_module('engine') + source=(retained/'check_circuits.py').read_text();oracle=(retained/'interval_kernel.py').read_text() + count=0;proper=0;wrong=0;classes=0;intervals=0;cases=[] + for n in (1,2,4): + builder=en.Builder(en.Phases(4,oracle),4,source) + first=[ex.C(F(1,4),F(1,8))]+[ex.C(F(1,j+4)) for j in range(1,n)] + top=[first[0]]+[ex.C(-F(1,j+6),F(1,16)) for j in range(1,n)] + mat=ex.Mat([[first[i-j] if i>=j else top[j-i] for j in range(n)] for i in range(n)]) + raw=builder.plan(mat);layers=[];cross=0 + for layer in raw: + used=set();converted=[];kinds=[] + for ids,g in layer: + need(not used.intersection(ids),'overlapping matching');used.update(ids) + rr=realify(g);converted.append((tuple(k for i in ids for k in (2*i,2*i+1)),rr)) + if all(i=n for i in ids): + need(mm(trans(rr),rr)==eye(len(rr)),'nonunitary bank gate');kinds.append('unitary') + else: + need(len(ids)==2 and ids[0]>j&1];rest=[g for j,g in enumerate(layer) if not mask>>j&1] + pre=layers[:k]+[sel];suf=[rest]+layers[k+1:] + p=word(pre,4*n);pi=word(pre,4*n,True);s=word(suf,4*n);si=word(suf,4*n,True) + triangular_certificate(p,pi,2*n);triangular_certificate(s,si,2*n) + need(mm(s,p)==total,'cut chronology wrong') + need(mm(pi,p)==eye(4*n) and mm(si,s)==eye(4*n),'four-way inverse fails') + count+=1;local+=1 + if mask not in (0,(1<0,'reversed source order not distinguished') + return dict(cases=cases,cuts=count,proper_sublayer_cuts=proper,four_way_certificates=4*count,classified_source_gates=classes,wrong_order_witnesses=wrong,arbitrary_intervals=intervals) + +def compensated(): + p=[[F(1),F(1,5)],[F(1,7),F(1)]];h=[[F(2),F(1)],[-F(1),F(3)]] + a=[[F(1),F(0)],[F(1,4),F(1)]];rem=[[F(1,5),F(1,3)],[F(1,9),-F(1,8)]] + i=eye(2);z=zero(2);pi=inv(p) + def low(b,d):return join(b,z,d,i) + def shear(x):return low(i,x) + hp=mm(h,p);term=mm(h,add(p,i,-1));c=add(term,rem) + steps=[diag(p,i),shear(h),diag(pi,i),shear(scale(h,-1))] + pres=[low(p,a),low(p,add(a,hp)),shear(add(a,hp)),shear(add(a,term))] + sufs=[low(pi,mm(c,pi)),low(pi,add(mm(c,pi),h,-1)),shear(add(c,hp,-1)),shear(add(c,term,-1))] + total=shear(add(a,c));prefix=shear(a) + for g,ep,es in zip(steps,pres,sufs): + prefix=mm(g,prefix);suffix=mm(total,inv(prefix)) + need(prefix==ep and suffix==es,'compensated checkpoint formula failed') + need(mm(suffix,prefix)==total,'checkpoint order wrong') + need(mm(inv(prefix),prefix)==eye(4) and mm(inv(suffix),suffix)==eye(4),'checkpoint inverse fails') + need(mm(steps[3],mm(steps[1],steps[0]))!=shear(term),'missing paired inverse accepted') + bad=mm(shear(add(scale(h,-1),[[F(1,32),F(0)],[F(0),F(0)]])),mm(steps[2],mm(steps[1],steps[0]))) + need(bad!=shear(term),'unpaired compensation accepted') + need(mm(steps[0],steps[1])!=mm(steps[1],steps[0]),'reversed term order not detected') + return dict(checkpoint_identities=16,missing_inverse_rejected=True,unpaired_compensation_rejected=True,wrong_order_rejected=True) + +def normalized_suffixes(): + ideal=[[[F(1),F(1,5)],[F(0),F(1)]],[[F(1),F(0)],[F(1,7),F(1)]],[[F(3,2),F(0)],[F(0),F(2,3)]],[[F(1),-F(1,11)],[F(0),F(1)]]] + errors=[[[F(1,1000*(j+1)),F(1,2000)],[F(0),-F(1,3000)]] for j in range(4)] + q=[eye(2)];stored=[eye(2)];normalized=[] + for a,e in zip(ideal,errors): + q.append(mm(a,q[-1]));normalized.append(add(eye(2),mm(mm(inv(q[-1]),e),q[-2]))) + stored.append(mm(add(a,e),stored[-1])) + wrong=0 + for j in range(5): + w=eye(2) + for g in normalized[j:]:w=mm(g,w) + actual=mm(stored[-1],inv(stored[j]));expected=mm(mm(q[-1],w),inv(q[j])) + need(actual==expected,'normalized suffix must use one consecutive product') + need(inv(actual)==mm(mm(q[j],inv(w)),inv(q[-1])),'normalized inverse suffix failed') + wr=eye(2) + for g in reversed(normalized[j:]):wr=mm(g,wr) + wrong+=wr!=w + need(wrong>0,'normalized noncommuting factors fail to distinguish reversal') + return dict(suffix_identities=5,inverse_suffix_identities=5,reversed_product_witnesses=wrong) + +def negative_controls(): + tiny=[[F(1,1024)]];wrong_b=F(256);need(inv(tiny)[0][0]>wrong_b,'unclamped conditioning control fails') + m=F(8);p0=[[m,F(0)],[F(1),1/m]];g=[[1/m,F(0)],[F(0),m]];p1=mm(g,p0);partial=[[F(1),F(0)],[F(0),m]];cap=m+2 + need(all(frob2(a)<=cap*cap for a in (p0,inv(p0),g,inv(g),p1,inv(p1))),'generic control endpoints not bounded') + bad=mm(partial,p0);need(sum(row[0]**2 for row in bad)>cap*cap,'unpaired scaling control does not escape envelope') + lower=[[F(1),F(0)],[F(2),F(1)]];upper=trans(lower);both=mm(upper,lower) + need(sum(row[0]**2 for row in both)>25,'opposite directions fail to defeat additive envelope') + splice=[[F(0),F(1)],[F(0),F(1)]];rejected=False + try:inv(splice) + except ValueError:rejected=True + need(rejected,'split swap coordinate writes not singular') + return dict(unclamped_conditioning={'lambda':'1/1024','Q':'1024','chi':'1','invalid_B':'256','actual_inverse_norm':'1024'},unpaired_scale={'endpoint_cap':str(cap),'intermediate_column_squared':str(sum(row[0]**2 for row in bad))},opposite_direction_shear={'false_cap':5,'column_squared':str(sum(row[0]**2 for row in both))},coordinate_write_swap_singular=True) + +def downset_cases(): + results=[] + for n in (1,2,4): + atoms=[];nodes=[] + def embed(a,offset): + out=eye(n) + for i,row in enumerate(a):out[offset+i][offset:offset+len(a)]=row + return out + def build(a,offset,parents): + m=len(a);node={'size':m,'offset':offset,'a':a};nodes.append(node) + if m==1: + index=len(atoms);atoms.append({'matrix':embed(a,offset),'requires':set(parents)}) + node.update(ids={index},scalar=index,l=eye(1),u=eye(1),d=a);return node + h=m//2;aa=block(a,0,0,h,h);bb=block(a,0,h,h,h);cc=block(a,h,0,h,h);dd=block(a,h,h,h,h) + rr=mm(inv(aa),bb);ll=mm(cc,inv(aa));ss=add(dd,mm(cc,rr),-1) + ur=join(eye(h),rr,zero(h),eye(h));lr=join(eye(h),zero(h),ll,eye(h)) + upper=len(atoms);atoms.append({'matrix':embed(ur,offset),'requires':set(parents)}) + left=build(aa,offset,set(parents)|{upper});right=build(ss,offset+h,set(parents)|{upper}) + lower=len(atoms);atoms.append({'matrix':embed(lr,offset),'requires':set(parents)|{upper}|left['ids']|right['ids']}) + node.update(ids={upper,lower}|left['ids']|right['ids'],upper=upper,lower=lower,left=left,right=right,ur=ur,l=mm(lr,diag(left['l'],right['l'])),d=diag(left['d'],right['d']),u=mm(diag(left['u'],right['u']),ur)) + need(mm(mm(node['l'],node['d']),node['u'])==a,'recursive LDU identity failed');return node + first=[F(2)]+[F(1,8+j) for j in range(1,n)];top=[first[0]]+[-F(1,10+j) for j in range(1,n)] + a=[[first[i-j] if i>=j else top[j-i] for j in range(n)] for i in range(n)];root=build(a,0,set()) + lam=max(F(1),max(envelope(t['a']) for t in nodes));qq=max(F(1),max(envelope(inv(t['a'])) for t in nodes));chi=lam*qq;b=256*n**3*chi**12 + def factors(t,selected): + m=t['size'] + if t['ids']<=selected:return t['l'],t['d'],t['u'],eye(m) + if m==1 or t['upper'] not in selected:return eye(m),eye(m),eye(m),t['u'] + l1,d1,u1,f1=factors(t['left'],selected);l2,d2,u2,f2=factors(t['right'],selected) + return diag(l1,l2),diag(d1,d2),mm(diag(u1,u2),t['ur']),diag(f1,f2) + count=0 + for mask in range(1<>j&1} + if any(not atoms[j]['requires']<=selected for j in selected):continue + p=eye(n) + for j,g in enumerate(atoms): + if j in selected:p=mm(g['matrix'],p) + ll,dd,uu,frontier=factors(root,selected) + need(mm(mm(ll,dd),uu)==p,'downset LDU factorization failed') + need(mm(frontier,uu)==root['u'],'unvisited upper frontier identity failed') + need(mm(mm(inv(uu),inv(dd)),inv(ll))==inv(p),'downset inverse order failed') + need(frob2(p)<=b*b and frob2(inv(p))<=b*b,'old downset envelope not sufficient') + count+=1 + need(count>1,'no nontrivial downsets checked') + results.append({'n':n,'atoms':len(atoms),'all_downsets':count,'lambda_envelope':str(lam),'inverse_envelope':str(qq),'old_B':str(b)}) + return {'cases':results,'downsets':sum(r['all_downsets'] for r in results)} + +def main(): + parser=argparse.ArgumentParser();parser.add_argument('--source',type=Path,required=True);parser.add_argument('--output',type=Path,required=True);args=parser.parse_args();start=time.monotonic() + source=args.source.resolve();proof=(source/'PROOF.md').read_bytes();need(sha256(proof).hexdigest()==PROOF_SHA,'reviewed proof changed') + origins=json.loads((source/'ORIGINS.json').read_text());checked=[] + for item in origins['files']: + data=(source/item['local']).read_bytes();need(len(data)==item['bytes'],'source size changed') + need(sha256(data).hexdigest()==item['sha256'],'source SHA256 changed') + need(sha1(b'blob '+str(len(data)).encode()+b'\0'+data).hexdigest()==item['git_blob'],'source Git blob changed');checked.append(item['local']) + result={'status':'PASS_INDEPENDENT_SOURCE_ALPHABET_CUT_REVIEW','proof_sha256':PROOF_SHA,'source_commit':origins['base_commit'],'source_files':checked,'method':'Own Fraction realification, reverse-pivot inverses, gate-word multiplication, recursive LDU downsets; imports retained coefficient factory only; never imports audit.py.'} + result['primitive_cuts']=primitives(source/'retained');result['compensated_generator']=compensated();result['normalized_suffixes']=normalized_suffixes();result['downsets']=downset_cases();result['negative_controls']=negative_controls() + need(sha256((source/'PROOF.md').read_bytes()).hexdigest()==PROOF_SHA,'proof changed during review');result['seconds']=round(time.monotonic()-start,3) + args.output.write_text(json.dumps(result,indent=2)+'\n');print(json.dumps({'status':result['status'],'cuts':result['primitive_cuts']['cuts'],'downsets':result['downsets']['downsets'],'seconds':result['seconds']})) +if __name__=='__main__':main() diff --git a/research/direct-circulant-production-precision/compiler-intervals/EVIDENCE.json b/research/direct-circulant-production-precision/compiler-intervals/EVIDENCE.json new file mode 100644 index 0000000000..6f6eb3d898 --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-intervals/EVIDENCE.json @@ -0,0 +1,184 @@ +{ + "authenticated_origins": 18, + "boundary": "Exact stored one/two-wire gate cuts, including arbitrary matching subsets; no split-output inverse claim", + "full_words": [ + { + "atoms": 4, + "child_target_bits": 111, + "coefficient_error": "1/8", + "cuts": 61, + "execution_bound": "50566979566069350400", + "gates": 30, + "global_frobenius_certificates": 244, + "label": "n2_nonzero_approximation", + "layers": 21, + "n": 2, + "noncommuting_prefix_controls": 30, + "normalized_suffix_identities": 5, + "proper_partial_cuts": 18, + "rejected_delayed_zero_atoms": 0, + "segments": { + "intervals": 48, + "nonprefix_nested_downsets": 0, + "normalized_product_identities": 192, + "normalized_psd_certificates": 96, + "same_layer_intervals": 45, + "segment_frobenius_certificates": 186, + "wrong_relative_orders": 8 + }, + "simultaneous_nonempty_fragments": 0, + "source_atom_timestamps": [ + [ + "R:0:2", + 0, + 10 + ], + [ + "D:0", + 10, + 11 + ], + [ + "D:1", + 10, + 11 + ], + [ + "L:0:2", + 11, + 21 + ] + ], + "theta": "1/549755813888", + "trace_equalities": 244, + "zero_duration_atoms": 0 + }, + { + "atoms": 10, + "child_target_bits": 154, + "coefficient_error": "10920822045372851498541422188282012939453125/89202980794122492566142873090593446023921664", + "cuts": 821, + "execution_bound": "78397326014400000000000000", + "gates": 318, + "global_frobenius_certificates": 3284, + "label": "n4_asymmetric_zero_atom", + "layers": 189, + "n": 4, + "noncommuting_prefix_controls": 453, + "normalized_suffix_identities": 11, + "proper_partial_cuts": 474, + "rejected_delayed_zero_atoms": 1, + "segments": { + "intervals": 48, + "nonprefix_nested_downsets": 7, + "normalized_product_identities": 192, + "normalized_psd_certificates": 96, + "same_layer_intervals": 240, + "segment_frobenius_certificates": 576, + "wrong_relative_orders": 9 + }, + "simultaneous_nonempty_fragments": 50, + "source_atom_timestamps": [ + [ + "R:0:4", + 0, + 84 + ], + [ + "R:0:2", + 84, + 94 + ], + [ + "D:0", + 94, + 95 + ], + [ + "D:1", + 94, + 95 + ], + [ + "L:0:2", + 95, + 105 + ], + [ + "R:2:4", + 84, + 84 + ], + [ + "D:2", + 84, + 85 + ], + [ + "D:3", + 84, + 85 + ], + [ + "L:2:4", + 85, + 95 + ], + [ + "L:0:4", + 105, + 189 + ] + ], + "theta": "84170560980141162872314453125/713623846352979940529142984724747568191373312", + "trace_equalities": 3284, + "zero_duration_atoms": 1 + } + ], + "negative_controls": [ + "coordinate-write splice is singular; no inverse-cut contract", + "nonunitary compensated bank gates violate a near-one fragment cap", + "nonunitary scalar adjoint is not its stored inverse", + "generic no-loss interpolation rejected; source structure is necessary" + ], + "primitive_words": [ + { + "cap": "2049/2048", + "cuts": 13, + "gates": 6, + "label": "zero_side1", + "layers": 4, + "nonreal_twiddle_inverse_control": "wrong conjugated-twiddle replacement rejected", + "proper_partial_cuts": 4, + "psd_certificates": 52, + "side": 1, + "unitary_gates": 4 + }, + { + "cap": "14339/6144", + "cuts": 61, + "gates": 20, + "label": "dirty_side2", + "layers": 12, + "nonreal_twiddle_inverse_control": "wrong conjugated-twiddle replacement rejected", + "proper_partial_cuts": 40, + "psd_certificates": 244, + "side": 2, + "unitary_gates": 16 + }, + { + "cap": "85519/30720", + "cuts": 61, + "gates": 20, + "label": "complex_side2", + "layers": 12, + "nonreal_twiddle_inverse_control": "wrong conjugated-twiddle replacement rejected", + "proper_partial_cuts": 40, + "psd_certificates": 244, + "side": 2, + "unitary_gates": 16 + } + ], + "scope": "Finite evidence corroborates PROOF.md; phase, rank and conditioning premises remain explicit", + "status": "PASS_SOURCE_ORDERED_FOUR_WAY_CUT_AUDIT" +} diff --git a/research/direct-circulant-production-precision/compiler-intervals/INTEGRATION.md b/research/direct-circulant-production-precision/compiler-intervals/INTEGRATION.md new file mode 100644 index 0000000000..aa11ae7511 --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-intervals/INTEGRATION.md @@ -0,0 +1,45 @@ +# Relative intervals after the published complete-gate result + +The remote base `e040fedfd8fcc51480d2468f3fa07562c8bacbf0` preserves the complete-gate result first published at `0a1c14499407b103ae964f36551b0e9c11400197`. It contains +the accepted complete-gate source theorem under `../compiler-cuts/`. +That entire subtree is retained byte-for-byte. Its proof hash is +`162dd4bb7a020dfb72dd3c80cb9a1de37212cc7f812f36fd4365d487d49b341b`. + +This directory contains a separately frozen recovery proof and review, +relocated by directory name only. Its proof hash is +`e942012e66adc2d696cde3fedd6ae9c73df98e77a71b16e5004f5a74ccdfaa07`. +Result A overlaps the already published complete-gate extension and is +corroborating source context. The additional mathematical claim is Result B: +for nested completed downsets, one common legal linearization cancels the +shared normalized perturbation prefix, giving interval and exact inverse cap +`B^2*H^2/(1-theta)<2*B^2*H^2` instead of the conservative `K_Full^2`. +The later spectral-downset consumer explicitly uses this proof and review. + +Both source constants must satisfy `lambda>=1` and `Q>=1` individually, +as already stated in this frozen proof. Stored inverses, whole-gate cuts, +source conditioning, rank, phase and per-atom coefficient errors retain +their existing meaning. No physical intermediate-output or scratch-state +claim is added. + +Nick Petalas's #5940 (`b709a6adb6a9543247260900b108166a4d469f6f`) already +supplies sharp conditioned matching interpolation and unitary no-loss. +Armin Pourshafeie / apoursh's #5240 +(`6d0a6043120880c696d0850e9242a16e6fb980a5`) already supplies the rounded +event/component-width discussion and singular coordinate-write swap control. +Those results and controls are credited precedents, not new claims here. +Brian/JoyboyBrian's #4755/#4976/#4977 and Nick Petalas's #4852 retain the +distinct attribution recorded in the proof and origin manifest. + +The unchanged `PROOF.md`, `README.md`, author evidence and independent +review retain their historical wording for byte identity. This integration +note supplies the publication chronology and overlap clarification. The +parent replay now runs the added checks in isolated copies and retains all +existing verification methods and published receipts. + +For the remaining implementation boundary, the canonical +`research/integer-rounded-gate` package already supplies Nick Petalas's +once-rounded supplied-coefficient arithmetic construction with +`W=B+4C+2`. Its pinned README is retained as provenance in the parent source +manifest. We do not import or re-audit that proof here. What remains is the +exact caller binding and complete live-word, coefficient-delivery, cleanup, +instruction and tape-cost accounting, not construction of that local kernel. diff --git a/research/direct-circulant-production-precision/compiler-intervals/ORIGINS.json b/research/direct-circulant-production-precision/compiler-intervals/ORIGINS.json new file mode 100644 index 0000000000..d3d018b180 --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-intervals/ORIGINS.json @@ -0,0 +1,167 @@ +{ + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "files": [ + { + "local": "retained/FULL-PROOF.md", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/rational-unitary-fft/FULL-PROOF.md", + "sha256": "acf8c596d91b5efd35a286735d6867ff8afce64354a13f680c2fae3dab824410", + "git_blob": "e650f46863115f810e27b403f916dd7f79b37786", + "bytes": 15002 + }, + { + "local": "retained/GENERATOR-PROOF.md", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/rational-unitary-fft/GENERATOR-PROOF.md", + "sha256": "cddda1f944299a349c837808b349fa6e4499cbb1889f7dacc00ca8afac9b580c", + "git_blob": "8bef383eec887450e86f14365a6f7b07c1310e9d", + "bytes": 9975 + }, + { + "local": "retained/PR4755-README.md", + "repository": "JoyboyBrian/integer-mult-bounds", + "commit": "653289c67733e1b0feb24ddac796003ebb827e55", + "path": "research/full-toeplitz-cut-audit/README.md", + "sha256": "5b514f93ab3b0a37a32978a599d74c545ed19122e235f9cccfff36faefb97a9b", + "git_blob": "f088efaaa828e415db6bb152a8cbeaea1dd68dd7", + "bytes": 10529 + }, + { + "local": "retained/PR4852-README.md", + "repository": "petalas/integer-mult-bounds", + "commit": "8acf04b4c42fe75894a87a3b2d37ddb68e96a798", + "path": "research/downset-block-solve-bound/README.md", + "sha256": "1e59ae73eb142ec3d4579ce98244295b733896afca0fec3693906fc6def26d3f", + "git_blob": "0b753c1b16f0a2977d3aad7242510ba55bec98a0", + "bytes": 11141 + }, + { + "local": "retained/PR4976-README.md", + "repository": "JoyboyBrian/integer-mult-bounds", + "commit": "8a7e0e9b4a085f4fb47a76700dfe135412b9c4ef", + "path": "research/matching-sublayer-norm/README.md", + "sha256": "ba6754f00779874ec981563101114cf18c03026c18338f37a813abd3fae59d21", + "git_blob": "eb7b8be250b6f23ae30e7e611e651a8fe300ac3e", + "bytes": 7062 + }, + { + "local": "retained/PR4977-README.md", + "repository": "JoyboyBrian/integer-mult-bounds", + "commit": "cd30004ff733d4acac45a47a74fc9b1e76ef35e4", + "path": "research/full-downset-allocation/README.md", + "sha256": "fd1f8cade22bc01f981f8855e6b4c0a62996875a007ff8391e258157ce80f56c", + "git_blob": "c5248440b72a566314aa1ba40647d706f2561f96", + "bytes": 8170 + }, + { + "local": "retained/PROOF.md", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/rational-unitary-fft/PROOF.md", + "sha256": "50e31e33e1275a133d10e87208ceb50dddce67d0678d2a89de9f7ba28d8380d9", + "git_blob": "99a55596f67ae3b94ef02ebb159b313f33bf22af", + "bytes": 14204 + }, + { + "local": "retained/SOURCES.json", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/rational-unitary-fft/SOURCES.json", + "sha256": "7324e22bcb202b5cc03b5f7ea713f6f0c7cd80ee60d320fb03b1e2f7b13b8c91", + "git_blob": "7ee22e983f54dfb73e74d20ed1910a64d2abb6cd", + "bytes": 7143 + }, + { + "local": "retained/STEIN-PROVENANCE.json", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/rational-unitary-fft/vendor/STEIN-PROVENANCE.json", + "sha256": "e7f0e8dc517387e302b1e8bf5dff7e12b29da8aa91abc6ea597f33c1ac08ba62", + "git_blob": "c602fb5bb332dbe098950b14d55da05ce2cf4312", + "bytes": 1366 + }, + { + "local": "retained/TRIANGLE-PROOF.md", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/rational-unitary-fft/TRIANGLE-PROOF.md", + "sha256": "abea26e3c86a9970225b070be034c47e7970e10fe1b5686f405e0b301acf3159", + "git_blob": "f923f4ff2dfe40401fa90d83727ade62b2ef5b5f", + "bytes": 10475 + }, + { + "local": "retained/check_circuits.py", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/capped-phase-fusion/evidence/inplace_algebra_ultra/check_circuits.py", + "sha256": "06d1861bfe8af543908e26557ffda7e451ff176bceb9bacfaf0f04f234b336d5", + "git_blob": "f80c141c8116b163c2bb5a028c28212077c8d5a9", + "bytes": 10774 + }, + { + "local": "retained/engine.py", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/rational-unitary-fft/engine.py", + "sha256": "9e36aee0835e6b1b62997433581f88b5a434ccab8ae43e5c25d1deaaf1ebf653", + "git_blob": "e9f2f2b08dc2bc4c646e47dca92059351ca89384", + "bytes": 13174 + }, + { + "local": "retained/exact.py", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/rational-unitary-fft/exact.py", + "sha256": "c9b89d7357210af69865690ba12e695366961f8b501a8fab9d0fefe3fb30c479", + "git_blob": "aae41e6acfb2e5a4fafdd85727891eb746b57b42", + "bytes": 7863 + }, + { + "local": "retained/full.py", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/rational-unitary-fft/full.py", + "sha256": "1f42d5f2858564ffb320e54ba6aa29651025491569823e25006bf5862457b803", + "git_blob": "7f85ad1a89e81b7dfc6b54e7bd9547120e86d5d3", + "bytes": 12561 + }, + { + "local": "retained/generator.py", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/rational-unitary-fft/generator.py", + "sha256": "827ef9fe1bd664859995892b59843c390f7969c938fb7e1e6dc585c31a54b555", + "git_blob": "d761d3c88b1685fb64d92d69f699b8218c9ec30f", + "bytes": 12562 + }, + { + "local": "retained/interval_kernel.py", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/cubic-cyclic-inverse/vendor/interval_kernel.py", + "sha256": "9b7bb24640a9a7d3f83c7951dfef483ec933db4c50de6c0130b85f450eeddfbe", + "git_blob": "1182175a55cb871481de0f56ea9ae56e474705fe", + "bytes": 2363 + }, + { + "local": "retained/stein_rational.py", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/rational-unitary-fft/vendor/stein_rational.py", + "sha256": "3065fc5d6d22ec44de533b08fb0c639603449456383668e561dc46629e641502", + "git_blob": "71b240a460a185ee2fe926cd189b56aeac6f997f", + "bytes": 6045 + }, + { + "local": "retained/triangular.py", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/rational-unitary-fft/triangular.py", + "sha256": "46780d95ddebfed22e8f0c18565fe2e768250afa5beeb31f450292cc06f7ec11", + "git_blob": "2bd8de01a7ac80de7e6b9f8252bc69d0e0a291e8", + "bytes": 10040 + } + ] +} diff --git a/research/direct-circulant-production-precision/compiler-intervals/PROOF.md b/research/direct-circulant-production-precision/compiler-intervals/PROOF.md new file mode 100644 index 0000000000..66b0e093ad --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-intervals/PROOF.md @@ -0,0 +1,353 @@ +# Source-ordered compiler cuts and a smaller interval envelope + +This supplement completes the interrupted audit of the exact stored word used +by the direct-circulant precision application. It is a scoped mathematical +interface result, not a complete multiplier or physical-tape theorem. All +norms below are Euclidean operator norms unless stated otherwise. + +Canonical source: `e54523517d0f03e58352e647c403a5af3e525a57`, +`research/rational-unitary-fft`. Executable bytes, predecessor notes and their +exact origins are authenticated by `ORIGINS.json`. + +## 1. Results, premises and the precise cut boundary + +Let `N=2^d`. Retain the source's admission and coefficient construction: + +* the exact rational reference matrix and every leading section are admitted + with component envelopes `lambda,Q >= 1`; +* `chi=lambda*Q`, every ideal completed-atom downset and its inverse have norm + at most `B=256*N^3*chi^12`; +* the displacement identities, exact generator-rank bound, certified phase + enclosure and coefficient-defect bounds are those of the pinned source; +* each stored atom differs from its ideal endpoint by at most `eta`, and + `theta=(3*N-2)*B^2*eta <= 1/4`; +* inversion uses the exact inverse of the same stored gate coefficients. + +Put `L0=max(1,lambda,Q)` and retain the literal source fragment constant + +``` +rank = 2*d+8 +alpha = 8*rank*N^2*chi +KG = 2*N+64*N^2*chi +Hgen = max(3200*N^3, 2+2*KG)*(10+4*alpha+2*KG) +U = lambda+lambda^2*Q +H = max(Hgen, U+1, 2*Q) +K = 2*L0*B*H. +``` + +**Result A.** At a cut after an arbitrary subset of a matching layer in the +actual stored full compiler word, its prefix, suffix, inverse prefix and +inverse suffix all have norm at most `K`. No extra generic interpolation +factor is needed for this particular source hierarchy. + +**Result B.** For any two ordered such cuts, the intervening exact stored +operator and its inverse have norm at most + +``` +S = B^2*H^2/(1-theta) <= (4/3)*B^2*H^2 < 2*B^2*H^2. +``` + +The convenient rational envelope `2*B^2*H^2` improves the source's generic +`K^2=4*L0^2*B^2*H^2`. It uses a *single consecutive normalized perturbation +product*, not separately bounded approximate endpoints. + +A cut is between whole invertible one- or two-wire mathematical gates. It is +not a cut between writing the two outputs of one gate to physical storage. +For example, the swap matrix is unitary, but overwriting its first coordinate +before computing the second can have intermediate map `[[0,1],[0,1]]`, which +is singular. Nothing here supplies an inverse for that intermediate map or +accounts for its saved temporaries. + +The ideal downset and coefficient/rank/phase hypotheses retain their original +proof obligations and credit. This supplement proves the source-specific +fragment extension and the relative-interval implication; finite replay is +corroboration and source binding, not a universal proof by exhaustion. + +## 2. Every actual primitive fragment has the original cap + +The adapted `engine.Builder` obtains exactly two spectral matchings. Each +cross-bank gate is a lower shear on one source/target pair. Every other gate +is supported entirely in one bank and is exactly unitary, including the +rational FFT butterfly and independently prepared twist entries. For a +partial matching, the product of any selected bank-local gates is still +unitary on its own support with identity elsewhere. + +Write `S(A)=[[I,0],[A,I]]`. For a bank unitary `V=diag(Vx,Vy)`, + +``` +V*S(A)*V^-1 = S(Vy*A*Vx^-1). +``` + +Consider any contiguous primitive gate interval. Move bank unitaries through +shears using this identity. The resulting shear parameter is a sum of at +most two unitary transforms of masked spectral diagonals. Masking a diagonal +cannot increase its norm. The two stored spectral diagonal norms are at most +`Mg+v` and `Mh+v`, so the interval is a bank-unitary product times a shear +whose parameter has norm at most `Mg+Mh+2*v`. Since +`||S(A)||,||S(A)^-1|| <= 1+||A||`, every interval and its inverse satisfy + +``` +Hprimitive = 1+Mg+Mh+2*v. +``` + +This proves all four fragment bounds at arbitrary matching subsets with the +original constant. It uses the actual spectral orientation and exact bank +unitarity; it is false for general compensated nonunitary bank changes. +Conjugating just the twiddle of a complex butterfly also does not in general +produce that butterfly's inverse: the full gate order and adjoint are needed. + +This is the source-structure route suggested by the open child-fragment +question in Brian/JoyboyBrian's #4755. His #4976 establishes a valid generic +`sqrt(2)` interpolation loss, including sharp examples. We do not claim that +generic result can be improved to one. + +## 3. The parity child retains its original cap at matching subsets + +The pinned `triangular.Triangle` composes equal-size sibling programs through +`parallel`, and explicitly checks their macro `(start,stop)` partitions agree. +At a given macro fragment, sibling pieces are therefore a direct sum. Each +shear piece is exactly the primitive of Section 2, with the admitted +`Mg+Mh+2*v <= 6`; all its four fragments have norm at most seven. A stored +scalar leaf and its reciprocal have norm at most four; a selected subset of +disjoint leaves has the maximum of its selected scalar norms and one. + +For completeness, the retained macro perturbation step is as follows. If +`A_j` are ideal macros, `Q_j=A_j...A_1`, and +`G_j=Q_j^-1*(Ahat_j-A_j)*Q_(j-1)`, then + +``` +Z_j = Q_j^-1*Qhat_j = (I+G_j)*Z_(j-1). +``` + +With the source ideal prefix/inverse-prefix bound `Btri=100*m^3` and its +allocated sum of defect bounds at most `1/4`, every consecutive product of +`I+G_j`, and its inverse, has norm less than two. Thus stored completed +prefixes and inverse prefixes have cap `2*Btri`; suffixes and inverse +suffixes have cap `4*Btri`, using the ideal whole endpoint and inverse cap +two. Combining a matching-subset fragment cap seven with those checkpoint +bounds gives at most `28*Btri < 32*Btri = 3200*m^3` in all four cases. + +The near-identity admission, ideal macro bound and local coefficient-error +inequalities are retained from Jose Manuel's `TRIANGLE-PROOF.md`; no new +claim about arbitrary matrices satisfying only whole-matrix conditioning is +made. The point proved here is that the actual primitive and scalar pieces +support the same numerical constant at the additional matching-subset cuts. + +## 4. The bounded-generator child also retains its cap + +One generator term uses the source order + +``` +P; S(G); P^-1; S(-G), +``` + +with the same stored `Phat`, its exact stored inverse, and compensation built +by negating the same stored spectral multipliers in their original order. +Let `p=Phat`, `h=Ghat`, `a=alpha+1`, `k=KG+1`. Here `A` is the sum of +stored completed term operators strictly before the current term, and `C` +is the sum of the current term plus all later stored completed term +operators, measured before the current term starts. Thus the full stored +endpoint is `S(A+C)`. The retained construction ensures `||p||<=2`, +`||p^-1||<=4`, `||h||<=k`, and both of these term sums have norm at most `a`. + +Writing `L(B,D)=[[B,0],[D,I]]`, the four checkpoint prefixes have forms + +``` +L(p,A), L(p,A+h*p), S(A+h*p), S(A+h*(p-I)), +``` + +and the four remaining suffixes have forms + +``` +L(p^-1,C*p^-1), L(p^-1,C*p^-1-h), +S(C-h*p), S(C-h*(p-I)). +``` + +Use `L(B,D)^-1=L(B^-1,-D*B^-1)`. Direct substitution bounds every listed +operator and inverse by `4+4*a+2*k = 10+4*alpha+2*KG`. The final checkpoint +uses the bound for a complete term sum. No commutation of `p,h,A,C` is used. + +Inside one of the four calls, Section 3 bounds the triangular fragments by +`3200*m^3`; Section 2 bounds a scaled shear and its compensation fragments by +`2+2*KG`. Multiplying one fragment bound and one checkpoint bound proves + +``` +Hgenerator = max(3200*m^3,2+2*KG)*(10+4*alpha+2*KG) +``` + +at arbitrary matching subsets. A zero-rank generator emits no layers and is +an identity atom, with no unfinished fragment. The exact generator identity, +the additive endpoint defect, and its preparation/rank admission remain +the credited predecessor results. + +## 5. Source-time downsets and the four full-word cuts + +Use the source atom DAG: upper shear, both child programs, lower shear; a +leaf is one scalar. Incomparable atoms have disjoint logical intervals, +regardless of physical wire names. Upper atoms finish before descendants +start, and lower atoms start after every descendant finishes. + +At a cut in matching layer `k`, before choosing its gate subset, classify + +``` +I = {atoms with stop <= k} +A = {atoms with start <= k < stop}. +``` + +The source timestamps include zero-duration identity atoms at their actual +position. Both `I` and `I union A` are downsets; members of `A` are pairwise +incomparable. A fragment may be empty or already contain the whole last +matching layer, which does not invalidate this convention. + +For each active atom split its exact stored endpoint as `Ahat_a=T_a*F_a`. +Brian's #4755 trace argument, applied to these actual timestamps and local +plans, gives the exact identities + +``` +Cprefix = F*Qhat(I), Csuffix = Rhat*T +Cprefix^-1 = Qhat(I)^-1*F^-1 +Csuffix^-1 = T^-1*Rhat^-1, +``` + +where `F,T` are direct sums of the active prefixes and tails with identity +elsewhere, and `Rhat` is the product of unstarted endpoints. Only disjoint +work moves past an active fragment. In particular `F*Qhat(I)` cannot be +replaced by `Qhat(I)*F`. + +Sections 2–4, and the stored scalar margin `|ahat|>=1/(2*Q)`, prove the +direct/inverse cap `H` for `F,T`. The number of active atoms introduces no +factor: a direct sum has the maximum of its blocks' spectral norms. + +In a legal atom linearization extending `I`, normalized perturbation gives +completed prefix/inverse-prefix caps `2*B`. Extending `I union A` first +gives remaining endpoint/inverse endpoint caps `2*L0*B`. These are the +predecessor's standard consecutive-product estimates, rederived in Section 6. +Multiplication proves Result A. Unequal sibling durations and simultaneous +nonempty fragments require no aligned full-compiler macro boundaries. + +## 6. Nested downsets give the stronger interval bound + +Take two source-ordered cuts `u<=v`, with completed sets `Iu,Iv`. Then +`Iu subset Iv`. A finite DAG admits a topological order listing `Iu` first, +then `Iv minus Iu`, then the complement: every predecessor of a member of a +downset is in that downset. Stored endpoints of incomparable atoms commute, +so products computed with this legal order agree with the source products. + +Write `Q_j=A_j...A_1`, `Qhat_j=Ahat_j...Ahat_1`. For this single order, + +``` +G_j = Q_j^-1*(Ahat_j-A_j)*Q_(j-1) +Z_j = Q_j^-1*Qhat_j +Z_j = (I+G_j)*Z_(j-1) +sum_j ||G_j|| <= theta. +``` + +If `i=|Iu|` and `j=|Iv|`, cancellation gives, in the stated order, + +``` +W = Z_j*Z_i^-1 = (I+G_j)...(I+G_(i+1)) +Qhat_j*Qhat_i^-1 = Q_j*W*Q_i^-1. +``` + +Let `g_l=||G_l||`. For a consecutive product, + +``` +||W|| <= product_l(1+g_l) <= 1/(1-sum_l g_l), +||W^-1|| <= product_l(1-g_l)^-1 <= 1/(1-sum_l g_l). +``` + +The first scalar inequality follows by comparing the finite product's +elementary symmetric sums with the geometric series in `sum g_l`; the +second uses `product(1-g_l)>=1-sum g_l`. Every `g_l<1` because their sum +is at most `theta<=1/4`. The inverse factors are genuine Neumann inverses. +Thus both norms are at most `1/(1-theta)`. Since ideal prefixes correspond +to downsets, `||Q_i^±1||,||Q_j^±1||<=B`, and + +``` +||Qhat_j*Qhat_i^-1||, ||Qhat_i*Qhat_j^-1|| + <= B^2/(1-theta). +``` + +Now use the two actual cut factorizations from Section 5. The segment is + +``` +C(v)*C(u)^-1 = Fv * Qhat(Iv)*Qhat(Iu)^-1 * Fu^-1. +``` + +The inverse reverses this order. Both boundary fragment factors have norm +at most `H`, proving Result B. No ideal *whole* endpoint enters this +argument. This is why the old extra `L0^2` is unnecessary for relative +intervals. The proof also covers identical completed sets, empty fragments, +zero-duration calls and final/root cuts. + +## 7. Consequence for the unchanged direct-circulant word + +The parent precision proof already establishes + +``` +B <= 2^68*t^39, H <= 2^26*t^11, K <= 2^98*t^52 +``` + +for one padded root of width `t>=2`. Therefore the new result gives + +``` +every original one/two-wire gate and its inverse <= 2^189*t^100, +``` + +because such a gate is a segment between adjacent source cuts. The prior +application used `K^2 <= 2^196*t^104`. This is an improved sufficient +envelope for the **unchanged stored word**; it does not change coefficient +construction, the source allocator or the operation count. A later selector +revision must propagate this bound through all sixteen-H lowering, routing, +tensor, cache and bootstrap terms and receive its own review. + +## 8. Exact finite evidence and failure detection + +`audit.py` imports authenticated source *factories* but uses a separate +Gaussian-rational representation, matrix multiplication, elimination, +Hermitian PSD test, predecessor reconstruction and cut oracle. It does not +call the source matrix/inverse helpers to establish the checked identities. +The compiler itself necessarily uses its retained exact arithmetic. + +The recovered baseline covers 135 primitive cuts and 540 exact PSD +certificates, plus 882 full-word cuts and 3,528 four-way trace equalities. +The asymmetric size-four word contains a zero-duration upper atom, 50 cuts +with simultaneous nonempty fragments and reversed physical wire order. +The source atom coefficient defects and forward/stored-inverse endpoints +are checked separately. Full-word norm checks use a deliberately conservative +Frobenius consequence and do not infer the universal spectral theorem. + +Controls reject a delayed zero-duration predecessor, the wrong prefix order, +a conjugated-twiddle replacement for a complex inverse, a scalar adjoint in +place of its reciprocal, a singular coordinate-write splice, compensated +nonunitary bank changes and generic loss-free matching interpolation. + +The source phase and generator/rank semantics are retained dependencies; +the checker is not an independent transcendental oracle, an all-size source +operational semantics proof or a physical bit-cost implementation. + +## Open next questions + +1. Independently review the numerical child-fragment bridge and the two-cut + normalized-product identity, particularly inverse order and same-layer cuts. +2. Propagate the new gate envelope through the complete explicit numerical + selector while retaining every rounding and private native-service premise. +3. Nick Petalas's #4852 and Brian's #4977 supply a smaller ideal downset + envelope. Can it be applied to this unchanged, already overprecise stored + word without modifying its allocation or silently changing source pins? +4. Join the exact mathematical cut theorem to actual physical output-write + temporaries and coded-field movement. This audit does not price those cuts. + +## Credit and status + +Jose Manuel (`jmbarrancoml`) supplied the rational full/parity/generator +compiler and polynomial precision analysis; Vlado Vojdanovski supplied the +recursive and displacement constructions; Chafik Boukhalfa supplied certified +phases. Brian/JoyboyBrian supplied #4755's source-time trace audit and #4976's +generic matching interpolation; Nick Petalas supplied #4852's block-solve +downset improvement, used by Brian's #4977. Ali Romman supplied the direct +circulant application. Their frozen sources and original notices remain +unchanged. Prepared for Jerry Chen / `@CubeJerry` with substantial OpenAI +assistance. This author-stage audit awaits separate model-assisted review; +neither human review nor formal-kernel acceptance is claimed. All five +canonical assumptions and the selected kappa remain unchanged. diff --git a/research/direct-circulant-production-precision/compiler-intervals/README.md b/research/direct-circulant-production-precision/compiler-intervals/README.md new file mode 100644 index 0000000000..0caff5e48c --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-intervals/README.md @@ -0,0 +1,53 @@ +# Audit actual compiler cuts and cancel shared perturbations across intervals + +This follow-up to #8093 completes a recovered source audit and adds one +relative-interval lemma. The actual rational FFT, parity, generator and full +compiler hierarchy retains its original four-way cut envelope at arbitrary +subsets of a matching layer. The argument uses exact bank unitarity and the +source's disjoint-support recursion, with explicit zero-duration atoms and +same-stored inverse coefficients. + +For the retained ideal-downset bound `B`, fragment bound `H` and normalized +perturbation spend `theta<=1/4`, any stored interval and its inverse have norm +at most + +``` +B^2*H^2/(1-theta) < 2*B^2*H^2. +``` + +The predecessor's generic prefix-quotient bound is +`4*L0^2*B^2*H^2`. The reduction comes from a common legal linearization of two +nested completed downsets and one consecutive normalized error product. It +does not assume that approximate scalar or shear gates are unitary, or replace +an inverse with an adjoint. + +For the unchanged direct-circulant word, the permitted original gate envelope +improves from `2^196*t^104` to `2^189*t^100`. The published production selector +is unchanged in this supplement. Its full error accounting remains valid, and +a further selector revision needs separate complete propagation and review. + +The universal argument is in [PROOF.md](PROOF.md). `audit.py` executes retained +source factories with independent exact matrix and PSD oracles; its bounded +coverage is recorded in `EVIDENCE.json`. It runs offline with Python 3.12 and +the standard library: + +```sh +python3 -I -W error -B audit.py +``` + +Expected marker: `PASS_SOURCE_ORDERED_FOUR_WAY_CUT_AUDIT`. The checker uses +explicit exceptions, so the same audit remains active with `-O`. + +Brian/JoyboyBrian's #4755 has priority for the asynchronous cut factorization; +his #4976 supplies the generic interpolation theorem. Jose Manuel supplied +the full rational compiler and numerical hierarchy, with Vlado's recursive +construction and Chafik's certified phases. Nick Petalas's #4852 and Brian's +#4977 are retained as prospective sharpening references, not newly claimed +results. Ali Romman supplied the direct-circulant consumer. Complete source +pins are in `ORIGINS.json` and the original files/notices remain unchanged. + +This is local numerical-interface progress with retained phase, rank, +conditioning, coefficient and native-service premises. No physical output +write/storage tariff, selected assumption removal or new kappa is claimed. +Prepared for Jerry Chen / `@CubeJerry` with substantial OpenAI assistance; +independent human or formal-kernel acceptance is not claimed. diff --git a/research/direct-circulant-production-precision/compiler-intervals/audit.py b/research/direct-circulant-production-precision/compiler-intervals/audit.py new file mode 100644 index 0000000000..34c83b161b --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-intervals/audit.py @@ -0,0 +1,638 @@ +#!/usr/bin/env python3 +"""Independent rational audit of exact stored compiler cuts. + +Actual source factories build the words. Matrix arithmetic, inverses, PSD +certificates, ownership/cut reconstruction and failure controls below are +independent of their exact.py matrix helpers and predecessor verifiers. +""" + +from dataclasses import dataclass +from fractions import Fraction as Q +from hashlib import sha256 +from itertools import combinations +from pathlib import Path +import json +import sys +import types + +HERE = Path(__file__).resolve().parent +RET = HERE/'retained' + + +def need(ok, why): + if not ok: + raise ValueError(why) + + +@dataclass(frozen=True) +class Z: + re: Q = Q(0) + im: Q = Q(0) + + @staticmethod + def get(x): + if isinstance(x, Z): + return x + if hasattr(x, 're') and hasattr(x, 'im'): + return Z(Q(x.re), Q(x.im)) + return Z(Q(x)) + + def __add__(self, other): + other = Z.get(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.get(other) + + def __rsub__(self, other): + return Z.get(other)+-self + + def __mul__(self, other): + other = Z.get(other) + return Z(self.re*other.re-self.im*other.im, + self.re*other.im+self.im*other.re) + + __rmul__ = __mul__ + + def bar(self): + return Z(self.re, -self.im) + + def norm2(self): + return self.re*self.re+self.im*self.im + + def __truediv__(self, other): + other = Z.get(other) + norm = other.norm2() + need(norm > 0, 'Independent zero divisor') + numerator = self*other.bar() + return Z(numerator.re/norm, numerator.im/norm) + + def __bool__(self): + return bool(self.re or self.im) + + +def matrix(a): + return [[Z.get(x) for x in row] for row in a] + + +def ident(n): + return [[Z(Q(i == j)) for j in range(n)] for i in range(n)] + + +def adjoint(a): + return [[a[j][i].bar() for j in range(len(a))] for i in range(len(a[0]))] + + +def multiply(a, b): + need(len(a[0]) == len(b), 'Independent matrix dimensions') + out = [[Z() for _ in b[0]] for _ in a] + for i, row in enumerate(a): + for k, x in enumerate(row): + if x: + for j, y in enumerate(b[k]): + if y: + out[i][j] = out[i][j]+x*y + return out + + +def subtract(a, b): + return [[x-y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)] + + +def inverse(a): + n = len(a) + rows = [list(row)+unit for row, unit in zip(a, ident(n))] + for j in range(n): + pivot = next((k for k in range(j, n) if rows[k][j]), None) + need(pivot is not None, 'Independent singular matrix') + rows[j], rows[pivot] = rows[pivot], rows[j] + v = rows[j][j] + rows[j] = [x/v for x in rows[j]] + for i in range(n): + if i != j and rows[i][j]: + v = rows[i][j] + rows[i] = [x-v*y for x, y in zip(rows[i], rows[j])] + return [row[n:] for row in rows] + + +def psd(a): + need(a == adjoint(a), 'Hermitian PSD input') + a = [list(row) for row in a] + for k in range(len(a)): + diagonal = a[k][k] + if diagonal.im or diagonal.re < 0: + return False + if not diagonal: + if any(a[k][j] for j in range(k+1, len(a))): + return False + continue + for i in range(k+1, len(a)): + for j in range(k+1, len(a)): + a[i][j] = a[i][j]-a[i][k]*a[k][j]/diagonal + return True + + +def norm_at_most(a, cap): + gram = multiply(adjoint(a), a) + margin = [[Z(cap*cap if i == j else 0)-x for j, x in enumerate(row)] + for i, row in enumerate(gram)] + return psd(margin) + + +def frobenius2(a): + return sum((x.norm2() for row in a for x in row), Q(0)) + + +def embed(a, ids, n): + out = ident(n) + for i, old_i in enumerate(ids): + for j, old_j in enumerate(ids): + out[old_i][old_j] = a[i][j] + return out + + +def convert_plan(plan, n): + out = [] + for layer in plan: + used, row = set(), [] + for ids, gate in layer: + ids = tuple(ids) + need(len(set(ids)) == len(ids) and not used.intersection(ids), 'Actual matching supports') + need(all(0 <= i < n for i in ids), 'Actual gate wires') + used.update(ids) + row.append((ids, matrix(gate))) + out.append(row) + return out + + +def product(plan, n): + out = ident(n) + for layer in plan: + for ids, gate in layer: + out = multiply(embed(gate, ids, n), out) + return out + + +def boundaries(plan, n): + prefixes, prefix_inverses = [ident(n)], [ident(n)] + for layer in plan: + p, pi = prefixes[-1], prefix_inverses[-1] + for ids, gate in layer: + p = multiply(embed(gate, ids, n), p) + pi = multiply(pi, embed(inverse(gate), ids, n)) + prefixes.append(p) + prefix_inverses.append(pi) + suffixes, suffix_inverses = [None]*(len(plan)+1), [None]*(len(plan)+1) + suffixes[-1], suffix_inverses[-1] = ident(n), ident(n) + for k in range(len(plan)-1, -1, -1): + g = product([plan[k]], n) + gi = inverse(g) + suffixes[k] = multiply(suffixes[k+1], g) + suffix_inverses[k] = multiply(gi, suffix_inverses[k+1]) + return prefixes, prefix_inverses, suffixes, suffix_inverses + + +def cuts(plan, n): + pre, pri, suf, sui = boundaries(plan, n) + for k, layer in enumerate(plan): + for mask in range(1 << len(layer)): + yes = [gate for j, gate in enumerate(layer) if mask >> j & 1] + no = [gate for j, gate in enumerate(layer) if not mask >> j & 1] + h, rest = product([yes], n), product([no], n) + yield (k, mask, multiply(h, pre[k]), multiply(pri[k], inverse(h)), + multiply(suf[k+1], rest), multiply(inverse(rest), sui[k+1])) + yield len(plan), 0, pre[-1], pri[-1], ident(n), ident(n) + + +def load_source(): + origins = json.loads((HERE/'ORIGINS.json').read_text()) + for row in origins['files']: + need(sha256((HERE/row['local']).read_bytes()).hexdigest() == row['sha256'], + 'Pinned source SHA-256: '+row['local']) + modules = {} + for name in ('exact', 'engine', 'triangular', 'generator', 'full'): + m = types.ModuleType(name) + m.__file__ = str(RET/(name+'.py')) + sys.modules[name] = m + exec(compile((RET/(name+'.py')).read_bytes(), m.__file__, 'exec', optimize=0), m.__dict__) + modules[name] = m + gen = modules['generator'] + raw = {gen.SOURCE+'check_circuits.py': (RET/'check_circuits.py').read_bytes(), + gen.ORACLE: (RET/'interval_kernel.py').read_bytes(), + gen.PRODUCER: (RET/'stein_rational.py').read_bytes(), + gen.PROVENANCE: (RET/'STEIN-PROVENANCE.json').read_bytes()} + return modules, raw, len(origins['files']) + + +def source_value(z, source): + z = Z.get(z) + return source.C(z.re, z.im) + + +def primitive_fixture(values, modules, raw, label): + exact, engine, gen = (modules[n] for n in ('exact', 'engine', 'generator')) + values = matrix(values) + n = len(values) + source_matrix = exact.Mat([[source_value(x, exact) for x in row] for row in values]) + # These are actual certified source words at a bounded declared precision. + phases = engine.Phases(12, raw[gen.ORACLE]) + builder = engine.Builder(phases, 12, raw[gen.SOURCE+'check_circuits.py']) + plan = convert_plan(builder.plan(source_matrix), 2*n) + # Exercise the nonreal butterfly twiddle site directly, even when this + # bounded whole fixture only needs smaller FFTs. + w=phases.phase(8,1) + butterfly=matrix(builder.butterfly(w)) + wrong_inverse=matrix(builder.butterfly(w.conjugate())) + need(multiply(adjoint(butterfly),butterfly)==ident(2), 'Nonreal rational butterfly is unitary') + need(multiply(wrong_inverse,butterfly)!=ident(2), 'Conjugating only the twiddle is not inversion') + mg, mh = builder.bounds + cap = 1+mg+mh+Q(2, 1 << 12) + spectral_layers, unitary_gates = [], 0 + for k, layer in enumerate(plan): + crossings = [] + for ids, gate in layer: + crossing = len(ids) == 2 and ids[0] < n <= ids[1] + if crossing: + need(gate[0][0] == Z(Q(1)) and gate[1][1] == Z(Q(1)) and not gate[0][1], + 'Actual crossing is one oriented shear') + crossings.append((ids, gate)) + else: + need(all(i < n for i in ids) or all(i >= n for i in ids), 'Actual bank-local support') + need(multiply(adjoint(gate), gate) == ident(len(gate)), 'Exact unitary bank gate') + unitary_gates += 1 + if crossings: + need(len(crossings) == n and len(crossings) == len(layer), 'Complete one-to-one spectral matching') + spectral_layers.append(k) + need(len(spectral_layers) == 2, 'Exactly two spectral sweeps') + count, partial, norm_checks = 0, 0, 0 + endpoint = product(plan,2*n) + for k, mask, p, pi, s, si in cuts(plan, 2*n): + count += 1 + partial += k < len(plan) and mask not in (0, (1 << len(plan[k]))-1) + for a in (p, pi, s, si): + need(norm_at_most(a, cap), 'Actual primitive four-way cut bound') + norm_checks += 1 + need(multiply(pi, p) == ident(2*n) and multiply(s, p) == endpoint, + 'Independent primitive inverse and concatenation') + return dict(label=label,side=n,layers=len(plan),gates=sum(map(len,plan)),cuts=count, + proper_partial_cuts=partial,psd_certificates=norm_checks, + unitary_gates=unitary_gates,cap=str(cap), + nonreal_twiddle_inverse_control='wrong conjugated-twiddle replacement rejected') + + +def atom_ideal(atom, n): + ids = atom['indices'] + a = matrix(atom['ideal']) + if atom['kind'] == 'leaf': + return embed(a, ids, n) + m = len(a) + local = ident(2*m) + for i in range(m): + for j in range(m): + local[m+i][j] = a[i][j] + return embed(local, ids, n) + + +def atom_prefix(atom, k, selected, n): + local = atom['converted'] + j = k-atom['start'] + out = atom['prefixes'][j] + for ids, gate in selected: + if set(ids).issubset(atom['indices']): + # Global coordinates are retained in every atom's converted plan. + out = multiply(embed(gate, ids, n), out) + return out + + +def timing_predecessors(atoms,depth): + predecessors=[set() for _ in atoms] + for i,a in enumerate(atoms): + need(0<=a['start']<=a['stop']<=depth, 'Source timestamp domain') + lo,hi=a['interval'] + descendants=[j for j,b in enumerate(atoms) + if (lo,hi)!=tuple(b['interval']) and lo<=b['interval'][0] 1): + by_layer[k] = row + layers = sorted(by_layer) + selected = sorted({layers[(j*(len(layers)-1))//17] for j in range(18)}) + chosen = [by_layer[k] for k in selected] + pairs = {(i,i+1) for i in range(len(chosen)-1)} + pairs |= {(0,j) for j in range(2,len(chosen))} + pairs |= {(i,len(chosen)-1) for i in range(1,len(chosen)-2)} + counts = dict(intervals=0, normalized_product_identities=0, + normalized_psd_certificates=0, segment_frobenius_certificates=0, + nonprefix_nested_downsets=0, wrong_relative_orders=0, + same_layer_intervals=0) + gamma = 1/(1-theta) + cap = 2*b*b*h*h + for iu,iv in sorted(pairs): + left,right = chosen[iu],chosen[iv] + u,v = left['layer'],right['layer'] + need(u>bit&1)] + tail=[g for bit,g in enumerate(plan[v]) if right['mask']>>bit&1] if v1}) + same_layers=sorted({same_layers[(j*(len(same_layers)-1))//11] + for j in range(12)}) if same_layers else [] + for k in same_layers: + group={row['mask']:row for row in records if row['layer']==k} + for m1,left in group.items(): + for m2,right in group.items(): + if m1==m2 or m1&m2!=m1: + continue + need(left['completed']==right['completed'], 'Same layer retains one completed downset') + added=[g for bit,g in enumerate(plan[k]) if (m2^m1)>>bit&1] + actual=product([added],n) + need(actual==multiply(right['fragments'],inverse(left['fragments'])), + 'Same-layer interval is the relative active fragment') + need(actual==multiply(right['prefix'],inverse(left['prefix'])), + 'Same-layer actual interval cancels the shared completed prefix') + for op in (actual,inverse(actual)): + need(frobenius2(op)<=cap*cap, 'Same-layer segment envelope') + counts['segment_frobenius_certificates']+=1 + counts['same_layer_intervals']+=1 + return counts + + +def full_fixture(values, modules, raw, label, reverse=False): + exact, full = modules['exact'], modules['full'] + values = matrix(values) + n = len(values) + source_matrix = exact.Mat([[source_value(x, exact) for x in row] for row in values]) + lam, q, _ = full.admission(source_matrix) + # Independently check the leading solves and component envelopes used by + # the source allocation. No computed whole-inverse bound is substituted. + for size in range(1,n+1): + a = [row[:size] for row in values[:size]] + ai = inverse(a) + need(multiply(a, ai) == ident(size), 'Independent leading-section inverse') + component = max(max(sum(abs(x.re)+abs(x.im) for x in row) for row in ai), + max(sum(abs(x.re)+abs(x.im) for x in col) for col in zip(*ai))) + need(component <= q, 'Admitted component inverse envelope') + bound = full.allocation(n, lam, q, 1, 1, 0) + compiler = full.Full(bound, raw) + ids = list(reversed(range(n))) if reverse else list(range(n)) + source_plan = compiler.plan(source_matrix, ids) + plan = convert_plan(source_plan, n) + target = embed(values, ids, n) + atoms = [dict(a) for a in source_plan.atoms] + predecessors=timing_predecessors(atoms,len(plan)) + for a in atoms: + mapping = a['indices'] + local = [[(tuple(mapping[i] for i in js), matrix(g)) for js,g in layer] + for layer in a['local_plan']] + need(len(local) == a['stop']-a['start'], 'Source atom duration') + a['converted'] = local + a['prefixes'] = boundaries(local,n)[0] + a['stored'] = a['prefixes'][-1] + a['ideal_global'] = atom_ideal(a,n) + need(norm_at_most(subtract(a['stored'], a['ideal_global']), bound['eta']), + 'Actual atom coefficient defect including same stored inverse') + # Literal ownership binds timestamps to every lowered source instruction. + for k, layer in enumerate(plan): + for ids0, gate in layer: + owners = [a for a in atoms if a['start'] <= k < a['stop'] and set(ids0).issubset(a['indices'])] + need(len(owners) == 1, 'Exactly one active source atom owns each gate') + a = owners[0] + need((ids0,gate) in a['converted'][k-a['start']], 'Exact source-owned gate and local timestamp') + ideal_endpoint = ident(n) + stored_endpoint = ident(n) + for a in atoms: + ideal_endpoint = multiply(a['ideal_global'],ideal_endpoint) + stored_endpoint = multiply(a['stored'],stored_endpoint) + need(ideal_endpoint == target, 'Independent complete ideal atomic product') + need(stored_endpoint == product(plan,n), 'Source linearization equals lowered stored endpoint') + stored_inverse = product(convert_plan(compiler.inverse(source_plan),n),n) + need(stored_inverse == inverse(stored_endpoint), 'Literal same-stored inverse word') + + # Independent noncommutative normalized-defect recurrence and suffix + # cancellation; no product of separately bounded approximate prefixes. + ideal_prefix,stored_prefix,z=ident(n),ident(n),ident(n) + normalized=[z] + for a in atoms: + previous=ideal_prefix + ideal_prefix=multiply(a['ideal_global'],ideal_prefix) + stored_prefix=multiply(a['stored'],stored_prefix) + g=multiply(multiply(inverse(ideal_prefix),subtract(a['stored'],a['ideal_global'])),previous) + factor=[[g[i][j]+int(i==j) for j in range(n)] for i in range(n)] + z=multiply(factor,z) + need(z==multiply(inverse(ideal_prefix),stored_prefix), 'Normalized perturbation recurrence') + normalized.append(z) + normalized_suffix_checks=0 + for j in range(len(atoms)+1): + qj=ident(n);hatqj=ident(n);rest=ident(n) + for a in atoms[:j]: + qj=multiply(a['ideal_global'],qj);hatqj=multiply(a['stored'],hatqj) + for a in atoms[j:]: + rest=multiply(a['stored'],rest) + interaction_tail=multiply(normalized[-1],inverse(normalized[j])) + need(multiply(multiply(target,interaction_tail),inverse(qj))==rest, + 'Consecutive normalized suffix identity') + need(multiply(stored_endpoint,inverse(hatqj))==rest, 'Stored suffix cancellation') + normalized_suffix_checks+=1 + + b,h,kphys,l0 = (bound['completed_prefix_bound'],bound['fragment_bound'], + bound['execution_bound'],max(Q(1),lam,q)) + need(kphys == 2*l0*b*h, 'Literal physical-cut constant') + counts = dict(cuts=0,proper_partial_cuts=0,simultaneous_nonempty_fragments=0, + trace_equalities=0,global_frobenius_certificates=0,noncommuting_prefix_controls=0) + records=[] + for k, mask, p, pi, s, si in cuts(plan,n): + selected = [g for j,g in enumerate(plan[k]) if mask >> j & 1] if k < len(plan) else [] + completed = [a for a in atoms if a['stop'] <= k] + active = [a for a in atoms if a['start'] <= k < a['stop']] + remaining = [a for a in atoms if a not in completed and a not in active] + completed_ids={j for j,a in enumerate(atoms) if a['stop']<=k} + for j,a in enumerate(atoms): + if a in completed or a in active: + need(predecessors[j].issubset(completed_ids), 'Completed/active source downset') + used = [i for a in active for i in a['indices']] + need(len(used)==len(set(used)), 'Active source atom supports are disjoint') + qhat, rem, fragments, tails = ident(n),ident(n),ident(n),ident(n) + for a in completed: + qhat = multiply(a['stored'],qhat) + for a in remaining: + rem = multiply(a['stored'],rem) + nonempty=0 + for a in active: + f = atom_prefix(a,k,selected,n) + t = multiply(a['stored'],inverse(f)) + fragments=multiply(f,fragments); tails=multiply(t,tails) + nonempty += f!=ident(n) and t!=ident(n) + need(multiply(fragments,qhat)==p, 'Exact active-prefix trace identity') + need(multiply(rem,tails)==s, 'Exact active-suffix trace identity') + need(multiply(inverse(qhat),inverse(fragments))==pi, 'Prefix inverse order') + need(multiply(inverse(tails),inverse(rem))==si, 'Suffix inverse order') + if multiply(qhat,fragments)!=p: + counts['noncommuting_prefix_controls']+=1 + for a in (p,pi,s,si): + need(frobenius2(a)<=kphys*kphys, 'Independent conservative Full spectral consequence') + counts['global_frobenius_certificates']+=1 + counts['cuts']+=1 + counts['proper_partial_cuts']+=k=2 + counts['trace_equalities']+=4 + records.append(dict(layer=k,mask=mask,completed=completed_ids, + stored_completed=qhat,fragments=fragments,prefix=p)) + need(norm_at_most(subtract(stored_endpoint,target),bound['coefficient_error']), 'Accumulated forward atom error') + need(norm_at_most(subtract(stored_inverse,inverse(target)),bound['coefficient_error']), 'Accumulated inverse atom error') + zero_controls=0 + for j,a in enumerate(atoms): + if a['start']!=a['stop']: + continue + mutated=[dict(row) for row in atoms] + mutated[j]['start']+=1;mutated[j]['stop']+=1 + try: + timing_predecessors(mutated,len(plan)) + except ValueError: + zero_controls+=1 + if any(a['start']==a['stop'] for a in atoms): + need(zero_controls>0, 'Delayed zero-duration source predecessor must reject') + intervals=segment_checks(plan,atoms,predecessors,records,n,b,h,bound['theta']) + return dict(label=label,n=n,layers=len(plan),gates=sum(map(len,plan)),atoms=len(atoms), + zero_duration_atoms=sum(a['start']==a['stop'] for a in atoms), + source_atom_timestamps=[(a['id'],a['start'],a['stop']) for a in atoms], + child_target_bits=bound['child_target_bits'],theta=str(bound['theta']), + coefficient_error=str(bound['coefficient_error']),execution_bound=str(kphys), + normalized_suffix_identities=normalized_suffix_checks, + rejected_delayed_zero_atoms=zero_controls,segments=intervals,**counts) + + +def controls(): + out=[] + # A whole unitary gate can have a singular intermediate coordinate write. + swap=matrix([[0,1],[1,0]]) + partial=matrix([[0,1],[0,1]]) + need(norm_at_most(swap,1) and not norm_at_most(partial,1), 'Split-write norm control') + try: + inverse(partial) + except ValueError: + out.append('coordinate-write splice is singular; no inverse-cut contract') + else: + raise ValueError('Singular intermediate write accepted') + # Endpoint restoration alone cannot bound fragments. + shrink=matrix([[Q(1,2),0],[0,1]]) + need(multiply(inverse(shrink),shrink)==ident(2) and not norm_at_most(inverse(shrink),Q(3,2)), + 'Missing exact-unitarity control') + out.append('nonunitary compensated bank gates violate a near-one fragment cap') + # Reusing an adjoint instead of the stored inverse breaks a nonunit pivot. + scalar=matrix([[Q(3,2)]]) + need(multiply(inverse(scalar),scalar)==ident(1) and multiply(adjoint(scalar),scalar)!=ident(1), + 'Stored inverse versus adjoint') + out.append('nonunitary scalar adjoint is not its stored inverse') + # The generic zero-loss adjacent-boundary interpolation rule is false. + p0=matrix([[6,0],[1,Q(1,6)]]) + p1=multiply(matrix([[Q(1,6),0],[0,6]]),p0) + cut=multiply(matrix([[1,0],[0,6]]),p0) + need(norm_at_most(p0,8) and norm_at_most(p1,8) and not norm_at_most(cut,8), + 'Generic matching interpolation still needs a loss') + out.append('generic no-loss interpolation rejected; source structure is necessary') + return out + + +def main(): + modules,raw,authenticated=load_source() + primitives=[primitive_fixture([[0]],modules,raw,'zero_side1'), + primitive_fixture([[1,Q(1,3)],[Q(-1,4),1]],modules,raw,'dirty_side2'), + primitive_fixture([[Z(Q(1),Q(1,4)),Z(Q(1,3),Q(-1,5))], + [Z(Q(-1,4),Q(1,7)),Z(Q(1),Q(1,4))]],modules,raw,'complex_side2')] + fulls=[full_fixture([[3,1],[1,3]],modules,raw,'n2_nonzero_approximation'), + full_fixture([[2,1,1,2],[1,2,1,1],[1,1,2,1],[0,1,1,2]],modules,raw, + 'n4_asymmetric_zero_atom',True)] + need(fulls[1]['zero_duration_atoms']>0 and fulls[1]['simultaneous_nonempty_fragments']>0, + 'Actual asymmetric fixture exercises the intended source risk') + need(sum(x['noncommuting_prefix_controls'] for x in fulls)>0, + 'Actual source distinguishes illegal factor order') + need(sum(x['segments']['nonprefix_nested_downsets'] for x in fulls)>0, + 'Actual intervals exercise completed sets beyond a fixed display prefix') + need(sum(x['segments']['wrong_relative_orders'] for x in fulls)>0, + 'Actual normalized interval rejects reversing relative-product order') + report=dict(status='PASS_SOURCE_ORDERED_FOUR_WAY_CUT_AUDIT',authenticated_origins=authenticated, + primitive_words=primitives,full_words=fulls,negative_controls=controls(), + boundary='Exact stored one/two-wire gate cuts, including arbitrary matching subsets; no split-output inverse claim', + scope='Finite evidence corroborates PROOF.md; phase, rank and conditioning premises remain explicit') + (HERE/'EVIDENCE.json').write_text(json.dumps(report,indent=2,sort_keys=True)+'\n') + print(json.dumps(dict(status=report['status'],primitive_cuts=sum(x['cuts'] for x in primitives), + primitive_psd=sum(x['psd_certificates'] for x in primitives), + full_cuts=sum(x['cuts'] for x in fulls), + full_trace_equalities=sum(x['trace_equalities'] for x in fulls), + actual_intervals=sum(x['segments']['intervals'] for x in fulls)),sort_keys=True)) + + +if __name__=='__main__': + main() diff --git a/research/direct-circulant-production-precision/compiler-intervals/retained/FULL-PROOF.md b/research/direct-circulant-production-precision/compiler-intervals/retained/FULL-PROOF.md new file mode 100644 index 0000000000..e650f46863 --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-intervals/retained/FULL-PROOF.md @@ -0,0 +1,374 @@ +# Full Toeplitz recursion with a polynomial conditioning envelope + +Jose Manuel (`jmbarrancoml`), with substantial OpenAI Codex assistance. +Apache-2.0. + +## 1. Domain, result and predecessor scope + +Let \(N=2^d\), and let \(T\in\mathbb Q(i)^{N\times N}\) be Toeplitz. +Write \(T_b=T[0:b,0:b]\). I assume +\[ +\Lambda,Q\ge1,\qquad \|T\|_2\le\Lambda,\qquad +\|T_b^{-1}\|_2\le Q\quad(1\le b\le N). +\tag{1} +\] +The full inverse bound alone would not suffice: the Toeplitz matrix +\(\left[\begin{smallmatrix}0&1\\1&0\end{smallmatrix}\right]\) is invertible +but has a singular first section. I include it as an admission control. +I allow indefinite and non-Hermitian matrices satisfying (1). + +I execute the retained `full_plan` on exactly \(N\) logical complex wires, +using the completed generator circuit and the same stored gates in reverse +for inversion. For input norm at most \(R\ge1\), incoming grid +\(F_0\in\mathbb Z_{\ge0}\) and target \(2^{-t}\), \(t\in\mathbb Z_{\ge1}\), +I prove forward and inverse error at most \(2^{-t}\) +with online widths +\[ +O(F_0+t+\log N+\log\Lambda+\log Q+\log R). +\tag{2} +\] +The circuit has \(O(\log^4N)\) layers and \(O(N\log^4N)\) gates. +I give explicit constants below. + +Vlado/PR1673 supplied the recursive compiler and displacement identities. +The retained `GAUGEFREE-INTERIORS.md`, Theorem 4.1, supplies a +conditioning-dependent guard of +\(O(\log N\log(2+\Lambda/\mu))\) for its accretive domain. +I use the scalar unit-LDU factors of legal completed-call sets to obtain +a joint polynomial envelope in dimension and conditioning. This +sharpens the sufficient guard's conditioning dependence under (1). +I leave the selected multiplication exponent unchanged. + +ToikY's [PR4209](https://github.com/CrocSwap/integer-mult-bounds/pull/4209) +at `ccc33bfde8baadef7979fac81e28c0a6f6f278c4` supplies sharper local +Schur closure under a row/column near-identity majorant. I retain that +distinct credit. I do not infer its hypothesis from (1) or use its +sharper constants in the present allocation. + +### Executable admission + +`admission()` computes exact inverses of the same root's leading sections. +It returns \(\lambda_c,Q_c\), each at least one, using the maximum row +and column sums of \(|\Re z|+|\Im z|\). These bound the corresponding +operator norms and also support the executable component-envelope guards. +The verifier binds them to the unchanged root passed to `Full.plan()`. +That lower-level factory does not repeat the complete admission. + +If (1) is supplied as operator-norm information, then +\[ +\lambda_c\le\sqrt{2N}\Lambda,\qquad +Q_c\le\sqrt{2N}Q. +\tag{3} +\] +I use the executable envelopes in its explicit constants. The inflation +in (3) preserves (2). The written operator lemma below uses any valid +\(\Lambda,Q\); passing uninflated operator bounds directly to the +component-guarded factory need not satisfy its stronger guards. + +Exact admission and Schur preparation are offline rational computations. +I do not equate their denominators with online data words or claim a +complete physical preparation/delivery tariff. + +## 2. Contiguous descendants, shears and rank + +The node on logical interval \([a,b)\) has reference matrix +\[ +M_{a,b}=S(a,b)=T_b/T_a, +\] +with the empty prefix convention at \(a=0\). Its children are \(S(a,c)\) +and \(S(c,b)\), where \(c=(a+b)/2\), by the Schur quotient identity. +Consequently +\[ +\|M_{a,b}\|\le U:=\Lambda+\Lambda^2Q,\qquad +\|M_{a,b}^{-1}\|\le Q. +\tag{4} +\] +The inverse is a principal block of \(T_b^{-1}\); the direct bound follows +from the Schur formula and restrictions of the original \(T\). + +At a split, write \(M=\left[\begin{smallmatrix}A&B\\C&D\end{smallmatrix}\right]\), +\(K=A^{-1}B\), \(L=CA^{-1}\). Let \(R_a\) select the coordinates +\([a,c)\) from \([0,c)\). The block inverse identities give +\[ +K=R_aT_c^{-1}T[0:c,c:b],\qquad +L=T[c:b,0:c]T_c^{-1}R_a^T. +\] +Thus, with \(\chi=\Lambda Q\), +\[ +\|K\|,\|L\|\le\chi. +\tag{5} +\] +The component-envelope versions follow under the executable admission. +The source computes \(L\) as `solve(A.T, C.T).T`. I preserve ordinary +transpose in this complex identity. + +The retained `SHALLOW-TOEPLITZ.md`, Sections 4–6, gives commutator rank +at most \(2+\text{depth}\) for the Schur nodes. Its rectangular identities +bound the shear commutator ranks by \(2\,\text{depth}+5\) and +\(2\,\text{depth}+7\). Conversion to +\(E_X=X-ZXZ^T\) adds at most one rank. I use the uniform allowance +\[ +r_*=2d+8. +\tag{6} +\] +The exact rational producer retains that rank; I do not use the numerical +source's floating SVD threshold as a universal rank argument. +The executable also checks exact generator rank against separate +elimination in its finite fixtures. + +## 3. Uniform scalar-LDU bounds + +Write \(M_J=\ell_J\delta_Ju_J\) for the scalar unit-LDU factors of a +contiguous descendant. All its leading sections are further \(S(a,c)\), +so (4) also applies during scalar elimination. +For \(A_k=M_J[0:k,0:k]\), the last row of +\(A_k^{-1}M_J[0:k,k:]\) is the corresponding unit-upper row tail. +The last column of \(M_J[k:,0:k]A_k^{-1}\) is the unit-lower column tail. +Each therefore has norm at most +\[ +UQ=\chi+\chi^2\le2\chi^2. +\] +The Frobenius estimate therefore permits +\[ +\|\ell_J\|,\|u_J\|\le W:=3N\chi^2. +\] +The pivot diagonal has norm at most \(U\) and inverse norm at most \(Q\). +From +\[ +u_J^{-1}=M_J^{-1}\ell_J\delta_J,\qquad +\ell_J^{-1}=\delta_Ju_JM_J^{-1} +\] +I obtain +\[ +\|\ell_J^{-1}\|,\|u_J^{-1}\|\le V:=6N\chi^4, +\tag{7} +\] +using \(QU\le2\chi^2\). A diagonal containing some completed pivots +and otherwise ones has direct and inverse norms at most \(2\chi^2\). + +## 4. Exact downsets and the upper frontier + +At an internal node \(v\), denote the upper and lower atomic calls by +\[ +R_v=\begin{pmatrix}I&K_v\\0&I\end{pmatrix},\qquad +B_v=\begin{pmatrix}I&0\\L_v&I\end{pmatrix}. +\] +The source executes \(R_v\), its two child programs in parallel, then +\(B_v\). A leaf executes its scalar pivot. +The atomic partial order places \(R_v\) before both children and both +children before \(B_v\). Incomparable calls act on disjoint intervals +and commute. I count identity shears as calls even when they emit zero layers. + +For a downset \(I\), let \(Q(I)\) be its product in any legal linearization. +At a node, the restricted downset is empty; or it contains \(R_v\) and +child downsets \(I_0,I_1\) but not \(B_v\); or it contains the whole node. +For an empty node set all three factors to identity. At a completed leaf +set them to \(I,d_i,I\). Otherwise define +\[ +\begin{aligned} +\mathcal L(I)&=B_v^\epsilon + \operatorname{diag}(\mathcal L(I_0),\mathcal L(I_1)),\\ +\mathcal D(I)&=\operatorname{diag}(\mathcal D(I_0),\mathcal D(I_1)),\\ +\mathcal U(I)&=\operatorname{diag}(\mathcal U(I_0),\mathcal U(I_1))R_v, +\end{aligned} +\tag{8} +\] +where \(\epsilon=1\) exactly when the lower call has completed. +Then both children are complete. Substituting the child identities gives +\[ +\boxed{Q(I)=\mathcal L(I)\mathcal D(I)\mathcal U(I).} +\tag{9} +\] +This induction never commutes overlapping factors. + +Uniqueness of scalar unit-LDU gives +\[ +\ell_v=B_v\operatorname{diag}(\ell_{v0},\ell_{v1}),\quad +\delta_v=\operatorname{diag}(\delta_{v0},\delta_{v1}),\quad +u_v=\operatorname{diag}(u_{v0},u_{v1})R_v. +\] +Hence \(\mathcal L(I)\) is the direct sum of full lower factors on the +maximal completed subtrees, with identity elsewhere. The partial diagonal +contains completed pivots and otherwise ones. + +For the upper frontier, stop at a node whose upper call has not completed; +otherwise descend to its two children. Retain singleton leaves. +The resulting intervals partition the coordinates. With +\(U_{\mathcal F}=\bigoplus_{v\in\mathcal F}u_v\), induction gives +\[ +u_{\rm root}=U_{\mathcal F}\mathcal U(I),\qquad +\mathcal U(I)=U_{\mathcal F}^{-1}u_{\rm root}. +\tag{10} +\] +At an unvisited node the identity is \(u_v=u_vI\); at a visited node, +substitute the two child identities and multiply by \(R_v\). + +Equations (7)–(10) bound the lower factor and its inverse by \(V\), +the partial diagonal and its inverse by \(2\chi^2\), and the upper +factor and its inverse by \(VW\). Thus +\[ +\boxed{\|Q(I)\|,\|Q(I)^{-1}\| +\le216N^3\chi^{12}<\mathcal B:=256N^3\chi^{12}.} +\tag{11} +\] +I use a fixed number of polynomial factors, rather than multiplying +conditioning factors through the recursion depth. + +## 5. Approximate atomic calls and physical cuts + +There are \(J=3N-2\) atomic calls: two shears per internal node and one +scalar per leaf. Approximate each by operator error at most \(\eta\). +For any legal linearization, set +\[ +G_j=Q_j^{-1}(\widehat A_j-A_j)Q_{j-1},\qquad +\theta=J\mathcal B^2\eta. +\] +The downset bound (11) applies to its prefixes. +If \(\theta\le1/4\), the product of \(I+G_j\), or its inverse, has norm +below two and distance from identity at most \(2\theta\). +Using \(\Lambda,Q\le\mathcal B\), I obtain +\[ +\|\widehat T-T\|,\|\widehat T^{-1}-T^{-1}\| +\le e:=2J\mathcal B^3\eta. +\tag{12} +\] +Completed approximate prefixes and inverse prefixes have norm at most +\(2\mathcal B\). Remaining suffixes and inverse suffixes have norm at most +\(2L_0\mathcal B\), where \(L_0=\max(1,\Lambda,Q)\). +I apply the exact LDU identities to the ideal calls, not to the +approximate endpoints. + +At a physical gate cut, completed calls form a downset \(I\). +Started but unfinished calls form a pairwise incomparable set \(A\): +the source finishes an upper call before starting its descendants and +finishes those descendants before its lower call. Active supports are +therefore disjoint, even when sibling ranks and lengths differ. + +Write each active stored endpoint as \(\widehat A_a=T_aF_a\), with executed +prefix \(F_a\) and remaining suffix \(T_a\). A completed call executed +after an active call began must act on a disjoint subtree, so I may commute +only that disjoint work. I obtain the exact identities +\[ +C_{\rm prefix}=(\bigoplus_{a\in A}F_a\oplus I)\widehat Q(I),\qquad +C_{\rm suffix}=\widehat Q_{\rm remaining} + (\bigoplus_{a\in A}T_a\oplus I). +\tag{13} +\] +The set \(I\cup A\) is also a downset, so I may order \(I\), then \(A\), +then the remaining calls in the suffix argument. +A direct sum contributes the largest fragment norm. I do not require +aligned child macro boundaries. A zero-layer identity completes at its +position in the source schedule and contributes no active fragment. + +## 6. Child, scalar and data bounds + +The component envelope used by a shear's exact producer satisfies +\(B_E\le4N\chi\): its displacement norm is at most \(2\chi\), and a +component row/column sum is at most \(\sqrt{2m}\) times that norm. +Substituting \(m\le N\), \(r\le r_*\), \(B_E\le4N\chi\) in +[GENERATOR-PROOF.md](GENERATOR-PROOF.md), put +\[ +\alpha_*=8r_*N^2\chi,\quad K_{G,*}=2N+64N^2\chi, +\] +\[ +H_*=\max(3200N^3,2+2K_{G,*})(10+4\alpha_*+2K_{G,*}). +\] +The generator's radius-one allocation supplies an unrounded operator +defect. I discard its local data grid and execute the flattened full +program on one global grid. + +A scalar pivot has \(1/Q\le|a|\le U\). I round it at \(s\) bits, +with \(\eta=2^{-s}\le1/(2Q)\), and invert the same stored value. +Then \(|\widehat a|\ge1/(2Q)\), its direct norm is at most \(U+1\), +and its inverse norm is at most \(2Q\). +Consequently +\[ +\mathcal H=\max(H_*,U+1,2Q),\qquad +K_{\rm phys}=2L_0\mathcal B\mathcal H +\tag{14} +\] +bounds physical prefixes, suffixes and their inverses. +An arbitrary segment needs the conservative bound \(K_{\rm phys}^2\). + +The unchanged source schedule permits +\[ +D_*=1+2dr_*(8d^2+32d+18),\qquad +G_*=N[1+dr_*(4d^2+24d+22)]. +\tag{15} +\] +I sum two generator calls per level and the \(N\) scalar leaves; parallel +siblings contribute their maximum depth. +Choose +\[ +s=t+\lceil\log_2(4J\mathcal B^3(R+1))\rceil,\quad +F=\max(F_0,t+\lceil\log_2(2D_*K_{\rm phys}N)\rceil). +\tag{16} +\] +These choices ensure the perturbation and scalar margins above. +One layer's rounding error is at most \(N2^{-F}\). Thus either direction +has error at most +\[ +eR+D_*K_{\rm phys}N2^{-F}\le2^{-t}, +\tag{17} +\] +and intermediate amplitude at most +\[ +A=K_{\rm phys}R+D_*K_{\rm phys}^2N2^{-F}. +\tag{18} +\] +The inverse direction uses the exact stored inverse program on its own +input satisfying the same \(R,F_0\) contract. I claim no exact rounded +forward/inverse round trip. + +If \(\widehat a=(a+ib)/2^s\) is a scalar leaf, its reciprocal +\(2^s(a-ib)/(a^2+b^2)\) has component height at most +\(2s+2\lceil\log_2(U+2)\rceil+8\). +I take the maximum of this bound and the generator children's declared +coefficient bounds, all fixed before online execution. +With \(I=\max(1,\lceil\log_2\max(1,A)\rceil)+2\), signed grid words fit +\(F+I\) bits and constant-size gate temporaries fit +\[ +2F+8C_{\rm bits}+2I+32. +\] +The constants in (6), (11), (14) and (15) are polynomial in \(N,\Lambda,Q\). +The child precision formulas and (16) therefore give (2), including the +executable envelope inflation (3). + +## 7. Source binding, finite evidence and limits + +I authenticate and execute the unmodified `full_plan`, `parallel` and +`inverse` ASTs. I supply exact rational matrix slicing, ordinary transpose, +solve, subtraction and multiplication; wrap recursive calls only to +record their exact reference matrices; and bind `lowdisp_shear` to the +completed generator program. I preserve source assertions in its +dependencies under optimized Python. + +The verifier checks direct full matrices and separate inverse references, +exact stored inversion, leading-section bounds, scalar-LDU identities, +legal downsets and upper-frontier identities. It enumerates all downsets +through size four and checks source-timed downsets on larger fixtures. +Selected physical cuts compare both identities in (13), including +simultaneous nonempty active fragments. Timing checks explicitly cover +unequal sibling lengths and zero-layer calls. + +I test indefinite and half-shift Gaussian matrices, complex inputs, +small and large scalar pivots, reversed wire labels, a nonzero 512-bit +incoming fixture and a size-16 identity with zero-layer shear calls. +The finite Frobenius inequalities include the dimension factor \(N\); +they corroborate consequences of the written operator proof rather than +independently establish its sharper bounds. +Exact dense matrices remain checker oracles outside the online +representation claim. Observed heights describe completed rational +components rather than exhaustive `Fraction` internals. + +I preserve the earlier FFT, triangular and generator receipts and the +fixed-head scope of James Reed's finite budget/source-seal audit at +`fdcdc269`. That audit excludes gate replay and universal-proof acceptance. +I credit Vlado Vojdanovski/PR1673 and the retained gauge-free source lineage +for the original recursive, displacement and conditioning arguments; +Chafik Boukhalfa/PR628 for certified phases; Cinna Davis for the later caller; +ToikY for the distinct same-rho Schur theorem; and classical LU/Schur methods. +Internal agents belong to the author process. + +Complete Gaussian assembly, physical coefficient setup/delivery, fixed-tape +costs and independent mathematical acceptance remain open. diff --git a/research/direct-circulant-production-precision/compiler-intervals/retained/GENERATOR-PROOF.md b/research/direct-circulant-production-precision/compiler-intervals/retained/GENERATOR-PROOF.md new file mode 100644 index 0000000000..8bef383eec --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-intervals/retained/GENERATOR-PROOF.md @@ -0,0 +1,277 @@ +# Complete rounded bounded-generator circuits + +Jose Manuel (`jmbarrancoml`), with substantial OpenAI Codex assistance. +Apache-2.0. + +## 1. Input, output and inherited generator identity + +I consider a rational complex matrix \(T\) of dyadic size \(m=2^d\). +Let \(Z\) be the nilpotent lower shift and \(E=T-ZTZ^T\), with rank \(r\). +The target is the dirty shear +\[ +S(T)(x,y)=(x,y+Tx) +\] +on exactly \(2m\) existing complex wires. I require no zero bank. +The input lies on an \(F_0\)-bit dyadic grid and has norm at most \(R\ge1\); +the requested output error is \(2^{-t}\), with integer \(t\ge1\). +I use a rational bound \(B_E\ge\|E\|_2\). The executable takes the maximum +of the row and column component sums, which bounds both induced norms. + +I execute the frozen PR4198 rational producer. For each nonzero orthogonal +residual \(v_j\) of \(E\), it chooses a dyadic \(c_j\) with +\(\|v_j\|\le c_j<2\|v_j\|\), then emits +\[ +g_j=v_j/c_j,\qquad +a_j=\frac{c_j}{v_j^*v_j}v_j^*E. +\] +The orthogonal projectors sum to the identity on the column space of \(E\). +Thus +\[ +E=\sum_{j=1}^r g_ja_j,\quad +\|g_j\|\le1,\quad \|a_j\|<2B_E,\quad +T=\sum_{j=1}^r L(g_j)U(a_j). +\tag{1} +\] +The last identity follows by telescoping +\(T=\sum_{k=0}^{m-1}Z^kE(Z^T)^k\). The \(a_j\) are coefficient rows; +I apply no further conjugation. + +I retain the producer's scale +\[ +\Gamma_j=\min\{2^e:2^e\ge\max(1,2\ell(a_j))\},\quad +\ell(a)=\sum_k(|\Re a_k|+|\Im a_k|), +\] +and put \(P_j=I+U(a_j)/\Gamma_j\), \(G_j=\Gamma_jL(g_j)\). +Then \(P_j\) satisfies the component-l1 admission used in +[TRIANGLE-PROOF.md](TRIANGLE-PROOF.md), and +\(\|P_j\|\le3/2,\ \|P_j^{-1}\|\le2\). +The source realizes the upper triangular map by reversing its source wires. + +I use the rational bounds +\[ +\alpha=2rmB_E,\qquad K_G=2m+16mB_E. +\tag{2} +\] +Indeed \(\|L(g_j)U(a_j)\|\le2mB_E\), and +\[ +\Gamma_j\sqrt m + <2\sqrt m+8\sqrt2\,mB_E\le K_G. +\] +The scaled shear's coefficient component sum is at most +\(\sqrt2K_G<2K_G\). I budget the approximation of \(G_j\) itself; +approximating \(L(g_j)\) first and multiplying by an uncharged +\(\Gamma_j\) would not meet this contract. + +## 2. Paired compensation and additive defects + +I retain the source's four calls: +\[ +P_j;\quad S(G_j);\quad P_j^{-1};\quad S(-G_j). +\tag{3} +\] +I compile \(\widehat P_j\) and reuse its exact stored inverse. +For the positive shear I use the certified FFT construction. +For its compensation I reuse the same unitary tables and negate the +stored spectral multipliers, preserving the source's cyclic-then-negacyclic +order. The two unrounded shear endpoints are exactly +\(S(\widehat G_j)\) and \(S(-\widehat G_j)\). + +Negating a nearest-grid value gives a nearest-grid value of the negative +exact quantity, so this paired rule retains the same multiplier-error +bound. At half-grid ties it need not agree with independent rounding +toward positive infinity. The verifier includes that discrepancy as a +control. I do not replace the negative child with a reversed whole +positive-shear program. + +For \(\|\widehat P_j-P_j\|,\|\widehat G_j-G_j\|\le\eta\le1/4\), +the exact stored-coefficient program has endpoint +\[ +(x,y)\longmapsto(x,y+\widehat G_j(\widehat P_j-I)x). +\] +Write \(T_j=G_j(P_j-I)\) and +\(\widehat T_j=\widehat G_j(\widehat P_j-I)\). Then +\[ +\|\widehat T_j-T_j\| +\le K_G\eta+(1/2+\eta)\eta\le(K_G+1)\eta. +\] +The completed terms restore the same source bank, so their endpoints +compose to \(S(\sum_j\widehat T_j)\). Consequently +\[ +\boxed{\|\sum_j\widehat T_j-T\|\le +\Delta:=r(K_G+1)\eta.} +\tag{4} +\] +I need no generic product-of-perturbed-matrices bound across completed +generator terms. This additive estimate uses exact stored-coefficient +restoration; data-rounding errors receive a separate bound below. + +## 3. Checkpoint prefixes and suffixes + +Assume \(\Delta\le1\). Any preceding or remaining sum of approximate terms +has norm at most \(a_*=\alpha+1\). +For the current term write \(p=\widehat P_j\), \(h=\widehat G_j\), +\(A=\sum_{i=1`, such that + +``` +Λ,Q >= 1, ||T||₂ <= Λ, ||T_k^-1||₂ <= Q for 1<=k<=N, +T_k = T[0:k,0:k]. +``` + +Every leading section is invertible. Put `χ=ΛQ` and `S=Λ+Λ²Q`. +Choose any binary tree of contiguous coordinate intervals. At `[a,b)` split +at `s`, the reference matrix is the Schur descendant `T_b/T_a`, with the +empty-prefix convention. Execute the upper shear, both children in any +legal interleaving, then the lower shear. A leaf executes its scalar pivot. +Atoms are complete ideal shears and scalars, including identity atoms. + +For every downset of this atomic dependency order, let `P` be its endpoint +product. Form a partition by stopping at a fully finished subtree or a +subtree none of whose atoms has executed, and otherwise descending. Label +its intervals finished or untouched. If their counts are `c` and `u`, then + +``` +||P||₂² <= c S² + u(1+χ²), +||P^-1||₂² <= c Q² + u(1+χ²). +``` + +The partition has `1<=c+u<=N`. Since `S>=1+χ>=sqrt(1+χ²)` and +`Q<=χ`, this implies + +``` +||P||₂ <= sqrt(N) (Λ+Λ²Q), +||P^-1||₂ <= sqrt(N(1+χ²)), +``` + +and the common envelope `2 sqrt(N) χ²`. Neither Toeplitz structure, +positivity, equal splits nor a balanced tree is required. The theorem +concerns complete calls. Cuts inside a generator/FFT call, rounded arithmetic, +storage, native cost and the complete multiplication theorem are outside scope. + +## Proof + +### 1. Retain the global factorization and its order + +Write the unique scalar unit-LDU factorization as `T=L D U`. For an interval +`J=[a,b)`, write `M_J=T_b/T_a` and `U_J=U[J,J]`. The identities +`M_J=L[J,J] D[J,J] U_J` and the completed-downset/frontier factorization +are inherited from Jose Manuel's `rational-unitary-fft/FULL-PROOF.md`, +sections 2 and 4, and Brian's PR #4788, sections 2 and 3, head +`ddd98e28b1d6a674b1d6b93c5d7de8a9f9c86eec`. +The latter includes arbitrary contiguous interval trees. They are cited +inputs, not results audited here. + +Let `B` be the finished/untouched partition. Define + +``` +U_B = direct_sum over J in B of U_J, +E_B = direct_sum over J in B of (M_J if finished, I_J if untouched). +``` + +The inherited factorization gives, in this order, + +``` +P = E_B U_B^-1 U, (1) +P^-1 = U^-1 U_B E_B^-1. (2) +``` + +Indeed the usual upper frontier stops at untouched internal nodes and has +singleton leaves inside finished nodes. Replacing those singletons within a +finished `J` by `U_J` changes its left factor from `L_J D_J` to +`M_J=L_J D_J U_J`; the new right factor `U_J^-1` cancels that change. +Untouched blocks already have left factor identity and upper block `U_J`. +This gives (1) without commuting overlapping factors. Incomparable atoms +have disjoint intervals, so all legal linearizations give the same product. +Equivalently, contract each finished or untouched node to one block. At an +open internal node its lower atom is absent, so its product is +`diag(P_left,P_right) R`. Substituting the child formulas and +`U_node=diag(U_left,U_right) R` proves (1) inductively for every interval +tree. The two stopping cases are respectively `P=M_J` and `P=I_J`. + +### 2. Bound forward block rows + +For a finished `J=[a,b)`, equation (1) gives + +``` +P[J,:a] = 0, +P[J,a:N] = T[J,a:N] - T[J,:a] T_a^-1 T[:a,a:N]. (3) +``` + +Eliminate the leading `a` rows of `T=LDU` and restrict the resulting +rectangular Schur row to `J`. Each restriction of `T` has norm at most `Λ`. +Thus this whole block row has norm at most `S`. At `a=0` the second term +is absent and `Λ<=S` suffices. + +For an untouched `J`, its row is `U_J^-1 U[J,:]`. It is zero before `a`, +identity on `J`, and has tail + +``` +K_J = (T_b^-1 T[:b,b:N])[a:b,:]. (4) +``` + +To see this, cancel `L_b D_b` in `T_b^-1 T[:b,b:N]`. The last block rows +of the result are `U_J^-1 U[J,b:N]`. Hence `||K_J||<=QΛ=χ`. +The row `[I_J K_J]` has squared norm `1+||K_J||²<=1+χ²` by its Gram +product. For any `x`, sum the squared norms of the disjoint block-row +outputs of `Px`. This proves `||P||²<=cS²+u(1+χ²)`. + +### 3. Bound inverse block columns + +For every interval `J=[a,b)`, triangular block inversion gives + +``` +(U^-1[:,J] U_J)[0:b,:] = [-T_a^-1 T[:a,J]; I_J], (5) +(U^-1[:,J] U_J)[b:N,:] = 0. +``` + +At `a=0` the top block is empty. For the top identity, invert the upper +`2×2` blocks on `[:a,J]` and use +`T_a^-1 T[:a,J]=U[:a,:a]^-1 U[:a,J]`. + +An untouched block column in (2) equals (5). Its norm is at most +`sqrt(1+χ²)`, using the original leading solve at `a`, or is one if `a=0`. +For a finished block, multiply (5) on the right by `M_J^-1`. +The ordinary block inverse formula identifies the result as + +``` +P^-1[0:b,J] = T_b^-1[:,a:b], +P^-1[b:N,J] = 0. (6) +``` + +Its whole block-column norm is at most `Q`. This avoids multiplying +separate bounds for the two factors in (5). + +For disjoint input blocks, `P^-1 x=sum_J C_J x_J`. The triangle and +Cauchy-Schwarz inequalities give + +``` +||sum_J C_J x_J|| <= sum_J ||C_J|| ||x_J|| + <= sqrt(sum_J ||C_J||²) ||x||. +``` + +This proves the inverse inequality. Empty downsets, finished roots, +singletons and zero-width tails are included. Finally +`S=Λ(1+χ)<=2Λχ<=2χ²` proves the common envelope. + +## Exact evidence and reproduction + +`verify.py` is a self-contained standard-library checker. It constructs +literal upper/child/lower atomic programs and checks all binary contiguous +interval trees through five leaves and every downset of each tree, for one +real and one nonreal rational fixture per size. Complex matrices use faithful +interleaved rational realification. No predecessor verifier or unmerged Git +object is imported. + +For each downset it computes `P` by literal atomic multiplication and its +inverse by exact elimination, then checks (1), (3), (4), (5) and (6). +Exact rational positive-semidefinite tests certify block norms and both +assembled squared bounds. The printed receipt enumerates its checks and +binds them to hashes of the package files. Checks use explicit exceptions +and remain enabled under `-O`. Rejection controls cover wrong factor order, +omitted finished endpoints, wrong inverse signs, invalid partitions, invalid +spectral certificates and using only the whole-matrix inverse premise. +The complete finite replay passes 46 trees, 2,380 downsets, 9,520 matrix +identities, 9,372 partition blocks and 23,504 downset spectral certificates. +Eleven control groups pass, including 2,244 wrong-order, 2,160 omitted-endpoint +and 1,940 inverse-sign distinguishing states. These are finite coverage counts, +not claims about every complex matrix. + +From the worktree root: + +```sh +~/git/integer-mult-bounds/.venv/bin/python3.12 -I -W error -B research/downset-block-solve-bound/verify.py +~/git/integer-mult-bounds/.venv/bin/python3.12 -I -O -W error -B research/downset-block-solve-bound/verify.py +~/git/integer-mult-bounds/.venv/bin/python3.12 -B scripts/research_package.py --package research/downset-block-solve-bound +~/git/integer-mult-bounds/.venv/bin/python3.12 -B scripts/check_research_commit.py --package research/downset-block-solve-bound --check-source-history +``` + +The last command follows committing. The universal claim rests on the written +proof. A selected-baseline metadata control passed; the selected construction +was not replayed. Independent human and formal proof-kernel review are unclaimed. + +Checker resource limits: Python/Fraction arithmetic allocates managed objects. +The checker fixes at most five logical coordinates and ten real coordinates, +at most 16 tree shapes per size, and at most 256 downsets per tree. Loop +bounds follow these capacities or fixed package-file inventories. No recursion, +dynamic imports, code evaluation, subprocesses or external runtime dependencies are used. +The three negative-control callbacks have fixed local targets and no retained +state. AST syntax validation and warning-strict execution supplement the replay; +no unavailable standalone lint or type-check pass is claimed. A future +parameterized checker must add input/bit-size limits before lifting these +fixed-fixture resource bounds. + +## Open next questions + +1. Can this envelope replace the old one in the complete rounded Full factory? + First list every old-envelope dependency and prove the new allocation + inequalities. Unfinished generator fragments and scalar/data grids retain + their own obligations. No factory substitution is supplied here. +2. Is square-root growth in the number of frontier blocks necessary when + `Λ,Q` stay bounded? Seek an explicit growing family or a bound exploiting + shared block-solve geometry. No asymptotic sharpness claim is made. + +## Attribution and overlap + +Credit Brian (JoyboyBrian), PR #4788, for global-factor restrictions, +arbitrary interval trees and the previous `32 N^(3/2)χ^8` envelope; +Jose Manuel (jmbarrancoml), PR #4205, for the original scalar-LDU/frontier +proof and polynomial Full-recursion envelope; and Vlado Vojdanovski, +PR #1673, for the recursive compiler. Classical Schur and block inverse +identities are background. The new step is the mixed finished/untouched +partition and direct original-leading-solve block norm estimate. Predecessor +credit and disclosures remain unchanged in their own packages. + +The task changes `uniform-transfer-audit` into a new precision-interface +inequality. Brian's open package studies the same quantity and is the +nearest predecessor. Triangular parity-prefix/suffix and dirty FFT gate-cut +packages use different schedules and boundaries; this does not extend their +exact constants or audit their results. + +Canonical base is `624de9dc66858af0945e5f8a0942488d62280d43`, priority revision 7. +The [advance claim](https://github.com/CrocSwap/integer-mult-bounds/discussions/1166#discussioncomment-19133325) +records the scope. Main README searches, merged PR searches, live open PR +bodies, recent handoffs and local reservations were checked. Those searches +do not cover unpublished investigations or every historical diff. +Provenance pins are in `SOURCES.json`; runtime needs only this package. +The overlap helper covered 367 open PRs and 3,821 Discussion records at its +21:46–21:47 UTC snapshot. Its sparse local inventory covered 115 of 6,319 +HEAD notes; separate `git grep` searched all main package READMEs for the +distinctive terms. No complete local-note inventory or novelty certificate +is claimed. A canonical refresh after the first replay retained the same base. diff --git a/research/direct-circulant-production-precision/compiler-intervals/retained/PR4976-README.md b/research/direct-circulant-production-precision/compiler-intervals/retained/PR4976-README.md new file mode 100644 index 0000000000..eb7b8be250 --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-intervals/retained/PR4976-README.md @@ -0,0 +1,121 @@ +# Numerical bounds inside a matching layer + +Prepared by JoyboyBrian with substantial OpenAI Codex assistance. Apache-2.0. + +## Result and scope + +The physical-cut trace audit `full-toeplitz-cut-audit` explicitly leaves the +numerical contract at a proper subset of a matching layer open. This package +supplies a dimension-independent interpolation lemma for all four operators: +prefix, suffix, inverse prefix and inverse suffix. It binds the lemma to the +actual retained rational FFT and Toeplitz-shear gates. It changes no frozen +factory or selected exponent. + +Let the complete layer be an invertible block diagonal operator G on disjoint +coordinate supports. Choose any subset of its complete gates, let E be the +orthogonal coordinate projection onto their supports, and let H be their +product, identity elsewhere. Then + +``` +H = E G + (I-E), H^-1 = E G^-1 + (I-E), EG=GE. +``` + +For the adjacent complete-layer prefixes P0 and P1=G P0 and suffixes +S0=S1 G, the cut inside this layer has P=H P0 and S=S1 G H^-1. Exactly, + +``` +P = E P1 + (I-E) P0, +P^-1 = P1^-1 E + P0^-1 (I-E), +S = S0 (I-E) + S1 E, +S^-1 = (I-E) S0^-1 + E S1^-1. +``` + +The order matters; the projection need not commute with any prefix or suffix. +All products act on columns and the most recent gate multiplies on the left. + +## Quantified norm proof + +For orthogonal output projections, the two summands' squared output norms add. +For orthogonal input projections, use the triangle inequality followed by +Cauchy–Schwarz. Thus if the two neighboring operators of any one of the four +types have norm at most a and b, the partial-layer operator has norm at most +`sqrt(a*a+b*b)`. In particular a common complete-layer bound F becomes +`sqrt(2) F`. This proof holds over C for every dimension and every finite +matching, including identity gates, empty/full selected subsets, and unused +coordinates. It does not split an individual gate's internal arithmetic. + +There is no valid generic zero-loss interpolation rule. For integer m>=4 use + +``` +P0 = [[m,0],[1,1/m]], G = diag(1/m,m), +P1 = [[1,0],[m,1]], H = diag(1,m). +``` + +Every complete boundary of the two-layer program P0;G, including its prefix, +suffix and both inverses, has norm at most `m+2` (their squared Frobenius +norms suffice). But `H P0` maps e0 to `(m,m)`, of norm `sqrt(2)m`. +For m>=5 this exceeds m+2, and its ratio to that common valid envelope tends +to sqrt(2). Consequently the generic factor sqrt(2) is sharp, even when the +four complete-boundary contracts are provided together. The witness uses two +disjoint scalar gates, so the complete-layer matching premise is preserved. + +## Consequence for the retained generator and Full caller + +The retained `GENERATOR-PROOF.md` complete-layer fragment bounds and the exact +physical-cut trace remain explicit inputs, rather than results re-proved here. +Apply the lemma separately to each actual local microprogram. A child with +four complete-layer bounds H has four arbitrary-matching-subset bounds +`sqrt(2)H`, with rational safe envelope `2H`. Active atoms have disjoint +supports, so their direct sum contributes the maximum such bound, without +multiplying by the number of active atoms. + +In FULL-PROOF.md (14), complete-layer `K_phys=2 L0 B H` therefore becomes +`sqrt(2) K_phys` at these added sublayer cuts; `2 K_phys` is a rational safe +choice. Arbitrary segments between two added cuts have bound `2 K_phys^2` +(or rational safe `4 K_phys^2`). If one keeps the predecessor's data-rounding +count and only doubles the suffix propagation envelope, one extra data bit +preserves its rounding allowance. This is an implication, not an installed +precision change or a claim covering extra rounding events. Rounding inside a +gate, asynchronous overlapping gates and changed non-coordinate layouts need +separate contracts. + +## Verification and attribution + +The written proof establishes the quantified result. The standard-library +checker uses exact Gaussian-rational scalar representation from Jose Manuel's +retained implementation; its matrix multiplication, inverse, PSD tests and cut +oracle are local. It checks all four identities and independently certifies +norm bounds at actual FFT/shear cuts and at nonunitary complex synthetic cuts. +Wrong projection sides, overlapping supports and a missing interpolation loss +have discriminating controls. Counts and commands are reported after replay. + +Credit Jose Manuel/jmbarrancoml for rational FFT/Full and numerical fragment +contracts, Vlado Vojdanovski/PR1673 for the matching scheduler, Chafik +Boukhalfa/PR628 for certified phases, and Brian/JoyboyBrian's physical-cut +trace audit for the explicit sublayer question. Original source notices remain. +The orthogonal row/column mixing inequality is elementary background; this +contribution is its four-way source-bound application and quantified interface +consequence, without a literature-priority claim. + +## Open next questions + +Can the retained primitive alphabet improve the generic sqrt(2) loss? +Start with its unitary butterflies and compensated shear layers, retaining the +same actual neighboring operators. The sharp generic witness need not belong +to that alphabet. A better bound would reduce added sublayer headroom, but +physical preparation, storage, tape and full supplier admission remain open. + +## Reproduction and evidence + +Canonical claim: https://github.com/CrocSwap/integer-mult-bounds/discussions/4202#discussioncomment-19138297 + +The fixed replay covers 97 cuts, including 52 proper sublayer cuts, 388 exact four-way identities and 388 independently PSD-certified partial-cut norm inequalities. Actual retained FFTs at widths two/four and a complete dirty Toeplitz shear contribute 73 cuts; the other four fixtures cover sharp nonunitary and complex controls. Six controls distinguish missing loss, wrong projection sides, overlapping supports and a complex adjoint norm failure. All checks use explicit exceptions and remain enabled under -O. + +```sh +/opt/local/bin/python3.12 -B scripts/research_package.py --package research/matching-sublayer-norm +python3 -B scripts/check_research_commit.py --package research/matching-sublayer-norm --check-source-history +``` + +The registered normal and optimized commands require CPython 3.12 and only the standard library. The local interpreter path above is environment-specific; the registered hook resolves its declared Python version. The source-history command follows committing. Official committed exports can run verify.py directly with -I -W error -B, and separately -O, without Git or a network. Automated execution is not independent human or proof-kernel acceptance. Hosted CI is unverified at publication. + +Base b91956876e5b4122fd89179f1b57557ff8378f15, priority revision 7. Fresh entry overlap covered 317 open PRs, 4064 Discussion records and all 6636 current-base local notes at 04:46–04:47 UTC. The scoped searches found the named explicit predecessor obligation; unpublished work, arbitrary closed histories and every historical diff are not covered. This is advisory coverage, not a novelty certificate. diff --git a/research/direct-circulant-production-precision/compiler-intervals/retained/PR4977-README.md b/research/direct-circulant-production-precision/compiler-intervals/retained/PR4977-README.md new file mode 100644 index 0000000000..c5248440b7 --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-intervals/retained/PR4977-README.md @@ -0,0 +1,141 @@ +# Bind the block-solve envelope to the rounded Full allocation + +Prepared by JoyboyBrian with substantial OpenAI Codex assistance. Apache-2.0. + +## Result and exact boundary + +Nick Petalas's `downset-block-solve-bound` gives the ideal completed-call +common spectral envelope `2 sqrt(N) (Lambda Q)^2`, and explicitly leaves its +rounded Full-factory substitution open. This package performs that substitution +through a one-expression, source-authenticated allocation adapter. Frozen +`rational-unitary-fft/full.py`, its compiler and every predecessor remain intact. +The uniform implication below retains the stated block-solve theorem and the +predecessor generator's local fragment/rank contracts as dependencies. + +Let N=2^d, Lambda,Q,R>=1, target t>=1 and incoming precision F0>=0, under the +original component-guarded Full admission contract. Set chi=Lambda Q and + +``` +B = 2 * 2^ceil(d/2) * chi^2. +``` + +Then `2 sqrt(N) chi^2 <= B <= 2 sqrt(2N) chi^2`. Also B dominates 1, Lambda +and Q. Use this B in place of `256 N^3 chi^12` in the original allocation, +leaving every other expression and check unchanged. The resulting actual +factory has the same retained forward and stored-inverse error target `2^-t` +at complete matching-layer boundaries. No new selected kappa or physical +preparation/delivery bound is claimed. This is not the sublayer interpolation +contract being studied in the separate `matching-sublayer-norm` contribution. + +## Every affected implication + +Put J=3N-2, tau=2^-t, and take + +``` +s = t + ceil(log2(4 J B^3 (R+1))), eta=2^-s, +theta = J B^2 eta. +``` + +The ideal completed-downset theorem is valid for every legal atom ordering. +For its prefixes Q_j and the approximate atom errors E_j, conjugated defects +`G_j=Q_j^-1 E_j Q_(j-1)` have sum of norms at most theta. Thus + +``` +theta <= tau/(4 B (R+1)) <= 1/16 < 1/4, +eta <= 1/(2Q), +e = 2 J B^3 eta <= tau/(2(R+1)). +``` + +Products of `I+G_j` have norm at most exp(theta)<2, and inverse products +have norm at most `1/(1-theta)<2`. Their distance from identity is below +`2 theta`, using exp(theta)-1<=2theta and theta/(1-theta)<=2theta on this +interval. Apply the same estimates to a contiguous suffix of the normalized +interaction factors, rather than multiplying two independently bounded +prefixes. All approximate completed prefixes and their inverses have norm +at most 2B; remaining suffixes and their inverses have norm at most 2L0B, +where L0=max(1,Lambda,Q). Both endpoint operator errors are at most e. +The inverse reference is the mathematical inverse of the unchanged ideal T; +it is not an independently rounded inverse coefficient table. + +For U=Lambda+Lambda^2 Q, let H be the predecessor's maximum of its generator +fragment allowance, U+1 and 2Q. Generator parameters, exact displacement/rank +bounds and polynomial H are unchanged. Although their requested accuracy is +smaller, every child still receives its full requested coefficient accuracy; +the existing child allocation is recomputed from s. For a scalar leaf a, +`|a|>=1/Q` and `|ahat-a|<=eta<=1/(2Q)` imply `|ahat|>=1/(2Q)` and direct/inverse +fragment bounds U+1 and 2Q. Inversion always uses the same stored ahat. +The physical-cut trace therefore gives the same formula + +``` +K = 2 L0 B H, segment <= K^2. +``` + +Let D be the original layer bound and choose + +``` +F=max(F0, t+ceil(log2(2 D K N))). +``` + +Nearest component rounding contributes at most N 2^-F per layer. Its propagated +endpoint error is at most D K N 2^-F <= tau/2. The coefficient charge is +`e R <= tau R/(2(R+1)) < tau/2`, hence the total is strictly below tau. +The same proof applies to the reversed stored program on its own input; +no exact rounded forward/inverse round trip is asserted. Intermediate +amplitude is bounded by `A=K R+D K^2 N 2^-F`, using the segment bound. +Consequently the original integer-bit and temporary-bit formulas remain valid. + +For scalar height, the unchanged pivot upper bound U and precision s give +`2s+2ceil(log2(U+2))+8`; actual generator coefficient heights are still +maximized after building the plan. Their original phase/multiplier recipes +are used, not stale heights from the old allocation. All quantities remain +polynomial in N,Lambda,Q,R before logarithms, preserving the original +`O(F0+t+log N+log Lambda+log Q+log R)` online-width conclusion. + +## Executable adapter and independent checks + +`allocation.py` authenticates exactly the original AST assignment to B, +replaces only that assignment in a private function, and compiles it with the +original exact helpers. All validation, output fields and subsequent formulas +are retained byte-for-byte at the AST level. The live Full factory and frozen +source files are not edited. The verifier authenticates every declared source +before imports and constructs actual plans with the adapted allocation. +It independently derives every affected formula and checks actual exact and +rounded forward/stored-inverse endpoints, source grid and word widths. +The written proof establishes the uniform implication; finite execution +binds it to the actual source and exercises error controls. + +## Attribution and remaining scope + +Credit Nick Petalas for the block-solve `2 sqrt(N) chi^2` theorem, Brian's +PR4788 for the earlier leading-section/downset bridge, Jose Manuel/jmbarrancoml +for rational Full, its all-size allocation and rounding proof, Vlado/PR1673 +for the recursive/displacement compiler, Chafik/PR628 for certified phases, +and the retained Stein and interval source contributors. Orthogonal block +estimates, Schur formulas and perturbation inequalities are background. +Author-process checks do not constitute independent human or proof-kernel +acceptance. Tape cost, physical coefficient preparation/delivery and the +complete multiplication theorem remain separate. + +## Open next questions + +Can a downstream normalized/raw Gaussian caller use the smaller actual Full +word widths while preserving immutable reference and intermediate-radius +contracts? Begin by threading this exact allocation receipt through one +normalized `Gaussian` instance and auditing its requested child grid. The +present Full contract is complete at its own boundary; the outer wrapper and +physical cost claims require their own source-bound proof. + +## Reproduction and evidence + +Canonical claim: https://github.com/CrocSwap/integer-mult-bounds/discussions/4202#discussioncomment-19138298 + +The fixed replay checks 63 allocation contracts (N from 1 through 2^20), then six actual Full factories and 24 rounded forward/stored-inverse trajectories. Cases include a complex scalar, a 2^-30 pivot, non-Hermitian complex N=2/N=4, a nonzero 512-bit input grid and zero-duration shears. At complex N=4 the source emits 189 layers, child precision falls 72 to 26 bits and data precision 76 to 61 bits; at complex N=2 these fall 82 to 28 and 72 to 54. A 512-bit incoming grid remains 512. These are fixture measurements, not a universal constant saving. Seven controls cover source-expression drift, invalid types/dimension, a rounded-zero pivot, wrong inverse ordering and an underfunded actual data grid. + +```sh +/opt/local/bin/python3.12 -B scripts/research_package.py --package research/full-downset-allocation +python3 -B scripts/check_research_commit.py --package research/full-downset-allocation --check-source-history +``` + +The registered normal and optimized commands require CPython 3.12 and only the standard library. The local interpreter path above is environment-specific; the registered hook resolves its declared Python version. The source-history command follows committing. Official committed exports can run verify.py directly with -I -W error -B, and separately -O, without Git or a network. Automated execution is not independent human or proof-kernel acceptance. Hosted CI is unverified at publication. + +Base b91956876e5b4122fd89179f1b57557ff8378f15, priority revision 7. Fresh entry overlap covered 317 open PRs, 4064 Discussion records and all 6636 current-base local notes at 04:46–04:47 UTC. The scoped searches found the named explicit predecessor obligation; unpublished work, arbitrary closed histories and every historical diff are not covered. This is advisory coverage, not a novelty certificate. diff --git a/research/direct-circulant-production-precision/compiler-intervals/retained/PROOF.md b/research/direct-circulant-production-precision/compiler-intervals/retained/PROOF.md new file mode 100644 index 0000000000..99a55596f6 --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-intervals/retained/PROOF.md @@ -0,0 +1,349 @@ +# Certified rational unitary FFT and rounded Toeplitz shear + +Jose Manuel (`jmbarrancoml`), with substantial OpenAI Codex assistance. +Apache-2.0. + +I instantiate Chafik Boukhalfa/PR628's rational unit-phase construction +inside Vlado Vojdanovski/PR1673's retained FFT and Toeplitz-shear schedule. +PR3709 already supplies certified inward dyadic twiddles and rounded FFT +execution. I retain those credits. The result here concerns the unitary +child, its composed approximation and its fixed-grid dirty-data contract. + +## 1. Contract and precision allocation + +Let \(n=2^d\ge1\), and let \(T\in\mathbb Q(i)^{n\times n}\) be Toeplitz, +with first column \(c\) and first row \(r\). Define +\[ +g_0=h_0=c_0/2,\quad +g_j=(c_j+r_{n-j})/2,\quad h_j=(c_j-r_{n-j})/2\quad(1\le j2/3\), while the endpoint error is below \(1/6\). +For the true rotated phase \(v_0\), put +\[ +\tau=\Im(v_0)/(1+\Re(v_0)). +\] +The denominator is at least \(3/2\). Compute quotient extrema at the box +corners, round their midpoint to the nearest \((P+4)\)-grid value \(t_0\), +and form +\[ +\sigma=C\frac{1-t_0^2+2it_0}{1+t_0^2}. +\] +Then \(|\sigma|=1\) exactly, \(|t_0|<1\), and +\[ +|\sigma-e^{2\pi ik/n}|\le4E_B+2^{-P-4}. +\] +This follows from the quotient bound \(2E_B\) and the stereographic +derivative bound \(2/(1+t^2)\le2\). + +The executable checks the **maximum endpoint** component-\(\ell^1\) +distance from \(\sigma\) to the entire oracle box. That distance is at +most \(10E_B+2^{-P-3}<\nu\). A minimum distance to the box would not +certify the approximation. + +The parameter denominator is at most \(2^{P+4}\). Unit-phase components +therefore have numerator/denominator height at most \(2P+9\), with +slightly larger allowances in the code. The oracle's offline exact +Machin sums, factorials and phase-description arithmetic use polynomial +time and space in \(P\) and the input description length. A long external +phase numerator is an input cost, not a free oracle argument. + +## 3. Exactly unitary butterflies and FFT approximation + +Use the certified phase \(a+ib\) approximating \(e^{i\pi/4}\), and a +certified twiddle \(w\). Define +\[ +B(a,b,w)= +\begin{pmatrix}a&bw\\b&-aw\end{pmatrix} += +\begin{pmatrix}a&b\\b&-a\end{pmatrix}\operatorname{diag}(1,w). +\] +Since \(a^2+b^2=|w|^2=1\), this matrix is exactly unitary. +Its adjoint is +\(\operatorname{diag}(1,\bar w)\left[\begin{smallmatrix}a&b\\b&-a\end{smallmatrix}\right]\). +It is generally not the same expression with \(w\) merely conjugated. + +The splitter difference from the ideal \(1/\sqrt2\) splitter has norm +\(|(a+ib)-e^{i\pi/4}|\). Hence each butterfly differs from its ideal gate +by at most \(2\nu\). Disjoint gates give the same layer bound. I retain +the source's exact bit reversal and its \(d\) butterfly layers, so +\[ +\boxed{\|\widetilde F-F\|_2\le2d\nu,\qquad +F=\mathrm{DFT}_{-}/\sqrt n.} +\] +We telescope products of unitary layers, so no amplification factor +appears. Every exact FFT prefix and suffix is unitary. Reverse the layers +and adjoint the stored gates to obtain \(\widetilde F^*\); do not generate +a new approximate inverse phase table. + +## 4. Spectral preparation and Toeplitz approximation + +For a kernel \(k\), the ideal circulant eigenvalues are the +**unnormalized** DFT +\[ +\lambda_\ell=\sum_j k_j e^{-2\pi i\ell j/n}. +\] +I approximate each root independently by a certified rational unit, +sum exactly offline, and round each multiplier component once to the +nearest \(S\)-grid value. If \(\|k\|_1\le M_k\), then +\[ +\|\widehat\lambda-\lambda\|_\infty\le M_k\nu+v,\qquad +\|\widehat\lambda\|_\infty\le M_k+v. +\] +The second bound uses exact unit modulus before rounding. It does not +add a spurious phase-error magnitude factor. + +I store the rounded multipliers before online use. The exact offline +sum can have a denominator whose size grows with \(n\); carrying that +sum into data gates would violate the stated coefficient-width bound. + +The actual circulant child applies +\[ +\widetilde C_k=\widetilde F^*\operatorname{diag}(\widehat\lambda)\widetilde F, +\] +so +\[ +\|\widetilde C_k-C_k\|_2 +\le M_k\nu+v+2M_k\|\widetilde F-F\|_2. +\] +Exact unitarity alone does not make \(\widetilde F\) an exact diagonalizer. + +For \(D=\operatorname{diag}(e^{\pi ij/n})\), the source decomposition is +\[ +T=C_g+D^*C_{Dh}D. +\] +I generate each diagonal entry of \(\widetilde D\) independently. Thus +\(\|\widetilde D-D\|_2\le\nu\), without a powers' accumulated error or +an \(nP\)-bit phase representation. The actual schedule is the first +circulant shear, the common twist \(\widetilde D\) on both banks, the +circulant shear prepared from \(\widetilde D h\), and the inverse twist. + +Twisting preserves \(\|h\|_1\). Charge \(M_h\nu\) for changing the +second kernel and \(2M_h\nu\) for its two exterior twists. Combining +these terms with the two circulant estimates gives +\[ +\|\widetilde T-T\|_2 +\le(4d+1)M_g\nu+(4d+4)M_h\nu+2v +\le\boxed{\delta}. +\] +In exact rational arithmetic the complete map is +\((x,y)\mapsto(x,y+\widetilde T x)\). The input matrix may be zero +or singular because the pointwise shear gates remain invertible. + +## 5. Prefix bounds and rounded execution + +Every non-spectral gate stays within one bank and is unitary. +Each of the two spectral layers has orientation +\[ +S(A)=\begin{pmatrix}I&0\\A&I\end{pmatrix}. +\] +For a bank unitary \(U=\operatorname{diag}(U_x,U_y)\), +\[ +US(A)U^*=S(U_yAU_x^*). +\] +Move the bank unitaries to the ends of any contiguous gate segment. +The remaining shear matrix is a sum of at most two unitarily transformed +spectral matrices. Their norms are at most \(M_g+v\) and \(M_h+v\). +Consequently every segment, inverse segment, prefix and suffix has norm +at most +\[ +\boxed{H=1+M_g+M_h+2v.} +\] +Masked partial spectral layers satisfy the same estimate. +I do not multiply a shear bound once per stage. + +Nearest component rounding has error at most \(u/2\); a complex output +has error at most \(u/\sqrt2\). A disjoint layer updates at most \(2n\) +complex wires, so its error vector has norm at most \(\sqrt n\,u\). +The source schedule has at most \(L=4d+8\) layers, including empty +bit-reversal layers. Transporting each local residual through its +remaining exact suffix gives +\[ +\|\widehat z-\widetilde S z_0\|_2 +\le LH\sqrt n\,u\le LHnu. +\] +Every pre-round and rounded state has amplitude at most +\[ +A=H(R+Lnu). +\] +The source-bank error receives no coefficient-approximation term, +because the unrounded rational circuit restores that bank exactly. +Fixed-grid execution can still have nonzero source-restoration error; +the verifier includes a small-grid witness. + +The precision choices in Section 1 close the requested budget: +\[ +4(d+1)M\nu R<2^{-t}/4,\quad 2vR<2^{-t}/4,\quad +LHnu<2^{-t}/2. +\] +Here \(v\le1/32\) and \(H= j else row[j-i] + for j in range(n)] for i in range(n)]) + + +def lower(c): + return toep(c) + + +def invseries(f): + n = len(f) + ans = np.zeros(n, complex) + ans[0] = 1 / f[0] + for j in range(1, n): + ans[j] = -sum(f[k] * ans[j-k] for k in range(1, j+1)) / f[0] + return ans + + +def conv(a, b, n): + return np.convolve(a, b)[:n] + + +def diag(indices, values): + return [[((int(i),), np.array([[v]], complex)) for i, v in zip(indices, values)]] + + +def inverse(plan): + return [[(ids, np.linalg.inv(g)) for ids, g in layer] + for layer in reversed(plan)] + + +def parallel(a, b): + return [(a[j] if j < len(a) else []) + (b[j] if j < len(b) else []) + for j in range(max(len(a), len(b)))] + + +def fft(indices): + n = len(indices) + if n <= 1: + return [] + assert n & (n - 1) == 0 + bits = n.bit_length() - 1 + rev = [int(f"{j:0{bits}b}"[::-1], 2) for j in range(n)] + plan = [[((indices[i], indices[j]), np.array([[0, 1], [1, 0]], complex)) + for i, j in enumerate(rev) if i < j]] + size = 2 + while size <= n: + layer = [] + for start in range(0, n, size): + for j in range(size // 2): + w = np.exp(-2j * np.pi * j / size) + layer.append(((indices[start+j], indices[start+j+size//2]), + np.array([[1, w], [1, -w]], complex) / math.sqrt(2))) + plan.append(layer) + size *= 2 + return plan + + +def circ_shear(target, source, kernel): + """target += circulant(kernel) source, using these wires only.""" + p = parallel(fft(target), fft(source)) + lams = np.fft.fft(kernel) + mid = [[((source[j], target[j]), np.array([[1, 0], [lams[j], 1]], complex)) + for j in range(len(source))]] + return p + mid + inverse(p) + + +def toeplitz_shear(target, source, T): + """Cyclic + negacyclic decomposition; source and target are disjoint.""" + n = len(source) + assert T.shape == (n, n) and len(target) == n + c, r = T[:, 0], T[0, :] + g = np.zeros(n, complex) + h = np.zeros(n, complex) + g[0] = h[0] = c[0] / 2 + for j in range(1, n): + g[j] = (c[j] + r[n-j]) / 2 + h[j] = (c[j] - r[n-j]) / 2 + gamma = np.exp(1j * np.pi / n) + d = gamma ** np.arange(n) + twists = parallel(diag(target, d), diag(source, d)) + return (circ_shear(target, source, g) + twists + + circ_shear(target, source, d * h) + inverse(twists)) + + +def triangle_plan(indices, f): + n = len(indices) + STATS["triangle_nodes"] += 1 + STATS["max_triangle_coefficient"] = max( + STATS["max_triangle_coefficient"], float(np.max(np.abs(f)))) + if n == 1: + return diag(indices, f) + assert n % 2 == 0 + m = n // 2 + ev, od = indices[::2], indices[1::2] + e, o = np.asarray(f[::2]), np.asarray(f[1::2]) + k = conv(o, invseries(e), m) + zk = np.r_[0, k[:-1]] + s = e - np.r_[0, conv(o, k, m)[:-1]] + right = toeplitz_shear(ev, od, lower(zk)) + middle = parallel(triangle_plan(ev, e), triangle_plan(od, s)) + left = toeplitz_shear(od, ev, lower(k)) + return right + middle + left + + +def lowdisp_shear(target, source, T): + n = len(source) + Z = np.eye(n, k=-1) + Delta = T - Z @ T @ Z.T + U, vals, Vh = np.linalg.svd(Delta) + cutoff = 1e-11 * max(1.0, vals[0]) + rank = int(np.sum(vals > cutoff)) + STATS["max_displacement_rank"] = max(STATS["max_displacement_rank"], rank) + STATS["generator_shears"] += 1 + result = [] + reconstructed = np.zeros_like(T) + for j in range(rank): + g = U[:, j] + h = vals[j] * Vh[j, :] + STATS["max_generator_entry"] = max( + STATS["max_generator_entry"], float(np.max(np.abs(g))), + float(np.max(np.abs(h)))) + reconstructed += lower(g) @ lower(h).T + gamma = max(1.0, 2 * float(np.sum(np.abs(h)))) + p = h / gamma + p[0] += 1 + # U(h)=J L(h) J. This is a genuinely invertible source transform. + transform = triangle_plan(source[::-1], p) + result += transform + result += toeplitz_shear(target, source, gamma * lower(g)) + result += inverse(transform) + result += toeplitz_shear(target, source, -gamma * lower(g)) + assert np.max(np.abs(T - reconstructed)) < 1e-9 + return result + + +def full_plan(indices, M): + n = len(indices) + STATS["full_nodes"] += 1 + if n == 1: + return diag(indices, [M[0, 0]]) + m = n // 2 + A, B, C, D = M[:m, :m], M[:m, m:], M[m:, :m], M[m:, m:] + K = np.linalg.solve(A, B) + L = np.linalg.solve(A.T, C.T).T + S = D - C @ K + right = lowdisp_shear(indices[:m], indices[m:], K) + mid = parallel(full_plan(indices[:m], A), full_plan(indices[m:], S)) + left = lowdisp_shear(indices[m:], indices[:m], L) + return right + mid + left + + +def replay(plan, n, track=True): + out = np.eye(n, dtype=complex) + peak = 1.0 + min_det = 1.0 + for layer in plan: + used = set() + for ids, g in layer: + assert not used.intersection(ids), "non-disjoint layer" + used.update(ids) + min_det = min(min_det, float(abs(np.linalg.det(g)))) + out[list(ids), :] = g @ out[list(ids), :] + if track: + peak = max(peak, float(np.linalg.norm(out, 2))) + STATS["min_gate_determinant"] = min(STATS["min_gate_determinant"], min_det) + return out, peak + + +def main(): + rng = np.random.default_rng(20261013) + rows = [] + for n in [2, 4, 8, 16]: + f = rng.normal(size=n) / (12 * n) + f[0] += 1 + p = triangle_plan(list(range(n)), f) + actual, peak = replay(p, n) + rows.append({"kind": "triangular", "n": n, "rounds": len(p), + "gates": sum(map(len, p)), + "max_error": float(np.max(np.abs(actual-lower(f)))), + "peak_prefix_norm_2": peak}) + + c = rng.normal(size=n) / (20 * n) + r = rng.normal(size=n) / (20 * n) + c[0] += 1 + H = toep(c, r) + p = full_plan(list(range(n)), H) + actual, peak = replay(p, n, track=n <= 8) + rows.append({"kind": "full_toeplitz", "n": n, "rounds": len(p), + "gates": sum(map(len, p)), + "max_error": float(np.max(np.abs(actual-H))), + "peak_prefix_norm_2": peak if n <= 8 else None, + "input_distance_from_I_2": float(np.linalg.norm(H-np.eye(n), 2))}) + # Destructive control: dropping the second subtraction computes the wrong map. + # Independent direct parity block algebra across a range of sizes. + identities = [] + for n in [2, 4, 8, 16, 32]: + f = rng.normal(size=n) / n + f[0] += 2 + m = n // 2 + e, o = f[::2], f[1::2] + k = conv(o, invseries(e), m) + s = e - np.r_[0, conv(o, k, m)[:-1]] + E, O, K = lower(e), lower(o), lower(k) + Z = np.eye(m, k=-1) + left = np.block([[np.eye(m), np.zeros((m,m))], [K, np.eye(m)]]) + diagblock = np.block([[E, np.zeros((m,m))], [np.zeros((m,m)), lower(s)]]) + right = np.block([[np.eye(m), Z@K], [np.zeros((m,m)), np.eye(m)]]) + order = list(range(0,n,2)) + list(range(1,n,2)) + exact = lower(f)[np.ix_(order,order)] + identities.append({"n": n, "error": float(np.max(np.abs(left@diagblock@right-exact)))}) + sylvester = [] + for b in [1, 2, 4, 8]: + f = np.array([1.0]) + g = np.array([1.0]) + for j in range(b): + f = np.convolve(f, [1.0, 256.0 ** (j-b+0.5)]) + g = np.convolve(g, [1.0, 256.0 ** (-j-0.5)]) + fp = np.r_[f, np.zeros(3*b+2-len(f))] + fi = invseries(fp) + def hc(k): + return sum(g[v]*fi[k+v] for v in range(b+1) if 0 <= k+v < len(fi)) + K = np.array([[hc(i-b-j) for j in range(b)] for i in range(b)]) + H = np.array([[hc(i-j) for j in range(b)] for i in range(b)]) + S = np.zeros((2*b, 2*b), complex) + for j in range(b): + for k in range(b+1): + if j+k < 2*b: + S[j+k, j] += f[k] + if 0 <= b+j-k < 2*b: + S[b+j-k, b+j] += g[k] + inds = list(range(2*b)) + p = toeplitz_shear(inds[:b], inds[b:], K) + p += full_plan(inds[b:], H) + p += triangle_plan(inds, np.r_[f, np.zeros(2*b-len(f))]) + actual, peak = replay(p, 2*b, track=b <= 4) + sylvester.append({"b": b, "total_wires": 2*b, "rounds": len(p), + "gates": sum(map(len, p)), + "max_error": float(np.max(np.abs(actual-S))), + "H_minus_I_norm_1": float(np.linalg.norm(H-np.eye(b), 1)), + "H_minus_I_norm_infinity": float(np.linalg.norm(H-np.eye(b), np.inf)), + "peak_prefix_norm_2": peak if b <= 4 else None}) + # Removing the compensating dirty subtraction must fail. + b = 4 + gi, hi = np.array([1, .02, .01, .005]), np.array([.1, .04, .02, .01]) + pi = hi.copy() + pi[0] += 1 + target = np.block([[np.eye(b), np.zeros((b,b))], [lower(gi)@lower(hi).T, np.eye(b)]]) + pp = triangle_plan(list(range(b))[::-1], pi) + correct = pp + toeplitz_shear(list(range(b, 2*b)), list(range(b)), lower(gi)) + inverse(pp) + broken_actual, _ = replay(correct, 2*b, track=False) + correct += toeplitz_shear(list(range(b, 2*b)), list(range(b)), -lower(gi)) + correct_actual, _ = replay(correct, 2*b, track=False) + omission = {"correct_error": float(np.max(np.abs(correct_actual-target))), + "omit_second_subtraction_error": float(np.max(np.abs(broken_actual-target)))} + result = {"seed": 20261013, "note": "Floating replay supports, does not replace, algebraic proof.", + "controls": rows, "polyphase_identity": identities, + "normalized_sylvester": sylvester, "omission_control": omission, "stats": STATS} + (ROOT / "CIRCUIT-REPLAY.json").write_text(json.dumps(result, indent=2)+"\n") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/research/direct-circulant-production-precision/compiler-intervals/retained/engine.py b/research/direct-circulant-production-precision/compiler-intervals/retained/engine.py new file mode 100644 index 0000000000..e9f2f2b08d --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-intervals/retained/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/compiler-intervals/retained/exact.py b/research/direct-circulant-production-precision/compiler-intervals/retained/exact.py new file mode 100644 index 0000000000..aae41e6acf --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-intervals/retained/exact.py @@ -0,0 +1,242 @@ +"""Exact complex rational arithmetic for coefficient and rounded-gate certificates. + +Jose Manuel (jmbarrancoml), with substantial OpenAI Codex assistance. +Apache-2.0. +""" +from fractions import Fraction as Q +from hashlib import sha256 + +TRACK = None + + +def need(ok, message): + if not ok: + raise ValueError(message) + + +def qheight(value): + return max(abs(value.numerator).bit_length(), value.denominator.bit_length()) + + +class C: + __slots__ = ("re", "im") + + def __init__(self, re=0, im=0): + need(type(re) in (int, Q) and type(im) in (int, Q), "exact rational components") + self.re, self.im = Q(re), Q(im) + if TRACK is not None: + TRACK["max_observed_height"] = max(TRACK["max_observed_height"], + qheight(self.re), qheight(self.im)) + + @staticmethod + def wrap(value): + return value if isinstance(value, C) else C(value) + + def __add__(self, other): + other = C.wrap(other) + return C(self.re + other.re, self.im + other.im) + + __radd__ = __add__ + + def __neg__(self): + return C(-self.re, -self.im) + + def __sub__(self, other): + return self + -C.wrap(other) + + def __rsub__(self, other): + return C.wrap(other) + -self + + def __mul__(self, other): + other = C.wrap(other) + return C(self.re * other.re - self.im * other.im, + self.re * other.im + self.im * other.re) + + __rmul__ = __mul__ + + def conjugate(self): + return C(self.re, -self.im) + + def norm2(self): + return self.re * self.re + self.im * self.im + + def __truediv__(self, other): + other = C.wrap(other) + denominator = other.norm2() + need(denominator > 0, "nonzero divisor") + product = self * other.conjugate() + return C(product.re / denominator, product.im / denominator) + + def __rtruediv__(self, other): + return C.wrap(other) / self + + def __eq__(self, other): + if not isinstance(other, C) and type(other) not in (int, Q): + return False + other = C.wrap(other) + return self.re == other.re and self.im == other.im + + def record(self): + return [str(self.re), str(self.im)] + + +class Vec(list): + def __init__(self, values): + super().__init__(C.wrap(x) for x in values) + + def __mul__(self, other): + if isinstance(other, C) or type(other) in (int, Q): + return Vec(x * other for x in self) + need(len(self) == len(other), "elementwise vector dimensions") + return Vec(x * y for x, y in zip(self, other)) + + __rmul__ = __mul__ + + def __sub__(self, other): + need(len(self) == len(other), "vector subtraction dimensions") + return Vec(x - y for x, y in zip(self, other)) + + def copy(self): + return Vec(self) + + def __truediv__(self, scalar): + return Vec(x / scalar for x in self) + + +class Mat(list): + def __init__(self, rows): + super().__init__([C.wrap(x) for x in row] for row in rows) + + def __rmul__(self, scalar): + return Mat([[scalar * x for x in row] for row in self]) + + @property + def shape(self): + return (len(self), len(list.__getitem__(self, 0)) if self else 0) + + def __getitem__(self, key): + if not isinstance(key, tuple): + return list.__getitem__(self, key) + row, column = key + if isinstance(row, slice): + rows = list.__getitem__(self, row) + return Mat([r[column] for r in rows]) if isinstance(column, slice) else Vec(r[column] for r in rows) + selected = list.__getitem__(self, row) + return Vec(selected[column]) if isinstance(column, slice) else selected[column] + + +def eye(n): + return Mat([[int(i == j) for j in range(n)] for i in range(n)]) + + +def adjoint(matrix): + return Mat([[matrix[j][i].conjugate() for j in range(len(matrix))] + for i in range(len(matrix[0]))]) + + +def multiply(left, right): + return Mat([[sum((x * right[k][j] for k, x in enumerate(row)), C()) + for j in range(len(right[0]))] for row in left]) + + +def unitary(matrix): + return multiply(adjoint(matrix), matrix) == eye(len(matrix)) + + +def inverse_gate(matrix): + if unitary(matrix): + return adjoint(matrix) + if matrix.shape == (1, 1): + return Mat([[1 / matrix[0][0]]]) + if matrix.shape == (2, 2) and matrix[0][0] == matrix[1][1] == 1 and matrix[0][1] == 0: + return Mat([[1, 0], [-matrix[1][0], 1]]) + raise ValueError("unsupported nonunitary inverse gate") + + +def round_q(value, bits): + scale = 1 << bits + shifted = value * scale + Q(1, 2) + return Q(shifted.numerator // shifted.denominator, scale) + + +def rounded(value, bits): + return C(round_q(value.re, bits), round_q(value.im, bits)) + + +def norm2(vector): + return sum((x.norm2() for x in vector), Q(0)) + + +def component_l1(vector): + return sum((abs(x.re) + abs(x.im) for x in vector), Q(0)) + + +def ceil_log2(value): + value = Q(value) + need(value > 0, "positive logarithm bound") + result = value.numerator.bit_length() - value.denominator.bit_length() + power = Q(1 << result) if result >= 0 else Q(1, 1 << -result) + while power < value: + result += 1 + power *= 2 + while power / 2 >= value: + result -= 1 + power /= 2 + return result + + +def upper(value, bits=160): + scale = 1 << bits + scaled = value * scale + return Q(-((-scaled.numerator) // scaled.denominator), scale) + + +def vector_hash(vector): + digest = sha256() + for entry in vector: + for value in (entry.re, entry.im): + for integer in (value.numerator, value.denominator): + raw = abs(integer).to_bytes(max(1, (abs(integer).bit_length() + 7) // 8), "big") + digest.update(bytes([integer < 0])) + digest.update(len(raw).to_bytes(8, "big")) + digest.update(raw) + return digest.hexdigest() + + +def apply(plan, vector, bits=None): + global TRACK + state = Vec(vector) + old_track = TRACK + stats = {"max_observed_height": 0, "max_grid_numerator_bits": 0, + "max_reduced_fractional_bits": 0, "rounded_outputs": 0} + if bits is not None: + need(bits >= 1, "positive data precision") + for entry in state: + for value in (entry.re, entry.im): + need((value * (1 << bits)).denominator == 1, "input already on data grid") + TRACK = stats + try: + for layer in plan: + used = set() + for ids, gate in layer: + need(len(ids) == len(gate) in (1, 2), "one- or two-wire gate") + need(not used.intersection(ids) and len(set(ids)) == len(ids), "disjoint layer") + need(all(0 <= i < len(state) for i in ids), "wire bounds") + used.update(ids) + before = [state[i] for i in ids] + outputs = [sum((a * x for a, x in zip(row, before)), C()) for row in gate] + for i, value in zip(ids, outputs): + if bits is not None: + value = rounded(value, bits) + stats["rounded_outputs"] += 1 + for part in (value.re, value.im): + grid_integer = part * (1 << bits) + need(grid_integer.denominator == 1, "rounded output grid") + stats["max_grid_numerator_bits"] = max(stats["max_grid_numerator_bits"], + abs(grid_integer.numerator).bit_length()) + stats["max_reduced_fractional_bits"] = max(stats["max_reduced_fractional_bits"], + part.denominator.bit_length() - 1) + state[i] = value + finally: + TRACK = old_track + return state, stats diff --git a/research/direct-circulant-production-precision/compiler-intervals/retained/full.py b/research/direct-circulant-production-precision/compiler-intervals/retained/full.py new file mode 100644 index 0000000000..7f85ad1a89 --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-intervals/retained/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/compiler-intervals/retained/generator.py b/research/direct-circulant-production-precision/compiler-intervals/retained/generator.py new file mode 100644 index 0000000000..d761d3c88b --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-intervals/retained/generator.py @@ -0,0 +1,233 @@ +"""Exact generators connected to the retained compensated gate program. + +Jose Manuel (jmbarrancoml), with substantial OpenAI Codex assistance. +Apache-2.0. Macro/compiler: Vlado/PR1673; certified phases: Chafik/PR628. +""" +import ast +import copy +from fractions import Fraction as Q +from hashlib import sha256 +import json + +from exact import C, Mat, Vec, ceil_log2, component_l1, inverse_gate, need, norm2 +from engine import Builder, Phases, split_kernel +from triangular import Triangle, allocation as triangle_allocation + +SOURCE = "research/capped-phase-fusion/evidence/inplace_algebra_ultra/" +PRODUCER = "research/rational-unitary-fft/vendor/stein_rational.py" +PROVENANCE = "research/rational-unitary-fft/vendor/STEIN-PROVENANCE.json" +ORACLE = "research/cubic-cyclic-inverse/vendor/interval_kernel.py" + + +def load_producer(raw): + record = json.loads(raw[PROVENANCE]) + need(record["source_commit"] == "e457d5e912a27307d725827aeca7198169320b84" + and record["source_git_blob"] == "71b240a460a185ee2fe926cd189b56aeac6f997f" + and sha256(raw[PRODUCER]).hexdigest() == record["sha256"], + "original producer identity and retained bytes") + namespace = {"__name__": "_frozen_rational_stein"} + exec(compile(raw[PRODUCER], "", "exec", optimize=0), namespace) + return namespace + + +def lower(vector): + return Mat([[vector[i - j] if i >= j else C() for j in range(len(vector))] + for i in range(len(vector))]) + + +def prepare(matrix, producer): + matrix = Mat(matrix) + m = len(matrix) + need(m > 0 and m & (m - 1) == 0 and matrix.shape == (m, m), "dyadic generator matrix") + displacement = Mat([[matrix[i][j] - (matrix[i - 1][j - 1] if i and j else C()) + for j in range(m)] for i in range(m)]) + old_c = producer["C"] + old_e = producer["Matrix"]([[old_c(x.re, x.im) for x in row] for row in displacement]) + old_items, heights = producer["generators"](old_e) + items = [dict(column=item["column"], gamma=item["gamma"], + scale=item["scale"], scale_exponent=item["scale_exponent"], + g=Vec(C(x.re, x.im) for x in item["g"]), + row=Vec(C(x.re, x.im) for x in item["row"])) for item in old_items] + bound_e = max(max(component_l1(row) for row in displacement), + max(component_l1(column) for column in zip(*displacement))) + need(all(norm2(item["g"]) <= 1 and norm2(item["row"]) < 4 * bound_e ** 2 + and 2 * component_l1(item["row"]) <= item["gamma"] for item in items), + "actual bounded rational generator output") + return items, displacement, bound_e, heights + + +def allocation(m, rank, bound_e, radius, target, incoming): + need(type(m) is int and m > 0 and m & (m - 1) == 0, "dyadic macro size") + need(type(rank) is int and 0 <= rank <= m and type(bound_e) in (int, Q) + and bound_e >= 0, "generator count and exact displacement bound") + need(type(radius) in (int, Q) and radius >= 1 and type(target) is int + and target >= 1 and type(incoming) is int and incoming >= 0, "global generator input") + d = m.bit_length() - 1 + kg, alpha = 2 * m + 16 * m * bound_e, 2 * rank * m * bound_e + checkpoint = 10 + 4 * alpha + 2 * kg + child = max(Q(3200 * m ** 3), 2 + 2 * kg) + execution = child * checkpoint + depth = rank * (8 * d * d + 32 * d + 18) + gates = rank * m * (4 * d * d + 24 * d + 22) + s = target + ceil_log2(4 * (rank + 1) * (kg + 1) * (radius + 1)) + eta = Q(1, 1 << s) + triangle = triangle_allocation(m, 1, s) + envelope = max(Q(6), 2 * kg) + p = max(triangle["phase_bits"], s + ceil_log2(32 * (d + 1) * (envelope + 1))) + mult = max(triangle["multiplier_bits"], s + 4) + triangle = dict(triangle, phase_bits=p, multiplier_bits=mult, + coefficient_height_bound=max(4 * p + 24, mult + 5, + 2 * triangle["leaf_bits"] + 16)) + data = max(incoming, target + ceil_log2(max(Q(1), 2 * depth * execution * m))) + u = Q(1, 1 << data) + defect = rank * (kg + 1) * eta + rounding = depth * execution * m * u + need(defect <= 1 and defect * radius + rounding <= Q(1, 1 << target), + "complete compensated-generator target budget") + amplitude = execution * radius + depth * execution ** 2 * m * u + integer = max(1, ceil_log2(max(Q(1), amplitude))) + 2 + height = max(4 * p + 24, mult + ceil_log2(envelope + 2) + 2, + 2 * triangle["leaf_bits"] + 16) + return dict(m=m, rank=rank, displacement_bound=bound_e, radius=radius, + target_bits=target, incoming_bits=incoming, kg=kg, alpha=alpha, + checkpoint_bound=checkpoint, child_bound=child, execution_bound=execution, + segment_bound=execution ** 2, layer_bound=depth, gate_bound=gates, + child_target_bits=s, eta=eta, phase_bits=p, multiplier_bits=mult, + leaf_bits=triangle["leaf_bits"], data_bits=data, + multiplier_envelope=envelope, coefficient_error=defect, + rounding_error=rounding, total_error=defect * radius + rounding, + amplitude_bound=amplitude, integer_bits=integer, + coefficient_height_bound=height, + temporary_bits=2 * data + 8 * height + 2 * integer + 32), triangle + + +def macro_template(source): + tree = ast.parse(source) + function = next(n for n in tree.body if isinstance(n, ast.FunctionDef) + and n.name == "lowdisp_shear") + loop = next(n for n in function.body if isinstance(n, ast.For)) + start = next(i for i, n in enumerate(loop.body) if isinstance(n, ast.Assign) + and isinstance(n.targets[0], ast.Name) and n.targets[0].id == "p") + tail = copy.deepcopy(loop.body[start:]) + need([type(n).__name__ for n in tail] == + ["Assign", "AugAssign", "Assign", "AugAssign", "AugAssign", "AugAssign", "AugAssign"], + "retained seven-statement macro") + identity = sha256(ast.dump(ast.Module(body=tail, type_ignores=[])).encode()).hexdigest() + need(identity == "2a2e0f16a779597fa555857307451831bace11e66861fdc3caf26d2373a21210", + "unchanged source macro identity") + function = ast.FunctionDef( + name="emit", args=ast.arguments(posonlyargs=[], args=[ast.arg(arg=n) for n in + ("target", "source", "g", "h", "gamma")], vararg=None, kwonlyargs=[], + kw_defaults=[], kwarg=None, defaults=[]), + body=[ast.Assign(targets=[ast.Name(id="result", ctx=ast.Store())], + value=ast.List(elts=[], ctx=ast.Load()))] + tail + + [ast.Return(value=ast.Name(id="result", ctx=ast.Load()))], + decorator_list=[], type_params=[]) + module = ast.fix_missing_locations(ast.Module(body=[function], type_ignores=[])) + return compile(module, "", "exec", optimize=0), identity + + +class PairedNegative(Builder): + def __init__(self, positive, source): + super().__init__(positive.phases, positive.multiplier_bits, source) + self.positive = positive + + def spectrum(self, kernel): + row = self.positive.spectra[len(self.spectra)] + need(Vec(kernel) == Vec(-x for x in row["kernel"]), "paired negative spectral kernel") + result = Vec(-x for x in row["multipliers"]) + bound = self.bounds[len(self.spectra)] + need(bound == row["bound"], "paired spectral envelope") + v = Q(1, 1 << self.multiplier_bits) + need(all(x.norm2() <= (bound + v) ** 2 for x in result), "negative stored multiplier bound") + self.spectra.append(dict(kernel=Vec(kernel), multipliers=result, bound=bound)) + return result + + +class Program: + def __init__(self, bound, triangle_bound, raw, phase_oracle=None): + self.bound, self.triangle_bound, self.raw = bound, triangle_bound, raw + self.phases = phase_oracle if phase_oracle is not None else Phases(bound["phase_bits"], raw[ORACLE]) + need(self.phases.bits == bound["phase_bits"], "common generator phase precision") + self.source = list(range(bound["m"])) + self.target = list(range(bound["m"], 2 * bound["m"])) + self.stages, self.position, self.calls = [], 0, [] + self.pending = None + self.last_triangle = None + self.triangles, self.shears = [], [] + code, self.macro_ast = macro_template(raw[SOURCE + "check_circuits.py"]) + namespace = dict(triangle_plan=self.triangle, toeplitz_shear=self.shear, + inverse=self.inverse, lower=lower) + exec(code, namespace) + self.emit = namespace["emit"] + + def record(self, kind, plan, **details): + self.calls.append(kind) + self.stages.append(dict(kind=kind, start=self.position, stop=self.position + len(plan), + **details)) + self.position += len(plan) + return plan + + def triangle(self, indices, coefficients): + builder = Triangle(self.triangle_bound, self.raw[SOURCE + "check_circuits.py"], + self.raw[ORACLE], self.phases) + local_indices = [self.source.index(i) for i in indices] + local = builder.plan(coefficients, local_indices) + plan = [[(tuple(self.source[i] for i in ids), gate) for ids, gate in layer] for layer in local] + need(builder.bound["coefficient_error"] <= self.bound["eta"], "triangle operator allowance") + self.last_triangle = plan + self.triangles.append(builder) + return self.record("triangle", plan, symbol=Vec(coefficients), indices=list(indices), + operator_error=builder.bound["coefficient_error"]) + + def inverse(self, plan): + need(plan is self.last_triangle, "inverse of the same stored triangle") + result = [[(ids, inverse_gate(gate)) for ids, gate in layer] for layer in reversed(plan)] + return self.record("inverse", result) + + def shear(self, target, source, matrix): + need(target == self.target and source == self.source, "literal complete dirty banks") + if self.pending is None: + builder = Builder(self.phases, self.bound["multiplier_bits"], + self.raw[SOURCE + "check_circuits.py"]) + local = builder.plan(matrix) + self.pending = (builder, matrix, local) + kind = "positive" + else: + positive, original, positive_plan = self.pending + need(matrix == -1 * original, "literal negative compensation matrix") + builder = PairedNegative(positive, self.raw[SOURCE + "check_circuits.py"]) + local = builder.plan(matrix) + m = len(source) + need(len(local) == len(positive_plan), "same compensation layer schedule") + for a, b in zip(positive_plan, local): + need(len(a) == len(b), "same compensation gate schedule") + for (ids, g), (other_ids, h) in zip(a, b): + crossing = len(ids) == 2 and ids[0] < m <= ids[1] + expected = Mat([[1, 0], [-g[1][0], 1]]) if crossing else g + need(ids == other_ids and h == expected, "paired coefficients preserve source order") + self.pending = None + kind = "compensation" + g, h = split_kernel(matrix) + envelope = component_l1(g) + component_l1(h) + defect = (4 * len(source).bit_length() * envelope * self.phases.nu + + Q(2, 1 << self.bound["multiplier_bits"])) + need(envelope <= self.bound["multiplier_envelope"] and defect <= self.bound["eta"], + "scaled shear absolute operator allowance") + self.shears.append(builder) + mapping = source + target + plan = [[(tuple(mapping[i] for i in ids), gate) for ids, gate in layer] for layer in local] + return self.record(kind, plan, matrix=matrix, operator_error=defect, envelope=envelope) + + def plan(self, items): + result = [] + for item in items: + before = Vec(item["row"]) + result += self.emit(self.target, self.source, item["g"], item["row"], item["gamma"]) + need(before == item["row"], "fresh division preserves generator row") + need(self.pending is None and self.calls == + ["triangle", "positive", "inverse", "compensation"] * len(items), + "complete retained compensated call sequence") + need(self.position == len(result) <= self.bound["layer_bound"] + and sum(map(len, result)) <= self.bound["gate_bound"], "full program gate/layer budget") + return result diff --git a/research/direct-circulant-production-precision/compiler-intervals/retained/interval_kernel.py b/research/direct-circulant-production-precision/compiler-intervals/retained/interval_kernel.py new file mode 100644 index 0000000000..1182175a55 --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-intervals/retained/interval_kernel.py @@ -0,0 +1,61 @@ +"""Outward-rounded rational enclosures for prime-power cyclic kernels.""" +from fractions import Fraction as F +import math +from functools import lru_cache + +BITS=1536 +SCALE=1<4:raise ValueError('angle bound') + itheta=(point(0),theta) + total=term=ONE + # Taylor remainder for complex exp: <=exp(4)*4^(N+1)/(N+1)! <128*... + n=0 + while True: + n+=1;term=cmul(term,itheta);term=(scale(term[0],F(1,n)),scale(term[1],F(1,n)));total=cadd(total,term) + remainder=F(128*4**(n+1),math.factorial(n+1)) + if remainder= 0 else Q(1, 1 << -exponent) + + +def norm_scale(squared): + need(squared > 0, "positive residual squared norm") + exponent = (squared.numerator.bit_length() - squared.denominator.bit_length()) // 2 + scale = pow2(exponent) + while scale * scale < squared: + exponent += 1 + scale *= 2 + while scale * scale / 4 >= squared: + exponent -= 1 + scale /= 2 + need(squared <= scale * scale < 4 * squared, "dyadic norm bracket") + observe(scale) + return scale, exponent + + +def upper_dyadic(value): + need(value > 0, "positive dyadic upper target") + exponent = value.numerator.bit_length() - value.denominator.bit_length() + result = pow2(exponent) + while result < value: + result *= 2 + while result / 2 >= value: + result /= 2 + return observe(result) + + +def height(matrix): + return max([1] + [max(abs(x.numerator).bit_length(), x.denominator.bit_length()) + for row in matrix for entry in row + for x in (C.wrap(entry).re, C.wrap(entry).im)]) + + +def generators(displacement): + """Return column g, explicit coefficient ROW r, and a dyadic admission scale.""" + global MAX_HEIGHT + displacement = Matrix(displacement) + size = len(displacement) + need(size > 0 and all(len(row) == size for row in displacement), "nonempty square displacement") + input_height = height(displacement) + MAX_HEIGHT = input_height + columns = [[displacement[i][j] for i in range(size)] for j in range(size)] + residuals, result = [], [] + for column_index, column in enumerate(columns): + residual = list(column) + for old, squared in residuals: + factor = inner(old, residual) / squared + residual = [x - factor * y for x, y in zip(residual, old)] + squared = norm2(residual) + if squared == 0: + continue + scale, exponent = norm_scale(squared) + g = Vector(x / scale for x in residual) + row = Vector(inner(residual, c) * (scale / squared) for c in columns) + gamma = upper_dyadic(max(Q(1), 2 * component_l1(row))) + need(norm2(g) <= 1 and 2 * component_l1(row) <= gamma, "bounded generator admission") + residuals.append((residual, squared)) + result.append({"column": column_index, "residual": residual, "squared_norm": squared, + "scale": scale, "scale_exponent": exponent, "g": g, "row": row, + "gamma": gamma}) + return result, {"input_height": input_height, "max_observed_height": MAX_HEIGHT} + + +def lower(vector): + return Matrix([[vector[i - j] if i >= j else C() for j in range(len(vector))] + for i in range(len(vector))]) + + +def transpose(matrix): + return Matrix(zip(*matrix)) + + +def frobenius2(matrix): + return observe(sum((C.wrap(x).norm2() for row in matrix for x in row), Q(0))) + + +def norm_bound(matrix): + """Rational upper bound for the induced 2-norm.""" + return max(max(component_l1(row) for row in matrix), + max(component_l1(column) for column in zip(*matrix))) + + +def exact_record(matrix): + return [[C.wrap(x).record() for x in row] for row in matrix] diff --git a/research/direct-circulant-production-precision/compiler-intervals/retained/triangular.py b/research/direct-circulant-production-precision/compiler-intervals/retained/triangular.py new file mode 100644 index 0000000000..2bd8de01a7 --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-intervals/retained/triangular.py @@ -0,0 +1,200 @@ +"""Source-bound rational parity recursion with a common precision allocation. + +Jose Manuel (jmbarrancoml), with substantial OpenAI Codex assistance. +Apache-2.0. Parity recursion and its stability premise: 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, inverse_gate, need, + rounded) +from engine import Builder, Phases, split_kernel + + +def allocation(n, radius, target, incoming=0): + need(type(n) is int and n > 0 and n & (n - 1) == 0, "dyadic triangle size") + need(type(radius) in (int, Q) and radius >= 1, "exact triangle radius") + need(type(target) is int and target >= 1, "positive triangle target") + need(type(incoming) is int and incoming >= 0, "incoming triangle grid") + d = n.bit_length() - 1 + q, depth, bound = 2 * d + 1, 4 * d * d + 12 * d + 1, 100 * n ** 3 + s = target + ceil_log2(4 * q * bound ** 3 * (radius + 1)) + p = s + ceil_log2(48 * (d + 1)) + multiplier = s + 2 + data = max(incoming, target + ceil_log2(64 * depth * bound * n)) + epsilon, u = Q(1, 1 << s), Q(1, 1 << data) + theta = q * bound ** 2 * epsilon + coefficient = 2 * q * bound ** 3 * epsilon + rounding = 32 * depth * bound * n * u + need(theta <= Q(1, 4) and coefficient * radius + rounding <= Q(1, 1 << target), + "complete triangular error allocation") + amplitude = 32 * bound * radius + 1024 * depth * bound ** 2 * n * u + integer = max(1, ceil_log2(max(Q(1), amplitude))) + 2 + height = max(4 * p + 24, multiplier + 5, 2 * s + 16) + return dict(n=n, radius=radius, target_bits=target, incoming_bits=incoming, + ideal_bound=bound, macro_layers=q, layer_bound=depth, + gate_bound=n * (2 * d * d + 8 * d + 1), + leaf_bits=s, phase_bits=p, multiplier_bits=multiplier, + data_bits=data, epsilon=epsilon, theta=theta, + coefficient_error=coefficient, rounding_error=rounding, + total_error=coefficient * radius + rounding, + physical_prefix_suffix_bound=32 * bound, + segment_bound=1024 * bound ** 2, amplitude_bound=amplitude, + integer_bits=integer, coefficient_height_bound=height, + temporary_bits=2 * data + 8 * height + 2 * integer + 32) + + +class Plan(list): + """Actual layers plus consecutive, disjoint-support macro partitions.""" + def __init__(self, layers, blocks): + super().__init__(layers) + self.blocks = blocks + + def __add__(self, other): + need(isinstance(other, Plan), "typed triangular composition") + offset = len(self) + blocks = [dict(block) for block in self.blocks] + blocks += [dict(start=b["start"] + offset, stop=b["stop"] + offset, + pieces=list(b["pieces"])) for b in other.blocks] + return Plan(list(self) + list(other), blocks) + + +class Concatenate: + def __getitem__(self, parts): + values = [] + for part in parts: + values.extend(part if isinstance(part, (list, tuple)) else [part]) + return Vec(values) + + +def convolution(a, b): + return Vec(sum((a[j] * b[k - j] for j in range(len(a)) + if 0 <= k - j < len(b)), C()) + for k in range(len(a) + len(b) - 1)) + + +class AdaptTriangle(ast.NodeTransformer): + def __init__(self): + self.changes = [] + + def visit_Assign(self, node): + if (len(node.targets) == 1 and isinstance(node.targets[0], ast.Subscript) + and isinstance(node.targets[0].slice, ast.Constant) + and node.targets[0].slice.value == "max_triangle_coefficient"): + self.changes.append("exact-component-diagnostic") + node.value = ast.parse( + "max(STATS['max_triangle_coefficient'], component_l1(f))", + mode="eval").body + return node + return self.generic_visit(node) + + def visit_Return(self, node): + if (isinstance(node.value, ast.Call) and isinstance(node.value.func, ast.Name) + and node.value.func.id == "diag"): + self.changes.append("stored-rounded-leaf") + node.value.func.id = "leaf_diag" + return self.generic_visit(node) + + +class Triangle: + def __init__(self, bound, circuit_source, oracle_source, phase_oracle=None): + self.bound, self.circuit_source = bound, circuit_source + self.phases = phase_oracle if phase_oracle is not None else Phases(bound["phase_bits"], oracle_source) + need(self.phases.bits == bound["phase_bits"], "common triangular phase precision") + base = Builder(self.phases, bound["multiplier_bits"], circuit_source) + self.source_parallel = base.namespace["parallel"] + self.source_inverse = base.namespace["inverse"] + self.children, self.leaves = [], [] + selected = {"toep", "lower", "invseries", "conv", "triangle_plan"} + tree = ast.parse(circuit_source) + 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 parity source") + self.original_ast = sha256(ast.dump(tree).encode()).hexdigest() + adapter = AdaptTriangle() + tree = ast.fix_missing_locations(adapter.visit(tree)) + need(adapter.changes == ["exact-component-diagnostic", "stored-rounded-leaf"], + "exact declared parity adaptations") + self.adapted_ast = sha256(ast.dump(tree).encode()).hexdigest() + facade = SimpleNamespace(asarray=lambda a, dtype=None: Vec(a), + array=lambda a, dtype=None: Mat(a), + zeros=lambda n, dtype=None: Vec([0] * n), + convolve=convolution, r_=Concatenate()) + self.stats = {"triangle_nodes": 0, "max_triangle_coefficient": Q(0)} + self.namespace = dict(np=facade, STATS=self.stats, component_l1=component_l1, + leaf_diag=self.leaf, parallel=self.parallel, + toeplitz_shear=self.shear) + exec(compile(tree, "", "exec", optimize=0), + self.namespace) + + def leaf(self, indices, values): + need(len(indices) == len(values) == 1, "scalar triangular leaf") + wanted = values[0] + stored = rounded(wanted, self.bound["leaf_bits"]) + epsilon = self.bound["epsilon"] + need(Q(1, 4) <= wanted.norm2() <= 4, "ideal scalar leaf margin") + need((stored - wanted).norm2() <= epsilon ** 2 + and stored.norm2() >= Q(1, 16), "stored scalar leaf margin") + gate = Mat([[stored]]) + inverse = inverse_gate(gate) + need(stored * inverse[0][0] == 1, "same stored scalar reciprocal") + piece = dict(kind="leaf", ids=list(indices), ideal=Mat([[wanted]]), + error=epsilon, stored=stored, reciprocal=inverse[0][0]) + self.leaves.append(piece) + return Plan([[(tuple(indices), gate)]], + [dict(start=0, stop=1, pieces=[piece])]) + + def shear(self, target, source, matrix): + n = len(source) + need(len(set(source + target)) == 2 * n, "owned disjoint parity banks") + child = Builder(self.phases, self.bound["multiplier_bits"], self.circuit_source) + local = child.plan(matrix) + g, h = split_kernel(matrix) + envelope = component_l1(g) + component_l1(h) + v = Q(1, 1 << self.bound["multiplier_bits"]) + defect = 4 * (n.bit_length()) * envelope * self.phases.nu + 2 * v + need(envelope + 2 * v <= 6 and defect <= self.bound["epsilon"], + "bounded parity child and allocated operator defect") + mapping = source + target + layers = [[(tuple(mapping[i] for i in ids), gate) for ids, gate in layer] + for layer in local] + piece = dict(kind="shear", ids=list(mapping), ideal=matrix, error=defect, + envelope=envelope, source_ast=child.original_ast, + adapted_ast=child.adapted_ast, local_layers=len(local)) + self.children.append(piece) + return Plan(layers, [dict(start=0, stop=len(layers), pieces=[piece])]) + + def parallel(self, left, right): + need([(b["start"], b["stop"]) for b in left.blocks] + == [(b["start"], b["stop"]) for b in right.blocks], + "equal sibling macro boundary partitions") + blocks = [] + for a, b in zip(left.blocks, right.blocks): + pieces = a["pieces"] + b["pieces"] + ids = [i for piece in pieces for i in piece["ids"]] + need(len(ids) == len(set(ids)), "disjoint sibling macro supports") + blocks.append(dict(start=a["start"], stop=a["stop"], pieces=pieces)) + return Plan(self.source_parallel(left, right), blocks) + + def plan(self, symbol, indices=None): + symbol = Vec(symbol) + n = len(symbol) + need(n == self.bound["n"], "allocated triangle dimension") + need(component_l1(symbol - Vec([1] + [0] * (n - 1))) <= Q(1, 2), + "component-l1 near-identity admission") + indices = list(range(n)) if indices is None else list(indices) + need(len(indices) == n and sorted(indices) == list(range(n)), "triangle wire permutation") + result = self.namespace["triangle_plan"](indices, symbol) + need(self.stats["triangle_nodes"] == 2 * n - 1, "complete parity recursion tree") + need(len(result.blocks) == self.bound["macro_layers"] + and len(result) <= self.bound["layer_bound"] + and sum(map(len, result)) <= self.bound["gate_bound"], "complete schedule bounds") + return result + + def inverse(self, plan): + # Forward pieces certify forward defects. Inverse endpoint bounds use + # the inverse-product proof, not relabelled forward macro certificates. + return self.source_inverse(plan) diff --git a/research/direct-circulant-production-precision/compiler-intervals/review/EVIDENCE-OPTIMIZED.json b/research/direct-circulant-production-precision/compiler-intervals/review/EVIDENCE-OPTIMIZED.json new file mode 100644 index 0000000000..09ebb7de38 --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-intervals/review/EVIDENCE-OPTIMIZED.json @@ -0,0 +1,39 @@ +{ + "status": "PASS_INDEPENDENT_NESTED_DOWNSET_REVIEW", + "proof_sha256": "e942012e66adc2d696cde3fedd6ae9c73df98e77a71b16e5004f5a74ccdfaa07", + "authenticated_origins": 18, + "primitive": { + "cuts": 17, + "ordered_intervals": 149, + "principal_minor_norm_certificates": 298, + "unchanged_cap": "14/9" + }, + "dag": { + "atoms": 10, + "downsets": 38, + "nested_downset_pairs": 475, + "noncommuting_wrong_order_controls": 394, + "matching_cuts": 53, + "ordered_intervals": 1404, + "same_layer_intervals": 136, + "simultaneous_nonempty_fragments": 22, + "zero_atom_predecessor_cases": 32, + "B": "25121/11220", + "eta": "1/1073741824", + "theta": "631064641/13517164023644160", + "H": "8589934597/5368709120", + "relative_interval_cap": "46564351760185622826204270169/3628485919113590199025664000", + "physical_wire_order": [ + 2, + 0, + 3, + 1 + ], + "scope": "synthetic rational DAG, not a source-factory execution" + }, + "generator": { + "prefix_suffix_checkpoint_equalities": 8, + "current_term_required_in_C": true + }, + "scope": "Exact synthetic rational corroboration and independent written proof/source review; no all-size enumeration" +} diff --git a/research/direct-circulant-production-precision/compiler-intervals/review/EVIDENCE.json b/research/direct-circulant-production-precision/compiler-intervals/review/EVIDENCE.json new file mode 100644 index 0000000000..09ebb7de38 --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-intervals/review/EVIDENCE.json @@ -0,0 +1,39 @@ +{ + "status": "PASS_INDEPENDENT_NESTED_DOWNSET_REVIEW", + "proof_sha256": "e942012e66adc2d696cde3fedd6ae9c73df98e77a71b16e5004f5a74ccdfaa07", + "authenticated_origins": 18, + "primitive": { + "cuts": 17, + "ordered_intervals": 149, + "principal_minor_norm_certificates": 298, + "unchanged_cap": "14/9" + }, + "dag": { + "atoms": 10, + "downsets": 38, + "nested_downset_pairs": 475, + "noncommuting_wrong_order_controls": 394, + "matching_cuts": 53, + "ordered_intervals": 1404, + "same_layer_intervals": 136, + "simultaneous_nonempty_fragments": 22, + "zero_atom_predecessor_cases": 32, + "B": "25121/11220", + "eta": "1/1073741824", + "theta": "631064641/13517164023644160", + "H": "8589934597/5368709120", + "relative_interval_cap": "46564351760185622826204270169/3628485919113590199025664000", + "physical_wire_order": [ + 2, + 0, + 3, + 1 + ], + "scope": "synthetic rational DAG, not a source-factory execution" + }, + "generator": { + "prefix_suffix_checkpoint_equalities": 8, + "current_term_required_in_C": true + }, + "scope": "Exact synthetic rational corroboration and independent written proof/source review; no all-size enumeration" +} diff --git a/research/direct-circulant-production-precision/compiler-intervals/review/FROZEN.json b/research/direct-circulant-production-precision/compiler-intervals/review/FROZEN.json new file mode 100644 index 0000000000..0a330a0345 --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-intervals/review/FROZEN.json @@ -0,0 +1,6 @@ +{ + "EVIDENCE-OPTIMIZED.json": "aac7dc89326bad10e8671a6454a2b86dfd28b92c12f93c149120562b264358aa", + "EVIDENCE.json": "aac7dc89326bad10e8671a6454a2b86dfd28b92c12f93c149120562b264358aa", + "REVIEW.md": "b254641c34ef041e70be90937c41974395a056ca90726fbf9b59219df014c972", + "independent.py": "57653629cbc939556795c4c6b80790d95d7fff754b4c723c5f64c69dc43b890b" +} diff --git a/research/direct-circulant-production-precision/compiler-intervals/review/REVIEW.md b/research/direct-circulant-production-precision/compiler-intervals/review/REVIEW.md new file mode 100644 index 0000000000..9fdc9a4bfb --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-intervals/review/REVIEW.md @@ -0,0 +1,208 @@ +# Separate review of source-ordered compiler cuts and relative intervals + +**Disposition: accept the scoped mathematical result under its stated +source premises.** The reviewed author proof is `norm/package/PROOF.md`, +SHA-256 +`e942012e66adc2d696cde3fedd6ae9c73df98e77a71b16e5004f5a74ccdfaa07`. +The explicit definition of C requested below is included in this reviewed +revision. It is the only clarification from the initial frozen draft; no +numerical constant or mathematical conclusion changed. + +The accepted scope is a statement about exact stored one- and two-wire +mathematical gates, including any subset of a matching layer. It is not +a claim about partially overwritten physical outputs, workspace lifetimes, +the complete multiplier or any canonical assumption discharge. + +## 1. Primitive partial matchings + +The retained `engine.Builder` adapts the authenticated FFT/shear syntax, +constructs exactly two spectral matchings and checks the certified rational +phases are unit modulus. Its butterfly has columns `(a,b)` and `(b*w,-a*w)`; +`a^2+b^2=1` and `|w|=1`, so these columns are exactly orthonormal. Independently +prepared twists are also exactly unitary. Each other primitive gate stays +inside one of the two banks. The two spectral layers consist of disjoint +lower-shear pairs. + +For a bank-diagonal unitary V and lower shear S(A), conjugation changes A +to `Vy A Vx^-1` without changing its norm. Moving all bank unitaries to one +side of an arbitrary gate interval leaves a sum of at most two such +transformed masked spectral diagonals. A partial matching merely replaces +some diagonal entries by zero. Its norm is no greater than the entire +diagonal's norm. Consequently the same `1+Mg+Mh+2v` cap holds for the +interval and its exact inverse. This argument is valid over the complex +numbers and uses no commutation between the two transformed A matrices. + +This does not improve Brian's #4976 generic interpolation theorem. An +arbitrary nonunitary compensating factor can violate the source-specific +claim. Nor does replacing a complex twiddle by its conjugate reverse the +entire butterfly. The source's complete inverse gate/order is necessary. + +## 2. Triangular and generator hierarchy + +The actual `Triangle.parallel` compares the siblings' `(start,stop)` macro +partitions and rejects overlapping macro supports. Thus the fragments at +this level really are direct sums. The source admission gives each shear +fragment cap seven and stored scalar reciprocal cap four. Its macro +perturbation argument gives completed prefix cap `2 Btri` and remaining +suffix cap `4 Btri`. Multiplication by at most seven yields `28 Btri`, +which is strictly below the retained `3200 m^3 = 32 Btri` allowance. +Matching-subset cuts add no extra interpolation constant. + +I checked the generator checkpoint formulas directly without commuting +any of p, h, A or C. The four chronological calls are + + diag(p,I); S(h); diag(p^-1,I); S(-h). + +They compose to `S(h(p-I))`. If A is the sum of preceding **stored** term +operators and C is the sum of the current stored term **plus all later +stored terms**, the four displayed prefixes and suffixes in the author +proof follow by matrix multiplication. In particular the suffix after +the first call is `L(p^-1, C p^-1)`. Defining C as only the later terms +would make that formula wrong. The retained `GENERATOR-PROOF.md` §3 +already gives the intended inclusive definition; the author has made +it explicit in the accepted supplement. + +The inverse formula is `L(B,D)^-1=L(B^-1,-D B^-1)`, with this order. +Using `||p||<=2`, `||p^-1||<=4`, `||h||<=k` and `||A||,||C||<=a` +gives the stated common checkpoint cap `4+4a+2k`. The final checkpoints +use the actual completed earlier/later term sums rather than bounding +every individual term again. Combining one unfinished child with one +checkpoint gives the original Hgen. A rank-zero child is an identity +atom with no active fragment. The conditioning, generator identities, +phase certification and coefficient-defect assumptions remain inherited. + +## 3. Source-time factorization and disjoint active atoms + +For this recursive source DAG, an upper atom precedes all descendants, +and the lower atom follows them. Incomparable atoms have disjoint logical +supports even if the physical wire list is permuted. Their exact stored +endpoints commute for that reason, not because all source matrices commute. + +At a cut in layer k, atoms with `stop<=k` form a downset I. A zero-duration +atom is included at its actual timestamp, even if that timestamp is also +the first layer of a descendant. Atoms with `start<=k=1-sum gl`. Neumann inversion then bounds W and W inverse +by `1/(1-theta)`. Therefore the relative completed endpoint and its inverse +have norm at most `B^2/(1-theta)`. + +Finally, + + C(v) C(u)^-1 = Fv [Qhat(Iv) Qhat(Iu)^-1] Fu^-1. + +Both boundary factors cost H. This proves the advertised interval and +inverse cap `B^2 H^2/(1-theta) <= (4/3)B^2 H^2 < 2B^2 H^2`. +No norm of the ideal whole endpoint is needed in this relative argument; +removing the old L0 squared factor is justified. The argument includes +identical completed sets and multiple simultaneous active atoms. In one +matching layer, actual time-ordered subsets are nested, and the same +formula applies. Empty or full local fragments cause no exception. + +Substituting the separately retained production inequalities gives +`2 B^2 H^2 <= 2^189 t^100`. That arithmetic is correct. Propagating this +gate cap through the external sixteen-H lowering and complete precision +selector remains separate work; the reviewed package does not claim it. + +## 5. Separate exact evidence + +`independent.py` imports neither the author's `audit.py` nor a retained +factory or source matrix helper. It authenticates all 18 retained origins +and checks a distinct set of rational fixtures using standard-library +Fractions. Its spectral oracle checks **all principal minors** of +`cap^2 I - A^T A`, independently of the author's Hermitian PSD engine. + +The completed normal and optimized Python runs check identical evidence: + +| Scope | Coverage | +| --- | ---: | +| Primitive cuts with two masked spectral matchings and rational rotations | 17 cuts, 149 ordered intervals | +| Exact spectral interval/inverse certificates | 298 | +| Asymmetric recursive synthetic DAG | 10 atoms, 38 downsets | +| Every nested pair of those downsets, with one shared legal order | 475 | +| Actual matching-subset cuts in that independent schedule | 53 | +| Ordered intervals and inverse envelopes | 1,404 | +| Same-layer interval cases | 136 | +| Cuts with simultaneous nonempty active fragments | 22 | +| Zero-duration-predecessor cases | 32 | +| Wrong relative order distinguished | 394 nested pairs | +| Noncommuting generator prefix/suffix formulas | 8 checkpoint equalities | + +The DAG fixture uses physical wire order `(2,0,3,1)`, unequal sibling +durations and one empty upper atom. Its matrices and defects are generated +independently and satisfy an explicitly computed B, eta and theta. These +are **synthetic fixtures**, not another run of the actual source factory. +They corroborate the general causal/algebraic implication while the author +fixture and the manual source review establish the specific source binding. + +The generator control verifies that omitting the current term from C changes +the remaining suffix. Noncommuting pairs ensure that an accidental reversal +of relative endpoint order would fail. The primitive oracle tests the +unchanged cap 14/9 for its exact two diagonal envelopes, including partial +bank-unitary and cross-bank matchings. It does not infer all-size validity +from the finite tests; that rests on the arguments above. + +## 6. Limits and remaining proof obligations + +The theorem assumes the original ideal downset envelope and source admission, +generator rank, certified phase and coefficient-defect bounds. It does not +replace them with an observed finite norm. Inverses are exact inverses of +the same stored coefficients. It is not a statement about independently +rounded inverse tables or a rounded forward/inverse round trip. + +A cut between writing two outputs of a single gate may be singular even +when the whole gate is unitary. The theorem correctly excludes those +physical microsteps and their saved temporaries. Actual tape movement, +coefficient production, storage and whole-multiplier recovery remain open +interfaces. The canonical five assumptions and selected kappa are unchanged. + +Credit Jose Manuel, Vlado Vojdanovski, Chafik Boukhalfa, Brian/JoyboyBrian, +Nick Petalas and Ali Romman for the distinct source/compiler, phase, trace, +matching, downset and application results identified in the author's exact +origin manifest. Prepared for Jerry Chen / @CubeJerry with substantial +OpenAI assistance. This is separate model-assisted review, not independent +human or formal-kernel acceptance. diff --git a/research/direct-circulant-production-precision/compiler-intervals/review/independent.py b/research/direct-circulant-production-precision/compiler-intervals/review/independent.py new file mode 100644 index 0000000000..0c5dafd210 --- /dev/null +++ b/research/direct-circulant-production-precision/compiler-intervals/review/independent.py @@ -0,0 +1,351 @@ +"""Separate exact tests for source-time cuts and the normalized interval lemma. + +No author audit, source factory or source matrix helper is imported. Rational +fixtures test the general DAG implication; the source grammar is reviewed in +REVIEW.md. Principal-minor PSD tests give a separate spectral-norm oracle. +""" +from fractions import Fraction as F +from functools import cache +from hashlib import sha1, sha256 +from itertools import combinations +from pathlib import Path +import argparse +import json +import time + +PROOF_SHA = "e942012e66adc2d696cde3fedd6ae9c73df98e77a71b16e5004f5a74ccdfaa07" + + +def need(ok, message): + if not ok: + raise ValueError(message) + + +def eye(n): + return tuple(tuple(F(i == j) for j in range(n)) for i in range(n)) + + +def matrix(rows): + return tuple(tuple(F(x) for x in row) for row in rows) + + +def tr(a): + return tuple(zip(*a)) + + +def mul(a, b): + bt = tr(b) + return tuple(tuple(sum(x*y for x, y in zip(row, col)) for col in bt) for row in a) + + +def add(a, b, scale=1): + return tuple(tuple(x+scale*y for x, y in zip(row, col)) for row, col in zip(a, b)) + + +@cache +def inv(a): + n = len(a) + w = [list(row)+list(eye(n)[i]) for i, row in enumerate(a)] + for k in range(n): + p = next((i for i in range(n-1, k-1, -1) if w[i][k]), None) + need(p is not None, "singular matrix") + w[p], w[k] = w[k], w[p] + d = w[k][k] + w[k] = [x/d for x in w[k]] + for i in range(n): + if i != k: + d = w[i][k] + w[i] = [x-d*y for x, y in zip(w[i], w[k])] + return tuple(tuple(row[n:]) for row in w) + + +def determinant(a): + if not a: + return F(1) + if len(a) == 1: + return a[0][0] + # Laplace expansion is intentionally different from the author's PSD test. + return sum((-1)**j*a[0][j]*determinant(tuple(tuple(x for k, x in enumerate(row) if k != j) + for row in a[1:])) for j in range(len(a))) + + +def psd(a): + need(a == tr(a), "PSD oracle needs a symmetric rational matrix") + return all(determinant(tuple(tuple(a[i][j] for j in ids) for i in ids)) >= 0 + for size in range(1, len(a)+1) for ids in combinations(range(len(a)), size)) + + +def spectral_below(a, cap): + return psd(add(tuple(tuple(cap*cap*x for x in row) for row in eye(len(a))), mul(tr(a), a), -1)) + + +def norm_majorant(a): + """max(induced 1-norm, induced infinity-norm), also an operator-2 bound.""" + return max(max(map(lambda row: sum(map(abs, row)), a)), + max(map(lambda row: sum(map(abs, row)), tr(a)))) + + +def embed(local, ids, n=4): + out = [list(row) for row in eye(n)] + for i, u in enumerate(ids): + for j, v in enumerate(ids): + out[u][v] = local[i][j] + return matrix(out) + + +def forward(matrices, n=4): + out = eye(n) + for a in matrices: + out = mul(a, out) + return out + + +def all_subsets(values): + values = tuple(values) + for mask in range(1 << len(values)): + yield frozenset(values[j] for j in range(len(values)) if mask >> j & 1) + + +def shear(a, upper=True): + return matrix([[1, a], [0, 1]]) if upper else matrix([[1, 0], [a, 1]]) + + +def primitive(): + rotation = matrix([[F(3, 5), F(4, 5)], [-F(4, 5), F(3, 5)]]) + layers = [ + [(embed(rotation, (0, 1)), (0, 1)), (embed(tr(rotation), (2, 3)), (2, 3))], + [(embed(shear(F(1, 3), False), (0, 2)), (0, 2)), + (embed(shear(F(-1, 5), False), (1, 3)), (1, 3))], + [(embed(tr(rotation), (0, 1)), (0, 1)), (embed(rotation, (2, 3)), (2, 3))], + [(embed(shear(F(-1, 7), False), (0, 2)), (0, 2)), + (embed(shear(F(2, 9), False), (1, 3)), (1, 3))], + ] + cuts = []; completed = eye(4) + for k, layer in enumerate(layers): + for selected in all_subsets(range(len(layer))): + cuts.append((k, selected, mul(forward([layer[j][0] for j in sorted(selected)]), completed))) + completed = mul(forward([gate for gate, _ in layer]), completed) + cuts.append((len(layers), frozenset(), completed)) + cap = 1+F(1, 3)+F(2, 9) + cases = 0 + for ku, su, u in cuts: + for kv, sv, v in cuts: + if ku > kv or (ku == kv and not su <= sv): + continue + segment = mul(v, inv(u)) + need(spectral_below(segment, cap) and spectral_below(inv(segment), cap), + "two spectral matchings exceeded the unchanged cap") + cases += 1 + return {"cuts": len(cuts), "ordered_intervals": cases, "principal_minor_norm_certificates": 2*cases, + "unchanged_cap": str(cap)} + + +def tree_fixture(): + # The logical recurrence matches R; parallel children; L. It is a + # deliberately synthetic rational fixture, not a source-factory replay. + physical = (2, 0, 3, 1) + delta = F(1, 1 << 30) + atoms = {} + + def atom(name, logical, coeffs, upper=True, predecessors=()): + ids = tuple(physical[i] for i in logical) + layers = []; ideals = [] + for k, coeff in enumerate(coeffs): + gates = []; want = [] + pairs = [(ids[0], ids[-1])] if len(ids) == 2 else [(ids[0], ids[2]), (ids[1], ids[3])] + for j, pair in enumerate(pairs): + amount = coeff/F(j+1) + gates.append((embed(shear(amount+delta if k == 0 else amount, upper), pair), pair)) + want.append(embed(shear(amount, upper), pair)) + layers.append(gates);ideals.extend(want) + atoms[name] = {"name": name, "support": frozenset(ids), "layers": layers, + "ideal": forward(ideals), "stored": forward([g for layer in layers for g, _ in layer]), + "pred": frozenset(predecessors)} + return name + + def leaf(name, logical, value, predecessors): + ids = (physical[logical],) + atoms[name] = {"name": name, "support": frozenset(ids), + "layers": [[(embed(matrix([[value+delta]]), ids), ids)]], + "ideal": embed(matrix([[value]]), ids), "stored": embed(matrix([[value+delta]]), ids), + "pred": frozenset(predecessors)} + return name + + atom("R", range(4), [F(1, 7), F(-1, 11)], predecessors=[]) + atom("R0", (0, 1), [F(1, 5)]*3, predecessors=["R"]) + atom("R1", (2, 3), [], predecessors=["R"]) + leaf("D0", 0, F(5, 4), ["R0"]);leaf("D1", 1, F(3, 4), ["R0"]) + leaf("D2", 2, F(7, 6), ["R1"]);leaf("D3", 3, F(6, 7), ["R1"]) + atom("L0", (0, 1), [F(1, 9), F(-1, 13)], False, ["D0", "D1"]) + atom("L1", (2, 3), [F(1, 11)]*5, False, ["D2", "D3"]) + atom("L", range(4), [F(1, 17)]*3, False, ["L0", "L1"]) + + def topo(chosen, done=()): + remaining = set(chosen);done = set(done);out = [] + while remaining: + ready = sorted(name for name in remaining if atoms[name]["pred"] <= done) + need(ready, "not a topological block") + name = ready[-1] # reverse lexical order deliberately differs from source chronology + out.append(name);done.add(name);remaining.remove(name) + return out + + labels = frozenset(atoms) + order = topo(labels) + layers = [] + for name in order: + a = atoms[name] + a["start"] = max((atoms[p]["stop"] for p in a["pred"]), default=0) + a["stop"] = a["start"]+len(a["layers"]) + for offset, layer in enumerate(a["layers"]): + k = a["start"]+offset + while len(layers) <= k: + layers.append([]) + layers[k].extend((name, j, gate, ids) for j, (gate, ids) in enumerate(layer)) + for layer in layers: + used = [i for _, _, _, ids in layer for i in ids] + need(len(used) == len(set(used)), "fixture layer is not a matching") + downsets = [s for s in all_subsets(sorted(labels)) if all(atoms[x]["pred"] <= s for x in s)] + exact = {s: forward([atoms[x]["ideal"] for x in topo(s)]) for s in downsets} + stored = {s: forward([atoms[x]["stored"] for x in topo(s)]) for s in downsets} + B = max(norm_majorant(m) for s in downsets for m in (exact[s], inv(exact[s]))) + eta = max(norm_majorant(add(a["stored"], a["ideal"], -1)) for a in atoms.values()) + theta = len(atoms)*B*B*eta + need(theta <= F(1, 4), "fixture perturbation budget is not small") + + nested = 0;wrong = 0 + for u in downsets: + for v in downsets: + if not u <= v: + continue + same_order = topo(u)+topo(v-u, u)+topo(labels-v, v) + need(len(same_order) == len(atoms) and len(set(same_order)) == len(atoms), "missing atom") + q = eye(4); z = eye(4); gs = []; qs = [q]; zs = [z]; qh = eye(4); qhs = [qh] + for name in same_order: + a = atoms[name];old = q;q = mul(a["ideal"], q) + g = mul(mul(inv(q), add(a["stored"], a["ideal"], -1)), old) + gs.append(g);z = mul(add(eye(4), g), z);qs.append(q);zs.append(z) + qh = mul(a["stored"], qh);qhs.append(qh) + need(mul(q, z) == qh, "left normalized perturbation recurrence") + i, j = len(u), len(v) + w = forward([add(eye(4), g) for g in gs[i:j]]) + relative = mul(stored[v], inv(stored[u])) + need(w == mul(zs[j], inv(zs[i])), "noncommutative consecutive cancellation") + need(relative == mul(mul(qs[j], w), inv(qs[i])), "relative endpoint factor order") + actual_sum = sum(norm_majorant(g) for g in gs[i:j]) + need(actual_sum <= theta, "normalized perturbations exceed declared sum") + cap = 1/(1-actual_sum) + need(norm_majorant(w) <= cap and norm_majorant(inv(w)) <= cap, + "exact relative normalized bound") + need(norm_majorant(relative) <= B*B/(1-theta), "relative endpoint envelope") + if relative != mul(inv(stored[u]), stored[v]): + wrong += 1 + nested += 1 + need(wrong, "fixture never challenged noncommutative relative order") + + cuts = [];completed = eye(4);H = F(1);simultaneous = 0;empty_predecessor = 0 + for k in range(len(layers)+1): + layer = layers[k] if k < len(layers) else [] + for selected in all_subsets(range(len(layer))): + c = mul(forward([layer[j][2] for j in sorted(selected)]), completed) + done = frozenset(name for name, a in atoms.items() if a["stop"] <= k) + active = frozenset(name for name, a in atoms.items() if a["start"] <= k < a["stop"]) + need(done in exact and done | active in exact, "timestamp sets are not downsets") + supports = [atoms[name]["support"] for name in active] + need(sum(map(len, supports)) == len(set().union(*supports)) if supports else True, + "active atoms overlap") + f = eye(4);tails = eye(4);nonempty = 0 + for name in sorted(active): + a = atoms[name];local = k-a["start"] + preceding = [g for lay in a["layers"][:local] for g, _ in lay] + pick = {layer[j][1] for j in selected if layer[j][0] == name} + part = forward(preceding+[g for j, (g, _) in enumerate(a["layers"][local]) if j in pick]) + tail = mul(a["stored"], inv(part)) + nonempty += bool(preceding or pick) + H = max(H, *(norm_majorant(x) for x in (part, inv(part), tail, inv(tail)))) + f = mul(part, f);tails = mul(tail, tails) + need(c == mul(f, stored[done]), "source-time prefix factorization") + rest = topo(labels-(done | active), done | active) + suffix = mul(forward([atoms[x]["stored"] for x in rest]), tails) + need(mul(suffix, c) == stored[labels], "source-time suffix factorization") + simultaneous += nonempty >= 2 + empty_predecessor += "R1" in done and any(x in active for x in ("D2", "D3", "L1")) + cuts.append((k, selected, c, done, f)) + completed = mul(forward([gate for _, _, gate, _ in layer]), completed) + interval_cap = B*B*H*H/(1-theta) + intervals = 0;same_layer = 0 + for ku, su, u, iu, fu in cuts: + for kv, sv, v, iv, fv in cuts: + if ku > kv or (ku == kv and not su <= sv): + continue + need(iu <= iv, "completed sets are not nested") + segment = mul(v, inv(u)) + need(segment == mul(mul(mul(fv, stored[iv]), inv(stored[iu])), inv(fu)), + "two actual-cut normalized factorization") + need(norm_majorant(segment) <= interval_cap and norm_majorant(inv(segment)) <= interval_cap, + "complete interval envelope") + intervals += 1;same_layer += ku == kv + need(simultaneous and empty_predecessor, "asynchronous/empty-atom cases missing") + return {"atoms": len(atoms), "downsets": len(downsets), "nested_downset_pairs": nested, + "noncommuting_wrong_order_controls": wrong, "matching_cuts": len(cuts), + "ordered_intervals": intervals, "same_layer_intervals": same_layer, + "simultaneous_nonempty_fragments": simultaneous, "zero_atom_predecessor_cases": empty_predecessor, + "B": str(B), "eta": str(eta), "theta": str(theta), "H": str(H), + "relative_interval_cap": str(interval_cap), "physical_wire_order": physical, + "scope": "synthetic rational DAG, not a source-factory execution"} + + +def generator_check(): + p = matrix([[1, F(1, 4)], [0, 1]]) + h = matrix([[F(1, 7), F(2, 9)], [-F(1, 8), F(1, 11)]]) + a = matrix([[F(1, 5), 0], [F(1, 13), F(-1, 7)]]) + later = matrix([[F(1, 3), F(-1, 8)], [0, F(1, 17)]]) + zero = matrix([[0, 0], [0, 0]]) + + def block(b, d): + return matrix([list(b[0])+list(zero[0]), list(b[1])+list(zero[1]), + list(d[0])+list(eye(2)[0]), list(d[1])+list(eye(2)[1])]) + + def s(d): + return block(eye(2), d) + + term = mul(h, add(p, eye(2), -1)) + c = add(term, later) # Crucially includes the current complete term. + gates = [block(p, zero), s(h), block(inv(p), zero), s(add(zero, h, -1))] + prefixes = [block(p, a), block(p, add(a, mul(h, p))), s(add(a, mul(h, p))), s(add(a, term))] + suffixes = [block(inv(p), mul(c, inv(p))), block(inv(p), add(mul(c, inv(p)), h, -1)), + s(add(c, mul(h, p), -1)), s(add(c, term, -1))] + for k in range(4): + pref = mul(forward(gates[:k+1]), s(a)) + suff = mul(s(later), forward(gates[k+1:])) + need(pref == prefixes[k] and suff == suffixes[k], "generator checkpoint formula") + need(mul(suff, pref) == s(add(add(a, term), later)), "generator total order") + need(suffixes[0] != block(inv(p), mul(later, inv(p))), "wrong C meaning did not fail") + return {"prefix_suffix_checkpoint_equalities": 8, "current_term_required_in_C": True} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--source", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args();started = time.monotonic();source = args.source.resolve() + need(sha256((source/"PROOF.md").read_bytes()).hexdigest() == PROOF_SHA, "reviewed author proof moved") + origins = json.loads((source/"ORIGINS.json").read_text()) + for row in origins["files"]: + data = (source/row["local"]).read_bytes() + need(sha256(data).hexdigest() == row["sha256"], "origin SHA-256 mismatch") + need(sha1(b"blob "+str(len(data)).encode()+b"\0"+data).hexdigest() == row["git_blob"], + "origin Git blob mismatch") + result = {"status": "PASS_INDEPENDENT_NESTED_DOWNSET_REVIEW", "proof_sha256": PROOF_SHA, + "authenticated_origins": len(origins["files"]), "primitive": primitive(), + "dag": tree_fixture(), "generator": generator_check(), + "scope": "Exact synthetic rational corroboration and independent written proof/source review; no all-size enumeration"} + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2)+"\n") + print(json.dumps({"status": result["status"], "seconds": time.monotonic()-started, + "primitive_intervals": result["primitive"]["ordered_intervals"], + "nested_pairs": result["dag"]["nested_downset_pairs"], + "cut_intervals": result["dag"]["ordered_intervals"]})) + + +if __name__ == "__main__": + main() diff --git a/research/direct-circulant-production-precision/evidence/reconciled-registered-replay.txt b/research/direct-circulant-production-precision/evidence/reconciled-registered-replay.txt new file mode 100644 index 0000000000..1d8fc29ccb --- /dev/null +++ b/research/direct-circulant-production-precision/evidence/reconciled-registered-replay.txt @@ -0,0 +1,323 @@ +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 +CHECK Authenticate 18 source files; exact source matching cuts, four-way envelopes, partial Full timestamps and order/alphabet rejection controls. Run the exact original command in an isolated byte-identical package copy; preserve published receipts. +REPLAY /opt/codex/runtimes/codex-primary-runtime/dependencies/python/bin/python3 -W error -I -B /tmp/circulant-reconciled-replay-0vok2x7w/package/compiler-cuts/audit.py +{"full_cuts": 885, "full_trace_equalities": 3540, "primitive_cuts": 135, "primitive_psd": 540, "status": "PASS_SOURCE_ORDERED_FOUR_WAY_CUT_AUDIT"} +PASS_PRESERVED_COMPILER_REPLAY 3 +CHECK Authenticate 18 source files; exact source matching cuts, four-way envelopes, partial Full timestamps and order/alphabet rejection controls. Run the exact original command in an isolated byte-identical package copy; preserve published receipts. +REPLAY /opt/codex/runtimes/codex-primary-runtime/dependencies/python/bin/python3 -W error -I -O -B /tmp/circulant-reconciled-replay-yjup6c4w/package/compiler-cuts/audit.py +{"full_cuts": 885, "full_trace_equalities": 3540, "primitive_cuts": 135, "primitive_psd": 540, "status": "PASS_SOURCE_ORDERED_FOUR_WAY_CUT_AUDIT"} +PASS_PRESERVED_COMPILER_REPLAY 4 +CHECK Independent rational realification, bank invariants, all matching subsets, primitive intervals, LDU downsets and conditioning/chronology controls; no author checker imported. Run the exact original command in an isolated byte-identical package copy; preserve published receipts. +REPLAY /opt/codex/runtimes/codex-primary-runtime/dependencies/python/bin/python3 -W error -I -B /tmp/circulant-reconciled-replay-bkxq_5to/package/compiler-cuts/review/check_independent.py --source /tmp/circulant-reconciled-replay-bkxq_5to/package/compiler-cuts --output /tmp/circulant-reconciled-replay-bkxq_5to/legacy-normal.json +{"status": "PASS_INDEPENDENT_SOURCE_ALPHABET_CUT_REVIEW", "cuts": 760, "downsets": 46, "seconds": 11.055} +PASS_PRESERVED_COMPILER_REPLAY 5 +CHECK Independent rational realification, bank invariants, all matching subsets, primitive intervals, LDU downsets and conditioning/chronology controls; no author checker imported. Run the exact original command in an isolated byte-identical package copy; preserve published receipts. +REPLAY /opt/codex/runtimes/codex-primary-runtime/dependencies/python/bin/python3 -W error -I -O -B /tmp/circulant-reconciled-replay-boodz55n/package/compiler-cuts/review/check_independent.py --source /tmp/circulant-reconciled-replay-boodz55n/package/compiler-cuts --output /tmp/circulant-reconciled-replay-boodz55n/legacy-optimized.json +{"status": "PASS_INDEPENDENT_SOURCE_ALPHABET_CUT_REVIEW", "cuts": 760, "downsets": 46, "seconds": 11.819} +PASS_PRESERVED_COMPILER_REPLAY 6 +CHECK Authenticate preserved remote subtree and frozen new proofs; replay relative-interval author audit, separate normal/optimized interval oracle, sharp selector source checks and separate normal/optimized selector oracle in isolated copies. +REPLAY /opt/codex/runtimes/codex-primary-runtime/dependencies/python/bin/python3 -I -W error -B /tmp/circulant-reconciled-replay-800qk25k/package/compiler-intervals/audit.py +{"actual_intervals": 96, "full_cuts": 882, "full_trace_equalities": 3528, "primitive_cuts": 135, "primitive_psd": 540, "status": "PASS_SOURCE_ORDERED_FOUR_WAY_CUT_AUDIT"} +REPLAY /opt/codex/runtimes/codex-primary-runtime/dependencies/python/bin/python3 -I -W error -B /tmp/circulant-reconciled-replay-800qk25k/package/compiler-intervals/review/independent.py --source /tmp/circulant-reconciled-replay-800qk25k/package/compiler-intervals --output /tmp/circulant-reconciled-replay-800qk25k/interval-normal.json +{"status": "PASS_INDEPENDENT_NESTED_DOWNSET_REVIEW", "seconds": 4.579962809999415, "primitive_intervals": 149, "nested_pairs": 475, "cut_intervals": 1404} +REPLAY /opt/codex/runtimes/codex-primary-runtime/dependencies/python/bin/python3 -I -O -W error -B /tmp/circulant-reconciled-replay-800qk25k/package/compiler-intervals/review/independent.py --source /tmp/circulant-reconciled-replay-800qk25k/package/compiler-intervals --output /tmp/circulant-reconciled-replay-800qk25k/interval-optimized.json +{"status": "PASS_INDEPENDENT_NESTED_DOWNSET_REVIEW", "seconds": 4.309554596999078, "primitive_intervals": 149, "nested_pairs": 475, "cut_intervals": 1404} +REPLAY /opt/codex/runtimes/codex-primary-runtime/dependencies/python/bin/python3 -I -W error -B /tmp/circulant-reconciled-replay-800qk25k/package/spectral-downset/check.py --parent /tmp/circulant-reconciled-replay-800qk25k/package --cuts /tmp/circulant-reconciled-replay-800qk25k/package/compiler-intervals +{"actual_padded_roots": 2, "allocation_cases": {"literal_child_allocations": 118, "unchanged_full": 116}, "selector_cases": 53, "status": "PASS_SPECTRAL_DOWNSET_CIRCULANT_PRECISION"} +REPLAY /opt/codex/runtimes/codex-primary-runtime/dependencies/python/bin/python3 -I -W error -B /tmp/circulant-reconciled-replay-800qk25k/package/spectral-downset/review/independent.py --candidate /tmp/circulant-reconciled-replay-800qk25k/package/spectral-downset --cuts /tmp/circulant-reconciled-replay-800qk25k/package/compiler-intervals --parent /tmp/circulant-reconciled-replay-800qk25k/package --output /tmp/circulant-reconciled-replay-800qk25k/selector-normal.json +{ + "status": "PASS_INDEPENDENT_SHARP_SELECTOR_REVIEW", + "source_bindings": [ + "actual prepared be and len(items)", + "same original child_target_bits", + "exact component row/column envelope", + "literal child norm formulas", + "unchanged component Lambda and Q guards", + "external work_bits+8" + ], + "cache": { + "symbolic_records": 254, + "numerical_records": 762, + "zero_factor_records": 507, + "rounding_grids": [ + 2, + 5, + 11 + ], + "broken_carry_records_rejected": 2 + }, + "domain_controls": { + "rotation_component_envelope": "7/5", + "full_inverse_only_rejected": true, + "non_toeplitz_padded_fixture": { + "spectral_root_cap": 2, + "leading_inverse_cap": 1, + "skew_frobenius_squared": "7/64" + } + } +} +REPLAY /opt/codex/runtimes/codex-primary-runtime/dependencies/python/bin/python3 -I -O -W error -B /tmp/circulant-reconciled-replay-800qk25k/package/spectral-downset/review/independent.py --candidate /tmp/circulant-reconciled-replay-800qk25k/package/spectral-downset --cuts /tmp/circulant-reconciled-replay-800qk25k/package/compiler-intervals --parent /tmp/circulant-reconciled-replay-800qk25k/package --output /tmp/circulant-reconciled-replay-800qk25k/selector-optimized.json +{ + "status": "PASS_INDEPENDENT_SHARP_SELECTOR_REVIEW", + "source_bindings": [ + "actual prepared be and len(items)", + "same original child_target_bits", + "exact component row/column envelope", + "literal child norm formulas", + "unchanged component Lambda and Q guards", + "external work_bits+8" + ], + "cache": { + "symbolic_records": 254, + "numerical_records": 762, + "zero_factor_records": 507, + "rounding_grids": [ + 2, + 5, + 11 + ], + "broken_carry_records_rejected": 2 + }, + "domain_controls": { + "rotation_component_envelope": "7/5", + "full_inverse_only_rejected": true, + "non_toeplitz_padded_fixture": { + "spectral_root_cap": 2, + "leading_inverse_cap": 1, + "skew_frobenius_squared": "7/64" + } + } +} +PASS_RELATIVE_INTERVAL_AND_SHARP_SELECTOR_ADDITIONS +PASS_REGISTERED_RESEARCH_PACKAGE research/direct-circulant-production-precision outcome=completed 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/grid-arithmetic/EVIDENCE-OPTIMIZED.json b/research/direct-circulant-production-precision/grid-arithmetic/EVIDENCE-OPTIMIZED.json new file mode 100644 index 0000000000..3253046533 --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/EVIDENCE-OPTIMIZED.json @@ -0,0 +1,85 @@ +{ + "actual_full": { + "actual_coefficient_height": 145, + "data_bits": 147, + "declared_height": 616, + "events": 90, + "fractional_bits": 79, + "gates": 30, + "initial_scalar_height": 240, + "layers": 21 + }, + "arithmetic": { + "cases": 20336, + "maximum_observed_bits": 9849 + }, + "chronology": { + "fractional_bits": 2, + "gate": [ + [ + [ + "1", + "0" + ], + [ + "0", + "0" + ] + ], + [ + [ + "7433581732843541047178572757549453835326805/22300745198530623141535718272648361505980416", + "0" + ], + [ + "1", + "0" + ] + ] + ], + "inputs": [ + -1, + -1, + -1, + -1 + ], + "lowered": [ + 0, + 0, + 0, + 0 + ], + "once_rounded": [ + -1, + -1, + -1, + -1 + ] + }, + "controls": { + "insufficient_width": 3, + "invalid_domain": 4, + "semantic": 7 + }, + "literal_source_mutants": 4, + "marker": "PASS_SUPPLIED_GRID_ARITHMETIC_BINDING", + "odometer": { + "multiply_calls": 320, + "scans": 10, + "zero_factor_calls": 144 + }, + "predecessor_scalar_cases": 486, + "production": { + "A": 323, + "B": 4924, + "E": 1483, + "P": 3438, + "W": 9849, + "local_data_bits": 88639, + "operand_numerator_exponent": 3431, + "required_signed_input_bits": 3433 + }, + "program_sha256": "cce97fcc515e3240224cada0a25c666fbac13454135b4fd71589f30bf67b3184", + "proof_sha256": "05e85b54fd4b8f834f1790ff18ca53f5cd05aaf58e316aef4ba72aabe2b7fa9a", + "sources": 23 +} diff --git a/research/direct-circulant-production-precision/grid-arithmetic/EVIDENCE.json b/research/direct-circulant-production-precision/grid-arithmetic/EVIDENCE.json new file mode 100644 index 0000000000..3253046533 --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/EVIDENCE.json @@ -0,0 +1,85 @@ +{ + "actual_full": { + "actual_coefficient_height": 145, + "data_bits": 147, + "declared_height": 616, + "events": 90, + "fractional_bits": 79, + "gates": 30, + "initial_scalar_height": 240, + "layers": 21 + }, + "arithmetic": { + "cases": 20336, + "maximum_observed_bits": 9849 + }, + "chronology": { + "fractional_bits": 2, + "gate": [ + [ + [ + "1", + "0" + ], + [ + "0", + "0" + ] + ], + [ + [ + "7433581732843541047178572757549453835326805/22300745198530623141535718272648361505980416", + "0" + ], + [ + "1", + "0" + ] + ] + ], + "inputs": [ + -1, + -1, + -1, + -1 + ], + "lowered": [ + 0, + 0, + 0, + 0 + ], + "once_rounded": [ + -1, + -1, + -1, + -1 + ] + }, + "controls": { + "insufficient_width": 3, + "invalid_domain": 4, + "semantic": 7 + }, + "literal_source_mutants": 4, + "marker": "PASS_SUPPLIED_GRID_ARITHMETIC_BINDING", + "odometer": { + "multiply_calls": 320, + "scans": 10, + "zero_factor_calls": 144 + }, + "predecessor_scalar_cases": 486, + "production": { + "A": 323, + "B": 4924, + "E": 1483, + "P": 3438, + "W": 9849, + "local_data_bits": 88639, + "operand_numerator_exponent": 3431, + "required_signed_input_bits": 3433 + }, + "program_sha256": "cce97fcc515e3240224cada0a25c666fbac13454135b4fd71589f30bf67b3184", + "proof_sha256": "05e85b54fd4b8f834f1790ff18ca53f5cd05aaf58e316aef4ba72aabe2b7fa9a", + "sources": 23 +} diff --git a/research/direct-circulant-production-precision/grid-arithmetic/FROZEN.json b/research/direct-circulant-production-precision/grid-arithmetic/FROZEN.json new file mode 100644 index 0000000000..0ffac82326 --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/FROZEN.json @@ -0,0 +1,44 @@ +{ + "files": { + "EVIDENCE-OPTIMIZED.json": "9d1a747ccf2c366edf2f9b90d46330a5bd6770327f4b89a7870ff1581a200512", + "EVIDENCE.json": "9d1a747ccf2c366edf2f9b90d46330a5bd6770327f4b89a7870ff1581a200512", + "PROOF.md": "05e85b54fd4b8f834f1790ff18ca53f5cd05aaf58e316aef4ba72aabe2b7fa9a", + "README.md": "8f1022510c0f6dea9b9cdff443a1c99d2c2e60eed6b63e93206463dc97bea7e7", + "SOURCES.json": "5bc0d3ea2f6b3e9a2c3e69d4693fdbba4f236987d061bcf1ca8b297038b2f9bf", + "TASK.json": "b9f6417c4a0b526f27fcd36be10388631deb70e04a3b9b0e205623e24feddc4e", + "VERIFY.json": "363e966ea518c555cedb82ca5060d9359056dea5639c18e364f2bc34465c1fb2", + "check.py": "d4490384a50bc6869b20adc93071d265b6d8649937d4687c7ae528e1c446719d", + "grid_arithmetic.py": "cce97fcc515e3240224cada0a25c666fbac13454135b4fd71589f30bf67b3184", + "retained/PROOF.md": "00d2782a462612ad061c46ff9556c0e85108e8a3e38b181bc878bf1589976b9d", + "retained/README.md": "8fbc9c0b34f5d9233664c9822034b3ab2e9725452c59227eb0b25f416b93951b", + "retained/SOURCES.json": "a3ce4df0d59bc95323134c2f8c2ee3165ae2cb04898eec9ab6cf6d9cb6a25ee7", + "retained/TASK.json": "a760a13208ecee3f65a85bf6a9b204da8ae3532c0c2e82bf5d8bec99c363dd4e", + "retained/VERIFY.json": "10c341a64b0bca5b614fbf616c65774e6f4a4819091373487aa06f702ea2b6f7", + "retained/compiler/STEIN-PROVENANCE.json": "e7f0e8dc517387e302b1e8bf5dff7e12b29da8aa91abc6ea597f33c1ac08ba62", + "retained/compiler/check_circuits.py": "06d1861bfe8af543908e26557ffda7e451ff176bceb9bacfaf0f04f234b336d5", + "retained/compiler/engine.py": "9e36aee0835e6b1b62997433581f88b5a434ccab8ae43e5c25d1deaaf1ebf653", + "retained/compiler/exact.py": "c9b89d7357210af69865690ba12e695366961f8b501a8fab9d0fefe3fb30c479", + "retained/compiler/full.py": "1f42d5f2858564ffb320e54ba6aa29651025491569823e25006bf5862457b803", + "retained/compiler/generator.py": "827ef9fe1bd664859995892b59843c390f7969c938fb7e1e6dc585c31a54b555", + "retained/compiler/interval_kernel.py": "9b7bb24640a9a7d3f83c7951dfef483ec933db4c50de6c0130b85f450eeddfbe", + "retained/compiler/stein_rational.py": "3065fc5d6d22ec44de533b08fb0c639603449456383668e561dc46629e641502", + "retained/compiler/triangular.py": "46780d95ddebfed22e8f0c18565fe2e768250afa5beeb31f450292cc06f7ec11", + "retained/direct/product.py": "29ab6c60f937b7cce58666f5ddd7a921c3197cf72abf91ecca0ff7ad9486850e", + "retained/direct/root_gate_plan.py": "379ca05625076824ac9c2399eac03c1c64c13fecee45ea17f78b8898df57cd2d", + "retained/direct/spectral.py": "ede9c48d34280c9c1c5c332b9434ff666fd321f4a18ffbf1f61b3339339e8ab6", + "retained/direct/tensor_word.py": "36c5a9a0082c9aa3c6cb2d04a9196af8debce0d551a0525975b710018ea02cac", + "retained/kernel.py": "33afb9b22d1b7e53f41747b5b798f98511b3e0d8053fecb504e7137ed5f208a9", + "retained/parent-PROOF.md": "26e4e214f0a5785c1d1414561465bb49a3248f9e6f59f6b514eb95a887bdfe2f", + "retained/precision.py": "9c3e99219f741c5b08c0628c30784cf72c60b4421beae3373fa976aeffcd8e20", + "retained/spectral-PROOF.md": "0501a6a9a5f467fff4c998606965babc8157e74d98cf33b93f71fb10674d57bb", + "retained/verify.py": "75e4e9aeca05475fba814986b6713e5f84970681718e2bcc7df3bb478cd11d52", + "review/EVIDENCE-OPTIMIZED.json": "8cb77f8a596e93cb1f56795e0a6ac95dc6bebdddf8d93a7b3f37a2d183395e7c", + "review/EVIDENCE.json": "8cb77f8a596e93cb1f56795e0a6ac95dc6bebdddf8d93a7b3f37a2d183395e7c", + "review/REVIEW.md": "9a2db500067a0832d1a744d5ff4b96be8ef2f66434fe80df2145b8e87af48048", + "review/independent.py": "95235b86e3f1a2fc1353a41d45233df6911318ee62ba11836ab00bc0f6e64e49" + }, + "program": "cce97fcc515e3240224cada0a25c666fbac13454135b4fd71589f30bf67b3184", + "proof": "05e85b54fd4b8f834f1790ff18ca53f5cd05aaf58e316aef4ba72aabe2b7fa9a", + "schema_version": 1, + "source_manifest": "5bc0d3ea2f6b3e9a2c3e69d4693fdbba4f236987d061bcf1ca8b297038b2f9bf" +} diff --git a/research/direct-circulant-production-precision/grid-arithmetic/INTEGRATION.md b/research/direct-circulant-production-precision/grid-arithmetic/INTEGRATION.md new file mode 100644 index 0000000000..5034ba9326 --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/INTEGRATION.md @@ -0,0 +1,39 @@ +# Sequential integration after the accepted precision supplement + +This directory adds the reviewed supplied-grid arithmetic result to +[#8093](https://github.com/CrocSwap/integer-mult-bounds/pull/8093) +at expected head `ea0274f8e6b6add282a63c11c5b8c4420ed3bc7e`, whose tree is +`c09b52f711358be141d4403f449c57dd89fb68b3`. It preserves all earlier scientific +files. Only the parent README, TASK and VERIFY metadata are extended. + +The accepted proof is SHA256 +`05e85b54fd4b8f834f1790ff18ca53f5cd05aaf58e316aef4ba72aabe2b7fa9a`; +the new program is SHA256 +`cce97fcc515e3240224cada0a25c666fbac13454135b4fd71589f30bf67b3184`. +`FROZEN.json` authenticates the complete author/reviewer package. The separate +review accepts the universal argument and includes its own exact oracle, +39,220 cases, 18,716 ties, 8,628 zero-multiplier cases, 1,020 literal odometer +calls, 28 API bindings and four adverse source mutations. Its normal and +optimized receipts agree byte for byte. + +Two execution-boundary clarifications in `review/REVIEW.md` apply to the +unchanged proof. The extracted Grid fixture supplies `operator.mul` as an +exact-integer helper; it does not execute or price the retained +`word_product` machine implementation. The new local shift/add implementation +is separately proved and charged quadratically. The example sides=(2,), +digit_bits=5 is an admissible explicit constructor geometry; no claim is made +that `multiply_uniform` selects that particular instance. + +The original seven verification registrations are unchanged. The eighth +registration now calls `run_registered.py`: it runs the exact previous eighth +command first, then the new author and independent reviewer checks in normal +and optimized modes. All four new receipts are generated in a private +temporary directory and compared byte for byte with frozen evidence. The +author's original sibling-import invocation is retained; independent review +uses isolated interpreter mode. No predecessor guards, proof APIs, source +coefficients, arithmetic chronology or published receipt are rewritten. + +The result covers supplied scalar arithmetic at the actual external calls. +Coefficient preparation, global transport and ownership, native private +storage, reversible cleanup and the accelerated outer tariff remain open. +All five selected assumptions and the selected kappa remain unchanged. diff --git a/research/direct-circulant-production-precision/grid-arithmetic/PROOF.md b/research/direct-circulant-production-precision/grid-arithmetic/PROOF.md new file mode 100644 index 0000000000..fbd1430dca --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/PROOF.md @@ -0,0 +1,233 @@ +# Binding supplied dyadic arithmetic to the actual external caller + +Prepared for Jerry Chen / @CubeJerry with substantial OpenAI assistance. +Apache-2.0. This supplements, and does not modify, Nick Petalas's canonical +`integer-rounded-gate` theorem. The source records are in `SOURCES.json`. + +## 1. Exact scope and predecessors + +Nick Petalas already proves a constant-word shift/add/long-division program +for a four-term rational row with signed B-bit data and C-bit coefficient +numerators/denominators. Its arithmetic width is B+4C+2. Its source fixture +already binds one rational-unitary butterfly to `exact.apply`. We do not claim +either construction or that existing fixture as new. Armin Pourshafeie's +matching-layer semantics and Jose Manuel's rational compiler remain credited +dependencies. Ali Romman's actual external tensor caller has an additional +boundary: each original gate is first lowered to sixteen H operations and +seventeen joined diagonal pairs, and each diagonal is converted to a grid. + +This note binds the arithmetic at the latter caller's actual +`Grid.multiply` sites. It supplies a smaller width for that special common +denominator, a constant register schedule, and an exact finite-reference +obstruction. It does not replace the externally lowered word by once-rounded +original gates. Coefficient synthesis, global array movement, native-H private +storage, ownership and reversible restoration remain separate obligations. +All five selected assumptions and the selected kappa remain unchanged. + +## 2. Literal caller semantics + +Let q=2^P. The source represents a complex value by integer numerators (a,b). +For u=(a,b), v=(c,d), `Grid.multiply` returns + + ((ac-bd+q/2) >> P, (ad+bc+q/2) >> P). (1) + +Python's signed right shift is floor division by q. Thus (1) rounds each +exact real or imaginary component once to the common grid, with ties toward +positive infinity, including negative halfway values. Its two identity +shortcuts return the same values as (1). Inputs are read before either output +is written. This is the same component rounding rule as `exact.round_q` and +the once-per-output sum in `exact.apply`. + +`Grid.word` is a different boundary: it uses Python `round(Fraction)` and +therefore ties to even. At P=2 the exact coefficient 1/8 becomes numerator 0 +under `Grid.word`, whereas multiplication of numerators 1 and 2 gives +numerator 1 under (1). The kernel must not replace coefficient conversion. +The supplied rounded coefficient is the input to this arithmetic lemma. + +For an original Full gate, expanding its complex rows gives at most four +real rational terms with no increase in component height. A one-wire gate +can be padded by an identity on a zero dummy coordinate. `Full.shear` records +the actual child allocation's coefficient height; `Full.plan` takes the +maximum over its actual atoms, including leaves. This is the correct source +of a declared coefficient bound, not the root allocation's initial scalar +height alone. A concrete two-wire Full fixture below has declared atom +heights 616 for each shear and 240 for each leaf, with actual maximum stored +component height 145. Reusing the initial scalar bound without the post-plan +maximum would miss the stated child contract. The original all-width +rational theorem applies to a Full event when its supplied data and actual +coefficient-height bounds are admitted. This observation does not price its +coefficient preparation or change its event order. + +An exact adverse example uses the first two-wire gate emitted by the pinned +`Full.plan` for [[3,1],[1,3]], target precision 1. At external P=2, input +numerators (-1,-1,-1,-1) return the same four numerators under once-rounded +`exact.apply`; the actual sixteen-H lowering with `Grid.word` conversions +returns (0,0,0,0). `check.py` obtains the gate from the source factory. This +small diagnostic proves a semantic distinction; it does not claim failure +at the sufficient production precision. + +## 3. Common-denominator arithmetic theorem + +Assume B>=2, 1<=P<=B, and all four input numerators lie in +[-2^(B-1),2^(B-1)-1]. There is a supplied-input arithmetic program computing +(1) with every signed arithmetic value fitting + + W = 2B+1. (2) + +Put M=2^(B-1). Compute ac, bd, ad, bc by signed shift/add multiplication. +Each exact product has absolute value at most M^2. To multiply x and y, +retain the sign, put T=abs(x), D=abs(y), U=0, and repeatedly add T to U when +D is odd, shift D right, and shift T left only if the remaining D is nonzero. +The loop invariant is the usual partial binary product. When y=0, the loop +does not run: the initialized T=abs(x)<=M fits and U=0 is the product. +When y is nonzero, every T and every U is at most abs(x*y): before a shift, +a remaining nonzero bit of y ensures abs(y)>=the next power of two. +Zero x also causes no exception. +The most-negative B-bit input has positive magnitude M, which fits W. +There are at most B iterations per product. + +Each sum or difference of two products has magnitude at most 2M^2. The +positive halfway offset is h=2^(P-1)<=M. Consequently every biased numerator +has absolute value at most 2M^2+M < 4M^2 = 2^(W-1), since M>=2. +The final arithmetic right shift cannot increase absolute value beyond the +signed W-bit interval. This proves (2), including extreme negative inputs, +zero factors, cancellation and signed ties. No denominator products or +general long division are required for this common grid. + +The ordinary all-rational theorem can also be applied here: treat a+ib as +the supplied scalar coefficient over q, use state (c,d,0,0), and take C=B+1 +in general (q may equal 2^B). At the production binding below P<=B-3, C=B +already suffices, giving its unchanged bound 5B+2. Formula (2) is a +specialization for this caller, not a smaller bound for arbitrary rational +four-term rows and not a minimum-width theorem. The same schedule with only +2B bits fails at a=b=c=d=-M: its imaginary sum is 2M^2, outside that signed +range. This is a control for the schedule, not an optimality claim. + +## 4. A fixed local register schedule and its cost + +Keep the four supplied B-bit inputs intact. Allocate seven W-bit registers: +two output slots, one accumulator R, the offset h, and multiplication +workspace T,D,U. Compute ac into U and copy to R; compute bd into U and +subtract from R; add h and arithmetic-shift R into the first output slot. +Then compute ad and bc in the same workspace, accumulate their sum, add h, +and shift into the second output slot. Both output values exist before the +caller overwrites either input. Reset the five nonoutput registers to zero. + +The simultaneous data storage of this schedule is at most + + 4B + 7W bits, plus O(log W) control bits. (3) + +Here coefficient inputs count among the four B-bit values; they are not +free read-only constants. The two output slots are included even while all +inputs remain live. `grid_arithmetic.py` is a separate all-width diagnostic +of this schedule, with each register write checked. It is not a mutation or +guard relaxation of the predecessor. Its Python objects and observer +metadata are not a physical storage proof. + +The four multiplication loops use at most 4B iterations in total. A fixed +implementation uses O(B) W-bit shifts, tests, additions and comparisons; +scanning each constant-size local register frame gives O(BW)=O(B^2) local +bit work, including local copies and zeroing. This is an explicit quadratic +cost. No fast-multiplication or native-service price is inferred, and the +outer recurrence is not repriced. Transporting actual array/coefficient +words to this frame is still charged to the caller's missing movement bound. + +The literal `product_diagonal` on T records makes at most (d+1)T calls: +there are d-1 initial suffix calls, two calls per record, and at most d-1 +suffix rebuilds at each of the T-1 transitions. Thus substituting this +local routine at every such call in at most J stages costs +O(J(d+1)T B^2) bit operations for this arithmetic portion alone. Identity +shortcuts can reduce that count; no saving from them is required. This +explicit charge does not include coefficient construction or transport and +does not establish compatibility with an assumed faster service invoice. + +Zeroing here means ordinary destructive overwrite. It does not establish +reversible uncomputation, restoration of a dirty owned region, or erasure +permission in a more restrictive machine model. Those cleanup obligations +remain retained. Statement (3) is a local simultaneous live-value bound, +not a count of every word resident in the surrounding tensor execution. + +## 5. All-size supplied-word binding from the frozen precision theorem + +Retain exactly the spectral-downset theorem's hypotheses and unchanged +literal caller. With d axes, binary widths ell_i>=1, and L=sum ell_i, set + + E=ceil(257L/2)+1354d, A=20L+303d, + J=20000(d+1)(max ell_i+2)^6, + C0=4J(d+1)^2+d+1, + P=4p+A+2E+bit_length(C0), p>=1. + +The accepted theorem supplies infinity-norm prefix and interval cap R=M0=2^E, +single exact diagonal scalar bound b_i=2^(302+20ell_i), local defect +epsilon(1+||z||), epsilon=(d+1)^2 2^(-P+A), and at most J stages. +Coefficient errors and private phase synthesis remain paid by that theorem. + +Conversion changes a complex scalar by at most 2^-P<=1, so each supplied +table factor has modulus at most b_i+1<=2b_i. Put F_i=2b_i>=2. For any +suffix of k factors the actual rounded product has modulus strictly less +than 2 times their product of F_i. Inductively, the k-1 multiplication +rounding errors, each at most 1, give the product plus the proper suffix +products; division by the full product bounds the added terms by the +geometric sum sum_(j>=1) 2^-j<1. This argument uses upper bounds F_i, +never divides by actual table entries, and permits zero factors. The literal +odometer invariant says a stored suffix is always a product of its current +factors, not a sum of errors from all earlier records. Therefore every +retained suffix and each final diagonal multiplier has modulus <2^(A+1). + +The represented data states at external stage boundaries obey ||z||<=R. +For completeness, let Z be the maximum over the finite computed run and +a=J M0 epsilon. Variation of constants and the half-disk input give +Z<=R/2+a(1+Z). The frozen selector gives a<1/4, so +Z<=(R/2+a)/(1-a)<=R for R>=1. This uses a finite maximum and a valid local +defect inequality, not a circular assumed bound on the computed states. +During a simultaneous diagonal's coordinatewise scan, a coordinate is +either its old or new stage value; the same bound applies. Thus all actual +Grid.multiply inputs and outputs, including retained coefficient caches, +fit the common signed width + + B = P + max(A,E) + 3. (4) + +Indeed numerator magnitudes are below 2^P times max(2^(A+1),2^E), strictly +below 2^(B-1). P<=B-3. The original rational-row coefficient premise is also +now explicit: for a supplied complex grid scalar use integer numerators +a,b and denominator q=2^P; their component heights are at most C=B. +The fixed local routine (2) consequently covers every actual multiply site +in `product_diagonal`, including its suffix updates and identity shortcuts. +It leaves `Grid.word`, native H, `public`, `public_product`, coefficient +construction, array routing and event ordering unchanged. + +For the valid constructor geometry sides=(2,), digit_bits=5, p=30, the frozen +selector gives P=3438, A=323, E=1483. Thus B=4924, W=9849, and (3) is +88639 data bits plus controls for one local frame. This is a sufficient +arithmetic bound, not an observed peak or full multiplier space claim. + +## 6. Finite reference obstruction + +The predecessor's universal written theorem has all B>=2,C>=1. Its literal +diagnostic API separately requires B<=2048, C<=256, W<=3074. We preserve +these guards byte for byte. In the actual `Multiplier.operand` source at +the valid geometry above, the operand 1 produces numerator + + 2^P/(4*2^5) = 2^3431. + +A positive numerator of that size requires signed B>=3433. The literal +capped predecessor API cannot admit even this actual caller input, whereas +the universal written theorem and the separately proved program above do +not have that finite cap. The checker invokes the extracted source operand +method with an identity CRT route at this one-axis position and verifies +that rejection leaves the supplied state unchanged. This is a precise +integration limitation of the finite reference, not a counterexample to +Nick Petalas's mathematical theorem. + +## 7. Evidence and remaining boundary + +The checker authenticates supplied source bytes, executes literal source +ASTs, compares to independent Fraction rounding, checks actual Full.shear +events and actual lowering, and tests the separate fixed-register program. +It includes all signed small inputs, extreme wide inputs, positive and +negative ties, zero coefficients, one-bit underallocation, identity +shortcuts, changed imaginary sign, per-product rounding, coefficient tie +substitution, premature input overwrite, and the capped production call. +Normal and optimized interpreter receipts must agree. Finite checks support +source bindings and reject adverse controls; Sections 3--5 are the all-size +argument. No claim of a complete physical `precision_tape` discharge follows. diff --git a/research/direct-circulant-production-precision/grid-arithmetic/README.md b/research/direct-circulant-production-precision/grid-arithmetic/README.md new file mode 100644 index 0000000000..6d5cd28f17 --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/README.md @@ -0,0 +1,73 @@ +# Supplied dyadic arithmetic at the actual tensor caller + +This package proves a local arithmetic bridge for the pinned direct-circulant +`Grid.multiply` operations. It preserves the earlier integer-rounded-gate +kernel and its finite diagnostic guards. Its new routine uses seven arithmetic +registers and four shift/add products; it rounds each complete component once, +with the caller's actual ties-toward-positive-infinity rule. + +## Result + +If the four supplied input numerators fit signed B bits, B>=2, and their common +fractional precision satisfies 1<=P<=B, every arithmetic temporary fits +W=2B+1. The routine keeps all four inputs and both outputs live simultaneously +within 4B+7W data bits plus O(log W) control bits. Its local arithmetic cost is +O(B^2). These are maximum word width and local register costs, not a total +tensor-memory or tape-time theorem. + +Under the already reviewed spectral-downset numerical theorem, the actual +external table entries, suffix caches and represented data fit +B=P+max(A,E)+3. Thus this new local routine can compute every literal +`product_diagonal` multiplication without changing its values or event order. +The source makes at most (d+1)T such calls per diagonal scan, so the replacement +charges O(J(d+1)T B^2) local arithmetic work over its J-stage bound. No faster +service price is assumed. + +For p=30 and one binary side width equal to one, P=3438, B=4924 and W=9849. +The local frame has at most 88639 data bits plus controls. The predecessor's +diagnostic API only accepts B<=2048 and C<=256; an actual constructor-domain +`operand(1)` already needs 3433 signed bits. This limit does not refute its +universal written theorem. The new implementation is separate and proved +for arbitrary valid B and P; no predecessor guard is changed. + +## Rounding boundaries + +`Grid.word` rounds coefficient ties to even. `Grid.multiply` and the retained +`exact.apply` round output ties toward positive infinity. The checker retains +an exact halfway example separating those rules. It also obtains an actual +Full.shear gate for which the source's sixteen-H lowering at a small diagnostic +grid differs from replacing the original gate by one rounded output. The +bridge acts on the actual scalar multiplication sites, preserving the +lowering, table conversions, coefficient errors and chronology. + +## Replay + +This directory is self-contained and uses only the Python standard library. + +```sh +python -B check.py --output /tmp/grid-binding-normal.json +python -B -O check.py --output /tmp/grid-binding-optimized.json +cmp /tmp/grid-binding-normal.json /tmp/grid-binding-optimized.json +``` + +Run from this directory, or use an absolute path to `check.py`. The source +manifest authenticates canonical predecessor blobs, the exact external caller +and the frozen reviewed numerical dependency. The rational oracle is separate +from both source arithmetic and the new register program. The normal and +optimized results must be byte-identical. + +## Boundary and credit + +Coefficient synthesis, global array movement and ownership, native-H private +storage, and reversible cleanup remain retained. Resetting five scratch +registers is destructive overwrite; no reversible restoration is claimed. +The quadratic arithmetic charge is explicit and does not reprice the outer +multiplier recurrence. All five selected assumptions and kappa are unchanged. + +Nick Petalas supplied the existing general rational-row arithmetic theorem; +Armin Pourshafeie supplied rounded matching-layer semantics; Jose Manuel +supplied the retained rational unitary compiler; Ali Romman supplied the +direct-circulant caller. The frozen numerical theorem retains the credits to +Vlado Vojdanovski, Chafik Boukhalfa, Brian/JoyboyBrian and the other authors +recorded in its source package. Prepared for Jerry Chen / @CubeJerry with +substantial OpenAI assistance. Separate review is required before publication. diff --git a/research/direct-circulant-production-precision/grid-arithmetic/SOURCES.json b/research/direct-circulant-production-precision/grid-arithmetic/SOURCES.json new file mode 100644 index 0000000000..2c94fd658c --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/SOURCES.json @@ -0,0 +1,209 @@ +{ + "files": [ + { + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "git_blob": "6909bff0ab15bf16c8c5d2d50eb6a7a1ddc3be92", + "local": "retained/PROOF.md", + "path": "research/integer-rounded-gate/PROOF.md", + "repository": "CrocSwap/integer-mult-bounds", + "sha256": "00d2782a462612ad061c46ff9556c0e85108e8a3e38b181bc878bf1589976b9d" + }, + { + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "git_blob": "45ffe0f280e6b88dbdd8873adbc2f8abc6d9f81f", + "local": "retained/kernel.py", + "path": "research/integer-rounded-gate/kernel.py", + "repository": "CrocSwap/integer-mult-bounds", + "sha256": "33afb9b22d1b7e53f41747b5b798f98511b3e0d8053fecb504e7137ed5f208a9" + }, + { + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "git_blob": "6da494b00401267476ede0a00322b3b5a91f7814", + "local": "retained/verify.py", + "path": "research/integer-rounded-gate/verify.py", + "repository": "CrocSwap/integer-mult-bounds", + "sha256": "75e4e9aeca05475fba814986b6713e5f84970681718e2bcc7df3bb478cd11d52" + }, + { + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "git_blob": "d32aacea72d1560fdb9443ad1e1c7ff8882a6d90", + "local": "retained/SOURCES.json", + "path": "research/integer-rounded-gate/SOURCES.json", + "repository": "CrocSwap/integer-mult-bounds", + "sha256": "a3ce4df0d59bc95323134c2f8c2ee3165ae2cb04898eec9ab6cf6d9cb6a25ee7" + }, + { + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "git_blob": "3bddd95b97bb4f443d825bc655fc2b8794170c90", + "local": "retained/TASK.json", + "path": "research/integer-rounded-gate/TASK.json", + "repository": "CrocSwap/integer-mult-bounds", + "sha256": "a760a13208ecee3f65a85bf6a9b204da8ae3532c0c2e82bf5d8bec99c363dd4e" + }, + { + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "git_blob": "1c7b65b6ddce2d5d92f26351043f4fbef481d9d0", + "local": "retained/VERIFY.json", + "path": "research/integer-rounded-gate/VERIFY.json", + "repository": "CrocSwap/integer-mult-bounds", + "sha256": "10c341a64b0bca5b614fbf616c65774e6f4a4819091373487aa06f702ea2b6f7" + }, + { + "bytes": 1366, + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "git_blob": "c602fb5bb332dbe098950b14d55da05ce2cf4312", + "local": "retained/compiler/STEIN-PROVENANCE.json", + "path": "research/rational-unitary-fft/vendor/STEIN-PROVENANCE.json", + "repository": "CrocSwap/integer-mult-bounds", + "sha256": "e7f0e8dc517387e302b1e8bf5dff7e12b29da8aa91abc6ea597f33c1ac08ba62" + }, + { + "bytes": 10774, + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "git_blob": "f80c141c8116b163c2bb5a028c28212077c8d5a9", + "local": "retained/compiler/check_circuits.py", + "path": "research/capped-phase-fusion/evidence/inplace_algebra_ultra/check_circuits.py", + "repository": "CrocSwap/integer-mult-bounds", + "sha256": "06d1861bfe8af543908e26557ffda7e451ff176bceb9bacfaf0f04f234b336d5" + }, + { + "bytes": 13174, + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "git_blob": "e9f2f2b08dc2bc4c646e47dca92059351ca89384", + "local": "retained/compiler/engine.py", + "path": "research/rational-unitary-fft/engine.py", + "repository": "CrocSwap/integer-mult-bounds", + "sha256": "9e36aee0835e6b1b62997433581f88b5a434ccab8ae43e5c25d1deaaf1ebf653" + }, + { + "bytes": 7863, + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "git_blob": "aae41e6acfb2e5a4fafdd85727891eb746b57b42", + "local": "retained/compiler/exact.py", + "path": "research/rational-unitary-fft/exact.py", + "repository": "CrocSwap/integer-mult-bounds", + "sha256": "c9b89d7357210af69865690ba12e695366961f8b501a8fab9d0fefe3fb30c479" + }, + { + "bytes": 12561, + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "git_blob": "7f85ad1a89e81b7dfc6b54e7bd9547120e86d5d3", + "local": "retained/compiler/full.py", + "path": "research/rational-unitary-fft/full.py", + "repository": "CrocSwap/integer-mult-bounds", + "sha256": "1f42d5f2858564ffb320e54ba6aa29651025491569823e25006bf5862457b803" + }, + { + "bytes": 12562, + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "git_blob": "d761d3c88b1685fb64d92d69f699b8218c9ec30f", + "local": "retained/compiler/generator.py", + "path": "research/rational-unitary-fft/generator.py", + "repository": "CrocSwap/integer-mult-bounds", + "sha256": "827ef9fe1bd664859995892b59843c390f7969c938fb7e1e6dc585c31a54b555" + }, + { + "bytes": 2363, + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "git_blob": "1182175a55cb871481de0f56ea9ae56e474705fe", + "local": "retained/compiler/interval_kernel.py", + "path": "research/cubic-cyclic-inverse/vendor/interval_kernel.py", + "repository": "CrocSwap/integer-mult-bounds", + "sha256": "9b7bb24640a9a7d3f83c7951dfef483ec933db4c50de6c0130b85f450eeddfbe" + }, + { + "bytes": 6045, + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "git_blob": "71b240a460a185ee2fe926cd189b56aeac6f997f", + "local": "retained/compiler/stein_rational.py", + "path": "research/rational-unitary-fft/vendor/stein_rational.py", + "repository": "CrocSwap/integer-mult-bounds", + "sha256": "3065fc5d6d22ec44de533b08fb0c639603449456383668e561dc46629e641502" + }, + { + "bytes": 10040, + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "git_blob": "2bd8de01a7ac80de7e6b9f8252bc69d0e0a291e8", + "local": "retained/compiler/triangular.py", + "path": "research/rational-unitary-fft/triangular.py", + "repository": "CrocSwap/integer-mult-bounds", + "sha256": "46780d95ddebfed22e8f0c18565fe2e768250afa5beeb31f450292cc06f7ec11" + }, + { + "commit": "3615fd982f2f4dc7172bef6f0dc9a4f77d5ab6dd", + "file": "product.py", + "git_blob": "6059b6e2cecd125f741d148ba91d32637ef41ac1", + "local": "retained/direct/product.py", + "path": "research/direct-circulant-fourier/product.py", + "repository": "aliromman/integer-mult-bounds", + "sha256": "29ab6c60f937b7cce58666f5ddd7a921c3197cf72abf91ecca0ff7ad9486850e", + "url": "https://github.com/aliromman/integer-mult-bounds/blob/3615fd982f2f4dc7172bef6f0dc9a4f77d5ab6dd/research/direct-circulant-fourier/product.py" + }, + { + "commit": "3615fd982f2f4dc7172bef6f0dc9a4f77d5ab6dd", + "file": "root_gate_plan.py", + "git_blob": "f306aa7fa8e1161caec399ae7f44a8af6a3db486", + "local": "retained/direct/root_gate_plan.py", + "path": "research/direct-circulant-fourier/root_gate_plan.py", + "repository": "aliromman/integer-mult-bounds", + "sha256": "379ca05625076824ac9c2399eac03c1c64c13fecee45ea17f78b8898df57cd2d", + "url": "https://github.com/aliromman/integer-mult-bounds/blob/3615fd982f2f4dc7172bef6f0dc9a4f77d5ab6dd/research/direct-circulant-fourier/root_gate_plan.py" + }, + { + "commit": "3615fd982f2f4dc7172bef6f0dc9a4f77d5ab6dd", + "file": "spectral.py", + "git_blob": "57d84e16559f6d2b235a41b6b13abb8a2e076ac6", + "local": "retained/direct/spectral.py", + "path": "research/direct-circulant-fourier/spectral.py", + "repository": "aliromman/integer-mult-bounds", + "sha256": "ede9c48d34280c9c1c5c332b9434ff666fd321f4a18ffbf1f61b3339339e8ab6", + "url": "https://github.com/aliromman/integer-mult-bounds/blob/3615fd982f2f4dc7172bef6f0dc9a4f77d5ab6dd/research/direct-circulant-fourier/spectral.py" + }, + { + "commit": "3615fd982f2f4dc7172bef6f0dc9a4f77d5ab6dd", + "file": "tensor_word.py", + "git_blob": "8bc7bc59957c1d56ae5cfeeec329e60fce02b998", + "local": "retained/direct/tensor_word.py", + "path": "research/direct-circulant-fourier/tensor_word.py", + "repository": "aliromman/integer-mult-bounds", + "sha256": "36c5a9a0082c9aa3c6cb2d04a9196af8debce0d551a0525975b710018ea02cac", + "url": "https://github.com/aliromman/integer-mult-bounds/blob/3615fd982f2f4dc7172bef6f0dc9a4f77d5ab6dd/research/direct-circulant-fourier/tensor_word.py" + }, + { + "commit": "ea0274f8e6b6add282a63c11c5b8c4420ed3bc7e", + "dependency": "frozen reviewed precision package, published PR8093 ea0274f8", + "git_blob": "76e89b74b3dd120e7ca54f9064e03f07956e498b", + "local": "retained/parent-PROOF.md", + "path": "research/direct-circulant-production-precision/PROOF.md", + "repository": "CubeJerry/integer-mult-bounds", + "sha256": "26e4e214f0a5785c1d1414561465bb49a3248f9e6f59f6b514eb95a887bdfe2f" + }, + { + "commit": "ea0274f8e6b6add282a63c11c5b8c4420ed3bc7e", + "dependency": "frozen reviewed precision package, published PR8093 ea0274f8", + "git_blob": "1f5901dadcf8959132c3a318ecb4d39cd4073fa8", + "local": "retained/spectral-PROOF.md", + "path": "research/direct-circulant-production-precision/spectral-downset/PROOF-DRAFT.md", + "repository": "CubeJerry/integer-mult-bounds", + "sha256": "0501a6a9a5f467fff4c998606965babc8157e74d98cf33b93f71fb10674d57bb" + }, + { + "commit": "ea0274f8e6b6add282a63c11c5b8c4420ed3bc7e", + "dependency": "frozen reviewed precision package, published PR8093 ea0274f8", + "git_blob": "2115eb2e584056fb21a25263f47914871b88918a", + "local": "retained/precision.py", + "path": "research/direct-circulant-production-precision/spectral-downset/precision.py", + "repository": "CubeJerry/integer-mult-bounds", + "sha256": "9c3e99219f741c5b08c0628c30784cf72c60b4421beae3373fa976aeffcd8e20" + }, + { + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "git_blob": "80e8ae627ef8b35553f43a014c2a4b4686c84def", + "local": "retained/README.md", + "path": "research/integer-rounded-gate/README.md", + "repository": "CrocSwap/integer-mult-bounds", + "sha256": "8fbc9c0b34f5d9233664c9822034b3ab2e9725452c59227eb0b25f416b93951b" + } + ], + "schema_version": 1 +} diff --git a/research/direct-circulant-production-precision/grid-arithmetic/TASK.json b/research/direct-circulant-production-precision/grid-arithmetic/TASK.json new file mode 100644 index 0000000000..67b04fae7d --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/TASK.json @@ -0,0 +1,26 @@ +{ + "schema_version": 1, + "title": "Bind supplied dyadic arithmetic to actual Grid.multiply events", + "status": "completed-with-separate-model-assisted-review", + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "accepted_numerical_dependency": "PR8093 ea0274f8e6b6add282a63c11c5b8c4420ed3bc7e", + "claims": [ + "Exact value agreement with the literal external multiplication and its signed tie rule", + "Universal temporary width W=2B+1 for supplied common-grid operands", + "Local simultaneous data storage 4B+7W plus logarithmic control bits", + "At most (d+1)T multiplication calls per literal diagonal scan", + "All-size caller input/output width B=P+max(A,E)+3 under the frozen numerical theorem", + "Explicit production-domain obstruction for the unchanged capped predecessor diagnostic" + ], + "retained": [ + "Coefficient synthesis and its arithmetic/storage costs", + "Global array and coefficient movement", + "Global ownership and native-H private storage", + "Reversible restoration and permission to erase scratch", + "Compatibility of the quadratic local arithmetic with an outer service invoice", + "All five selected assumptions and selected kappa" + ], + "cost": "O(J(d+1)T B^2) for this local arithmetic portion; no outer recurrence repricing", + "stopping_rule": "Freeze after source authentication, independent Fraction comparisons, literal-source adverse controls, normal/-O equality and independent review; no broader precision_tape claim.", + "review": "review/REVIEW.md" +} diff --git a/research/direct-circulant-production-precision/grid-arithmetic/VERIFY.json b/research/direct-circulant-production-precision/grid-arithmetic/VERIFY.json new file mode 100644 index 0000000000..3335a77a02 --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/VERIFY.json @@ -0,0 +1,11 @@ +{ + "schema_version": 1, + "commands": [ + "python -B check.py --output /tmp/grid-binding-normal.json", + "python -B -O check.py --output /tmp/grid-binding-optimized.json", + "cmp /tmp/grid-binding-normal.json /tmp/grid-binding-optimized.json" + ], + "success_marker": "PASS_SUPPLIED_GRID_ARITHMETIC_BINDING", + "timeout_seconds": 120, + "writes": "Only explicit output receipts; predecessor and frozen dependency files remain unchanged." +} diff --git a/research/direct-circulant-production-precision/grid-arithmetic/check.py b/research/direct-circulant-production-precision/grid-arithmetic/check.py new file mode 100644 index 0000000000..8ba50914f0 --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/check.py @@ -0,0 +1,326 @@ +#!/usr/bin/env python3 +"""Independent rational oracles and literal-source integration checks.""" + +import argparse +import ast +from fractions import Fraction as Q +from hashlib import sha1, sha256 +import importlib.util +from itertools import product +import json +from math import prod +import operator +from pathlib import Path +import sys +from types import SimpleNamespace + +from grid_arithmetic import multiply_grid + +HERE = Path(__file__).resolve().parent +RET = HERE / 'retained' + + +def need(ok, why): + if not ok: + raise ValueError(why) + + +def load(path, name): + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + spec.loader.exec_module(module) + return module + + +def authenticate(): + rows = json.loads((HERE / 'SOURCES.json').read_text())['files'] + for row in rows: + data = (HERE / row['local']).read_bytes() + need(sha256(data).hexdigest() == row['sha256'], 'source SHA256 ' + row['local']) + if 'git_blob' in row: + actual = sha1(b'blob ' + str(len(data)).encode() + b'\0' + data).hexdigest() + need(actual == row['git_blob'], 'source Git blob ' + row['local']) + return len(rows) + + +def literal_tensor(): + tree = ast.parse((RET / 'direct/tensor_word.py').read_text()) + names = {'Grid', 'product_diagonal', 'hadamard'} + nodes = [n for n in tree.body if isinstance(n, (ast.FunctionDef, ast.ClassDef)) + and n.name in names] + need(len(nodes) == 3, 'literal external arithmetic source inventory') + namespace = {'Fraction': Q, 'word_product': operator.mul, 'prod': prod} + exec(compile(ast.Module(body=nodes, type_ignores=[]), '', 'exec'), namespace) + return namespace + + +def nearest(value): + floor, remainder = divmod(value.numerator, value.denominator) + return floor + int(remainder + remainder >= value.denominator) + + +def oracle(u, v, p): + a, b = (Q(x, 1 << p) for x in u) + c, d = (Q(x, 1 << p) for x in v) + return nearest((a*c-b*d)*(1 << p)), nearest((a*d+b*c)*(1 << p)) + + +def one_case(grid_type, b, p, values): + u, v = tuple(values[:2]), tuple(values[2:]) + wanted = oracle(u, v, p) + actual, frame = multiply_grid(u, v, p, b) + need(actual == wanted == grid_type(p).multiply(u, v), 'independent/source/program agreement') + need(frame.peak <= 2*b+1 and frame.iterations <= 4*b, 'arithmetic width and loop budget') + need(frame.registers[2:] == [0]*5, 'five nonoutput scratch registers reset') + need(u == tuple(values[:2]) and v == tuple(values[2:]), 'supplied inputs unchanged') + return frame.peak + + +def arithmetic_cases(grid_type): + count, peak = 0, 0 + for b in (2, 3): + for p in range(1, b+1): + for values in product(range(-(1 << (b-1)), 1 << (b-1)), repeat=4): + peak = max(peak, one_case(grid_type, b, p, values)); count += 1 + for b in (4, 8, 17, 128): + m = 1 << (b-1) + for p in sorted({1, b//2, b}): + for values in product((-m, -1, 0, 1, m-1), repeat=4): + peak = max(peak, one_case(grid_type, b, p, values)); count += 1 + for b in (1024, 3433, 4924): + m = 1 << (b-1) + for p in (1, min(3438, b), b): + for values in ((-m,)*4, (m-1,)*4, (-m, 0, m-1, 1), (1, -1, 0, 0)): + peak = max(peak, one_case(grid_type, b, p, values)); count += 1 + return dict(cases=count, maximum_observed_bits=peak) + + +def scalar_rows(u, p): + a, b = (Q(x, 1 << p) for x in u) + values = ((a, -b, Q(0), Q(0)), (b, a, Q(0), Q(0)), + (Q(0), Q(0), Q(1), Q(0)), (Q(0), Q(0), Q(0), Q(1))) + return tuple(tuple((x.numerator, x.denominator) for x in row) for row in values) + + +def predecessor_cases(kernel, grid_type): + count = 0 + for b in (3, 8, 18): + for p in (1, b-1): + for values in product((-3, 0, 3), repeat=4): + u, v = values[:2], values[2:] + rows = scalar_rows(u, p) + c = max(max(abs(n).bit_length(), d.bit_length()) for row in rows for n, d in row) + state = list(v) + [0, 0] + kernel.apply_gate(rows, state, b, c) + need(tuple(state[:2]) == oracle(u, v, p), 'unchanged predecessor scalar binding') + count += 1 + return count + + +def compiler_fixture(): + modules = {} + for name in ('exact', 'engine', 'triangular', 'generator', 'full'): + modules[name] = load(RET / 'compiler' / (name + '.py'), name) + g = modules['generator'] + raw = {g.SOURCE+'check_circuits.py': (RET/'compiler/check_circuits.py').read_bytes(), + g.ORACLE: (RET/'compiler/interval_kernel.py').read_bytes(), + g.PRODUCER: (RET/'compiler/stein_rational.py').read_bytes(), + g.PROVENANCE: (RET/'compiler/STEIN-PROVENANCE.json').read_bytes()} + e, f = modules['exact'], modules['full'] + matrix = e.Mat([[3, 1], [1, 3]]) + lam, q, _ = f.admission(matrix) + compiler = f.Full(f.allocation(2, lam, q, 1, 1, 0), raw) + plan = compiler.plan(matrix) + return modules, compiler, plan + + +def gate_rows(gate): + values = [[z for z in row] for row in gate] + if len(values) == 1: + zero = values[0][0] * 0 + values = [[values[0][0], zero], [zero, zero+1]] + rows = [] + for row in values: + for real in (True, False): + parts = [v for z in row for v in ((z.re, -z.im) if real else (z.im, z.re))] + rows.append(tuple((x.numerator, x.denominator) for x in parts)) + return tuple(rows) + + +def full_events(kernel, modules, compiler, plan): + e = modules['exact']; f = compiler.bound['data_bits']; scale = 1 << f + b = f + compiler.bound['integer_bits']; count = 0; maximum = 0 + for atom in plan.atoms: + for layer in atom['local_plan']: + for ids, gate in layer: + h = max(max(abs(n).bit_length(), d.bit_length()) + for row in gate_rows(gate) for n, d in row) + need(h <= atom['coefficient_height'], 'actual atom coefficient height') + maximum = max(maximum, h) + for initial in ((-7, -2, 3, 4), (1, 0, 0, 1), (0, 0, 0, 0)): + vector = e.Vec([e.C(Q(initial[j], scale), Q(initial[j+1], scale)) for j in (0, 2)]) + expected, _ = e.apply(plan, vector, f) + state = [list(initial[:2]), list(initial[2:])] + for layer in plan: + for ids, gate in layer: + rows = gate_rows(gate); before = [part for i in ids for part in state[i]] + before += [0] * (4-len(before)) + c = max(max(abs(n).bit_length(), d.bit_length()) for row in rows for n, d in row) + wanted = [nearest(sum((Q(n, d)*x for (n, d), x in zip(row, before)), Q())) + for row in rows] + actual = list(before); kernel.apply_gate(rows, actual, b, c) + need(actual == wanted, 'actual Full primitive independent row oracle') + for j, wire in enumerate(ids): + state[wire] = actual[2*j:2*j+2] + count += 1 + wanted = [[int(part*scale) for part in (z.re, z.im)] for z in expected] + need(state == wanted, 'whole actual source Full word once-rounded replay') + return dict(events=count, layers=len(plan), gates=sum(map(len, plan)), + actual_coefficient_height=maximum, declared_height=compiler.bound['coefficient_height_bound'], + initial_scalar_height=compiler.bound['scalar_height_bound'], data_bits=b, fractional_bits=f) + + +def chronology_control(grid_type, modules, plan): + root = load(RET/'direct/root_gate_plan.py', 'binding_root_gate_plan') + e = modules['exact']; gate = next(g for layer in plan for ids, g in layer if len(ids) == 2) + grid = grid_type(2); initial = (-1, -1, -1, -1) + vector = e.Vec([e.C(Q(-1, 4), Q(-1, 4))]*2) + expected, _ = e.apply([[((0, 1), gate)]], vector, 2) + once = tuple(int(v*4) for z in expected for v in (z.re, z.im)) + state = [initial[:2], initial[2:]] + diagonals = [tuple(grid.word(z) for z in diag) for diag in root.lower_pair(gate)] + need(len(diagonals) == 17, 'literal sixteen-H lowering') + for j, diag in enumerate(diagonals): + state = [grid.multiply(diag[k], state[k]) for k in range(2)] + if j < 16: + (a, b), (c, d) = state; state = [(a+c, b+d), (a-c, b-d)] + lowered = tuple(v for z in state for v in z) + need(once == initial and lowered == (0, 0, 0, 0), 'lowered and once-rounded semantics differ') + return dict(gate=[[z.record() for z in row] for row in gate], fractional_bits=2, + inputs=initial, once_rounded=once, lowered=lowered) + + +def cache_cases(namespace): + base = namespace['Grid']; count = 0; calls = 0; zeros = 0 + class CheckedGrid(base): + def multiply(self, u, v): + nonlocal calls, zeros + value, frame = multiply_grid(u, v, self.bits, self.bits+32) + need(value == super().multiply(u, v), 'literal cache multiplication value') + calls += 1; zeros += int(u == (0, 0) or v == (0, 0)) + return value + for p in (2, 7): + q = 1 << p + factors = [(0, 0), (q, 0), (-q, 0), (0, q), (q//2, -q//2)] + for offset in range(5): + tables = [tuple(factors[(offset+j+k)%5] for j in range(size)) + for k, size in enumerate((2, 3, 2))] + before = [(q//4, -q//4)]*12 + reference, actual = list(before), list(before) + namespace['product_diagonal'](reference, tables, base(p)) + earlier_calls = calls + namespace['product_diagonal'](actual, tables, CheckedGrid(p)) + need(actual == reference, 'literal odometer output with replacement local arithmetic') + need(calls-earlier_calls <= (len(tables)+1)*len(actual), 'literal per-scan call charge') + count += 1 + return dict(scans=count, multiply_calls=calls, zero_factor_calls=zeros) + + +def semantic_controls(grid_type): + g = grid_type(2) + need(g.word(Q(1, 8)) == (0, 0) and g.multiply((1, 0), (2, 0)) == (1, 0), + 'coefficient ties-even cannot replace multiplication ties-positive') + need(grid_type(1).multiply((-1, 0), (1, 0)) == (0, 0), 'negative halfway tie') + need(g.multiply((0, 2), (0, 2)) == (-1, 0), 'real product sign') + need(grid_type(1).multiply((1, 1), (1, 1)) == (0, 1), 'sum before rounding') + need(nearest(Q(1, 2))+nearest(Q(1, 2)) == 2, 'per-product rounding mutation differs') + need(grid_type(1).multiply((1, 2), (3, 4)) == (-2, 5), 'saved input example') + need(((-2)*4+2*3+1) >> 1 == -1, 'premature overwrite mutation differs') + for b in (2, 8, 128): + m = 1 << (b-1) + try: + multiply_grid((-m, -m), (-m, -m), b, b, diagnostic_width=2*b) + except OverflowError: + continue + raise ValueError('underallocated signed arithmetic word accepted') + for args in (((1, 0), (1, 0), 0, 2), ((1, 0), (1, 0), 3, 2), + ((2, 0), (1, 0), 1, 2), ((True, 0), (1, 0), 1, 2)): + try: + multiply_grid(*args) + except ValueError: + continue + raise ValueError('invalid new-program domain accepted') + return dict(semantic=7, insufficient_width=3, invalid_domain=4) + + +def literal_mutants(): + source = (RET/'direct/tensor_word.py').read_text() + recipes = [('word_product(a,d)+word_product(b,c)+half', + 'word_product(a,d)-word_product(b,c)+half', 2, (1, 2), (3, 4)), + ('+half', '', 1, (1, 0), (1, 0)), + ('word_product(a,d)', 'word_product(a,c)', 1, (1, 0), (0, 2)), + ('>> self.bits', '>> (self.bits+1)', 1, (3, 0), (3, 0))] + for old, new, p, u, v in recipes: + need(old in source, 'literal mutation target exists') + tree = ast.parse(source.replace(old, new)) + node = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'Grid') + ns = {'Fraction': Q, 'word_product': operator.mul} + exec(compile(ast.Module(body=[node], type_ignores=[]), '', 'exec'), ns) + need(ns['Grid'](p).multiply(u, v) != oracle(u, v, p), 'independent oracle kills literal mutant') + return len(recipes) + + +def production_binding(kernel, grid_type): + precision = load(RET/'precision.py', 'binding_precision') + budget = precision.precision_budget(30, (1,)); p = budget.fractional_bits + a, e = budget.local_error_exponent, budget.interval_exponent + b = p+max(a, e)+3; w = 2*b+1 + tree = ast.parse((RET/'direct/product.py').read_text()) + owner = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'Multiplier') + operand = next(n for n in owner.body if isinstance(n, ast.FunctionDef) and n.name == 'operand') + helpers = [n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name in ('digits', 'ordinal')] + ns = {'prod': prod}; exec(compile(ast.Module(body=helpers+[operand], type_ignores=[]), + '', 'exec'), ns) + caller = SimpleNamespace(widths=(2,), sides=(2,), size=2, base=32, + grid=grid_type(p), crt=lambda x: x) + field, used = ns['operand'](caller, 1) + numerator = field[0][0] + need(used == 1 and numerator == 1 << 3431 and p == 3438, 'literal production operand') + state = [numerator, 0, 0, 0]; before = tuple(state) + identity = tuple(tuple((int(i == j), 1) for j in range(4)) for i in range(4)) + try: + kernel.apply_gate(identity, state, numerator.bit_length()+1, 1) + except ValueError as exc: + need(str(exc) == 'data width' and tuple(state) == before, 'literal finite API guard preserved') + else: + raise ValueError('capped predecessor incorrectly admitted production operand') + value, frame = multiply_grid(field[0], (1 << p, 0), p, b) + need(value == field[0] and frame.peak <= w, 'new all-width program production identity call') + return dict(P=p, A=a, E=e, B=b, W=w, local_data_bits=4*b+7*w, + operand_numerator_exponent=3431, required_signed_input_bits=numerator.bit_length()+1) + + +def main(): + parser = argparse.ArgumentParser(); parser.add_argument('--output', type=Path) + args = parser.parse_args(); sources = authenticate(); namespace = literal_tensor() + kernel = load(RET/'kernel.py', 'preserved_predecessor_kernel') + modules, compiler, plan = compiler_fixture() + receipt = dict(marker='PASS_SUPPLIED_GRID_ARITHMETIC_BINDING', sources=sources, + arithmetic=arithmetic_cases(namespace['Grid']), + predecessor_scalar_cases=predecessor_cases(kernel, namespace['Grid']), + actual_full=full_events(kernel, modules, compiler, plan), + chronology=chronology_control(namespace['Grid'], modules, plan), + odometer=cache_cases(namespace), controls=semantic_controls(namespace['Grid']), + literal_source_mutants=literal_mutants(), + production=production_binding(kernel, namespace['Grid'])) + receipt['proof_sha256'] = sha256((HERE/'PROOF.md').read_bytes()).hexdigest() + receipt['program_sha256'] = sha256((HERE/'grid_arithmetic.py').read_bytes()).hexdigest() + payload = json.dumps(receipt, sort_keys=True, indent=2)+'\n' + if args.output: + args.output.write_text(payload) + print(payload, end='') + + +if __name__ == '__main__': + main() diff --git a/research/direct-circulant-production-precision/grid-arithmetic/grid_arithmetic.py b/research/direct-circulant-production-precision/grid-arithmetic/grid_arithmetic.py new file mode 100644 index 0000000000..8727e1e43d --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/grid_arithmetic.py @@ -0,0 +1,68 @@ +"""A separate fixed-register diagnostic for the supplied-grid arithmetic lemma. + +This is not a replacement of the predecessor kernel or a physical tape emitter. +The seven registers model arithmetic live values, not Python heap allocation. +""" + + +def need(ok, message): + if not ok: + raise ValueError(message) + + +class Frame: + def __init__(self, width): + self.width = width + self.limit = 1 << (width - 1) + self.registers = [0] * 7 + self.peak = 0 + self.iterations = 0 + self.writes = 0 + + def put(self, index, value): + if not -self.limit <= value < self.limit: + raise OverflowError("arithmetic word exceeds declared signed width") + self.registers[index] = value + self.peak = max(self.peak, abs(value).bit_length() + 1) + self.writes += 1 + + def multiply(self, left, right): + negative = (left < 0) != (right < 0) + self.put(4, abs(left)) + self.put(5, abs(right)) + self.put(6, 0) + while self.registers[5]: + self.iterations += 1 + if self.registers[5] & 1: + self.put(6, self.registers[6] + self.registers[4]) + self.put(5, self.registers[5] >> 1) + if self.registers[5]: + self.put(4, self.registers[4] << 1) + if negative: + self.put(6, -self.registers[6]) + + +def multiply_grid(u, v, bits, data_bits, *, diagnostic_width=None): + need(type(bits) is int and type(data_bits) is int + and data_bits >= 2 and 1 <= bits <= data_bits, "1 <= P <= B, B >= 2") + need(isinstance(u, (tuple, list)) and isinstance(v, (tuple, list)) + and len(u) == len(v) == 2, "two complex grid numerators") + inputs = tuple(u) + tuple(v) + limit = 1 << (data_bits - 1) + need(all(type(x) is int and -limit <= x < limit for x in inputs), + "signed B-bit supplied inputs") + width = 2 * data_bits + 1 + frame = Frame(width if diagnostic_width is None else diagnostic_width) + frame.put(3, 1 << (bits - 1)) + for output, first, second, subtract in ((0, (0, 2), (1, 3), True), + (1, (0, 3), (1, 2), False)): + frame.multiply(inputs[first[0]], inputs[first[1]]) + frame.put(2, frame.registers[6]) + frame.multiply(inputs[second[0]], inputs[second[1]]) + frame.put(2, frame.registers[2] - frame.registers[6] if subtract + else frame.registers[2] + frame.registers[6]) + frame.put(2, frame.registers[2] + frame.registers[3]) + frame.put(output, frame.registers[2] >> bits) + for index in range(2, 7): + frame.put(index, 0) + return tuple(frame.registers[:2]), frame diff --git a/research/direct-circulant-production-precision/grid-arithmetic/retained/PROOF.md b/research/direct-circulant-production-precision/grid-arithmetic/retained/PROOF.md new file mode 100644 index 0000000000..6909bff0ab --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/retained/PROOF.md @@ -0,0 +1,152 @@ +# A smaller arithmetic width for once-rounded rational gates + +This scoped construction and proof were produced by Nick Petalas. Apache-2.0. + +## Statement + +Let B>=2 and C>=1 be integers. Four signed input grid numerators X_j satisfy + + -2^(B-1) <= X_j < 2^(B-1), 0<=j<4. + +A rational row has coefficients p_j/d_j, with integer p_j and d_j such that + + |p_j| < 2^C, 1 <= d_j < 2^C. + +The coefficients need not be reduced. There is a constant-word arithmetic +program that computes + + floor(sum_j (p_j/d_j) X_j + 1/2) + +with every signed data-arithmetic temporary fitting + + W = B + 4C + 2 bits. (1) + +The program uses shifts, bit tests, addition, subtraction and comparisons. +Multiplication and division below are implemented by bounded binary loops. +They are not assumed machine instructions. Four applications to saved inputs +implement any two-coordinate Gaussian rational matrix gate, rounding each +real and imaginary output once with ties toward positive infinity. + +This is an upper bound, not a minimum-width theorem. It concerns arithmetic +words after coefficients and input data are supplied. No reversible circuit, +bit-tape running time, memory layout or coefficient-preparation bound follows. + +## Common-denominator accumulation + +Set + + D = product_j d_j, + N_j = p_j X_j product_(k!=j) d_k, + S = sum_j N_j. + +Compute D by four successive products starting from one. Compute each N_j +from p_j X_j and then the three other denominators. Accumulate its exact +integer value before proceeding to the next term. No product is rounded. + +We have + + 1 <= D < 2^(4C), + |N_j| < 2^(B+4C-1), + |sum_(j in J) N_j| < 4 * 2^(B+4C-1) = 2^(W-1) (2) + +for every partial sum occurring in this fixed four-term order. The bound +uses |X_j|<=2^(B-1), including the most negative B-bit input. Strictness +comes from the four coefficient numerator/denominator factors, each strictly +below 2^C. Signs and cancellation are unrestricted. + +Each nonzero partial product has magnitude at most the corresponding full +product: every remaining denominator is at least one. A zero numerator +remains zero. All these intermediate values fit (1), by (2). D and its +partial products fit as well. The exact rational row value is S/D. + +For signed multiplication, retain the result sign and use unsigned +magnitudes. Scan the multiplier's binary digits from low to high, adding +the shifted multiplicand when a digit is one. Every shifted multiplicand +and every partial sum is at most the full magnitude product. Hence the +same word bound applies to the shift/add implementation, including its +positive magnitude words. None of these constructed products is the most +negative W-bit integer, so taking its absolute value is safe. + +## Division and signed ties + +Put t=|S|. Binary long division scans exactly W-1 positions of t, from +most significant to least significant. Maintain a quotient prefix q and +remainder r. At each position with digit b, replace + + r by 2r+b, + q by 2q, + if r>=D, subtract D from r and add one to q. + +The ordinary prefix-division induction proves that the final pair satisfies +t=qD+r and 0<=r=2, this is below 2^(W-1). +Each quotient prefix is at most the final quotient, which is at most t. +The shifted quotient prefix before its next digit is no larger than the +next completed quotient prefix. Thus every quotient and remainder word +fits (1). The Python helper enforces the sufficient additional contract +D<2^(W-2), which holds here by the stronger D<2^(4C). + +The final rounded integer is + + q + [2r>=D], if S>=0, + -q - [2r>D], if S<0. (3) + +For S>=0, this is floor(q+r/D+1/2). For S<0, it is +floor(-q-r/D+1/2). The strict inequality in the negative branch is +essential: -1/2 rounds to zero. The positive halfway value 1/2 rounds to +one. The word 2r is below 2D, so its comparison is also safe. + +If D=1, r=0 and rounding changes nothing. If D>=2 and t>=1, the rounded +result's magnitude is at most q+1<=t. At t=0 it is zero. Therefore the +final result also fits W signed bits. Equations (2) and (3), rather than +finite extrapolation, prove the all-B, all-C construction. + +## Complex gates, input snapshots and the cited allowance + +For a complex row a_0 z_0+a_1 z_1, expand its real and imaginary parts +using the four real input coordinates. Each real row has exactly four +rational coefficients, with signs but no increased component height. +If the inputs are 2^-F X_j, multiplying a rounded output by 2^F gives +exactly the integer expression above. The arithmetic bound depends on +B=F+I, not separately on F. The input grid cancels before arithmetic. + +Save all four inputs, compute all four output integers, then overwrite +the four stored coordinates. This gives the same saved-input, +exact-local-sum, once-per-output rounding contract as Jose Manuel's +`rational-unitary-fft/exact.py:apply`. Armin Pourshafeie's PR5240 asks for +such a concrete arithmetic implementation. Its layer and stored-state +theorems are cited premises, not re-proved or audited here. + +The same source's `engine.py:certificate` and FULL-PROOF.md use the +conservative temporary allowance + + 2F + 8C + 2I + 32 = 2B + 8C + 32. + +The new arithmetic construction uses + + B + 4C + 2 = (2B + 8C + 32)/2 - 14. (4) + +This reduces a sufficient maximum arithmetic-word width. It does not +establish a reduction in total live bits, elapsed time or a complete +caller's allocation. Output data still need that caller's independent +amplitude bound before they can be stored back in B bits. The kernel +permits W-bit outputs and makes no unconditional B-bit output claim. + +## One source-produced butterfly + +The verifier calls the retained `Phases(4, source)` and +`Builder.butterfly` with the exact phase i. They produce + + [ 13575/19193, 13568 i/19193 ] + [ 13568/19193, -13575 i/19193 ]. + +The maximum component height is C=15. For B=18, the new bound is 80 bits. +Evaluating the cited allowance at these same parameters gives 188 bits. +This comparison does not assert that a complete source caller selected +C=15 or allocated an 188-bit word. It is a same-parameter comparison of +two sufficient formulas. Actual coefficient production is used to supply +this finite fixture; its approximation theorem is not an audit target. + +The independent Fraction oracle, source executor comparisons, large-height +fixtures and controls corroborate the implementation. They do not replace +the proof or establish any physical supplier or multiplication theorem. diff --git a/research/direct-circulant-production-precision/grid-arithmetic/retained/README.md b/research/direct-circulant-production-precision/grid-arithmetic/retained/README.md new file mode 100644 index 0000000000..80e8ae627e --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/retained/README.md @@ -0,0 +1,131 @@ +# Once-rounded rational gates with smaller arithmetic words + +This contribution was produced by Nick Petalas. Apache-2.0. + +Claim type: scoped arithmetic construction and written proof with exact +finite corroboration. A two-coordinate Gaussian rational gate can compute +each output with one final nearest rounding, using signed arithmetic words +of width B+4C+2. Here B is the signed input-numerator width, and C bounds +the bit length of every coefficient component's numerator magnitude and +positive denominator. B>=2 and C>=1; the input fractional grid is arbitrary. + +The cited rational FFT/Full allowance is 2B+8C+32. The new sufficient width +is half that allowance minus fourteen bits. [PROOF.md](PROOF.md) proves the +all-width bound by four-term common-denominator accumulation and bounded +binary multiplication/division. [kernel.py](kernel.py) implements it with +integer shifts, tests, additions, subtraction and comparisons. It uses no +machine multiplication/division instruction or intermediate rounding. +All four real inputs are saved before output writes. + +This answers the arithmetic question left open by Armin Pourshafeie in +[PR5240](https://github.com/CrocSwap/integer-mult-bounds/pull/5240). +The result is a new implementation and resource bound, not an audit of the +predecessor's rounded-layer theorem. No new kappa or selected-frontier +change is claimed. The bound is sufficient, not proved minimal. + +## Evidence and reproduction + +The exact finite checks cover 50,625 four-term rows, 3,600 two-term rows, +31,744 binary divisions, 50 large-height rows and 768 complete complex-gate +cases. Eight semantic checks distinguish signed ties, product rounding and +input overwrite. Seventeen invalid-domain/overflow requests reject. +The largest tested data/coefficient widths are 2048 and 256 bits. +The word observer checks arithmetic intermediates at each operation. + +The retained phase factory at precision four supplies an actual butterfly +with component height fifteen. For B=18, our construction uses 80-bit +temporaries; the cited formula evaluated at those same parameters gives +188 bits. This does not assert a particular full caller allocated 188 bits. +The verifier compares all four rounded output components with the retained +saved-input executor, on three grids and all 256 stated input combinations. + +From the repository root, standard-library CPython 3.12: + +```sh +/Users/nick/git/integer-mult-bounds/.venv/bin/python3.12 -I -W error -B research/integer-rounded-gate/verify.py +/Users/nick/git/integer-mult-bounds/.venv/bin/python3.12 -I -W error -O -B research/integer-rounded-gate/verify.py +/Users/nick/git/integer-mult-bounds/.venv/bin/python3.12 -B scripts/research_package.py --package research/integer-rounded-gate +/Users/nick/git/integer-mult-bounds/.venv/bin/python3.12 -B scripts/check_research_commit.py --package research/integer-rounded-gate --check-source-history --check-modes +``` + +Other machines can substitute their CPython 3.12 path. Both registered +commands have a 120-second cap. The direct marker is +`PASS_INTEGER_ROUNDED_GATE`. Its generated stdout receipt binds every +package file by SHA256. Verification writes no package files. No receipt +is handwritten or committed. Source pins and the complete originating +card are in [SOURCES.json](SOURCES.json) and [TASK.json](TASK.json). + +## Scope and credit + +The theorem concerns arithmetic data words, given supplied coefficients. +The executable accepts 2<=B<=2048 and 1<=C<=256. Its word observer uses +host arithmetic to detect overflow; it is not a physical machine emitter. +Output values fit W=B+4C+2 bits. Returning them to B-bit data storage still +requires the caller's separate amplitude contract. No total-live-storage, +runtime or bit-tape improvement is claimed. + +Coefficient preparation, its local temporaries, reversible cleanup, actual +instruction encoding, tape movement, all-size compiler funding and supplier +admission remain open. All five selected framework assumptions remain. +No selected scientific replay, native/Lean/Docker build, independent human +review or proof-kernel acceptance is claimed. + +Credit Armin Pourshafeie / apoursh for PR5240's explicit arithmetic seam; +Jose Manuel / jmbarrancoml for the rational executor, phase producer and +coefficient/temporary contracts; Vlado Vojdanovski for the schedule; +Chafik Boukhalfa for phases; Brian / JoyboyBrian and James Reed for the +retained cut/allocator work; Cinna Davis and the numerical/compiler lineage. +Common-denominator arithmetic, long multiplication/division and nearest +rounding are classical. Nick Petalas's PR5940 concerns conditioned operator +interpolation; that theorem and its follow-up question are not extended. +Predecessor files and their credit lines remain unchanged. + +Base is canonical main 7c49fe32c55de02c2c873655c804b16e4c3fef0a, +priority revision eight, selected PR6030. The source-binding baseline passed. +The supplier-boundary-audit card explicitly changes to this constructive +arithmetic side result, because a missing local kernel separates stored-state +bounds from an implementation. This does not change a supplier family or +admit a new one. The [advance claim](https://github.com/CrocSwap/integer-mult-bounds/discussions/1166#discussioncomment-19361639) +reserves the same scope. + +Live claims, local reservations, open/account PRs, main formula/object +searches, merged searches and the cached card report were checked. The +cache covered 370 open PRs and 6,284 Discussion records, with complete +remote pagination. Its sparse local corpus covered 115 of 8,917 notes; +relevant packages were materialized and main README searches supplemented +it. Arbitrary historical diffs and unpublished work remain coverage limits. + +## Open next questions + +Bind this kernel to one complete Full allocation and charge its exact live +word count, source snapshots, output staging, bit operations, cleanup and +tape movement. Start from one emitted two-wire call and its proved input +and output amplitude bounds. A physical arithmetic/ownership contract and +the complete caller invoice remain missing. The present maximum word width +does not settle those costs. No further optimization is reserved. + +## Code constraints + +Foundational Thinking fixes grid numerators and coefficient pairs before +arithmetic. Build the Lever supplies the retained kernel and independent +Fraction oracle. Prove It Works requires actual source-produced gate +conformance, overflow checks and rejection controls. + +All new functions fit sixty lines. There is no recursion or generated code +in the new kernel. Each multiplication scans at most W-1 multiplier bits; +each division scans exactly W-1 positions; W<=3074. Gate loops have four +iterations. Fixed finite verification domains bound all other loops. +Explicit exceptions retain checks under optimized Python. + +Power of Ten rule 3 deviation: CPython allocates integers and containers +during this bounded reference execution. Fixed B,C limits, four-coordinate +state and one current row bound the kernel's live collections. A static +memory backend is needed before a fixed-allocation claim. The width +observer's capacity and operation counters are verification metadata outside the +claimed data-word program. Rule 8/9 fixture deviation: the unchanged phase +factory executes its authenticated interval source; imports and dispatch +are limited to the five declared inputs and their standard-library imports. +Its preparation is outside the arithmetic-width theorem. The 120-second +registered timeout also bounds this finite fixture. Warning-strict normal +and optimized replay and AST/function-size checks supply local diagnostics; +no separate type analyzer or linter is claimed. diff --git a/research/direct-circulant-production-precision/grid-arithmetic/retained/SOURCES.json b/research/direct-circulant-production-precision/grid-arithmetic/retained/SOURCES.json new file mode 100644 index 0000000000..d32aacea72 --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/retained/SOURCES.json @@ -0,0 +1,48 @@ +{ + "schema_version": 1, + "base_commit": "7c49fe32c55de02c2c873655c804b16e4c3fef0a", + "files": [ + { + "path": "certificates/selected-result.json", + "usage": "provenance", + "git_blob": "d59b5035e7b4cbaa9d688a1d32dd0d6eb79c466a", + "sha256": "9b8d0eea95b3bf0dfcb7938a732a6439b87a2685dec2a5ab9e525b3b34debbfa" + }, + { + "path": "docs/research/agent-task-catalog.json", + "usage": "provenance", + "git_blob": "3404fbdd5e7529a0674eef26114b5071e4586cec", + "sha256": "ead6cdc9d0af6d58e8a49744d8ec8c7c15e13d2ba93c276c434bcf9b51b93a81" + }, + { + "path": "research/cubic-cyclic-inverse/vendor/interval_kernel.py", + "usage": "input", + "git_blob": "1182175a55cb871481de0f56ea9ae56e474705fe", + "sha256": "9b7bb24640a9a7d3f83c7951dfef483ec933db4c50de6c0130b85f450eeddfbe" + }, + { + "path": "research/matching-layer-rounding/README.md", + "usage": "input", + "git_blob": "99f648abd626c91312ae03dffc41bf307a33176a", + "sha256": "ba0225a7af7aa7547d719831f3122c02af09bd56ae32eb45aecccb2e66d8cbdb" + }, + { + "path": "research/rational-unitary-fft/FULL-PROOF.md", + "usage": "input", + "git_blob": "e650f46863115f810e27b403f916dd7f79b37786", + "sha256": "acf8c596d91b5efd35a286735d6867ff8afce64354a13f680c2fae3dab824410" + }, + { + "path": "research/rational-unitary-fft/engine.py", + "usage": "input", + "git_blob": "e9f2f2b08dc2bc4c646e47dca92059351ca89384", + "sha256": "9e36aee0835e6b1b62997433581f88b5a434ccab8ae43e5c25d1deaaf1ebf653" + }, + { + "path": "research/rational-unitary-fft/exact.py", + "usage": "input", + "git_blob": "aae41e6acfb2e5a4fafdd85727891eb746b57b42", + "sha256": "c9b89d7357210af69865690ba12e695366961f8b501a8fab9d0fefe3fb30c479" + } + ] +} diff --git a/research/direct-circulant-production-precision/grid-arithmetic/retained/TASK.json b/research/direct-circulant-production-precision/grid-arithmetic/retained/TASK.json new file mode 100644 index 0000000000..3bddd95b97 --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/retained/TASK.json @@ -0,0 +1,110 @@ +{ + "schema_version": 1, + "task_id": "supplier-boundary-audit", + "priority_revision": 8, + "base_commit": "7c49fe32c55de02c2c873655c804b16e4c3fef0a", + "original_card": { + "id": "supplier-boundary-audit", + "question": "Does one changed supplier have complete source-bound native, caller, ordinary and outer admission coverage?", + "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": "Pin the current sources and one obligation; the historical owner audit is an example, not evidence of a current bug.", + "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 latest uncovered candidate and build a delta coverage map against the selected review. For P104, #5717 changes owned-lifetime assumptions and #5719 covers exact #5713 causal premises; neither automatically transfers to #5718. For BIT, #5679/#5708 need component admission and compatible outer use. Check controls and exact source identity before reuse; stop with one resolved gap or explicit remaining obligation. A heavy full replay requires a separate serial resource budget.", + "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": [ + "supplier admission", + "5717", + "5719", + "5708", + "owned lifetime" + ], + "existing_checks": [ + { + "scope": "PR #4088: author-checked local words, native receipts, owner/phase fill and exact moment.", + "evidence": "research/staged544-mixed-fourth-entry/README.md", + "remaining": "Rebind and validate ordinary/outer admission with all four providers; full mixed release not established.", + "status": "author-checked", + "source_commit": "72d7efc181edb21806a878f174847c96dd410ab0", + "selected_record_sha256": "bb2eaa58647b353f88d0aec2eafb9d30df1be53589231b23e12ceef3e4bad129" + }, + { + "scope": "PR #3801: successor scatter-boundary decision package.", + "evidence": "research/scatter-boundary-decision/README.md", + "remaining": "Consult its exact acceptance scope before any new exporter audit; not proof of a selected failure.", + "status": "author-checked", + "source_commit": "911f8800ba7a4b03603ef62c5ffc6240e53cb5fd", + "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": "changed", + "actual_scope": "Construct a once-rounded two-coordinate Gaussian rational gate using B+4C+2-bit signed integer arithmetic temporaries, including a concrete retained butterfly.", + "scope_change_reason": "Answer PR5240 arithmetic Open next question with an original implementation and width theorem. This is a constructive precision-boundary side result, not an audit or supplier-admission decision.", + "bottleneck_link": "The source stored-grid theorem assumes exact local products/sums and bounded temporaries. This supplies a smaller sufficient arithmetic width, while physical implementation, preparation and complete supplier costs remain open.", + "budget_minutes": 60, + "stop_rule": "Ship the first proved width improvement with exact conformance and rejection evidence; do not optimize the bound or extend to a full caller.", + "outcome": "completed", + "evidence": "PROOF.md proves the all-B,C construction. kernel.py uses checked binary arithmetic; verify.py supplies Fraction and source-produced butterfly conformance, signed ties, input-snapshot and domain/overflow controls.", + "author": "Nick Petalas", + "ai_assistance": "Independent human and formal proof-kernel review are unclaimed.", + "open_questions": [ + { + "question": "Can one complete Full allocation use this kernel with a fully priced physical arithmetic and ownership contract?", + "why_it_matters": "A smaller maximum arithmetic-word width alone does not reduce a complete supplier invoice.", + "first_step": "Select one emitted two-wire call; derive its input/output amplitude bounds and count live snapshots, output staging, bit operations, cleanup and movement.", + "blocked_by": "Physical backend, exact live-word and tape costs, and the complete caller invoice." + } + ], + "claim_url": "https://github.com/CrocSwap/integer-mult-bounds/discussions/1166#discussioncomment-19361639", + "source_question": { + "pr": 5240, + "author": "apoursh", + "head": "6d0a6043120880c696d0850e9242a16e6fb980a5", + "scope": "Open next question on bounded-word two-coordinate multiply/add/round arithmetic." + }, + "claim_type": "scoped arithmetic construction and proof with exact finite corroboration", + "environment": { + "python": "CPython 3.12.15", + "dependencies": "standard library", + "platform": "Darwin 27.0.0 arm64" + }, + "limitations": [ + "No optimality, total-storage, runtime or bit-tape improvement claim.", + "No physical instruction emitter, reversible cleanup or coefficient-preparation proof.", + "No complete Full allocation, supplier admission, new kappa or selected-frontier change.", + "All five framework assumptions remain; no independent human or formal proof-kernel acceptance." + ] +} diff --git a/research/direct-circulant-production-precision/grid-arithmetic/retained/VERIFY.json b/research/direct-circulant-production-precision/grid-arithmetic/retained/VERIFY.json new file mode 100644 index 0000000000..1c7b65b6dd --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/retained/VERIFY.json @@ -0,0 +1,40 @@ +{ + "schema_version": 1, + "status": "ready", + "python": "3.12", + "requirements": [], + "inputs": [ + "research/cubic-cyclic-inverse/vendor/interval_kernel.py", + "research/matching-layer-rounding/README.md", + "research/rational-unitary-fft/FULL-PROOF.md", + "research/rational-unitary-fft/engine.py", + "research/rational-unitary-fft/exact.py" + ], + "commands": [ + { + "argv": [ + "{python}", + "-I", + "-W", + "error", + "-B", + "{package}/verify.py" + ], + "timeout_seconds": 120, + "checks": "New width/rounding construction, exact rational oracle, actual source butterfly conformance and semantic/domain/overflow controls." + }, + { + "argv": [ + "{python}", + "-I", + "-W", + "error", + "-O", + "-B", + "{package}/verify.py" + ], + "timeout_seconds": 120, + "checks": "New width/rounding construction, exact rational oracle, actual source butterfly conformance and semantic/domain/overflow controls." + } + ] +} diff --git a/research/direct-circulant-production-precision/grid-arithmetic/retained/compiler/STEIN-PROVENANCE.json b/research/direct-circulant-production-precision/grid-arithmetic/retained/compiler/STEIN-PROVENANCE.json new file mode 100644 index 0000000000..c602fb5bb3 --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/retained/compiler/STEIN-PROVENANCE.json @@ -0,0 +1,14 @@ +{ + "schema_version": 1, + "source_pr": "https://github.com/CrocSwap/integer-mult-bounds/pull/4198", + "source_commit": "e457d5e912a27307d725827aeca7198169320b84", + "source_path": "research/rational-stein-generators/rational.py", + "source_git_blob": "71b240a460a185ee2fe926cd189b56aeac6f997f", + "sha256": "3065fc5d6d22ec44de533b08fb0c639603449456383668e561dc46629e641502", + "retained_path": "research/rational-unitary-fft/vendor/stein_rational.py", + "byte_comparison": "I compared the retained bytes with git show at the original source commit before the local archive commit.", + "usage": "Execute the exact bounded rational generator producer as a coefficient-preparation dependency of the complete gate program.", + "proof": "https://github.com/CrocSwap/integer-mult-bounds/blob/e457d5e912a27307d725827aeca7198169320b84/research/rational-stein-generators/PROOF.md", + "credit": "Jose Manuel (jmbarrancoml), with substantial OpenAI Codex assistance. The producer refines Vlado Vojdanovski/PR1673's rational Gram-Schmidt route; Cinna Davis supplied the later caller. Apache-2.0.", + "history_boundary": "The original sibling PR commit is not an ancestor of PR4205. SOURCES.json will pin these local retained bytes at their archive commit, separately from this original-source identity. The later integration does not claim original sibling-branch ancestry." +} diff --git a/research/direct-circulant-production-precision/grid-arithmetic/retained/compiler/check_circuits.py b/research/direct-circulant-production-precision/grid-arithmetic/retained/compiler/check_circuits.py new file mode 100644 index 0000000000..f80c141c81 --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/retained/compiler/check_circuits.py @@ -0,0 +1,285 @@ +"""Numerical replay of n-wire, invertible 1x1/2x2 gate circuits. + +The production theorem is algebraic. This independent small-size replay +checks the parity Toeplitz factor, low-displacement LU recursion, the +Stein sum-LU identity, and the actual no-ancilla FFT/shear gate schedule. +""" +import json +import math +from pathlib import Path +import numpy as np + +ROOT = Path(__file__).parent +STATS = {"triangle_nodes": 0, "full_nodes": 0, "generator_shears": 0, + "max_displacement_rank": 0, "min_gate_determinant": 1.0, + "max_generator_entry": 0.0, "max_triangle_coefficient": 0.0} + + +def toep(c, row=None): + c = np.asarray(c, dtype=complex) + row = c.copy() * 0 if row is None else np.asarray(row, dtype=complex) + row[0] = c[0] + n = len(c) + return np.array([[c[i-j] if i >= j else row[j-i] + for j in range(n)] for i in range(n)]) + + +def lower(c): + return toep(c) + + +def invseries(f): + n = len(f) + ans = np.zeros(n, complex) + ans[0] = 1 / f[0] + for j in range(1, n): + ans[j] = -sum(f[k] * ans[j-k] for k in range(1, j+1)) / f[0] + return ans + + +def conv(a, b, n): + return np.convolve(a, b)[:n] + + +def diag(indices, values): + return [[((int(i),), np.array([[v]], complex)) for i, v in zip(indices, values)]] + + +def inverse(plan): + return [[(ids, np.linalg.inv(g)) for ids, g in layer] + for layer in reversed(plan)] + + +def parallel(a, b): + return [(a[j] if j < len(a) else []) + (b[j] if j < len(b) else []) + for j in range(max(len(a), len(b)))] + + +def fft(indices): + n = len(indices) + if n <= 1: + return [] + assert n & (n - 1) == 0 + bits = n.bit_length() - 1 + rev = [int(f"{j:0{bits}b}"[::-1], 2) for j in range(n)] + plan = [[((indices[i], indices[j]), np.array([[0, 1], [1, 0]], complex)) + for i, j in enumerate(rev) if i < j]] + size = 2 + while size <= n: + layer = [] + for start in range(0, n, size): + for j in range(size // 2): + w = np.exp(-2j * np.pi * j / size) + layer.append(((indices[start+j], indices[start+j+size//2]), + np.array([[1, w], [1, -w]], complex) / math.sqrt(2))) + plan.append(layer) + size *= 2 + return plan + + +def circ_shear(target, source, kernel): + """target += circulant(kernel) source, using these wires only.""" + p = parallel(fft(target), fft(source)) + lams = np.fft.fft(kernel) + mid = [[((source[j], target[j]), np.array([[1, 0], [lams[j], 1]], complex)) + for j in range(len(source))]] + return p + mid + inverse(p) + + +def toeplitz_shear(target, source, T): + """Cyclic + negacyclic decomposition; source and target are disjoint.""" + n = len(source) + assert T.shape == (n, n) and len(target) == n + c, r = T[:, 0], T[0, :] + g = np.zeros(n, complex) + h = np.zeros(n, complex) + g[0] = h[0] = c[0] / 2 + for j in range(1, n): + g[j] = (c[j] + r[n-j]) / 2 + h[j] = (c[j] - r[n-j]) / 2 + gamma = np.exp(1j * np.pi / n) + d = gamma ** np.arange(n) + twists = parallel(diag(target, d), diag(source, d)) + return (circ_shear(target, source, g) + twists + + circ_shear(target, source, d * h) + inverse(twists)) + + +def triangle_plan(indices, f): + n = len(indices) + STATS["triangle_nodes"] += 1 + STATS["max_triangle_coefficient"] = max( + STATS["max_triangle_coefficient"], float(np.max(np.abs(f)))) + if n == 1: + return diag(indices, f) + assert n % 2 == 0 + m = n // 2 + ev, od = indices[::2], indices[1::2] + e, o = np.asarray(f[::2]), np.asarray(f[1::2]) + k = conv(o, invseries(e), m) + zk = np.r_[0, k[:-1]] + s = e - np.r_[0, conv(o, k, m)[:-1]] + right = toeplitz_shear(ev, od, lower(zk)) + middle = parallel(triangle_plan(ev, e), triangle_plan(od, s)) + left = toeplitz_shear(od, ev, lower(k)) + return right + middle + left + + +def lowdisp_shear(target, source, T): + n = len(source) + Z = np.eye(n, k=-1) + Delta = T - Z @ T @ Z.T + U, vals, Vh = np.linalg.svd(Delta) + cutoff = 1e-11 * max(1.0, vals[0]) + rank = int(np.sum(vals > cutoff)) + STATS["max_displacement_rank"] = max(STATS["max_displacement_rank"], rank) + STATS["generator_shears"] += 1 + result = [] + reconstructed = np.zeros_like(T) + for j in range(rank): + g = U[:, j] + h = vals[j] * Vh[j, :] + STATS["max_generator_entry"] = max( + STATS["max_generator_entry"], float(np.max(np.abs(g))), + float(np.max(np.abs(h)))) + reconstructed += lower(g) @ lower(h).T + gamma = max(1.0, 2 * float(np.sum(np.abs(h)))) + p = h / gamma + p[0] += 1 + # U(h)=J L(h) J. This is a genuinely invertible source transform. + transform = triangle_plan(source[::-1], p) + result += transform + result += toeplitz_shear(target, source, gamma * lower(g)) + result += inverse(transform) + result += toeplitz_shear(target, source, -gamma * lower(g)) + assert np.max(np.abs(T - reconstructed)) < 1e-9 + return result + + +def full_plan(indices, M): + n = len(indices) + STATS["full_nodes"] += 1 + if n == 1: + return diag(indices, [M[0, 0]]) + m = n // 2 + A, B, C, D = M[:m, :m], M[:m, m:], M[m:, :m], M[m:, m:] + K = np.linalg.solve(A, B) + L = np.linalg.solve(A.T, C.T).T + S = D - C @ K + right = lowdisp_shear(indices[:m], indices[m:], K) + mid = parallel(full_plan(indices[:m], A), full_plan(indices[m:], S)) + left = lowdisp_shear(indices[m:], indices[:m], L) + return right + mid + left + + +def replay(plan, n, track=True): + out = np.eye(n, dtype=complex) + peak = 1.0 + min_det = 1.0 + for layer in plan: + used = set() + for ids, g in layer: + assert not used.intersection(ids), "non-disjoint layer" + used.update(ids) + min_det = min(min_det, float(abs(np.linalg.det(g)))) + out[list(ids), :] = g @ out[list(ids), :] + if track: + peak = max(peak, float(np.linalg.norm(out, 2))) + STATS["min_gate_determinant"] = min(STATS["min_gate_determinant"], min_det) + return out, peak + + +def main(): + rng = np.random.default_rng(20261013) + rows = [] + for n in [2, 4, 8, 16]: + f = rng.normal(size=n) / (12 * n) + f[0] += 1 + p = triangle_plan(list(range(n)), f) + actual, peak = replay(p, n) + rows.append({"kind": "triangular", "n": n, "rounds": len(p), + "gates": sum(map(len, p)), + "max_error": float(np.max(np.abs(actual-lower(f)))), + "peak_prefix_norm_2": peak}) + + c = rng.normal(size=n) / (20 * n) + r = rng.normal(size=n) / (20 * n) + c[0] += 1 + H = toep(c, r) + p = full_plan(list(range(n)), H) + actual, peak = replay(p, n, track=n <= 8) + rows.append({"kind": "full_toeplitz", "n": n, "rounds": len(p), + "gates": sum(map(len, p)), + "max_error": float(np.max(np.abs(actual-H))), + "peak_prefix_norm_2": peak if n <= 8 else None, + "input_distance_from_I_2": float(np.linalg.norm(H-np.eye(n), 2))}) + # Destructive control: dropping the second subtraction computes the wrong map. + # Independent direct parity block algebra across a range of sizes. + identities = [] + for n in [2, 4, 8, 16, 32]: + f = rng.normal(size=n) / n + f[0] += 2 + m = n // 2 + e, o = f[::2], f[1::2] + k = conv(o, invseries(e), m) + s = e - np.r_[0, conv(o, k, m)[:-1]] + E, O, K = lower(e), lower(o), lower(k) + Z = np.eye(m, k=-1) + left = np.block([[np.eye(m), np.zeros((m,m))], [K, np.eye(m)]]) + diagblock = np.block([[E, np.zeros((m,m))], [np.zeros((m,m)), lower(s)]]) + right = np.block([[np.eye(m), Z@K], [np.zeros((m,m)), np.eye(m)]]) + order = list(range(0,n,2)) + list(range(1,n,2)) + exact = lower(f)[np.ix_(order,order)] + identities.append({"n": n, "error": float(np.max(np.abs(left@diagblock@right-exact)))}) + sylvester = [] + for b in [1, 2, 4, 8]: + f = np.array([1.0]) + g = np.array([1.0]) + for j in range(b): + f = np.convolve(f, [1.0, 256.0 ** (j-b+0.5)]) + g = np.convolve(g, [1.0, 256.0 ** (-j-0.5)]) + fp = np.r_[f, np.zeros(3*b+2-len(f))] + fi = invseries(fp) + def hc(k): + return sum(g[v]*fi[k+v] for v in range(b+1) if 0 <= k+v < len(fi)) + K = np.array([[hc(i-b-j) for j in range(b)] for i in range(b)]) + H = np.array([[hc(i-j) for j in range(b)] for i in range(b)]) + S = np.zeros((2*b, 2*b), complex) + for j in range(b): + for k in range(b+1): + if j+k < 2*b: + S[j+k, j] += f[k] + if 0 <= b+j-k < 2*b: + S[b+j-k, b+j] += g[k] + inds = list(range(2*b)) + p = toeplitz_shear(inds[:b], inds[b:], K) + p += full_plan(inds[b:], H) + p += triangle_plan(inds, np.r_[f, np.zeros(2*b-len(f))]) + actual, peak = replay(p, 2*b, track=b <= 4) + sylvester.append({"b": b, "total_wires": 2*b, "rounds": len(p), + "gates": sum(map(len, p)), + "max_error": float(np.max(np.abs(actual-S))), + "H_minus_I_norm_1": float(np.linalg.norm(H-np.eye(b), 1)), + "H_minus_I_norm_infinity": float(np.linalg.norm(H-np.eye(b), np.inf)), + "peak_prefix_norm_2": peak if b <= 4 else None}) + # Removing the compensating dirty subtraction must fail. + b = 4 + gi, hi = np.array([1, .02, .01, .005]), np.array([.1, .04, .02, .01]) + pi = hi.copy() + pi[0] += 1 + target = np.block([[np.eye(b), np.zeros((b,b))], [lower(gi)@lower(hi).T, np.eye(b)]]) + pp = triangle_plan(list(range(b))[::-1], pi) + correct = pp + toeplitz_shear(list(range(b, 2*b)), list(range(b)), lower(gi)) + inverse(pp) + broken_actual, _ = replay(correct, 2*b, track=False) + correct += toeplitz_shear(list(range(b, 2*b)), list(range(b)), -lower(gi)) + correct_actual, _ = replay(correct, 2*b, track=False) + omission = {"correct_error": float(np.max(np.abs(correct_actual-target))), + "omit_second_subtraction_error": float(np.max(np.abs(broken_actual-target)))} + result = {"seed": 20261013, "note": "Floating replay supports, does not replace, algebraic proof.", + "controls": rows, "polyphase_identity": identities, + "normalized_sylvester": sylvester, "omission_control": omission, "stats": STATS} + (ROOT / "CIRCUIT-REPLAY.json").write_text(json.dumps(result, indent=2)+"\n") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/research/direct-circulant-production-precision/grid-arithmetic/retained/compiler/engine.py b/research/direct-circulant-production-precision/grid-arithmetic/retained/compiler/engine.py new file mode 100644 index 0000000000..e9f2f2b08d --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/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/grid-arithmetic/retained/compiler/exact.py b/research/direct-circulant-production-precision/grid-arithmetic/retained/compiler/exact.py new file mode 100644 index 0000000000..aae41e6acf --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/retained/compiler/exact.py @@ -0,0 +1,242 @@ +"""Exact complex rational arithmetic for coefficient and rounded-gate certificates. + +Jose Manuel (jmbarrancoml), with substantial OpenAI Codex assistance. +Apache-2.0. +""" +from fractions import Fraction as Q +from hashlib import sha256 + +TRACK = None + + +def need(ok, message): + if not ok: + raise ValueError(message) + + +def qheight(value): + return max(abs(value.numerator).bit_length(), value.denominator.bit_length()) + + +class C: + __slots__ = ("re", "im") + + def __init__(self, re=0, im=0): + need(type(re) in (int, Q) and type(im) in (int, Q), "exact rational components") + self.re, self.im = Q(re), Q(im) + if TRACK is not None: + TRACK["max_observed_height"] = max(TRACK["max_observed_height"], + qheight(self.re), qheight(self.im)) + + @staticmethod + def wrap(value): + return value if isinstance(value, C) else C(value) + + def __add__(self, other): + other = C.wrap(other) + return C(self.re + other.re, self.im + other.im) + + __radd__ = __add__ + + def __neg__(self): + return C(-self.re, -self.im) + + def __sub__(self, other): + return self + -C.wrap(other) + + def __rsub__(self, other): + return C.wrap(other) + -self + + def __mul__(self, other): + other = C.wrap(other) + return C(self.re * other.re - self.im * other.im, + self.re * other.im + self.im * other.re) + + __rmul__ = __mul__ + + def conjugate(self): + return C(self.re, -self.im) + + def norm2(self): + return self.re * self.re + self.im * self.im + + def __truediv__(self, other): + other = C.wrap(other) + denominator = other.norm2() + need(denominator > 0, "nonzero divisor") + product = self * other.conjugate() + return C(product.re / denominator, product.im / denominator) + + def __rtruediv__(self, other): + return C.wrap(other) / self + + def __eq__(self, other): + if not isinstance(other, C) and type(other) not in (int, Q): + return False + other = C.wrap(other) + return self.re == other.re and self.im == other.im + + def record(self): + return [str(self.re), str(self.im)] + + +class Vec(list): + def __init__(self, values): + super().__init__(C.wrap(x) for x in values) + + def __mul__(self, other): + if isinstance(other, C) or type(other) in (int, Q): + return Vec(x * other for x in self) + need(len(self) == len(other), "elementwise vector dimensions") + return Vec(x * y for x, y in zip(self, other)) + + __rmul__ = __mul__ + + def __sub__(self, other): + need(len(self) == len(other), "vector subtraction dimensions") + return Vec(x - y for x, y in zip(self, other)) + + def copy(self): + return Vec(self) + + def __truediv__(self, scalar): + return Vec(x / scalar for x in self) + + +class Mat(list): + def __init__(self, rows): + super().__init__([C.wrap(x) for x in row] for row in rows) + + def __rmul__(self, scalar): + return Mat([[scalar * x for x in row] for row in self]) + + @property + def shape(self): + return (len(self), len(list.__getitem__(self, 0)) if self else 0) + + def __getitem__(self, key): + if not isinstance(key, tuple): + return list.__getitem__(self, key) + row, column = key + if isinstance(row, slice): + rows = list.__getitem__(self, row) + return Mat([r[column] for r in rows]) if isinstance(column, slice) else Vec(r[column] for r in rows) + selected = list.__getitem__(self, row) + return Vec(selected[column]) if isinstance(column, slice) else selected[column] + + +def eye(n): + return Mat([[int(i == j) for j in range(n)] for i in range(n)]) + + +def adjoint(matrix): + return Mat([[matrix[j][i].conjugate() for j in range(len(matrix))] + for i in range(len(matrix[0]))]) + + +def multiply(left, right): + return Mat([[sum((x * right[k][j] for k, x in enumerate(row)), C()) + for j in range(len(right[0]))] for row in left]) + + +def unitary(matrix): + return multiply(adjoint(matrix), matrix) == eye(len(matrix)) + + +def inverse_gate(matrix): + if unitary(matrix): + return adjoint(matrix) + if matrix.shape == (1, 1): + return Mat([[1 / matrix[0][0]]]) + if matrix.shape == (2, 2) and matrix[0][0] == matrix[1][1] == 1 and matrix[0][1] == 0: + return Mat([[1, 0], [-matrix[1][0], 1]]) + raise ValueError("unsupported nonunitary inverse gate") + + +def round_q(value, bits): + scale = 1 << bits + shifted = value * scale + Q(1, 2) + return Q(shifted.numerator // shifted.denominator, scale) + + +def rounded(value, bits): + return C(round_q(value.re, bits), round_q(value.im, bits)) + + +def norm2(vector): + return sum((x.norm2() for x in vector), Q(0)) + + +def component_l1(vector): + return sum((abs(x.re) + abs(x.im) for x in vector), Q(0)) + + +def ceil_log2(value): + value = Q(value) + need(value > 0, "positive logarithm bound") + result = value.numerator.bit_length() - value.denominator.bit_length() + power = Q(1 << result) if result >= 0 else Q(1, 1 << -result) + while power < value: + result += 1 + power *= 2 + while power / 2 >= value: + result -= 1 + power /= 2 + return result + + +def upper(value, bits=160): + scale = 1 << bits + scaled = value * scale + return Q(-((-scaled.numerator) // scaled.denominator), scale) + + +def vector_hash(vector): + digest = sha256() + for entry in vector: + for value in (entry.re, entry.im): + for integer in (value.numerator, value.denominator): + raw = abs(integer).to_bytes(max(1, (abs(integer).bit_length() + 7) // 8), "big") + digest.update(bytes([integer < 0])) + digest.update(len(raw).to_bytes(8, "big")) + digest.update(raw) + return digest.hexdigest() + + +def apply(plan, vector, bits=None): + global TRACK + state = Vec(vector) + old_track = TRACK + stats = {"max_observed_height": 0, "max_grid_numerator_bits": 0, + "max_reduced_fractional_bits": 0, "rounded_outputs": 0} + if bits is not None: + need(bits >= 1, "positive data precision") + for entry in state: + for value in (entry.re, entry.im): + need((value * (1 << bits)).denominator == 1, "input already on data grid") + TRACK = stats + try: + for layer in plan: + used = set() + for ids, gate in layer: + need(len(ids) == len(gate) in (1, 2), "one- or two-wire gate") + need(not used.intersection(ids) and len(set(ids)) == len(ids), "disjoint layer") + need(all(0 <= i < len(state) for i in ids), "wire bounds") + used.update(ids) + before = [state[i] for i in ids] + outputs = [sum((a * x for a, x in zip(row, before)), C()) for row in gate] + for i, value in zip(ids, outputs): + if bits is not None: + value = rounded(value, bits) + stats["rounded_outputs"] += 1 + for part in (value.re, value.im): + grid_integer = part * (1 << bits) + need(grid_integer.denominator == 1, "rounded output grid") + stats["max_grid_numerator_bits"] = max(stats["max_grid_numerator_bits"], + abs(grid_integer.numerator).bit_length()) + stats["max_reduced_fractional_bits"] = max(stats["max_reduced_fractional_bits"], + part.denominator.bit_length() - 1) + state[i] = value + finally: + TRACK = old_track + return state, stats diff --git a/research/direct-circulant-production-precision/grid-arithmetic/retained/compiler/full.py b/research/direct-circulant-production-precision/grid-arithmetic/retained/compiler/full.py new file mode 100644 index 0000000000..7f85ad1a89 --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/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/grid-arithmetic/retained/compiler/generator.py b/research/direct-circulant-production-precision/grid-arithmetic/retained/compiler/generator.py new file mode 100644 index 0000000000..d761d3c88b --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/retained/compiler/generator.py @@ -0,0 +1,233 @@ +"""Exact generators connected to the retained compensated gate program. + +Jose Manuel (jmbarrancoml), with substantial OpenAI Codex assistance. +Apache-2.0. Macro/compiler: Vlado/PR1673; certified phases: Chafik/PR628. +""" +import ast +import copy +from fractions import Fraction as Q +from hashlib import sha256 +import json + +from exact import C, Mat, Vec, ceil_log2, component_l1, inverse_gate, need, norm2 +from engine import Builder, Phases, split_kernel +from triangular import Triangle, allocation as triangle_allocation + +SOURCE = "research/capped-phase-fusion/evidence/inplace_algebra_ultra/" +PRODUCER = "research/rational-unitary-fft/vendor/stein_rational.py" +PROVENANCE = "research/rational-unitary-fft/vendor/STEIN-PROVENANCE.json" +ORACLE = "research/cubic-cyclic-inverse/vendor/interval_kernel.py" + + +def load_producer(raw): + record = json.loads(raw[PROVENANCE]) + need(record["source_commit"] == "e457d5e912a27307d725827aeca7198169320b84" + and record["source_git_blob"] == "71b240a460a185ee2fe926cd189b56aeac6f997f" + and sha256(raw[PRODUCER]).hexdigest() == record["sha256"], + "original producer identity and retained bytes") + namespace = {"__name__": "_frozen_rational_stein"} + exec(compile(raw[PRODUCER], "", "exec", optimize=0), namespace) + return namespace + + +def lower(vector): + return Mat([[vector[i - j] if i >= j else C() for j in range(len(vector))] + for i in range(len(vector))]) + + +def prepare(matrix, producer): + matrix = Mat(matrix) + m = len(matrix) + need(m > 0 and m & (m - 1) == 0 and matrix.shape == (m, m), "dyadic generator matrix") + displacement = Mat([[matrix[i][j] - (matrix[i - 1][j - 1] if i and j else C()) + for j in range(m)] for i in range(m)]) + old_c = producer["C"] + old_e = producer["Matrix"]([[old_c(x.re, x.im) for x in row] for row in displacement]) + old_items, heights = producer["generators"](old_e) + items = [dict(column=item["column"], gamma=item["gamma"], + scale=item["scale"], scale_exponent=item["scale_exponent"], + g=Vec(C(x.re, x.im) for x in item["g"]), + row=Vec(C(x.re, x.im) for x in item["row"])) for item in old_items] + bound_e = max(max(component_l1(row) for row in displacement), + max(component_l1(column) for column in zip(*displacement))) + need(all(norm2(item["g"]) <= 1 and norm2(item["row"]) < 4 * bound_e ** 2 + and 2 * component_l1(item["row"]) <= item["gamma"] for item in items), + "actual bounded rational generator output") + return items, displacement, bound_e, heights + + +def allocation(m, rank, bound_e, radius, target, incoming): + need(type(m) is int and m > 0 and m & (m - 1) == 0, "dyadic macro size") + need(type(rank) is int and 0 <= rank <= m and type(bound_e) in (int, Q) + and bound_e >= 0, "generator count and exact displacement bound") + need(type(radius) in (int, Q) and radius >= 1 and type(target) is int + and target >= 1 and type(incoming) is int and incoming >= 0, "global generator input") + d = m.bit_length() - 1 + kg, alpha = 2 * m + 16 * m * bound_e, 2 * rank * m * bound_e + checkpoint = 10 + 4 * alpha + 2 * kg + child = max(Q(3200 * m ** 3), 2 + 2 * kg) + execution = child * checkpoint + depth = rank * (8 * d * d + 32 * d + 18) + gates = rank * m * (4 * d * d + 24 * d + 22) + s = target + ceil_log2(4 * (rank + 1) * (kg + 1) * (radius + 1)) + eta = Q(1, 1 << s) + triangle = triangle_allocation(m, 1, s) + envelope = max(Q(6), 2 * kg) + p = max(triangle["phase_bits"], s + ceil_log2(32 * (d + 1) * (envelope + 1))) + mult = max(triangle["multiplier_bits"], s + 4) + triangle = dict(triangle, phase_bits=p, multiplier_bits=mult, + coefficient_height_bound=max(4 * p + 24, mult + 5, + 2 * triangle["leaf_bits"] + 16)) + data = max(incoming, target + ceil_log2(max(Q(1), 2 * depth * execution * m))) + u = Q(1, 1 << data) + defect = rank * (kg + 1) * eta + rounding = depth * execution * m * u + need(defect <= 1 and defect * radius + rounding <= Q(1, 1 << target), + "complete compensated-generator target budget") + amplitude = execution * radius + depth * execution ** 2 * m * u + integer = max(1, ceil_log2(max(Q(1), amplitude))) + 2 + height = max(4 * p + 24, mult + ceil_log2(envelope + 2) + 2, + 2 * triangle["leaf_bits"] + 16) + return dict(m=m, rank=rank, displacement_bound=bound_e, radius=radius, + target_bits=target, incoming_bits=incoming, kg=kg, alpha=alpha, + checkpoint_bound=checkpoint, child_bound=child, execution_bound=execution, + segment_bound=execution ** 2, layer_bound=depth, gate_bound=gates, + child_target_bits=s, eta=eta, phase_bits=p, multiplier_bits=mult, + leaf_bits=triangle["leaf_bits"], data_bits=data, + multiplier_envelope=envelope, coefficient_error=defect, + rounding_error=rounding, total_error=defect * radius + rounding, + amplitude_bound=amplitude, integer_bits=integer, + coefficient_height_bound=height, + temporary_bits=2 * data + 8 * height + 2 * integer + 32), triangle + + +def macro_template(source): + tree = ast.parse(source) + function = next(n for n in tree.body if isinstance(n, ast.FunctionDef) + and n.name == "lowdisp_shear") + loop = next(n for n in function.body if isinstance(n, ast.For)) + start = next(i for i, n in enumerate(loop.body) if isinstance(n, ast.Assign) + and isinstance(n.targets[0], ast.Name) and n.targets[0].id == "p") + tail = copy.deepcopy(loop.body[start:]) + need([type(n).__name__ for n in tail] == + ["Assign", "AugAssign", "Assign", "AugAssign", "AugAssign", "AugAssign", "AugAssign"], + "retained seven-statement macro") + identity = sha256(ast.dump(ast.Module(body=tail, type_ignores=[])).encode()).hexdigest() + need(identity == "2a2e0f16a779597fa555857307451831bace11e66861fdc3caf26d2373a21210", + "unchanged source macro identity") + function = ast.FunctionDef( + name="emit", args=ast.arguments(posonlyargs=[], args=[ast.arg(arg=n) for n in + ("target", "source", "g", "h", "gamma")], vararg=None, kwonlyargs=[], + kw_defaults=[], kwarg=None, defaults=[]), + body=[ast.Assign(targets=[ast.Name(id="result", ctx=ast.Store())], + value=ast.List(elts=[], ctx=ast.Load()))] + tail + + [ast.Return(value=ast.Name(id="result", ctx=ast.Load()))], + decorator_list=[], type_params=[]) + module = ast.fix_missing_locations(ast.Module(body=[function], type_ignores=[])) + return compile(module, "", "exec", optimize=0), identity + + +class PairedNegative(Builder): + def __init__(self, positive, source): + super().__init__(positive.phases, positive.multiplier_bits, source) + self.positive = positive + + def spectrum(self, kernel): + row = self.positive.spectra[len(self.spectra)] + need(Vec(kernel) == Vec(-x for x in row["kernel"]), "paired negative spectral kernel") + result = Vec(-x for x in row["multipliers"]) + bound = self.bounds[len(self.spectra)] + need(bound == row["bound"], "paired spectral envelope") + v = Q(1, 1 << self.multiplier_bits) + need(all(x.norm2() <= (bound + v) ** 2 for x in result), "negative stored multiplier bound") + self.spectra.append(dict(kernel=Vec(kernel), multipliers=result, bound=bound)) + return result + + +class Program: + def __init__(self, bound, triangle_bound, raw, phase_oracle=None): + self.bound, self.triangle_bound, self.raw = bound, triangle_bound, raw + self.phases = phase_oracle if phase_oracle is not None else Phases(bound["phase_bits"], raw[ORACLE]) + need(self.phases.bits == bound["phase_bits"], "common generator phase precision") + self.source = list(range(bound["m"])) + self.target = list(range(bound["m"], 2 * bound["m"])) + self.stages, self.position, self.calls = [], 0, [] + self.pending = None + self.last_triangle = None + self.triangles, self.shears = [], [] + code, self.macro_ast = macro_template(raw[SOURCE + "check_circuits.py"]) + namespace = dict(triangle_plan=self.triangle, toeplitz_shear=self.shear, + inverse=self.inverse, lower=lower) + exec(code, namespace) + self.emit = namespace["emit"] + + def record(self, kind, plan, **details): + self.calls.append(kind) + self.stages.append(dict(kind=kind, start=self.position, stop=self.position + len(plan), + **details)) + self.position += len(plan) + return plan + + def triangle(self, indices, coefficients): + builder = Triangle(self.triangle_bound, self.raw[SOURCE + "check_circuits.py"], + self.raw[ORACLE], self.phases) + local_indices = [self.source.index(i) for i in indices] + local = builder.plan(coefficients, local_indices) + plan = [[(tuple(self.source[i] for i in ids), gate) for ids, gate in layer] for layer in local] + need(builder.bound["coefficient_error"] <= self.bound["eta"], "triangle operator allowance") + self.last_triangle = plan + self.triangles.append(builder) + return self.record("triangle", plan, symbol=Vec(coefficients), indices=list(indices), + operator_error=builder.bound["coefficient_error"]) + + def inverse(self, plan): + need(plan is self.last_triangle, "inverse of the same stored triangle") + result = [[(ids, inverse_gate(gate)) for ids, gate in layer] for layer in reversed(plan)] + return self.record("inverse", result) + + def shear(self, target, source, matrix): + need(target == self.target and source == self.source, "literal complete dirty banks") + if self.pending is None: + builder = Builder(self.phases, self.bound["multiplier_bits"], + self.raw[SOURCE + "check_circuits.py"]) + local = builder.plan(matrix) + self.pending = (builder, matrix, local) + kind = "positive" + else: + positive, original, positive_plan = self.pending + need(matrix == -1 * original, "literal negative compensation matrix") + builder = PairedNegative(positive, self.raw[SOURCE + "check_circuits.py"]) + local = builder.plan(matrix) + m = len(source) + need(len(local) == len(positive_plan), "same compensation layer schedule") + for a, b in zip(positive_plan, local): + need(len(a) == len(b), "same compensation gate schedule") + for (ids, g), (other_ids, h) in zip(a, b): + crossing = len(ids) == 2 and ids[0] < m <= ids[1] + expected = Mat([[1, 0], [-g[1][0], 1]]) if crossing else g + need(ids == other_ids and h == expected, "paired coefficients preserve source order") + self.pending = None + kind = "compensation" + g, h = split_kernel(matrix) + envelope = component_l1(g) + component_l1(h) + defect = (4 * len(source).bit_length() * envelope * self.phases.nu + + Q(2, 1 << self.bound["multiplier_bits"])) + need(envelope <= self.bound["multiplier_envelope"] and defect <= self.bound["eta"], + "scaled shear absolute operator allowance") + self.shears.append(builder) + mapping = source + target + plan = [[(tuple(mapping[i] for i in ids), gate) for ids, gate in layer] for layer in local] + return self.record(kind, plan, matrix=matrix, operator_error=defect, envelope=envelope) + + def plan(self, items): + result = [] + for item in items: + before = Vec(item["row"]) + result += self.emit(self.target, self.source, item["g"], item["row"], item["gamma"]) + need(before == item["row"], "fresh division preserves generator row") + need(self.pending is None and self.calls == + ["triangle", "positive", "inverse", "compensation"] * len(items), + "complete retained compensated call sequence") + need(self.position == len(result) <= self.bound["layer_bound"] + and sum(map(len, result)) <= self.bound["gate_bound"], "full program gate/layer budget") + return result diff --git a/research/direct-circulant-production-precision/grid-arithmetic/retained/compiler/interval_kernel.py b/research/direct-circulant-production-precision/grid-arithmetic/retained/compiler/interval_kernel.py new file mode 100644 index 0000000000..1182175a55 --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/retained/compiler/interval_kernel.py @@ -0,0 +1,61 @@ +"""Outward-rounded rational enclosures for prime-power cyclic kernels.""" +from fractions import Fraction as F +import math +from functools import lru_cache + +BITS=1536 +SCALE=1<4:raise ValueError('angle bound') + itheta=(point(0),theta) + total=term=ONE + # Taylor remainder for complex exp: <=exp(4)*4^(N+1)/(N+1)! <128*... + n=0 + while True: + n+=1;term=cmul(term,itheta);term=(scale(term[0],F(1,n)),scale(term[1],F(1,n)));total=cadd(total,term) + remainder=F(128*4**(n+1),math.factorial(n+1)) + if remainder= 0 else Q(1, 1 << -exponent) + + +def norm_scale(squared): + need(squared > 0, "positive residual squared norm") + exponent = (squared.numerator.bit_length() - squared.denominator.bit_length()) // 2 + scale = pow2(exponent) + while scale * scale < squared: + exponent += 1 + scale *= 2 + while scale * scale / 4 >= squared: + exponent -= 1 + scale /= 2 + need(squared <= scale * scale < 4 * squared, "dyadic norm bracket") + observe(scale) + return scale, exponent + + +def upper_dyadic(value): + need(value > 0, "positive dyadic upper target") + exponent = value.numerator.bit_length() - value.denominator.bit_length() + result = pow2(exponent) + while result < value: + result *= 2 + while result / 2 >= value: + result /= 2 + return observe(result) + + +def height(matrix): + return max([1] + [max(abs(x.numerator).bit_length(), x.denominator.bit_length()) + for row in matrix for entry in row + for x in (C.wrap(entry).re, C.wrap(entry).im)]) + + +def generators(displacement): + """Return column g, explicit coefficient ROW r, and a dyadic admission scale.""" + global MAX_HEIGHT + displacement = Matrix(displacement) + size = len(displacement) + need(size > 0 and all(len(row) == size for row in displacement), "nonempty square displacement") + input_height = height(displacement) + MAX_HEIGHT = input_height + columns = [[displacement[i][j] for i in range(size)] for j in range(size)] + residuals, result = [], [] + for column_index, column in enumerate(columns): + residual = list(column) + for old, squared in residuals: + factor = inner(old, residual) / squared + residual = [x - factor * y for x, y in zip(residual, old)] + squared = norm2(residual) + if squared == 0: + continue + scale, exponent = norm_scale(squared) + g = Vector(x / scale for x in residual) + row = Vector(inner(residual, c) * (scale / squared) for c in columns) + gamma = upper_dyadic(max(Q(1), 2 * component_l1(row))) + need(norm2(g) <= 1 and 2 * component_l1(row) <= gamma, "bounded generator admission") + residuals.append((residual, squared)) + result.append({"column": column_index, "residual": residual, "squared_norm": squared, + "scale": scale, "scale_exponent": exponent, "g": g, "row": row, + "gamma": gamma}) + return result, {"input_height": input_height, "max_observed_height": MAX_HEIGHT} + + +def lower(vector): + return Matrix([[vector[i - j] if i >= j else C() for j in range(len(vector))] + for i in range(len(vector))]) + + +def transpose(matrix): + return Matrix(zip(*matrix)) + + +def frobenius2(matrix): + return observe(sum((C.wrap(x).norm2() for row in matrix for x in row), Q(0))) + + +def norm_bound(matrix): + """Rational upper bound for the induced 2-norm.""" + return max(max(component_l1(row) for row in matrix), + max(component_l1(column) for column in zip(*matrix))) + + +def exact_record(matrix): + return [[C.wrap(x).record() for x in row] for row in matrix] diff --git a/research/direct-circulant-production-precision/grid-arithmetic/retained/compiler/triangular.py b/research/direct-circulant-production-precision/grid-arithmetic/retained/compiler/triangular.py new file mode 100644 index 0000000000..2bd8de01a7 --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/retained/compiler/triangular.py @@ -0,0 +1,200 @@ +"""Source-bound rational parity recursion with a common precision allocation. + +Jose Manuel (jmbarrancoml), with substantial OpenAI Codex assistance. +Apache-2.0. Parity recursion and its stability premise: 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, inverse_gate, need, + rounded) +from engine import Builder, Phases, split_kernel + + +def allocation(n, radius, target, incoming=0): + need(type(n) is int and n > 0 and n & (n - 1) == 0, "dyadic triangle size") + need(type(radius) in (int, Q) and radius >= 1, "exact triangle radius") + need(type(target) is int and target >= 1, "positive triangle target") + need(type(incoming) is int and incoming >= 0, "incoming triangle grid") + d = n.bit_length() - 1 + q, depth, bound = 2 * d + 1, 4 * d * d + 12 * d + 1, 100 * n ** 3 + s = target + ceil_log2(4 * q * bound ** 3 * (radius + 1)) + p = s + ceil_log2(48 * (d + 1)) + multiplier = s + 2 + data = max(incoming, target + ceil_log2(64 * depth * bound * n)) + epsilon, u = Q(1, 1 << s), Q(1, 1 << data) + theta = q * bound ** 2 * epsilon + coefficient = 2 * q * bound ** 3 * epsilon + rounding = 32 * depth * bound * n * u + need(theta <= Q(1, 4) and coefficient * radius + rounding <= Q(1, 1 << target), + "complete triangular error allocation") + amplitude = 32 * bound * radius + 1024 * depth * bound ** 2 * n * u + integer = max(1, ceil_log2(max(Q(1), amplitude))) + 2 + height = max(4 * p + 24, multiplier + 5, 2 * s + 16) + return dict(n=n, radius=radius, target_bits=target, incoming_bits=incoming, + ideal_bound=bound, macro_layers=q, layer_bound=depth, + gate_bound=n * (2 * d * d + 8 * d + 1), + leaf_bits=s, phase_bits=p, multiplier_bits=multiplier, + data_bits=data, epsilon=epsilon, theta=theta, + coefficient_error=coefficient, rounding_error=rounding, + total_error=coefficient * radius + rounding, + physical_prefix_suffix_bound=32 * bound, + segment_bound=1024 * bound ** 2, amplitude_bound=amplitude, + integer_bits=integer, coefficient_height_bound=height, + temporary_bits=2 * data + 8 * height + 2 * integer + 32) + + +class Plan(list): + """Actual layers plus consecutive, disjoint-support macro partitions.""" + def __init__(self, layers, blocks): + super().__init__(layers) + self.blocks = blocks + + def __add__(self, other): + need(isinstance(other, Plan), "typed triangular composition") + offset = len(self) + blocks = [dict(block) for block in self.blocks] + blocks += [dict(start=b["start"] + offset, stop=b["stop"] + offset, + pieces=list(b["pieces"])) for b in other.blocks] + return Plan(list(self) + list(other), blocks) + + +class Concatenate: + def __getitem__(self, parts): + values = [] + for part in parts: + values.extend(part if isinstance(part, (list, tuple)) else [part]) + return Vec(values) + + +def convolution(a, b): + return Vec(sum((a[j] * b[k - j] for j in range(len(a)) + if 0 <= k - j < len(b)), C()) + for k in range(len(a) + len(b) - 1)) + + +class AdaptTriangle(ast.NodeTransformer): + def __init__(self): + self.changes = [] + + def visit_Assign(self, node): + if (len(node.targets) == 1 and isinstance(node.targets[0], ast.Subscript) + and isinstance(node.targets[0].slice, ast.Constant) + and node.targets[0].slice.value == "max_triangle_coefficient"): + self.changes.append("exact-component-diagnostic") + node.value = ast.parse( + "max(STATS['max_triangle_coefficient'], component_l1(f))", + mode="eval").body + return node + return self.generic_visit(node) + + def visit_Return(self, node): + if (isinstance(node.value, ast.Call) and isinstance(node.value.func, ast.Name) + and node.value.func.id == "diag"): + self.changes.append("stored-rounded-leaf") + node.value.func.id = "leaf_diag" + return self.generic_visit(node) + + +class Triangle: + def __init__(self, bound, circuit_source, oracle_source, phase_oracle=None): + self.bound, self.circuit_source = bound, circuit_source + self.phases = phase_oracle if phase_oracle is not None else Phases(bound["phase_bits"], oracle_source) + need(self.phases.bits == bound["phase_bits"], "common triangular phase precision") + base = Builder(self.phases, bound["multiplier_bits"], circuit_source) + self.source_parallel = base.namespace["parallel"] + self.source_inverse = base.namespace["inverse"] + self.children, self.leaves = [], [] + selected = {"toep", "lower", "invseries", "conv", "triangle_plan"} + tree = ast.parse(circuit_source) + 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 parity source") + self.original_ast = sha256(ast.dump(tree).encode()).hexdigest() + adapter = AdaptTriangle() + tree = ast.fix_missing_locations(adapter.visit(tree)) + need(adapter.changes == ["exact-component-diagnostic", "stored-rounded-leaf"], + "exact declared parity adaptations") + self.adapted_ast = sha256(ast.dump(tree).encode()).hexdigest() + facade = SimpleNamespace(asarray=lambda a, dtype=None: Vec(a), + array=lambda a, dtype=None: Mat(a), + zeros=lambda n, dtype=None: Vec([0] * n), + convolve=convolution, r_=Concatenate()) + self.stats = {"triangle_nodes": 0, "max_triangle_coefficient": Q(0)} + self.namespace = dict(np=facade, STATS=self.stats, component_l1=component_l1, + leaf_diag=self.leaf, parallel=self.parallel, + toeplitz_shear=self.shear) + exec(compile(tree, "", "exec", optimize=0), + self.namespace) + + def leaf(self, indices, values): + need(len(indices) == len(values) == 1, "scalar triangular leaf") + wanted = values[0] + stored = rounded(wanted, self.bound["leaf_bits"]) + epsilon = self.bound["epsilon"] + need(Q(1, 4) <= wanted.norm2() <= 4, "ideal scalar leaf margin") + need((stored - wanted).norm2() <= epsilon ** 2 + and stored.norm2() >= Q(1, 16), "stored scalar leaf margin") + gate = Mat([[stored]]) + inverse = inverse_gate(gate) + need(stored * inverse[0][0] == 1, "same stored scalar reciprocal") + piece = dict(kind="leaf", ids=list(indices), ideal=Mat([[wanted]]), + error=epsilon, stored=stored, reciprocal=inverse[0][0]) + self.leaves.append(piece) + return Plan([[(tuple(indices), gate)]], + [dict(start=0, stop=1, pieces=[piece])]) + + def shear(self, target, source, matrix): + n = len(source) + need(len(set(source + target)) == 2 * n, "owned disjoint parity banks") + child = Builder(self.phases, self.bound["multiplier_bits"], self.circuit_source) + local = child.plan(matrix) + g, h = split_kernel(matrix) + envelope = component_l1(g) + component_l1(h) + v = Q(1, 1 << self.bound["multiplier_bits"]) + defect = 4 * (n.bit_length()) * envelope * self.phases.nu + 2 * v + need(envelope + 2 * v <= 6 and defect <= self.bound["epsilon"], + "bounded parity child and allocated operator defect") + mapping = source + target + layers = [[(tuple(mapping[i] for i in ids), gate) for ids, gate in layer] + for layer in local] + piece = dict(kind="shear", ids=list(mapping), ideal=matrix, error=defect, + envelope=envelope, source_ast=child.original_ast, + adapted_ast=child.adapted_ast, local_layers=len(local)) + self.children.append(piece) + return Plan(layers, [dict(start=0, stop=len(layers), pieces=[piece])]) + + def parallel(self, left, right): + need([(b["start"], b["stop"]) for b in left.blocks] + == [(b["start"], b["stop"]) for b in right.blocks], + "equal sibling macro boundary partitions") + blocks = [] + for a, b in zip(left.blocks, right.blocks): + pieces = a["pieces"] + b["pieces"] + ids = [i for piece in pieces for i in piece["ids"]] + need(len(ids) == len(set(ids)), "disjoint sibling macro supports") + blocks.append(dict(start=a["start"], stop=a["stop"], pieces=pieces)) + return Plan(self.source_parallel(left, right), blocks) + + def plan(self, symbol, indices=None): + symbol = Vec(symbol) + n = len(symbol) + need(n == self.bound["n"], "allocated triangle dimension") + need(component_l1(symbol - Vec([1] + [0] * (n - 1))) <= Q(1, 2), + "component-l1 near-identity admission") + indices = list(range(n)) if indices is None else list(indices) + need(len(indices) == n and sorted(indices) == list(range(n)), "triangle wire permutation") + result = self.namespace["triangle_plan"](indices, symbol) + need(self.stats["triangle_nodes"] == 2 * n - 1, "complete parity recursion tree") + need(len(result.blocks) == self.bound["macro_layers"] + and len(result) <= self.bound["layer_bound"] + and sum(map(len, result)) <= self.bound["gate_bound"], "complete schedule bounds") + return result + + def inverse(self, plan): + # Forward pieces certify forward defects. Inverse endpoint bounds use + # the inverse-product proof, not relabelled forward macro certificates. + return self.source_inverse(plan) diff --git a/research/direct-circulant-production-precision/grid-arithmetic/retained/direct/product.py b/research/direct-circulant-production-precision/grid-arithmetic/retained/direct/product.py new file mode 100644 index 0000000000..6059b6e2ce --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/retained/direct/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/grid-arithmetic/retained/direct/root_gate_plan.py b/research/direct-circulant-production-precision/grid-arithmetic/retained/direct/root_gate_plan.py new file mode 100644 index 0000000000..f306aa7fa8 --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/retained/direct/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/grid-arithmetic/retained/direct/spectral.py b/research/direct-circulant-production-precision/grid-arithmetic/retained/direct/spectral.py new file mode 100644 index 0000000000..57d84e1655 --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/retained/direct/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/grid-arithmetic/retained/direct/tensor_word.py b/research/direct-circulant-production-precision/grid-arithmetic/retained/direct/tensor_word.py new file mode 100644 index 0000000000..8bc7bc5995 --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/retained/direct/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/grid-arithmetic/retained/kernel.py b/research/direct-circulant-production-precision/grid-arithmetic/retained/kernel.py new file mode 100644 index 0000000000..45ffe0f280 --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/retained/kernel.py @@ -0,0 +1,112 @@ +"""Once-rounded four-term rows with bounded signed integer arithmetic. + +Produced by Nick Petalas. Apache-2.0. +""" + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +class Words: + """A width observer; its capacity constants are outside the data program.""" + + def __init__(self, width): + require(type(width) is int and 8 <= width <= 3074, "word capacity") + self.width = width + self.peak = 0 + self.operations = 0 + + def check(self, value): + require(type(value) is int, "integer word") + limit = 1 << (self.width - 1) + if not -limit <= value < limit: + raise OverflowError("signed word overflow") + self.peak = max(self.peak, abs(value).bit_length() + 1) + self.operations += 1 + return value + + def multiply(self, left, right): + """Shift/add multiplication; no integer multiplication instruction.""" + self.check(left) + self.check(right) + negative = (left < 0) != (right < 0) + term, digits = self.check(abs(left)), self.check(abs(right)) + result = 0 + for bit in range(digits.bit_length()): + if (digits >> bit) & 1: + result = self.check(result + term) + if bit + 1 < digits.bit_length(): + term = self.check(term << 1) + return self.check(-result if negative else result) + + def divide(self, numerator, denominator): + """Unsigned binary division, using a fixed number of bit positions.""" + require(numerator >= 0 and denominator > 0, "division domain") + require(denominator < (1 << (self.width - 2)), "division remainder capacity") + self.check(numerator) + self.check(denominator) + quotient = remainder = 0 + for bit in range(self.width - 2, -1, -1): + remainder = self.check((remainder << 1) + ((numerator >> bit) & 1)) + quotient = self.check(quotient << 1) + if remainder >= denominator: + remainder = self.check(remainder - denominator) + quotient = self.check(quotient + 1) + require(0 <= remainder < denominator, "division remainder invariant") + return quotient, remainder + + +def validate(rows, state, data_bits, coefficient_bits): + require(type(data_bits) is int and 2 <= data_bits <= 2048, "data width") + require(type(coefficient_bits) is int and 1 <= coefficient_bits <= 256, + "coefficient width") + require(type(rows) in (tuple, list), "row collection") + require(len(state) == 4 and len(rows) == 4, "four real coordinates") + limit = 1 << (data_bits - 1) + require(all(type(x) is int and -limit <= x < limit for x in state), + "signed input numerators") + for row in rows: + require(type(row) in (tuple, list), "row representation") + require(len(row) == 4, "four terms per row") + for pair in row: + require(type(pair) is tuple and len(pair) == 2, "rational pair") + numerator, denominator = pair + require(type(numerator) is int and type(denominator) is int, + "integer rational components") + require(abs(numerator).bit_length() <= coefficient_bits + and 0 < denominator < (1 << coefficient_bits), + "coefficient height") + + +def rounded_row(row, state, words): + denominator = 1 + for _, divisor in row: + denominator = words.multiply(denominator, divisor) + accumulator = 0 + for term_index in range(4): + numerator = words.multiply(row[term_index][0], state[term_index]) + for divisor_index in range(4): + if divisor_index != term_index: + numerator = words.multiply(numerator, row[divisor_index][1]) + accumulator = words.check(accumulator + numerator) + quotient, remainder = words.divide(words.check(abs(accumulator)), denominator) + twice_remainder = words.check(remainder << 1) + if accumulator < 0: + result = -quotient - int(twice_remainder > denominator) + else: + result = quotient + int(twice_remainder >= denominator) + return words.check(result) + + +def apply_gate(rows, state, data_bits, coefficient_bits): + """Overwrite four grid numerators after all outputs have been computed.""" + require(type(state) is list, "mutable four-coordinate state") + validate(rows, state, data_bits, coefficient_bits) + words = Words(data_bits + 4 * coefficient_bits + 2) + before = tuple(state) + outputs = [rounded_row(row, before, words) for row in rows] + for index in range(4): + state[index] = outputs[index] + return words diff --git a/research/direct-circulant-production-precision/grid-arithmetic/retained/parent-PROOF.md b/research/direct-circulant-production-precision/grid-arithmetic/retained/parent-PROOF.md new file mode 100644 index 0000000000..76e89b74b3 --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/retained/parent-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/grid-arithmetic/retained/precision.py b/research/direct-circulant-production-precision/grid-arithmetic/retained/precision.py new file mode 100644 index 0000000000..2115eb2e58 --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/retained/precision.py @@ -0,0 +1,38 @@ +"""Sufficient external precision under the spectral-downset source contracts. + +No compiler allocation or retained coefficient routine is changed. See the +accompanying proof for spectral versus component bounds and inherited premises. +""" + +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 = (257*length+1)//2+1354*d + local = 20*length+303*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 precision_budget(public_bits,side_widths).fractional_bits diff --git a/research/direct-circulant-production-precision/grid-arithmetic/retained/spectral-PROOF.md b/research/direct-circulant-production-precision/grid-arithmetic/retained/spectral-PROOF.md new file mode 100644 index 0000000000..1f5901dadc --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/retained/spectral-PROOF.md @@ -0,0 +1,182 @@ +# Apply spectral downset bounds to the unchanged direct-circulant word + +Author-stage derivation, awaiting independent review. The exact source pins, +scope, decisive obligations and complete optimistic budget are in TARGET.md. +The first-wave source-cut audit is a dependency, not part of this review. + +## 1. Prospective theorem + +Under the same source phase/rank, exact represented-input native H, Fourier +and recovery contracts as #8093, let d>=1 axes have widths ell_i>=1, true +orders 2<=r_i<=t_i=2^ell_i, public precision p>=1 and L=sum ell_i. Put + +``` +E = ceil(257*L/2)+1354*d +A = 20*L+303*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 Grid(P) and the unchanged producer target P+8. The same complete padded +input half-disk contract then gives raw coordinate error strictly below +2^(-4p). The inherited public-grid recovery theorem consequently retains its +144/B_radix^2<1/2 error bound for B_radix>=32 under the separate scale, true +volume, no-wrap and CRT-character premises. + +The linear term is 4p+277L+3011d+(L mod 2). It saves exactly 1084L+1735d +fractional bits against #8093 at fixed p and widths. This is a sufficient +selector comparison, not measured speed, space, optimal precision or kappa. + +## 2. Use smaller spectral constants only in the proof + +For every P>=1, the parent's root synthesis and accretivity argument gives +the actual stored padded root T the spectral estimates + +``` +||T|| < 2, +||T_b^-1|| <= 4*r <= 4*t for every leading section. +``` + +Take Lambda=2, Q=4t and chi=8t as mathematical estimates. The executable +component envelopes remain lambda_c=max(1,norm_upper(T)) and Q_c=8tr. No +smaller spectral number is passed to the stronger component-guarded factory. + +Nick Petalas's #4852 theorem applies to every matrix with invertible leading +sections and every contiguous-interval elimination tree, including the +source's non-Toeplitz identity-padded root. Thus each ideal completed downset +and its inverse have cap 2*sqrt(t)*chi^2<=Bnew=2^7*t^3. The theorem bounds +finished forward block rows by Lambda+Lambda^2 Q and untouched rows by +sqrt(1+chi^2); finished inverse block columns are original leading-inverse +restrictions with bound Q, while untouched columns have the block-solve bound +sqrt(1+chi^2). Summing squared block bounds gives the result. The full +credited proof is retained unchanged; this result does not claim that theorem +or Brian's subsequent #4977 allocation adapter as new. + +The old allocation uses +Bold=256*t^3*(lambda_c*Q_c)^12>=256*t^3>Bnew. Its actual atomic error eta +therefore obeys + +``` +theta_new=(3t-2)*Bnew^2*eta <= theta_old <= 1/4. +``` + +For each fixed external P, this reanalyses the exact word produced by the +original allocation at that same P. No child target, grid or coefficient is +changed relative to that source call. Choosing the new external selector +does change P, and therefore regenerates the word through the unchanged +factory's precision rules; identical coefficient bytes across two different +external selectors are not claimed. The forward endpoint synthesis error is +still the parent's original source-allocation theorem at P+8, not an endpoint +estimate obtained by passing smaller spectral numbers to component guards. + +## 3. Bound the actual prepared children + +For each source full split the original-leading-solve identities imply +||K||,||L||<=chi=8t. The displacement E=X-ZXZ^T has norm at most 2chi. +For a child of side m<=t, the exact component row/column envelope returned by +generator.prepare is therefore + +``` +be <= sqrt(2m)*||E|| <= 2*sqrt(2m)*chi <= 4t*chi. +``` + +The source forwards this actual be and actual rank to generator.allocation; +it does not substitute the full compiler's larger global envelope. Retaining +rank<=2ell+8<=5t, the literal child formulas give + +``` +alpha=2*rank*m*be <= 320t^4 +KG=2m+16m*be <= 514t^3. +``` + +By the first-wave source-cut proof, the actual child four-way fragment cap at +arbitrary matching subsets is +max(3200m^3,2+2KG)*(10+4alpha+2KG). Hence + +``` +max(3200t^3,2+1028t^3) <= 3200t^3, +10+1280t^4+1028t^3 <= 2318t^4, +Hgen <= 7,417,600t^7 < 2^23*t^7. +``` + +Ideal scalar pivots have modulus between 1/Q and +U=Lambda+Lambda^2 Q=2+16t<=18t. The unchanged eta satisfies +eta<=1/(2Q_c)<=1/(2Q), since r>=2. Stored scalar and stored inverse fragments +have bounds U+1 and 2Q, both below Hnew=2^23*t^7. Thus Hnew bounds every +actual local fragment and inverse. The old full-level component guards and +their larger recorded fragment bound remain unchanged. + +## 4. All lowering, routing and tensor factors + +Use L0=max(1,Lambda,Q)=4t. The four-way cut and relative-interval lemmas give + +``` +K=2*L0*Bnew*Hnew <= 2^33*t^11, +G=2*Bnew^2*Hnew^2 <= 2^61*t^20. +``` + +K bounds prefixes/suffixes and their inverses; G bounds arbitrary intervals +and inverses, including each original source gate. These are exact stored +operators before data rounding. + +The parent's pivoted sixteen-H proof supplies at most forty ordinary factors +of norm and inverse norm <=64, and exactly one pivot factor bounded both ways +by 2G. A routed partial switch contributes four; each matching is a direct +sum. Every routed root prefix and inverse prefix consequently have cap + +``` +4*K*64^40*(2G) <= 2^337*t^31. +``` + +The two root passes and two external diagonals, each bounded both ways by +2t, give the one-axis cap 2^676*t^64. The retained partial tensor-H allowance +is 2^d at each interval end. Tensoring axes therefore gives spectral interval +cap 2^(1354d+128L); converting to infinity norm costs sqrt(2^L), proving +the stated 2^E envelope. One joined diagonal scalar has modulus at most +64^40*(2G)<=2^302*t^20, including the exterior and routing cases. + +## 5. Close the complete local numerical budget + +Retain the parent's proved odometer invariant: each stored suffix is the +rounded product of its current factors, using at most d-1 multiplications. +It does not accumulate one error per earlier scan record. The new scalar +bound gives local defect epsilon*(1+||z||_infinity), where + +``` +epsilon=(d+1)^2*2^(-P+A), A=20L+303d. +``` + +The stage count J and exact-native-H premise are unchanged. Root-column +synthesis and exact endpoint bias also remain unchanged; their tensor bias +is bounded by beta=(d+1)*2^(-P+E), since +2^E>=2^(d-1)*sqrt(2^L). With prefix and interval caps R=M=2^E, the same +bootstrap gives + +``` +raw error <= J*M*epsilon*(2+2R)+beta + <= C*2^(-P+A+2E). +``` + +For the proposed P this is strictly below 2^(-4p), as C<2^bit_length(C). +The bootstrap spend is strictly below 2^(-4p-E)/4<=1/4, so the computed-state +bound closes without circularity. Both signs use these absolute bounds. + +No helper operation, native private arithmetic, physical setup, copying or +restoration is repriced. The statement is the complete local numerical +budget under its named interfaces, not the complete multiplication recurrence. + +## Verification boundary and remaining questions + +Check every exact exponent and positive polynomial comparison, the unchanged +Full/generator allocations and their actual argument forwarding. Include +bounded padded root words with r=2. Thus signed width W=2B+1 covers every arithmetic value, including the most-negative input's positive magnitude and the full imaginary sum before rounding. A right shift then cannot create overflow. + +The seven-register schedule is complete for this supplied arithmetic task: two outputs, one row accumulator, one offset, and three multiplication registers. It retains all four B-bit input components until both outputs are ready. Accordingly its local live data bill is `4B+7W = 18B+7` bits, plus logarithmic control. Signs, loop indices and the word-width parameters fit that control allowance. This is a written register schedule, not a measurement of the Python diagnostic's heap. Destructive zeroing is stated explicitly; reversible uncomputation and return of a dirty owned region are not derived. + +The all-size caller bridge is sound under the retained precision theorem. Every rounded table factor is bounded by F_i=2b_i>=2. Expanding the right-associated rounded recurrence gives the product of the F_i plus proper suffix products. Normalizing by the positive upper bounds, rather than by actual factors, produces a geometric sum below one. This proves the factor-cache cap even when actual factors vanish. The pinned odometer refreshes each affected suffix from current factors, so the number of prior records does not enter that bound. + +For data states, taking the finite maximum Z of the computed run gives `Z <= R/2 + a(1+Z)`, where a=J*M0*epsilon<1/4 and R>=1. Hence `(R/2+a)/(1-a) <= R`; the argument does not assume the conclusion as a loop invariant. During the source diagonal scan, complete coordinates are old or new stage coordinates. Combining this with the coefficient-cache cap proves `B=P+max(A,E)+3`. In particular P<=B-3, and the supplied rational coefficient denominator and numerators meet C=B in the predecessor theorem. The sharper common-grid bound therefore applies to every `product_diagonal` multiplication while leaving coefficient conversion, H, public truncation/product, routing and event order untouched. + +The quadratic local bit cost is honest. It proves an available local arithmetic implementation; it does not establish the accelerated tariff needed by the full multiplication recurrence. No claim that this replacement preserves that asymptotic price is accepted here. + +## Independent executable evidence + +`independent.py` imports the arithmetic program as the subject under test, but imports neither the author's checker nor its expected outputs. It authenticates the retained inputs and extracts the literal `Grid` and `product_diagonal` definitions. Its result oracle uses the half-open integer interval above and an independently expressed rational ceiling. It checks 39,220 arithmetic cases, including 18,716 halfway components and 8,628 cases with a zero real multiplier component. Wide signed inputs extend through B=4924; the largest observed arithmetic word has 9849 bits. + +A separate mixed-radix position enumeration constructs each coefficient as a right-associated product at the current coordinate. This agrees with 15 literal odometer scans containing 1,020 multiplication calls. Twenty-eight parameter bindings check the published precision API, strict bootstrap numerator and both signed-width margins, including a 129-axis case. Adverse controls reject incorrect negative-tie rounding, an imaginary subtraction, rounding the separate products before addition, substituting ties-to-even coefficient rounding, and a one-bit-short register schedule. + +Both the normal and optimized reviewer commands pass and produce identical scientific JSON. The commands are: + +```sh +python3 -IB review/independent.py --source . --output /tmp/grid-independent.json +python3 -I -O -B review/independent.py --source . --output /tmp/grid-independent-optimized.json +``` + +The expected marker is `PASS_INDEPENDENT_GRID_CALLER_REVIEW`. These finite checks corroborate the written all-size proof and source binding; they do not prove the universal claim by exhaustive sampling. + +## Source and execution boundaries + +The extracted expression fixtures supply Python `operator.mul` as an exact-integer helper. They do not claim to execute the retained `word_product` tape machine or its complete instruction schedule. The separately proved local multiplier is the new supplied-word construction; its physical caller transport remains retained. + +The `(2,)` side, five-digit-bit example is an admissible explicit `Multiplier` geometry. It is not a claim about which geometry the outer `multiply_uniform` selector chooses at a particular input length. The literal `operand` method, with the one-axis identity CRT adapter, produces `2^3431` at P=3438 from operand 1. The unchanged predecessor diagnostic rejects the necessary signed B=3433 before mutating its input. This is a finite-reference integration limitation, not a refutation of Nick Petalas's all-width mathematical theorem. + +The original once-rounded Full-gate semantics must also remain distinct from the externally lowered sixteen-H chronology. The source-level discussion and small counterexample establish that distinction; they are not evidence of failure at the sufficient production precision. Coefficient delivery, synthesis, global resident arrays, native private workspace, physical movement and reversible cleanup remain separate. + +Credit Nick Petalas for the original all-rational arithmetic width theorem; Armin Pourshafeie for rounded-event and partial-write semantics; Jose Manuel and the rational compiler lineage; Ali Romman for the external tensor caller and recovery integration; and all retained source authors and notices. Apache-2.0. diff --git a/research/direct-circulant-production-precision/grid-arithmetic/review/independent.py b/research/direct-circulant-production-precision/grid-arithmetic/review/independent.py new file mode 100644 index 0000000000..858ad401df --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/review/independent.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python3 +"""Independent arithmetic and caller review; imports no author checker.""" +import argparse, ast, hashlib, importlib.util, itertools, json, math, operator, random, sys +from fractions import Fraction +from pathlib import Path + +def need(value, why): + if not value: raise ValueError(why) + +def load(path, name): + spec=importlib.util.spec_from_file_location(name,path) + module=importlib.util.module_from_spec(spec);sys.modules[name]=module;spec.loader.exec_module(module);return module + +def certificate(numerators, values, P): + q=1<

','exec'),ns) + Grid=ns['Grid'];prod_diag=ns['product_diagonal'] + counts={'arithmetic_cases':0,'zero_multiplier_cases':0,'halfway_components':0,'source_odometer_scans':0,'source_odometer_calls':0,'parameter_bindings':0} + maximum=0 + def check(B,P,v): + nonlocal maximum + u=tuple(v[:2]);w=tuple(v[2:]);a,b=u;c,d=w + result,frame=subject.multiply_grid(u,w,P,B) + certificate((a*c-b*d,a*d+b*c),result,P) + need(result==Grid(P).multiply(u,w),'literal Grid expression') + need(result==direct(u,w,P),'independent rational ceiling oracle') + need(len(frame.registers)==7 and frame.registers[2:]==[0]*5,'fixed seven-register frame and reset') + need(frame.iterations<=4*B and frame.peak<=2*B+1,'written width/iteration envelope') + maximum=max(maximum,frame.peak);counts['arithmetic_cases']+=1 + counts['zero_multiplier_cases']+=int(c==0 or d==0) + q=1<=1 and P<=B-3,'strict bootstrap numerator and coefficient denominator height') + need(A+1','exec'),on) + class Caller:pass + caller=Caller();caller.sides=(2,);caller.widths=(2,);caller.size=2;caller.base=32;caller.grid=Grid(3438);caller.crt=lambda field:field + field,used=on['operand'](caller,1);need(field[0]==(1<<3431,0) and used==1,'actual pre-CRT input height');state=[field[0][0],0,0,0];saved=state[:];identity=tuple(tuple((int(i==j),1) for j in range(4)) for i in range(4)) + rejected=False + try:kernel.apply_gate(identity,state,3433,1) + except ValueError as e:rejected=str(e)=='data width' + need(rejected and state==saved,'unmodified finite predecessor guard') + controls={} + for label,nums,z,P in [('negative_tie_away',(-1,0),(-1,0),1),('imaginary_difference',(0,2),(0,0),1),('per_product_round',(0,2),(0,2),1),('coefficient_ties_even',(2,0),(0,0),2)]: + try:certificate(nums,z,P) + except ValueError:controls[label]=True + else:raise ValueError('adverse rounding mutation survived '+label) + for B in (2,7,128): + M=1<<(B-1) + try:subject.multiply_grid((-M,-M),(-M,-M),B,B,diagnostic_width=2*B) + except OverflowError:pass + else:raise ValueError('underallocated sum passed') + report={'marker':'PASS_INDEPENDENT_GRID_CALLER_REVIEW','source_count':len(source_rows),'proof_sha256':hashlib.sha256((root/'PROOF.md').read_bytes()).hexdigest(),'program_sha256':hashlib.sha256((root/'grid_arithmetic.py').read_bytes()).hexdigest(),'counts':counts,'maximum_observed_word_bits':maximum,'rejected_controls':controls,'finite_guard_preserved':True,'scope':'local supplied arithmetic and literal expressions; exact helper adapter, no encoded tape execution'} + args.output.write_text(json.dumps(report,sort_keys=True,indent=2)+'\n');print(json.dumps(report,sort_keys=True)) +if __name__=='__main__':main() diff --git a/research/direct-circulant-production-precision/grid-arithmetic/run_registered.py b/research/direct-circulant-production-precision/grid-arithmetic/run_registered.py new file mode 100644 index 0000000000..0bad19b269 --- /dev/null +++ b/research/direct-circulant-production-precision/grid-arithmetic/run_registered.py @@ -0,0 +1,66 @@ +"""Preserve the eighth registered replay and append accepted grid checks. + +All scientific programs and source bytes are frozen. New receipts are written +into disposable copies and compared with the published normal/optimized ones. +""" +from hashlib import sha256 +import json +from pathlib import Path +import shutil +import subprocess +import sys +from tempfile import TemporaryDirectory + +HERE = Path(__file__).resolve().parent +PACKAGE = HERE.parent + + +def need(ok, why): + if not ok: + raise ValueError(why) + + +def authenticate(): + frozen = json.loads((HERE/'FROZEN.json').read_text()) + for relative, expected in frozen['files'].items(): + need(sha256((HERE/relative).read_bytes()).hexdigest() == expected, + 'frozen grid source or review changed: '+relative) + + +def run(argv, cwd, timeout): + print('REPLAY '+' '.join(map(str, argv)), flush=True) + subprocess.run(list(map(str, argv)), cwd=cwd, check=True, timeout=timeout) + + +def grid_replay(): + with TemporaryDirectory(prefix='circulant-grid-replay-') as directory: + temporary = Path(directory) + copied = temporary/'grid-arithmetic' + shutil.copytree(HERE, copied) + for optimized in (False, True): + mode = 'optimized' if optimized else 'normal' + evidence = 'EVIDENCE-OPTIMIZED.json' if optimized else 'EVIDENCE.json' + # The frozen author program imports its sibling module. Preserve + # its original -B invocation; the independent checker uses -I. + flags = [sys.executable, *(['-O'] if optimized else []), '-W', 'error', '-B'] + author = temporary/('author-'+mode+'.json') + run([*flags, copied/'check.py', '--output', author], temporary, 120) + need(author.read_bytes() == (HERE/evidence).read_bytes(), 'fresh author receipt differs') + review = temporary/('review-'+mode+'.json') + run([*flags[:1], '-I', *flags[1:], copied/'review/independent.py', + '--source', copied, '--output', review], temporary, 120) + need(review.read_bytes() == (HERE/'review'/evidence).read_bytes(), + 'fresh independent receipt differs') + + +def main(): + authenticate() + run([sys.executable, '-I', '-W', 'error', '-B', + PACKAGE/'reconciliation/replay.py', '--additions'], PACKAGE, 480) + grid_replay() + authenticate() + print('PASS_PRESERVED_ADDITIONS_AND_GRID_ARITHMETIC', flush=True) + + +if __name__ == '__main__': + main() 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/reconciliation/COMPATIBILITY-EVIDENCE.json b/research/direct-circulant-production-precision/reconciliation/COMPATIBILITY-EVIDENCE.json new file mode 100644 index 0000000000..0837ae8ee0 --- /dev/null +++ b/research/direct-circulant-production-precision/reconciliation/COMPATIBILITY-EVIDENCE.json @@ -0,0 +1,28 @@ +{ + "frozen_relocated_files": 38, + "frozen_reviewer_files": 10, + "new_review_edits": false, + "owner_registered_replay_observed_pass": true, + "preserved_remote_files": 32, + "prior_reviewed_base": "0a1c14499407b103ae964f36551b0e9c11400197", + "private_new_output_compared": true, + "registered_commands_after": 8, + "registered_commands_before": 7, + "remote_base": "e040fedfd8fcc51480d2468f3fa07562c8bacbf0", + "remote_tree": "fc5a918a95e2d853afbd99227d6ae17f7b28c129", + "review_sha256": "52d41926b078dc4c3a28d548c7f56467cd5620e1d8b3dac70b30563c2bf676ff", + "reviewed_snapshot": { + "README.md": "b0f7e3e0913134d4b9ef07da0a6e98b8d8aef51c8ef0741bc0508def9ab34393", + "VERIFY.json": "243fb8d7fdcfb99e8740ce5dac589e0db52c54b27067b0ad5855cfcb7f9365fd", + "compiler-intervals/INTEGRATION.md": "6b394e90e1648dd51d4779e4f67d47e2171b9c27889c9240b1a54a2b903294d2", + "evidence/reconciled-registered-replay.txt": "baa84517edc3694f80e048acd81e8e47d115a4a5ebd68519af442f2909b3f4d9", + "reconciliation/FROZEN-ADDITIONS.json": "66485f5c2da0d620530a5954ef284013a7422ce7e901ac30869dd4ec5b3863e3", + "reconciliation/PRESERVED-CUTS.json": "13ba46f58615459688145f472f75c07b6ee7b5f63b004b95ad46e972df71177e", + "reconciliation/REMOTE-VERIFY.json": "bf4d5e09ec8c75c07ced6228450f7cfed5c7eac38bb8252898616cfe5e577da1", + "reconciliation/replay.py": "0e51182692ad2a7c820ee4b301c8696a535dfce204f46ed47da2561ac41e6e5e", + "spectral-downset/README.md": "7b64a8d00d7b16466fa1674fdf058e02f98a706e84e032522c3bd92e6fd55c9b", + "spectral-downset/run_check.py": "942686f322310d64a40653fde154446ac731419c43281b40376535f4805e631f" + }, + "scope": "read-only integration review; no new source mathematical claim or physical tariff review", + "status": "ACCEPTED_COMPATIBILITY_AND_PRESERVATION" +} diff --git a/research/direct-circulant-production-precision/reconciliation/COMPATIBILITY-REVIEW.md b/research/direct-circulant-production-precision/reconciliation/COMPATIBILITY-REVIEW.md new file mode 100644 index 0000000000..ac6d31b5a0 --- /dev/null +++ b/research/direct-circulant-production-precision/reconciliation/COMPATIBILITY-REVIEW.md @@ -0,0 +1,116 @@ +# Compatibility review of the reconciled #8093 supplements + +**Disposition: accepted.** This is a short integration and preservation +review, not a new mathematical review or a replay of unchanged historical +claims. It supplements the separately frozen interval and selector reviews. +No files in the author's reconciliation checkout were modified. + +## Exact integration boundary + +Reviewed package: +`/workspace/scratch/e64488edfaad/reconcile-precision/research/direct-circulant-production-precision`. + +The final reviewed intervening remote base is +`e040fedfd8fcc51480d2468f3fa07562c8bacbf0`, with tree +`fc5a918a95e2d853afbd99227d6ae17f7b28c129`. The local Git object independently +reports that tree identity. The published `compiler-cuts/` proof remains +`162dd4bb7a020dfb72dd3c80cb9a1de37212cc7f812f36fd4365d487d49b341b`. + +An initial check used its parent +`0a1c14499407b103ae964f36551b0e9c11400197` and tree +`691d6a647e64c2b6d2084849fe4d2a7ff0273da6`. The subsequent four-file remote +delta changed only VERIFY output locations, an integration note and elapsed +fields in two receipts. No proof or checker changed. The complete protected +subtree was checked again against the newer actual Git tree. + +The separate recovered interval proof is under `compiler-intervals/`, +retaining SHA-256 +`e942012e66adc2d696cde3fedd6ae9c73df98e77a71b16e5004f5a74ccdfaa07`. +The sharper selector is under `spectral-downset/`, retaining proof +`0501a6a9a5f467fff4c998606965babc8157e74d98cf33b93f71fb10674d57bb` and +API `9c3e99219f741c5b08c0628c30784cf72c60b4421beae3373fa976aeffcd8e20`. + +## Independent preservation checks + +I compared the complete `compiler-cuts/` path set, Git blob identities and +disk SHA-256 identities against the actual Git tree at the intervening +commit. All **32 files** agree, including the already published source, +proof, independent review and elapsed-time receipts. This check does not +merely trust the new preservation manifest. + +I separately compared the relocated additions against their original +frozen workspace files: + +| Relocated subtree | Frozen files matched byte for byte | +| --- | ---: | +| `compiler-intervals/` author package | 23 | +| `compiler-intervals/review/` | 5 | +| `spectral-downset/` author scientific files | 5 | +| `spectral-downset/review/` | 5 | + +The original parent README is an exact byte prefix of the reconciled +README. The integration appends the new chronology rather than rewriting +the earlier published account. + +## Claim boundaries and dependency binding + +The appended parent README and `compiler-intervals/INTEGRATION.md` correctly +identify the earlier complete-gate Result A as overlapping source context. +They identify the additional mathematical claim as Result B: cancellation +along one common legal linearization of nested completed downsets, yielding +`B^2 H^2/(1-theta)<2B^2 H^2` for the interval and its exact inverse. + +The source requirements `lambda>=1` and `Q>=1` are stated individually. +The text does not replace them by the weaker product-only condition. +The earlier #5940 conditioned interpolation and #5240 event/partial-write +precedents are credited explicitly. The selector credits #4852 and retains +its spectral-versus-component distinction and unchanged per-P allocation. + +The new selector's path adapter and the registered replay both pass +`compiler-intervals` explicitly. The independent selector oracle still pins +the exact e942 interval proof and the original parent proof. It therefore +does not accidentally consume the differently hashed published +`compiler-cuts` proof after the folder reconciliation. + +Historical author-stage labels remain inside frozen scientific files. +The new README explains that their separate reviews subsequently accepted +those exact bytes. This preserves provenance without misrepresenting their +current review disposition. + +## Registered replay compatibility + +The exact seven original verification commands are retained in +`reconciliation/REMOTE-VERIFY.json`, which matches the intervening Git +object. The first three registrations are unchanged. Registrations 3–6 +invoke the original source programs and flags, including the two optimized +modes, through disposable copies. The copies prevent regenerated elapsed +fields from rewriting published receipts; their proof-relevant output is +compared after dropping only the top-level `seconds` field. + +The newer remote reviewer commands already write outside the package. +The adapter explicitly redirects their `--output` argument into its private +temporary directory and compares that freshly produced receipt. It does +not compare the untouched copied receipt with its own frozen original. +Both updated legacy runs were observed to use and compare the private +`legacy-normal.json` and `legacy-optimized.json` outputs successfully. + +An eighth registration runs the added author and independent interval and +selector methods, explicitly selecting the frozen interval dependency. +Both normal and optimized independent modes are present. The replay +authenticates protected files before and after its isolated execution. + +I observed the owner's completed registered-replay log, ending in +`PASS_RELATIVE_INTERVAL_AND_SHARP_SELECTOR_ADDITIONS` and +`PASS_REGISTERED_RESEARCH_PACKAGE ... outcome=completed`. I did not count +that owner's execution as a second independent mathematical replay. + +Two small nonblocking refinements were sent to the author and applied: +the selector README now describes both independent modes, and all ten +unchanged review files are included in the new authentication inventory. +The inventory covers all 38 frozen additions. The original remote VERIFY +file is itself SHA-256 authenticated. Neither refinement changes a +scientific proof, dependency pin or acceptance result. + +Prepared as a separate model-assisted integration check for Jerry Chen / +@CubeJerry. This acceptance is limited to the observed reconciliation; +publication and remote reconciliation remain the parent agent's task. diff --git a/research/direct-circulant-production-precision/reconciliation/FROZEN-ADDITIONS.json b/research/direct-circulant-production-precision/reconciliation/FROZEN-ADDITIONS.json new file mode 100644 index 0000000000..7475381610 --- /dev/null +++ b/research/direct-circulant-production-precision/reconciliation/FROZEN-ADDITIONS.json @@ -0,0 +1,40 @@ +{ + "compiler-intervals/EVIDENCE.json": "b05ec559db2511cfefd240ddb5c6a74f7bbb224db5836503cdbc2e51724a5b17", + "compiler-intervals/ORIGINS.json": "fd8db560cc9e05fe194e3ddd4ff744bcb01cc4a585abfe28abc902d1207a31b0", + "compiler-intervals/PROOF.md": "e942012e66adc2d696cde3fedd6ae9c73df98e77a71b16e5004f5a74ccdfaa07", + "compiler-intervals/README.md": "22d0fa757b95ba55bfcb8067d2339864f0997af9da24f61e24a9fbdbe3dcdc49", + "compiler-intervals/audit.py": "d854b580ff64ae80a53b020578bf69474aefe5eb4c45efd949cab1526e68b1fe", + "compiler-intervals/retained/FULL-PROOF.md": "acf8c596d91b5efd35a286735d6867ff8afce64354a13f680c2fae3dab824410", + "compiler-intervals/retained/GENERATOR-PROOF.md": "cddda1f944299a349c837808b349fa6e4499cbb1889f7dacc00ca8afac9b580c", + "compiler-intervals/retained/PR4755-README.md": "5b514f93ab3b0a37a32978a599d74c545ed19122e235f9cccfff36faefb97a9b", + "compiler-intervals/retained/PR4852-README.md": "1e59ae73eb142ec3d4579ce98244295b733896afca0fec3693906fc6def26d3f", + "compiler-intervals/retained/PR4976-README.md": "ba6754f00779874ec981563101114cf18c03026c18338f37a813abd3fae59d21", + "compiler-intervals/retained/PR4977-README.md": "fd1f8cade22bc01f981f8855e6b4c0a62996875a007ff8391e258157ce80f56c", + "compiler-intervals/retained/PROOF.md": "50e31e33e1275a133d10e87208ceb50dddce67d0678d2a89de9f7ba28d8380d9", + "compiler-intervals/retained/SOURCES.json": "7324e22bcb202b5cc03b5f7ea713f6f0c7cd80ee60d320fb03b1e2f7b13b8c91", + "compiler-intervals/retained/STEIN-PROVENANCE.json": "e7f0e8dc517387e302b1e8bf5dff7e12b29da8aa91abc6ea597f33c1ac08ba62", + "compiler-intervals/retained/TRIANGLE-PROOF.md": "abea26e3c86a9970225b070be034c47e7970e10fe1b5686f405e0b301acf3159", + "compiler-intervals/retained/check_circuits.py": "06d1861bfe8af543908e26557ffda7e451ff176bceb9bacfaf0f04f234b336d5", + "compiler-intervals/retained/engine.py": "9e36aee0835e6b1b62997433581f88b5a434ccab8ae43e5c25d1deaaf1ebf653", + "compiler-intervals/retained/exact.py": "c9b89d7357210af69865690ba12e695366961f8b501a8fab9d0fefe3fb30c479", + "compiler-intervals/retained/full.py": "1f42d5f2858564ffb320e54ba6aa29651025491569823e25006bf5862457b803", + "compiler-intervals/retained/generator.py": "827ef9fe1bd664859995892b59843c390f7969c938fb7e1e6dc585c31a54b555", + "compiler-intervals/retained/interval_kernel.py": "9b7bb24640a9a7d3f83c7951dfef483ec933db4c50de6c0130b85f450eeddfbe", + "compiler-intervals/retained/stein_rational.py": "3065fc5d6d22ec44de533b08fb0c639603449456383668e561dc46629e641502", + "compiler-intervals/retained/triangular.py": "46780d95ddebfed22e8f0c18565fe2e768250afa5beeb31f450292cc06f7ec11", + "spectral-downset/EVIDENCE.json": "d2377d5cb672eee75537553b2e21284db660b6442ede929b5fbd1f7d53b2f395", + "spectral-downset/PROOF-DRAFT.md": "0501a6a9a5f467fff4c998606965babc8157e74d98cf33b93f71fb10674d57bb", + "spectral-downset/TARGET.md": "c54ce9533c7e82120bb41feae8084b2464c52e34d1f5ec57b3cfd1d7550b32bf", + "spectral-downset/check.py": "4eccf9d085d53ebb3580ba0f4868d177c4e077f3146754f2b2b4fb10c9267420", + "spectral-downset/precision.py": "9c3e99219f741c5b08c0628c30784cf72c60b4421beae3373fa976aeffcd8e20", + "compiler-intervals/review/independent.py": "57653629cbc939556795c4c6b80790d95d7fff754b4c723c5f64c69dc43b890b", + "compiler-intervals/review/REVIEW.md": "b254641c34ef041e70be90937c41974395a056ca90726fbf9b59219df014c972", + "compiler-intervals/review/EVIDENCE.json": "aac7dc89326bad10e8671a6454a2b86dfd28b92c12f93c149120562b264358aa", + "compiler-intervals/review/FROZEN.json": "75ca430453139d7e0919233877ec4fbd8e37036927bc42931b1f9faa2b6e8210", + "compiler-intervals/review/EVIDENCE-OPTIMIZED.json": "aac7dc89326bad10e8671a6454a2b86dfd28b92c12f93c149120562b264358aa", + "spectral-downset/review/independent.py": "995b0e8910e0516a871cc8ae7f9f9bd4cb255925dc67d6b78fa426b9eab8c8d2", + "spectral-downset/review/REVIEW.md": "7d05d73425d5d785d354612af1df3e7d462cb20a1af58942c5b02d7d0215af6b", + "spectral-downset/review/EVIDENCE.json": "ede90dae5aa43513db8fe6b985d2073ce98e1aaa0b15b9935cd9673ff8fcf569", + "spectral-downset/review/FROZEN.json": "5f4fd0aec835546ac794d7adc99a8cc62427c0aa19a9678d849a122eb5b89dd1", + "spectral-downset/review/EVIDENCE-OPTIMIZED.json": "ede90dae5aa43513db8fe6b985d2073ce98e1aaa0b15b9935cd9673ff8fcf569" +} diff --git a/research/direct-circulant-production-precision/reconciliation/PRESERVED-CUTS.json b/research/direct-circulant-production-precision/reconciliation/PRESERVED-CUTS.json new file mode 100644 index 0000000000..d1f9efac1e --- /dev/null +++ b/research/direct-circulant-production-precision/reconciliation/PRESERVED-CUTS.json @@ -0,0 +1,231 @@ +{ + "base_commit": "e040fedfd8fcc51480d2468f3fa07562c8bacbf0", + "base_tree": "fc5a918a95e2d853afbd99227d6ae17f7b28c129", + "files": [ + { + "path": "compiler-cuts/AUTHOR-RECEIPT.json", + "git_blob": "fe77a0aa16cf576d9255282c41f3a08ee48b6d96", + "mode": "100644", + "sha256": "97513d661e30d3019152c74bafe8c50ca2da7ae9832b9ddcb24e440cc4f28e36", + "bytes": 1030 + }, + { + "path": "compiler-cuts/EVIDENCE.json", + "git_blob": "6cf13661d6799b9428e92a251cacd48b90987188", + "mode": "100644", + "sha256": "aa1ada5b2e9f1275815c9780b3055874c21ff289cde859001d1a536ac903ca15", + "bytes": 5096 + }, + { + "path": "compiler-cuts/INTEGRATION.md", + "git_blob": "dd18a4152b705b699739808f2d1c7f9524bf9a0b", + "sha256": "cdb6b798c9a0918b11ad0ab9eb66e87a6438e22ee61591e4d5c4b17191e11f80", + "bytes": 3496, + "mode": "100644" + }, + { + "path": "compiler-cuts/LICENSE", + "git_blob": "261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64", + "mode": "100644", + "sha256": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4", + "bytes": 11357 + }, + { + "path": "compiler-cuts/NOTICE.md", + "git_blob": "d236f8104d2f5b60629b273b9405fce264a0a457", + "mode": "100644", + "sha256": "fdff11619c42afb4c500a73c2663ca1a45edebb426d87a704e17db44bf91e55d", + "bytes": 1872 + }, + { + "path": "compiler-cuts/ORIGINS.json", + "git_blob": "d3d018b180f1d7b7d74477dc3e49bc39755e15fe", + "mode": "100644", + "sha256": "fd8db560cc9e05fe194e3ddd4ff744bcb01cc4a585abfe28abc902d1207a31b0", + "bytes": 7249 + }, + { + "path": "compiler-cuts/PROOF.md", + "git_blob": "9c0aa700067adeab928a9b47e306af92a5f4bd59", + "mode": "100644", + "sha256": "162dd4bb7a020dfb72dd3c80cb9a1de37212cc7f812f36fd4365d487d49b341b", + "bytes": 17259 + }, + { + "path": "compiler-cuts/README.md", + "git_blob": "09a32492b94fdf3e9561327ec8043303d222e5df", + "mode": "100644", + "sha256": "0f042058578fb5097857de1bb471c424f2297555193d7252685a1f9f3c32a24d", + "bytes": 5006 + }, + { + "path": "compiler-cuts/audit.py", + "git_blob": "04f27d7379b4d81a850699ff9b81bb25613b6e1c", + "mode": "100644", + "sha256": "e7756cc6fec1c789dcdb5ef5e7c828c3b4981c4ace681029c49e16607628b6a4", + "bytes": 24242 + }, + { + "path": "compiler-cuts/retained/FULL-PROOF.md", + "git_blob": "e650f46863115f810e27b403f916dd7f79b37786", + "mode": "100644", + "sha256": "acf8c596d91b5efd35a286735d6867ff8afce64354a13f680c2fae3dab824410", + "bytes": 15002 + }, + { + "path": "compiler-cuts/retained/GENERATOR-PROOF.md", + "git_blob": "8bef383eec887450e86f14365a6f7b07c1310e9d", + "mode": "100644", + "sha256": "cddda1f944299a349c837808b349fa6e4499cbb1889f7dacc00ca8afac9b580c", + "bytes": 9975 + }, + { + "path": "compiler-cuts/retained/PR4755-README.md", + "git_blob": "f088efaaa828e415db6bb152a8cbeaea1dd68dd7", + "mode": "100644", + "sha256": "5b514f93ab3b0a37a32978a599d74c545ed19122e235f9cccfff36faefb97a9b", + "bytes": 10529 + }, + { + "path": "compiler-cuts/retained/PR4852-README.md", + "git_blob": "0b753c1b16f0a2977d3aad7242510ba55bec98a0", + "mode": "100644", + "sha256": "1e59ae73eb142ec3d4579ce98244295b733896afca0fec3693906fc6def26d3f", + "bytes": 11141 + }, + { + "path": "compiler-cuts/retained/PR4976-README.md", + "git_blob": "eb7b8be250b6f23ae30e7e611e651a8fe300ac3e", + "mode": "100644", + "sha256": "ba6754f00779874ec981563101114cf18c03026c18338f37a813abd3fae59d21", + "bytes": 7062 + }, + { + "path": "compiler-cuts/retained/PR4977-README.md", + "git_blob": "c5248440b72a566314aa1ba40647d706f2561f96", + "mode": "100644", + "sha256": "fd1f8cade22bc01f981f8855e6b4c0a62996875a007ff8391e258157ce80f56c", + "bytes": 8170 + }, + { + "path": "compiler-cuts/retained/PROOF.md", + "git_blob": "99a55596f67ae3b94ef02ebb159b313f33bf22af", + "mode": "100644", + "sha256": "50e31e33e1275a133d10e87208ceb50dddce67d0678d2a89de9f7ba28d8380d9", + "bytes": 14204 + }, + { + "path": "compiler-cuts/retained/SOURCES.json", + "git_blob": "7ee22e983f54dfb73e74d20ed1910a64d2abb6cd", + "mode": "100644", + "sha256": "7324e22bcb202b5cc03b5f7ea713f6f0c7cd80ee60d320fb03b1e2f7b13b8c91", + "bytes": 7143 + }, + { + "path": "compiler-cuts/retained/STEIN-PROVENANCE.json", + "git_blob": "c602fb5bb332dbe098950b14d55da05ce2cf4312", + "mode": "100644", + "sha256": "e7f0e8dc517387e302b1e8bf5dff7e12b29da8aa91abc6ea597f33c1ac08ba62", + "bytes": 1366 + }, + { + "path": "compiler-cuts/retained/TRIANGLE-PROOF.md", + "git_blob": "f923f4ff2dfe40401fa90d83727ade62b2ef5b5f", + "mode": "100644", + "sha256": "abea26e3c86a9970225b070be034c47e7970e10fe1b5686f405e0b301acf3159", + "bytes": 10475 + }, + { + "path": "compiler-cuts/retained/check_circuits.py", + "git_blob": "f80c141c8116b163c2bb5a028c28212077c8d5a9", + "mode": "100644", + "sha256": "06d1861bfe8af543908e26557ffda7e451ff176bceb9bacfaf0f04f234b336d5", + "bytes": 10774 + }, + { + "path": "compiler-cuts/retained/engine.py", + "git_blob": "e9f2f2b08dc2bc4c646e47dca92059351ca89384", + "mode": "100644", + "sha256": "9e36aee0835e6b1b62997433581f88b5a434ccab8ae43e5c25d1deaaf1ebf653", + "bytes": 13174 + }, + { + "path": "compiler-cuts/retained/exact.py", + "git_blob": "aae41e6acfb2e5a4fafdd85727891eb746b57b42", + "mode": "100644", + "sha256": "c9b89d7357210af69865690ba12e695366961f8b501a8fab9d0fefe3fb30c479", + "bytes": 7863 + }, + { + "path": "compiler-cuts/retained/full.py", + "git_blob": "7f85ad1a89e81b7dfc6b54e7bd9547120e86d5d3", + "mode": "100644", + "sha256": "1f42d5f2858564ffb320e54ba6aa29651025491569823e25006bf5862457b803", + "bytes": 12561 + }, + { + "path": "compiler-cuts/retained/generator.py", + "git_blob": "d761d3c88b1685fb64d92d69f699b8218c9ec30f", + "mode": "100644", + "sha256": "827ef9fe1bd664859995892b59843c390f7969c938fb7e1e6dc585c31a54b555", + "bytes": 12562 + }, + { + "path": "compiler-cuts/retained/interval_kernel.py", + "git_blob": "1182175a55cb871481de0f56ea9ae56e474705fe", + "mode": "100644", + "sha256": "9b7bb24640a9a7d3f83c7951dfef483ec933db4c50de6c0130b85f450eeddfbe", + "bytes": 2363 + }, + { + "path": "compiler-cuts/retained/stein_rational.py", + "git_blob": "71b240a460a185ee2fe926cd189b56aeac6f997f", + "mode": "100644", + "sha256": "3065fc5d6d22ec44de533b08fb0c639603449456383668e561dc46629e641502", + "bytes": 6045 + }, + { + "path": "compiler-cuts/retained/triangular.py", + "git_blob": "2bd8de01a7ac80de7e6b9f8252bc69d0e0a291e8", + "mode": "100644", + "sha256": "46780d95ddebfed22e8f0c18565fe2e768250afa5beeb31f450292cc06f7ec11", + "bytes": 10040 + }, + { + "path": "compiler-cuts/review/CROSS-REVIEW.md", + "git_blob": "044ede502eb5f52f876bb8cb2f63162fc32b170f", + "mode": "100644", + "sha256": "b9b2ff6ac1b4454c5a4b62489bb4b00ad0de89b37dfbe8f13da48db0a3ed45ae", + "bytes": 15884 + }, + { + "path": "compiler-cuts/review/EVIDENCE-OPTIMIZED.json", + "git_blob": "f6f6614046be6ff67656217cb8b87e2f8087d3ba", + "sha256": "04a27e7865a42f0ad609010b30f67ff08e7ddd13093585834770f4419ea59561", + "bytes": 2999, + "mode": "100644" + }, + { + "path": "compiler-cuts/review/EVIDENCE.json", + "git_blob": "864edddad214202e9e9b1c47ecdc2b405cbc64e1", + "sha256": "db6f12ffdb0909fef4f83e4e91d0f41090435191b6ca13da1a9be31dee7f7347", + "bytes": 2999, + "mode": "100644" + }, + { + "path": "compiler-cuts/review/RECEIPT.json", + "git_blob": "882635a60688594b1bc4cbe329b50fc285fdaea5", + "mode": "100644", + "sha256": "e1a12e899056562cb3ea42fca3ece09d979471ecdaa5f1bbd84e1ebf67201e57", + "bytes": 988 + }, + { + "path": "compiler-cuts/review/check_independent.py", + "git_blob": "1fae72e9d09a6b7fa0ebee1029e412df6aefe041", + "mode": "100644", + "sha256": "d18064eb86ff9975d59446907cde80ef1c9665188c04409d9287f35b75040ddd", + "bytes": 14774 + } + ], + "remote_verify_sha256": "bf4d5e09ec8c75c07ced6228450f7cfed5c7eac38bb8252898616cfe5e577da1" +} diff --git a/research/direct-circulant-production-precision/reconciliation/REMOTE-VERIFY.json b/research/direct-circulant-production-precision/reconciliation/REMOTE-VERIFY.json new file mode 100644 index 0000000000..354fe7408e --- /dev/null +++ b/research/direct-circulant-production-precision/reconciliation/REMOTE-VERIFY.json @@ -0,0 +1,101 @@ +{ + "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." + }, + { + "argv": [ + "{python}", + "-W", + "error", + "-I", + "-B", + "{package}/compiler-cuts/audit.py" + ], + "timeout_seconds": 180, + "checks": "Authenticate 18 source files; exact source matching cuts, four-way envelopes, partial Full timestamps and order/alphabet rejection controls." + }, + { + "argv": [ + "{python}", + "-W", + "error", + "-I", + "-O", + "-B", + "{package}/compiler-cuts/audit.py" + ], + "timeout_seconds": 180, + "checks": "Authenticate 18 source files; exact source matching cuts, four-way envelopes, partial Full timestamps and order/alphabet rejection controls." + }, + { + "argv": [ + "{python}", + "-W", + "error", + "-I", + "-B", + "{package}/compiler-cuts/review/check_independent.py", + "--source", + "{package}/compiler-cuts", + "--output", + "/tmp/direct-circulant-cut-review-normal.json" + ], + "timeout_seconds": 60, + "checks": "Independent rational realification, bank invariants, all matching subsets, primitive intervals, LDU downsets and conditioning/chronology controls; no author checker imported." + }, + { + "argv": [ + "{python}", + "-W", + "error", + "-I", + "-O", + "-B", + "{package}/compiler-cuts/review/check_independent.py", + "--source", + "{package}/compiler-cuts", + "--output", + "/tmp/direct-circulant-cut-review-optimized.json" + ], + "timeout_seconds": 60, + "checks": "Independent rational realification, bank invariants, all matching subsets, primitive intervals, LDU downsets and conditioning/chronology controls; no author checker imported." + } + ] +} diff --git a/research/direct-circulant-production-precision/reconciliation/replay.py b/research/direct-circulant-production-precision/reconciliation/replay.py new file mode 100644 index 0000000000..b6e7fc6020 --- /dev/null +++ b/research/direct-circulant-production-precision/reconciliation/replay.py @@ -0,0 +1,115 @@ +"""Path-only replay adapter preserving frozen publication bytes. + +The original seven registered checks retain their source programs and flags. +The four compiler-cut checks execute in disposable byte-identical copies so +their regenerated elapsed-time receipts cannot rewrite the published review. +The eighth registration executes the added interval/selector checks similarly. +""" +from __future__ import annotations + +import argparse +from hashlib import sha256 +import json +from pathlib import Path +import shutil +import subprocess +import sys +from tempfile import TemporaryDirectory + +HERE = Path(__file__).resolve().parent +PACKAGE = HERE.parent + + +def require(ok, reason): + if not ok: + raise ValueError(reason) + + +def authenticate(): + receipt = json.loads((HERE / 'PRESERVED-CUTS.json').read_text()) + require(sha256((HERE / 'REMOTE-VERIFY.json').read_bytes()).hexdigest() + == receipt['remote_verify_sha256'], 'original remote verification commands changed') + for row in receipt['files']: + data = (PACKAGE / row['path']).read_bytes() + require(sha256(data).hexdigest() == row['sha256'], 'preserved remote file changed: ' + row['path']) + for path, expected in json.loads((HERE / 'FROZEN-ADDITIONS.json').read_text()).items(): + require(sha256((PACKAGE / path).read_bytes()).hexdigest() == expected, + 'frozen supplement changed: ' + path) + + +def compare(actual, frozen, elapsed=False): + left, right = json.loads(actual.read_text()), json.loads(frozen.read_text()) + if elapsed: + left.pop('seconds', None) + right.pop('seconds', None) + require(left == right, 'replayed proof-relevant receipt changed: ' + str(frozen)) + + +def run(argv, cwd, seconds): + print('REPLAY ' + ' '.join(map(str, argv)), flush=True) + subprocess.run(list(map(str, argv)), cwd=cwd, timeout=seconds, check=True) + + +def legacy(index, temporary, copied): + require(index in range(3, 7), 'select one of the four preserved compiler checks') + command = json.loads((HERE / 'REMOTE-VERIFY.json').read_text())['commands'][index] + argv = [sys.executable if arg == '{python}' else arg.replace('{package}', str(copied)) + for arg in command['argv']] + if index in (3, 4): + relative = 'compiler-cuts/EVIDENCE.json' + actual = copied / relative + else: + relative = 'compiler-cuts/review/' + ('EVIDENCE.json' if index == 5 else 'EVIDENCE-OPTIMIZED.json') + # The newer remote command already redirects its receipt outside the + # package. Give that same output a private per-run location as well. + output_index = argv.index('--output') + 1 + actual = temporary / ('legacy-normal.json' if index == 5 else 'legacy-optimized.json') + argv[output_index] = str(actual) + run(argv, temporary, command['timeout_seconds']) + compare(actual, PACKAGE / relative, elapsed=True) + print('PASS_PRESERVED_COMPILER_REPLAY ' + str(index), flush=True) + + +def additions(temporary, copied): + cuts = copied / 'compiler-intervals' + sharp = copied / 'spectral-downset' + python = [sys.executable, '-I', '-W', 'error', '-B'] + run([*python, cuts / 'audit.py'], temporary, 300) + compare(cuts / 'EVIDENCE.json', PACKAGE / 'compiler-intervals/EVIDENCE.json') + for optimized in (False, True): + flags = [sys.executable, '-I', *(['-O'] if optimized else []), '-W', 'error', '-B'] + output = temporary / ('interval-optimized.json' if optimized else 'interval-normal.json') + run([*flags, cuts / 'review/independent.py', '--source', cuts, '--output', output], temporary, 120) + compare(output, PACKAGE / 'compiler-intervals/review/EVIDENCE.json') + # This explicit path is the only adaptation to the frozen source checker. + run([*python, sharp / 'check.py', '--parent', copied, '--cuts', cuts], temporary, 60) + compare(sharp / 'EVIDENCE.json', PACKAGE / 'spectral-downset/EVIDENCE.json') + for optimized in (False, True): + flags = [sys.executable, '-I', *(['-O'] if optimized else []), '-W', 'error', '-B'] + output = temporary / ('selector-optimized.json' if optimized else 'selector-normal.json') + run([*flags, sharp / 'review/independent.py', '--candidate', sharp, + '--cuts', cuts, '--parent', copied, '--output', output], temporary, 120) + compare(output, PACKAGE / 'spectral-downset/review/EVIDENCE.json') + print('PASS_RELATIVE_INTERVAL_AND_SHARP_SELECTOR_ADDITIONS', flush=True) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + choice = parser.add_mutually_exclusive_group(required=True) + choice.add_argument('--legacy', type=int) + choice.add_argument('--additions', action='store_true') + args = parser.parse_args() + authenticate() + with TemporaryDirectory(prefix='circulant-reconciled-replay-') as directory: + temporary = Path(directory) + copied = temporary / 'package' + shutil.copytree(PACKAGE, copied) + if args.legacy is not None: + legacy(args.legacy, temporary, copied) + else: + additions(temporary, copied) + authenticate() + + +if __name__ == '__main__': + main() 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