diff --git a/research/native-coprime-grid/.gitattributes b/research/native-coprime-grid/.gitattributes new file mode 100644 index 0000000000..625449502b --- /dev/null +++ b/research/native-coprime-grid/.gitattributes @@ -0,0 +1 @@ +* -text diff --git a/research/native-coprime-grid/LICENSE b/research/native-coprime-grid/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/research/native-coprime-grid/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/native-coprime-grid/MANIFEST.json b/research/native-coprime-grid/MANIFEST.json new file mode 100644 index 0000000000..ee19e0f5e8 --- /dev/null +++ b/research/native-coprime-grid/MANIFEST.json @@ -0,0 +1,70 @@ +{ + "format": 1, + "files": [ + { + "path": ".gitattributes", + "size": 9, + "sha256": "8b9c3028d6467ff3be7c793141927841d70f47f52d0590677438f488ca154992" + }, + { + "path": "grid.py", + "size": 8097, + "sha256": "a7584f41aaf9734e1ea6ed848f305e82648562622a92a70d828167a0013b29af" + }, + { + "path": "LICENSE", + "size": 11357, + "sha256": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4" + }, + { + "path": "NOTICE.txt", + "size": 1465, + "sha256": "35d97923ccc86ac1570c692fa6e27a8ee692a2da064c43a99ded7bfe0582199f" + }, + { + "path": "PROOF.md", + "size": 10692, + "sha256": "aa02a23e16c575968f381569a33b1126003ce57e144a05262c667d80881e6bee" + }, + { + "path": "README.md", + "size": 7305, + "sha256": "c180783791bf1b43d9682d77f3811a6d564ee216c82b4e8bfc5920c7275da4c0" + }, + { + "path": "RESULT.json", + "size": 5388, + "sha256": "bd7e3cb610b2405a169bf79e258dc88772f2b6738a7a21cf014e5a5c4475e77a" + }, + { + "path": "source/tensor_plan.py", + "size": 12079, + "sha256": "474730f42fcd2bd24720af4e08c71fb51cc374c3e16b8b6d7e565900f1a9e7c3" + }, + { + "path": "source_guard.py", + "size": 1992, + "sha256": "6427c8bfdd266bdc15e8a9fe3a0e07288acc2d3b7ea0fdb06333226ef90ec7ab" + }, + { + "path": "SOURCES.json", + "size": 4019, + "sha256": "5b11f60f17ba7ba623280f64d8da394e2008db6450a6762ea9ac4abe62f339ad" + }, + { + "path": "TASK.json", + "size": 5869, + "sha256": "baf097e8e961ac4157baddb1d043e4ca01ce9b9b041709acc9f36c43812a2ddb" + }, + { + "path": "VERIFY.json", + "size": 1390, + "sha256": "7b79466ed0e947a69d9859c308e0f2b2c01a86333f42b941dcf840259f683760" + }, + { + "path": "verify.py", + "size": 7182, + "sha256": "08000b24526d9be36895203a0a68e5e1656d4ccc7b19ae04d41bccf147623113" + } + ] +} diff --git a/research/native-coprime-grid/NOTICE.txt b/research/native-coprime-grid/NOTICE.txt new file mode 100644 index 0000000000..c1afe7b257 --- /dev/null +++ b/research/native-coprime-grid/NOTICE.txt @@ -0,0 +1,7 @@ +New gcd-grid implementation, proof assembly, reference checks and package: Dugongue, with substantial OpenAI Codex assistance by one solo worker. Apache-2.0. No independent human or proof-kernel review is asserted. + +source/tensor_plan.py is an unchanged source export by Jose Manuel (jmbarrancoml), PR3935, preserved through ToikY's PR4029 archive. Original commit 240597ed313fc2854c0462b23c89dc3bae72aaf5, original path research/physical-gaussian-tensor/tensor_plan.py. Its existing header is retained. The host AST extraction/checking method follows ToikY PR4029; Tekalign (tekuuu) PR4024 supplies earlier encoded CRT-address work. + +Retain the source08/OpenAI manuscript and Douglas Colkitt repository lineage; earlier prime selection by Cinna Davis, Chafik Boukhalfa/chafreaky PR1786, and JosieElliston's audit. Credit unpaidmoon PR4142 for the loading/oddness boundary; Nick Petalas PR5149 and PR5152 for the later cutoff and product-envelope improvements. Harvey and van der Hoeven, Agarwal and Cooley, and Good and Thomas are mathematical predecessors. Their larger caller and precision contracts are not proved by this package. + +Iwaniec's Jacobsthal theorem is imported mathematical input, checked through Carl Pomerance's research exposition. No paper text is vendored. Mathlib source inspection supplied existing coprimality/CRT precedents; it is not a formal verification of these new claims. This is not an official OpenAI release or endorsement. diff --git a/research/native-coprime-grid/PROOF.md b/research/native-coprime-grid/PROOF.md new file mode 100644 index 0000000000..7e202209c9 --- /dev/null +++ b/research/native-coprime-grid/PROOF.md @@ -0,0 +1,91 @@ +# Native coprime-grid construction and exact tensorization + +This proof establishes the finite returned-object contract and an eventual polynomial setup theorem. It does not establish a new integer-multiplication exponent. All logarithmic asymptotics below concern growing input parameters; constants are independent of the target widths. + +## 1. Imported number theory and model + +Use the classical theorem of Henryk Iwaniec, *On the problem of Jacobsthal*, Demonstratio Mathematica 11 (1978), 225–232, [DOI](https://doi.org/10.1515/dema-1978-0121): there is an absolute constant C such that every interval of at least C (r log(r + 2))^2 consecutive integers contains an integer coprime to G, whenever G has r distinct prime factors. Enlarging C covers small r and integer rounding. This is an imported theorem, not reproved here. [Carl Pomerance, Coprime Matchings, section 3](https://math.dartmouth.edu/~carlp/coprime11_12rev.pdf) gives a modern use of Iwaniec's stronger interval estimate. The original publisher PDF was not retrieved successfully during this session; the attribution and bound were checked through that primary research source. No effective numerical C is extracted. + +Use a random-access machine with W = c p bits per word for a fixed sufficiently large c, unit-cost word addition, subtraction, comparison, multiplication, division/remainder and random-access memory. Signed intermediates fit in W bits. If division is not a primitive, binary long division uses O(p) of the remaining word operations and only enlarges the polynomial setup bound below. Neither the linear address-stream bound nor its recurrence uses division after setup. Python implements these algorithms as an exact reference; Python timing is not a unit-cost Word RAM timing claim. + +Take p = 1 + sum_i log2(t_i) for power-of-two target axes. Words(8 times a slightly larger integer bit bound) in the implementation is a conservative reference guard. Products of selected moduli are below product_i t_i; arithmetic used for gcd, extended gcd, square roots, bands and CRT weights has O(p) bits. For example, even a conservative bound of the square of the full product for an extended-gcd intermediate fits a constant multiple of p bits. Loop counters and addresses also fit. There is no unbounded integer packed into a single fixed-size word. + +## 2. Greedy selection lemma + +Let intervals J_i of positive integers lie below t_i, with lower endpoints at least 3, and let their lengths be at least H = ceil(C' p^2 log^2(p + 2)). There is a deterministic greedy algorithm selecting an odd s_i in J_i with pairwise gcd 1, using O(D p^3 log^2(p + 2)) native operations when division is available. + +Proof. Initially G = 2. At stage i, G = 2 product_{j s, + (2d−1) g < ((2d−1)/(3d)) t < ((3d−1)/(3d)) t < s. + +For the period guard, impose the separate sufficient premise + + target_halo + 2w ≤ 2^(ell−3). + +Since t ≥ 2^(ell−1), (1) gives s > (1−1/(3d)) 2^(ell−1) > 2^(ell−2), which is at least 2(target_halo + 2w). All three strict comparisons hold. source_guard.py executes the complete pinned method with a host Count adapter, checking the actual method's comparisons rather than an independently typed copy. Finite fixtures use halo = width = 1. They do not replace the universal argument or show any physical tape execution. + +Let T = product_i t_i and S = product_i s_i. The band gives + + T/S < (1−1/(3d))^(−(d−1)) < 3/2. + +For the last inequality, product_i(1−1/(3d)) ≥ 1−D/(3d) > 2/3. This is the predecessor bound, not a new improvement. PR5152 already supplies the sharper exp(1/3) envelope. Choosing axes very close to t_i generally fails the first guard; the verifier rejects an explicit such example. Therefore the separate near-dyadic construction in grid.build is not silently substituted into the original caller. No statement is made here about production_common, including its Gaussian or precision conditions. ∎ + +## 5. Optional near-dyadic variant + +For B = 2^k and p = 1 + Dk, greedy search downward from B−1 yields deficits δ_i = B−s_i = O(p^2 log^2(p + 2)) whenever B is sufficiently large. For Δ = sum_i δ_i < B, + + product_i s_i / B^D = product_i(1−δ_i/B) ≥ 1−Δ/B, + B^D / product_i s_i ≤ B/(B−Δ). + +This follows by induction from (1−a)(1−b) ≥ 1−a−b for a,b in [0,1]. For even k, selecting roots below 2^(k/2) and squaring gives deficits O(2^(k/2) p^2 log^2(p + 2)). In the stretched-exponential regime of section 3 the relative volume loss tends to zero. This useful standalone grid has a different gap contract: it is not accepted by all the source's production-axis guards. + +## 6. Exact CRT and Good–Thomas identity + +For any returned coprime grid put N = product_i s_i, M_i = N/s_i, and u_i = M_i^(-1) modulo s_i. Define + + a(x) = sum_i x_i M_i u_i modulo N, + b(y) = sum_i y_i M_i modulo N, + +for 0 ≤ x_i,y_i < s_i. The first map has residues x_i. The second has residues y_i M_i, a bijective coordinate rescaling because M_i is a unit modulo s_i. Both maps are bijections. + +Expand a(x)b(y). For i ≠ j, M_i M_j is divisible by N. For i = j, M_i u_i = 1 modulo s_i, so M_i^2 u_i = M_i modulo N. Therefore + + a(x)b(y) = sum_i x_i y_i M_i modulo N. (2) + +Let ζ be exp(2πi/N) and ζ_i = ζ^(M_i). Reindex the finite DFT sum by a(x); at output b(y), (2) factors its phase as product_i ζ_i^(x_i y_i). This is precisely the tensor product of the axis DFTs. No primality of s_i is used. The input and output maps are different: using a(y) as the output map is generally false. The negative control exhibits this error. The same group isomorphism proves cyclic convolution equals product-group convolution. These are classical CRT/Good–Thomas facts, supplied here with explicit conventions and a scoped executable use; they are not claimed as new algebra. ∎ + +## 7. Linear native address streams + +For the input stream use weights c_i = M_i u_i; for the output stream c_i = M_i. Both satisfy 0 < c_i < N and s_i c_i = 0 modulo N. Maintain mixed-radix digits and one current address. On each digit increment, add c_i and subtract N once if needed. When the digit rolls from s_i−1 to 0, the same addition is correct because −(s_i−1)c_i = c_i modulo N. Then carry to the next digit. + +Among N emitted positions, the number of first-coordinate changes is at most N−1; second-coordinate changes are at most N/s_1, third at most N/(s_1 s_2), and so on. Since all radices are at least 2, the total is strictly below 2N. Each change costs O(1) word operations and no division. Initialization costs O(D) after the CRT weights are prepared; Euclid and the weight construction are polynomial in p. This gives O(N + D) native stream work and O(D) metadata. Applying the stream to an array costs O(N) loads/stores, requires O(N) data memory, and relies on the model's random-access instruction. There is no free arbitrary permutation or tape simulation hidden in this statement. + +The coordinates=True testing option copies D digits per emitted item and is deliberately excluded from the linear stream bound. The reference word counter records arithmetic calls, not every control instruction or interpreter cost. ∎ + +## 8. Exact scope of the result + +Sections 2–4 supply a sufficient algorithm for guard-safe coprime axis selection. Sections 6–7 supply an exact native tensorization/permutation contract. Together they remove primality testing from this specific setup and CRT interface, including an all-composite construction. They do not replace any other theorem that may rely on prime axes, establish numerical Gaussian error bounds, implement an efficient axis transform, admit a native supplier, or recover the integer product with a smaller recurrence. + +In particular, polynomial setup in log N versus an inherited subleading setup does not change the dominant exponent. A new κ needs a changed dominant paid recurrence and a complete exact or controlled-precision caller. No such conclusion is derived from this package. diff --git a/research/native-coprime-grid/README.md b/research/native-coprime-grid/README.md new file mode 100644 index 0000000000..85a3c8d7a1 --- /dev/null +++ b/research/native-coprime-grid/README.md @@ -0,0 +1,50 @@ +# Prime-free native coprime tensor grids + +A scoped constructive Word RAM result: deterministically construct odd pairwise-coprime axes in the existing guard-safe bands, including an all-composite option, without primality testing or a Turing-machine simulation. Supply exact CRT input/output streams and a Good–Thomas factorization with the two different address conventions. This is a reference implementation and mathematical proof, not an emitted native instruction trace or a complete multiplication algorithm. + +**No larger κ is established.** The donor requested a substantial Word RAM advance. This session does not meet that target. Faster grid setup alone does not improve κ, since the predecessor setup was already subleading. The reusable contribution is a different axis-selection algorithm for a precisely bounded contract; no change to selected-result metadata is proposed. + +## Constructive result + +Let D = d − 1, with targets t_i in {2^ell, 2^(ell−1)}. For each target choose an odd integer in + + t_i (1 − 1/(3d)) < s_i ≤ t_i (1 − 1/(4d)). + +Repeated gcd tests against twice the product of earlier choices select pairwise-coprime axes. Iwaniec's classical Jacobsthal bound guarantees polynomial setup in p = 1 + sum_i log2(t_i), once each selection interval has polynomial length in p. In the usual stretched-exponential axis regime, this holds eventually. The same construction on square roots gives guaranteed composite axes and still succeeds eventually. No explicit finite analytic threshold is claimed; finite requests fail explicitly if an interval is exhausted. + +The band satisfies the **complete pinned `production_axis` method**, provided the separate period premise in PROOF.md holds. It does not establish `production_common`, Gaussian approximation, precision, or the rest of the original caller. Actual guard execution is a host semantic adaptation of the pinned source, not execution of the physical tape code. + +The two CRT streams use O(N + D) word operations for N = product_i s_i, after polynomial setup, with O(D) metadata. Optional copied coordinate tuples are test-only and cost O(D) each. Materializing or applying the permutation uses O(N) additional data memory. The theorem assumes O(p)-bit native words and explicitly charges setup and memory access. + +## Evidence and replay + +Python 3.12, standard library only, from the repository root: + +```sh +python3 -I -B research/native-coprime-grid/verify.py +python3 -I -O -B research/native-coprime-grid/verify.py +python3 -B scripts/research_package.py --package research/native-coprime-grid +``` + +The direct commands also work from a Git-free export. RESULT.json is generated by the verifier. Checks cover six ordinary grids, four guaranteed-composite grids, six guard-bound band fixtures, 2,200 permutation entries in each direction, 1,600 exact phase identities, 48 sparse convolutions, and all 225 outputs of a modular DFT on composite axes 9 and 25. The wrong output-address convention produces 645 counterexamples. Ten invalid-input/contract controls reject. These finite checks corroborate the separate proof; they do not prove the imported analytic theorem or an asymptotic multiplication bound. Word counters cover displayed arithmetic only, not every loop/control instruction. + +## Overlap and credit + +The band and source-binding method are ToikY's [#4029](https://github.com/CrocSwap/integer-mult-bounds/pull/4029). Jose Manuel's [#3935](https://github.com/CrocSwap/integer-mult-bounds/pull/3935) supplies the pinned TensorPlan source; Tekalign's [#4024](https://github.com/CrocSwap/integer-mult-bounds/pull/4024) precedes these CRT streams. Classical CRT/Good–Thomas algebra and Euclidean gcd are not new results. Nick Petalas's [#5149](https://github.com/CrocSwap/integer-mult-bounds/pull/5149) lowers the prime-supply cutoff; [#5152](https://github.com/CrocSwap/integer-mult-bounds/pull/5152) already sharpens the same band's product loss. This package does not claim those improvements or a new padding envelope. + +The new scoped implementation uses Jacobsthal-guided gcd selection, including square moduli, in those existing bands. The review covered 200 recently updated PR records, targeted searches, relevant source notes, and two later prime-band PR bodies. It was not an exhaustive historical diff or literature audit; absence of a matching search result does not establish project-wide or mathematical novelty. The shared DAG returned source-only coprimality declarations, and Mathlib's Nat Chinese remainder source was inspected. No new Lean proof or kernel check was performed. See SOURCES.json, PROOF.md and NOTICE.txt. + +## Why this does not yet meet the larger-κ target + +At the frozen main, the selected conditional value is 0.003027288235. [#5554](https://github.com/CrocSwap/integer-mult-bounds/pull/5554) analyzes the specific rank-eight productive-helper path and reports essentially exhausted controller-only headroom at the selected local bill; it is not a universal ceiling on other architectures. [#5561](https://github.com/CrocSwap/integer-mult-bounds/pull/5561) proposes 0.0030814243 under additional free helper-start/final-frame assumptions. Its claim was read, not independently replayed here. + +The much larger complex-only headline in [#4629](https://github.com/CrocSwap/integer-mult-bounds/pull/4629) is not automatically a complete native multiplication bound. The exact changed charts, controller interface and native assembly must be joined before removing a BIT bottleneck yields that exponent. [#4694](https://github.com/CrocSwap/integer-mult-bounds/pull/4694) and [#4698](https://github.com/CrocSwap/integer-mult-bounds/pull/4698) supply constructive coupled interfaces but explicitly retain unpaid physical-consumer obligations. This package neither repairs nor refutes their large-exponent route. + +The existing native Gaussian adapter recount already includes forward chirp convolutions, banded inverse factor reuse and linear address metadata. Rebranding those ideas would not be a new route. Likewise, [#5479](https://github.com/CrocSwap/integer-mult-bounds/pull/5479) supplies a production-scale conditioning result, not a complete native inverse algorithm. These distinctions motivated a new axis-selection experiment, but its successful setup/CRT proof still leaves the dominant transform unchanged. The next budget should go to a complete changed transform or an affordable consumer, not further optimization of this selector. + +## Open next questions + +1. Can composite axes be used throughout a complete native resampling/recovery caller, including every prime-only hypothesis? Start with the pinned production-common and numerical contracts. The exact CRT result here covers none of their error bounds. +2. Can a direct native transform reduce the repeated dominant work by a fixed power of the relevant logarithm, with all precision, random-access and recovery costs paid? That is the missing route to a substantial κ improvement. A faster axis selector or constant-factor transform saving is insufficient. + +Structured scope and stop rules are in TASK.json. Dugongue, with substantial OpenAI Codex assistance from one solo worker; Apache-2.0. No independent human or formal-kernel acceptance is claimed. diff --git a/research/native-coprime-grid/RESULT.json b/research/native-coprime-grid/RESULT.json new file mode 100644 index 0000000000..dd53a87165 --- /dev/null +++ b/research/native-coprime-grid/RESULT.json @@ -0,0 +1,239 @@ +{ + "exact_modular_dft_outputs": 225, + "grid_fixtures": [ + { + "arithmetic_operations": 148, + "axes": 4, + "candidates": 11, + "k": 8, + "maximum_deficit": 9, + "moduli_sha256": "204b8bb455905db2fcdd4aac1b7206e7787bf88d4aada0fc22bce2e8f9a21920", + "peak_bits": 33, + "sum_deficits": 18, + "word_bits": 272 + }, + { + "arithmetic_operations": 1276, + "axes": 8, + "candidates": 67, + "k": 12, + "maximum_deficit": 35, + "moduli_sha256": "4e6cac78e239c313274816e34810cc2abe3ba1b81dda6229b7f25bcfda6a3e30", + "peak_bits": 97, + "sum_deficits": 126, + "word_bits": 784 + }, + { + "arithmetic_operations": 6901, + "axes": 16, + "candidates": 300, + "k": 16, + "maximum_deficit": 87, + "moduli_sha256": "fccf2b1d5721dd485cb7432e2a9d3ee4eeade07bbf02998ea1af16cddcb46f69", + "peak_bits": 257, + "sum_deficits": 584, + "word_bits": 2064 + }, + { + "arithmetic_operations": 43960, + "axes": 32, + "candidates": 1169, + "k": 32, + "maximum_deficit": 155, + "moduli_sha256": "1fd69b2aec081714c6a88f515be524cc7699cb54862f75da98f9a019b2562d79", + "peak_bits": 1025, + "sum_deficits": 2306, + "word_bits": 8208 + }, + { + "arithmetic_operations": 457192, + "axes": 64, + "candidates": 5936, + "k": 64, + "maximum_deficit": 405, + "moduli_sha256": "365a17664e2130cd46cbe46ef0a1094a2203f0f5c4bee0c70636386cb6f47f03", + "peak_bits": 4097, + "sum_deficits": 11808, + "word_bits": 32784 + }, + { + "arithmetic_operations": 4458259, + "axes": 128, + "candidates": 27851, + "k": 128, + "maximum_deficit": 957, + "moduli_sha256": "a4d29dd7b051055f2eb76f7bfd4a00591ad3a286504004c79fa7eb83bd2632e5", + "peak_bits": 16385, + "sum_deficits": 55574, + "word_bits": 131088 + } + ], + "guaranteed_composite_fixtures": [ + { + "axes": 4, + "k": 16, + "maximum_deficit": 4527, + "sum_deficits": 9100 + }, + { + "axes": 16, + "k": 32, + "maximum_deficit": 11395695, + "sum_deficits": 76513648 + }, + { + "axes": 32, + "k": 64, + "maximum_deficit": 1331439837735, + "sum_deficits": 19808388928048 + }, + { + "axes": 64, + "k": 128, + "maximum_deficit": 14941862699704736644935, + "sum_deficits": 435638308044724767831472 + } + ], + "new_kappa_claimed": false, + "permutation_entries_each_direction": 2200, + "phase_checks": 1600, + "rejecting_controls": 10, + "scope": "exact reference algorithms; no full multiplier, native instruction trace or Lean audit", + "source_bound_band_fixtures": [ + { + "arithmetic_operations": 54, + "candidates": 4, + "ell": 20, + "flags": [ + 1, + 0, + 1 + ], + "moduli": [ + 983039, + 491519, + 983037 + ], + "peak_bits": 60, + "squares": false, + "word_bits": 528 + }, + { + "arithmetic_operations": 210, + "candidates": 4, + "ell": 20, + "flags": [ + 1, + 0, + 1 + ], + "moduli": [ + 982081, + 491401, + 978121 + ], + "peak_bits": 31, + "squares": true, + "word_bits": 528 + }, + { + "arithmetic_operations": 86, + "candidates": 6, + "ell": 20, + "flags": [ + 0, + 1, + 0, + 1 + ], + "moduli": [ + 498073, + 996147, + 498071, + 996145 + ], + "peak_bits": 79, + "squares": false, + "word_bits": 688 + }, + { + "arithmetic_operations": 348, + "candidates": 8, + "ell": 20, + "flags": [ + 0, + 1, + 0, + 1 + ], + "moduli": [ + 497025, + 994009, + 494209, + 982081 + ], + "peak_bits": 40, + "squares": true, + "word_bits": 688 + }, + { + "arithmetic_operations": 430, + "candidates": 25, + "ell": 28, + "flags": [ + 1, + 0, + 1, + 1, + 0, + 1, + 0, + 1 + ], + "moduli": [ + 260978915, + 130489457, + 260978913, + 260978911, + 130489453, + 260978909, + 130489451, + 260978903 + ], + "peak_bits": 222, + "squares": false, + "word_bits": 1864 + }, + { + "arithmetic_operations": 965, + "candidates": 25, + "ell": 28, + "flags": [ + 1, + 0, + 1, + 1, + 0, + 1, + 0, + 1 + ], + "moduli": [ + 260919409, + 130484929, + 260854801, + 260790201, + 130393561, + 260725609, + 130256569, + 260661025 + ], + "peak_bits": 112, + "squares": true, + "word_bits": 1864 + } + ], + "sparse_convolution_cases": 48, + "status": "PASS_NATIVE_COPRIME_GRID", + "wrong_dual_witnesses": 645 +} diff --git a/research/native-coprime-grid/SOURCES.json b/research/native-coprime-grid/SOURCES.json new file mode 100644 index 0000000000..84c997c719 --- /dev/null +++ b/research/native-coprime-grid/SOURCES.json @@ -0,0 +1,112 @@ +{ + "schema_version": 1, + "base_commit": "5e0052ca0aa3036a3afa8b0438927377c8d97d53", + "files": [ + { + "path": "docs/research/agent-task-catalog.json", + "usage": "provenance", + "git_blob": "f126dd2e2dad2b669e75d1d0d0bd05c600725602", + "sha256": "f7a48bfa2659b88378282a8eee7d9fe52cdf505594124c4d1686b58510fffd72" + }, + { + "path": "certificates/selected-result.json", + "usage": "provenance", + "git_blob": "fc3d4ba105e1f097d0d7d051a308281e86ab1446", + "sha256": "66974efdced4083c00025f97d95d83909a226cdf801edb9301c195c6641f6903" + }, + { + "path": "research/many-axis-prime-supply/source/PR3935-tensor_plan.py", + "usage": "provenance", + "git_blob": "239caba2d2ccf2640c36d377949df3fb6a920cf0", + "sha256": "474730f42fcd2bd24720af4e08c71fb51cc374c3e16b8b6d7e565900f1a9e7c3" + } + ], + "vendored_source": { + "local": "source/tensor_plan.py", + "canonical_archive": "research/many-axis-prime-supply/source/PR3935-tensor_plan.py", + "original_pr": 3935, + "original_commit": "240597ed313fc2854c0462b23c89dc3bae72aaf5", + "original_path": "research/physical-gaussian-tensor/tensor_plan.py", + "sha256": "474730f42fcd2bd24720af4e08c71fb51cc374c3e16b8b6d7e565900f1a9e7c3" + }, + "literature": [ + { + "author": "Henryk Iwaniec", + "title": "On the problem of Jacobsthal", + "year": 1978, + "url": "https://doi.org/10.1515/dema-1978-0121", + "use": "Imported asymptotic interval bound; original full text not retrieved." + }, + { + "author": "Carl Pomerance", + "title": "Coprime Matchings", + "url": "https://math.dartmouth.edu/~carlp/coprime11_12rev.pdf", + "use": "Primary research exposition of the Iwaniec estimate, section 3." + } + ], + "formal_precedents": [ + { + "repository": "leanprover-community/mathlib4", + "path": "Mathlib/Data/Nat/ChineseRemainder.lean", + "declarations": [ + "Nat.chineseRemainderOfList", + "Nat.chineseRemainderOfList_lt_prod", + "Nat.chineseRemainderOfList_modEq_unique" + ], + "status": "Source inspection only; no Lean replay or claim of new formal result." + } + ], + "overlap": { + "recent_pr_records": 200, + "searches": [ + "Word RAM", + "batching", + "quotient", + "coprime", + "Jacobsthal", + "prime-free" + ], + "coverage": "Bodies and targeted source notes, not all diffs or exhaustive historical coverage.", + "final_main": "5e0052ca0aa3036a3afa8b0438927377c8d97d53", + "later_prime_band_prs": [ + { + "number": 5149, + "head": "ef5136a007437627d140698bdd1fd052489d8692", + "scope": "Read PR body; predecessor proof replay not rerun." + }, + { + "number": 5152, + "head": "91a444590bdf7547903c16873064e6398e55f9d3", + "scope": "Read PR body; predecessor proof replay not rerun." + } + ], + "novelty": "New scoped implementation proposed; neither world novelty nor exhaustive project novelty is established.", + "candidate_heads": [ + { + "pr": 5554, + "head": "18c1770246340e9f4aaac5a9ebd712e23498d0a3", + "status": "Body/intake read; complete scientific replay not rerun." + }, + { + "pr": 5561, + "head": "452d27dde67ee9f772dbbd3be129db97a8ecb9c1", + "status": "Body/intake read; complete scientific replay not rerun." + }, + { + "pr": 5479, + "head": "299f129800f3045cc6fafba8e63ad9890aadfe9e", + "status": "Body/intake read; complete scientific replay not rerun." + }, + { + "pr": 5467, + "head": "6c768fb1df95fd5ee49a9d9ac74f1fa97b9cabe6", + "status": "Body/intake read; complete scientific replay not rerun." + }, + { + "pr": 5466, + "head": "18541b5cfb34823cdcb6f1b66465b088dc24933f", + "status": "Body/intake read; complete scientific replay not rerun." + } + ] + } +} diff --git a/research/native-coprime-grid/TASK.json b/research/native-coprime-grid/TASK.json new file mode 100644 index 0000000000..faebaa9ef2 --- /dev/null +++ b/research/native-coprime-grid/TASK.json @@ -0,0 +1,96 @@ +{ + "schema_version": 1, + "task_id": "supplier-boundary-audit", + "original_card": { + "id": "supplier-boundary-audit", + "question": "Can the #4088 four-provider dispatch satisfy the complete ordinary/outer admission contract?", + "starting_points": [ + "docs/research/research-family-status.md", + "certificates/selected-result.json", + "research/staged544-mixed-fourth-entry/README.md", + "research/scatter-boundary-decision/README.md" + ], + "methods": [ + "Trace one hypothesis through the source, checker and complete caller.", + "Construct one semantically invalid but superficially well-formed fixture and test rejection." + ], + "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_baseline.py" + ], + "expected": "PASS_RESEARCH_BASELINE_BINDINGS_ONLY", + "inspect": "Read #4088 Scope and Open next questions: local words, native receipts and literal fill do not include a rerun of the mixed four-provider ordinary/outer engine. #3801 is the newer scatter-boundary decision; do not restart #2977 as if untouched.", + "scope": "Source-binding orientation only; no scientific replay, theorem acceptance or supplier admission. Budget any heavy replay separately." + }, + "first_experiment": "Pin the provider registry, four native source closures and dispatch. Make a bounded acceptance coverage map or one registry adapter preserving every inherited admission predicate and rejection control (including an omitted fourth provider). Record remaining ordinary/outer obligations and a resource estimate before heavy execution. Stop at unresolved source/caller dependencies; no selected-result promotion from a local pass.", + "bottleneck_link": "Closing a current acceptance gap or proof obligation strengthens reliability even without changing kappa.", + "allowed_variations": [ + "One provider-registry, dispatch, native-closure or admission-predicate obligation; separate branches must name distinct coverage." + ], + "scope_change_triggers": [ + "Reporting the historical timing-only diagnostic as a new current acceptance bug.", + "Calling a malformed mutant a failure of the selected construction, or importing an opt-in repair without testing the exporter boundary.", + "Running another root enclosure instead of validating dispatch or weakening an inherited predicate to make mixed admission pass." + ], + "overlap_terms": [ + "owner boundary", + "bridge omission", + "hosting", + "2977", + "scatter export", + "duplicate index", + "parity semantics", + "4088", + "3801", + "staged544-mixed-fourth-entry", + "scatter-boundary-decision" + ], + "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_status": "changed", + "scope_change_reason": "Explicit donor assignment: investigate a substantially stronger native Word RAM route, solo; not the historical four-provider card.", + "actual_scope": "Construct guard-safe pairwise-coprime and guaranteed-composite axes by gcd, then exact native CRT streams. Partial reusable result, not the requested kappa improvement.", + "bottleneck_link": "Changes the axis-selection mechanism; does not reduce the dominant multiplier recurrence.", + "time_budget_minutes": 60, + "outcome": "partial", + "stop_rule": "Stop after this bounded sufficient construction and replay; do not iterate small padding constants or claim setup improves kappa.", + "evidence": "Proof with imported Jacobsthal theorem; source-bound guard execution and exact CRT/DFT/convolution controls.", + "author": "Dugongue", + "ai_assistance": "Substantial OpenAI Codex assistance; one solo worker.", + "base_commit": "5e0052ca0aa3036a3afa8b0438927377c8d97d53", + "new_kappa_claimed": false, + "open_questions": [ + { + "question": "Admit composite axes throughout a complete native caller.", + "why_it_matters": "The exact grid and CRT contract does not pay or prove resampling and recovery.", + "first_step": "Trace prime-only hypotheses through production_common and the numerical assembly.", + "blocked_by": "No complete composite-axis numerical caller or native supplier supplied here." + }, + { + "question": "Reduce the dominant native transform recurrence by a fixed logarithmic power.", + "why_it_matters": "This is needed for a substantial kappa gain; setup is already subleading.", + "first_step": "Derive a fully paid recurrence before implementing a new transform.", + "blocked_by": "No fixed-power saving for the complete native transform has been established." + } + ] +} diff --git a/research/native-coprime-grid/VERIFY.json b/research/native-coprime-grid/VERIFY.json new file mode 100644 index 0000000000..8474aad7d0 --- /dev/null +++ b/research/native-coprime-grid/VERIFY.json @@ -0,0 +1,46 @@ +{ + "schema_version": 1, + "status": "ready", + "python": "3.12", + "requirements": [], + "inputs": [], + "commands": [ + { + "argv": [ + "{python}", + "-I", + "-B", + "{package}/verify.py" + ], + "checks": "Exact grid, source-bound axis guards, CRT, modular DFT and convolution checks; no kappa claim.", + "timeout_seconds": 120 + }, + { + "argv": [ + "{python}", + "-I", + "-O", + "-B", + "{package}/verify.py" + ], + "checks": "Optimized replay preserves explicit rejection guards and generated receipt.", + "timeout_seconds": 120 + } + ], + "package_local_inputs": [ + "research/native-coprime-grid/.gitattributes", + "research/native-coprime-grid/LICENSE", + "research/native-coprime-grid/MANIFEST.json", + "research/native-coprime-grid/NOTICE.txt", + "research/native-coprime-grid/PROOF.md", + "research/native-coprime-grid/README.md", + "research/native-coprime-grid/RESULT.json", + "research/native-coprime-grid/SOURCES.json", + "research/native-coprime-grid/TASK.json", + "research/native-coprime-grid/VERIFY.json", + "research/native-coprime-grid/grid.py", + "research/native-coprime-grid/source/tensor_plan.py", + "research/native-coprime-grid/source_guard.py", + "research/native-coprime-grid/verify.py" + ] +} diff --git a/research/native-coprime-grid/grid.py b/research/native-coprime-grid/grid.py new file mode 100644 index 0000000000..a8ada7d592 --- /dev/null +++ b/research/native-coprime-grid/grid.py @@ -0,0 +1,195 @@ +"""Native coprime tensor-grid reference model. Apache-2.0. +Dugongue, with substantial OpenAI Codex assistance. +Counters concern displayed arithmetic, not an emitted RAM instruction trace. +""" +from math import prod + + +def need(ok, message): + if not ok: + raise ValueError(message) + + +class Words: + def __init__(self, width): + need(type(width) is int and width >= 2, 'invalid word width') + self.width = width + self.limit = (1 << (width - 1)) - 1 + self.operations = 0 + self.peak = 0 + + def keep(self, value, cost=1): + need(type(value) is int and abs(value) <= self.limit, 'word overflow') + self.operations += cost + self.peak = max(self.peak, abs(value).bit_length()) + return value + + def gcd(self, a, b): + a, b = self.keep(a), self.keep(b) + while b: + a, b = b, self.keep(a % b, 3) # DIV, MUL, SUB + return a + + def inverse(self, a, modulus): + need(modulus > 1 and 0 < a < modulus, 'inverse domain') + old_r, r, old_x, x = modulus, a, 0, 1 + while r: + q = self.keep(old_r // r) + old_r, r = r, self.keep(old_r - self.keep(q*r)) + old_x, x = x, self.keep(old_x - self.keep(q*x)) + need(old_r == 1, 'non-coprime inverse') + return self.keep(old_x % modulus, 3) + + +def build(k, count, words=None, candidate_budget=None): + need(type(k) is int and k >= 2 and type(count) is int and count >= 1, + 'invalid grid shape') + if candidate_budget is not None: + need(type(candidate_budget) is int and candidate_budget >= 0, 'invalid budget') + w = words or Words(8*(k*count + 2)) + bound = w.keep(1 << k) + exclusion = 2 + moduli = [] + trials = 0 + for _ in range(count): + candidate = bound - 1 + while candidate > 1: + if candidate_budget is not None and trials >= candidate_budget: + raise ValueError('candidate budget exhausted; no completed grid') + trials += 1 + if w.gcd(candidate, exclusion) == 1: + moduli.append(candidate) + exclusion = w.keep(exclusion*candidate) + break + candidate = w.keep(candidate-2) + else: + raise ValueError('not enough admissible moduli below target') + return moduli, {'candidates': trials, 'arithmetic_operations': w.operations, + 'peak_bits': w.peak, 'word_bits': w.width, + 'maximum_deficit': max(bound-s for s in moduli), + 'sum_deficits': sum(bound-s for s in moduli)} + + +class CRTGrid: + def __init__(self, moduli, words=None): + need(bool(moduli) and all(type(s) is int and s >= 3 and s % 2 for s in moduli), + 'odd moduli >= 3 required') + self.moduli = tuple(moduli) + bits = sum(s.bit_length() for s in moduli) + 2 + self.words = w = words or Words(8*bits) + product = 1 + for s in moduli: + need(w.gcd(product, s) == 1, 'moduli must be pairwise coprime') + product = w.keep(product*s) + self.size = product + self.input_steps = [] + self.output_steps = [] + for s in moduli: + cofactor = w.keep(product//s) + inverse = w.inverse(w.keep(cofactor % s, 3), s) + self.input_steps.append(w.keep(cofactor*inverse)) + self.output_steps.append(cofactor) + + def indices(self, dual=False, coordinates=False): + """Stream addresses; copying d coordinates is an optional test-only cost.""" + digits = [0]*len(self.moduli) + steps = self.output_steps if dual else self.input_steps + address = 0 + changes = 0 + for serial in range(self.size): + yield (address, tuple(digits)) if coordinates else address + if serial + 1 == self.size: + break + for axis, radix in enumerate(self.moduli): + digits[axis] += 1 + changes += 1 + address = self.words.keep(address+steps[axis]) + if address >= self.size: + address = self.words.keep(address-self.size) + if digits[axis] < radix: + break + digits[axis] = 0 + self.last_changes = changes + + def from_coordinates(self, coordinates, dual=False): + need(len(coordinates) == len(self.moduli) and + all(type(x) is int and 0 <= x < s for x, s in zip(coordinates,self.moduli)), + 'coordinate domain') + steps = self.output_steps if dual else self.input_steps + total = 0 + for x, c in zip(coordinates, steps): + term = self.words.keep(x*c) + total = self.words.keep((total+term) % self.size, 4) + return total + + +def volume_certificate(k, moduli): + bound = 1 << k + need(all(type(s) is int and 1 < s < bound for s in moduli), 'volume domain') + deficit = sum(bound-s for s in moduli) + need(deficit < bound, 'simple product lower bound is nonpositive') + source = prod(moduli) + target = bound**len(moduli) + need(source*bound >= target*(bound-deficit), 'product lower bound failed') + return {'source_volume': source, 'target_volume': target, + 'inflation_upper_numerator': bound, 'inflation_upper_denominator': bound-deficit} + + +def build_squares(k, count): + """Guaranteed composite axes below 2**k; k must be even.""" + need(type(k) is int and k >= 4 and k % 2 == 0, 'even exponent >= 4 required') + roots, stats = build(k//2, count) + w=Words(8*(k*count+2)) + moduli=[w.keep(a*a) for a in roots] + stats={'root_construction':stats,'squaring_operations':w.operations, + 'maximum_deficit':max((1<= 0, 'square-root domain') + low, high = 0, words.keep(1 << ((value.bit_length()+1)//2)) + while low < high: + middle=words.keep((low+high+1)//2) + if words.keep(middle*middle) <= value: + low=middle + else: + high=middle-1 + return low + + +def build_bands(targets, squares=False, candidate_budget=None): + """Use the actual PR4029 guard-safe intervals; optionally only composites.""" + need(bool(targets) and all(type(t) is int and t >= 4 and t&(t-1)==0 for t in targets), + 'power-of-two targets required') + need(type(squares) is bool, 'boolean square mode required') + if candidate_budget is not None: + need(type(candidate_budget) is int and candidate_budget >= 0, 'invalid budget') + d=len(targets)+1 + words=Words(8*(sum(t.bit_length() for t in targets)+4)) + excluded=2;moduli=[];witnesses=[];trials=0 + for target in targets: + lower=words.keep(target*(3*d-1)//(3*d)+1) + upper=words.keep(target*(4*d-1)//(4*d)) + if squares: + low=root_floor(lower,words) + if low*low= max(3,low): + if candidate_budget is not None and trials >= candidate_budget: + raise ValueError('candidate budget exhausted; no completed grid') + trials+=1 + if words.gcd(candidate,excluded)==1: + excluded=words.keep(excluded*candidate) + modulus=words.keep(candidate*candidate) if squares else candidate + moduli.append(modulus);witnesses.append(candidate) + break + candidate=words.keep(candidate-2) + else: + raise ValueError('guard-safe interval exhausted') + return moduli, witnesses, {'candidates':trials,'arithmetic_operations':words.operations, + 'peak_bits':words.peak,'word_bits':words.width} diff --git a/research/native-coprime-grid/source/tensor_plan.py b/research/native-coprime-grid/source/tensor_plan.py new file mode 100644 index 0000000000..239caba2d2 --- /dev/null +++ b/research/native-coprime-grid/source/tensor_plan.py @@ -0,0 +1,249 @@ +"""Encoded global tensor shape, common Gaussian policy and restoration guard.""" +from tensor_sources import active +active() +from cardinal_counts import Count, positive +from compact_counts import read_fixed, write_fixed +from encoded import compare, subtract +from expansion_geometry import ProductionBlock +from expansion_records import Fields +from gaussian_rationals import read_count, write_count +from ring_words import power_two +from router_metadata import ceiling_log, indices, owned +from twiddle_setup import quotient +from words import BLANK, need + + +def band(precision, u): + with owned(Count(precision)) as (numerator,): + numerator.multiply_small(16) + with owned(quotient(numerator, u, True)) as (target,): + root = Count.literal(0) + try: + while True: + with owned(Count.product(root, root)) as (square,): + if compare(square, target) >= 0: + break + root.increment() + root.increment() + root.increment() + return root + except BaseException: + root.close() + raise + + +class Policy(Fields): + def __init__(self, p, alpha): + super().__init__() + try: + self.keep("block", ProductionBlock(p, alpha)) + for name in ("P", "sigma", "radius"): + self.keep(name, Count(getattr(self.block, name))) + with owned(Count.product(p, p)) as (square,): + self.keep("halo", Count.product(square, p)) + self.halo.multiply_small(4096) + with owned(Count.product(square, square)) as (fourth,): + with owned(Count.product(fourth, fourth)) as (eighth,): + self.keep("inner_bits", ceiling_log(eighth)) + self.keep("expansion_capacity", power_two(self.inner_bits)) + self.keep("w", band(p, self.block.u)) + except BaseException: + self.close() + raise + + +class TensorHeader(Fields): + names = ("version", "mode", "p", "ell", "axes", "alpha", "inner_bits", "P", + "sigma", "radius", "expansion_capacity", "halo", "w") + + def __init__(self, page): + super().__init__() + try: + for name in self.names: + self.keep(name, read_count(page)) + with owned(Count.literal(1)) as (one,): + need(compare(self.version, one) == 0 and compare(self.mode, one) <= 0, + "tensor catalogue version and production mode") + except BaseException: + self.close() + raise + + @classmethod + def dump(cls, plan, page): + for name in cls.names: + write_count(getattr(plan, name), page) + + +class AxisRow(Fields): + names = ("s", "t", "width", "tiles") + + def __init__(self, source): + super().__init__() + try: + for name in self.names: + self.keep(name, read_count(source)) + except BaseException: + self.close() + raise + + +class TensorPlan(Fields): + """Common policy plus the complete source words and target-axis flags.""" + def __init__(self, sources, flags, axes, ell, p, alpha, inner_bits, P, sigma, + radius, expansion_capacity, halo, w, factory, production=False): + super().__init__() + self.sources = self.flags = self.axis_rows = None + try: + need(type(production) is bool, "compiled tensor production policy") + self.keep("version", Count.literal(1)) + self.keep("mode", Count.literal(int(production))) + for name, value in (("p", p), ("ell", ell), ("axes", axes), ("alpha", alpha), + ("inner_bits", inner_bits), ("P", P), ("sigma", sigma), + ("radius", radius), ("expansion_capacity", expansion_capacity), + ("halo", halo), ("w", w)): + self.keep(name, Count(value)) + if name != "sigma": + positive(value) + with owned(Count.literal(16), Count.literal(2)) as (sixteen, two): + need(compare(p, sixteen) >= 0 and compare(ell, two) >= 0 and compare(ell, p) < 0, + "complete tensor chirp precision and exponent") + need(compare(alpha, two) >= 0, "complete tensor integer alpha") + need(compare(P, p) >= 0, "tensor work grid covers target grid") + self.keep("dimensions", Count(axes)) + self.dimensions.increment() + self.keep("d", Count(self.dimensions)) + self.d.increment() + self.keep("L", power_two(inner_bits)) + self.keep("u", Count.product(alpha, alpha)) + self.keep("target_halo", Count(halo)) + self.target_halo.multiply_small(2) + self.target_halo.add(self.L) + with owned(Count(p)) as (scaled,): + scaled.multiply_small(32) + self.keep("j", ceiling_log(scaled)) + with owned(Count(self.u)) as (scale,): + scale.multiply_small(2) + scale.add(self.j) + scale.increment() + self.keep("gamma", Count.product(self.dimensions, scale)) + self.keep("component_bits", Count(p)) + self.component_bits.increment() + self.component_bits.increment() + self.keep("record_bits", Count(self.component_bits)) + self.record_bits.multiply_small(2) + self.keep("source_product", Count.literal(1)) + self.keep("address_bits", Count.literal(0)) + self.sources, self.flags, self.axis_rows = factory(), factory(), factory() + sources.rewind() + flags.rewind() + for index in indices(self.dimensions): + flag = 1 if compare(index, axes) == 0 else flags.read() + need(flag in (0, 1), "complete tensor target flags") + if compare(index, axes) < 0: + self.flags.append(flag) + flags.step(1) + with owned(Count.literal(1)) as (one,): + with owned(Count(ell) if flag else subtract(ell, one)) as (width,): + need(compare(width, inner_bits) > 0, "at least two complete target tiles per axis") + with owned(read_fixed(sources, ell)) as (s,): + positive(s) + need(s.read() == 1, "odd original tensor source axis") + with owned(power_two(width), Count(s)) as (t, twice_s): + twice_s.multiply_small(2) + need(compare(s, t) < 0 and compare(t, twice_s) < 0, "near-one original tensor axis") + with owned(subtract(width, inner_bits)) as (coarse_width,): + with owned(power_two(coarse_width)) as (tiles,): + for value in (s, t, width, tiles): + write_count(value, self.axis_rows) + write_fixed(s, self.sources, ell) + following = Count.product(self.source_product, s) + self.source_product.close() + self.fields["source_product"] = following + self.address_bits.add(width) + if production: + self.production_axis(s, t) + need(sources.read() == flags.read() == BLANK, "complete tensor source words and flags") + for tape in (self.sources, self.flags, self.axis_rows): + tape.rewind() + self.keep("target_product", power_two(self.address_bits)) + self.keep("outer_bits", subtract(self.address_bits, ell)) + with owned(Count.literal(13)) as (margin,): + with owned(Count(self.outer_bits)) as (minimum,): + minimum.add(margin) + need(compare(p, minimum) >= 0, "complete chirp p-A margin") + self.keep("inner_address_bits", Count.product(self.dimensions, inner_bits)) + self.keep("coarse_address_bits", subtract(self.address_bits, self.inner_address_bits)) + self.keep("coarse_product", power_two(self.coarse_address_bits)) + if production: + self.production_common() + except BaseException: + self.close() + raise + finally: + sources.rewind() + flags.rewind() + + def production_axis(self, s, t): + with owned(subtract(t, s)) as (gap,): + with owned(Count.product(self.d, gap)) as (lower,): + lower.multiply_small(4) + need(compare(lower, s) > 0, "production tensor strict lower ratio") + with owned(Count(self.d), Count.literal(1)) as (twice_d, one): + twice_d.multiply_small(2) + with owned(subtract(twice_d, one)) as (factor,): + with owned(Count.product(factor, gap)) as (upper,): + need(compare(upper, s) < 0, "production tensor strict upper ratio") + with owned(Count(self.target_halo), Count(self.w)) as (required, bands): + bands.multiply_small(2) + required.add(bands) + required.multiply_small(2) + need(compare(s, required) > 0, "production tensor period exceeds paired halo") + + def production_common(self): + with owned(Policy(self.p, self.alpha)) as (expected,): + for name in ("P", "sigma", "radius", "inner_bits", "expansion_capacity", "halo", "w"): + need(compare(getattr(self, name), getattr(expected, name)) == 0, + "exact production tensor Gaussian policy") + with owned(Count(self.p)) as (eight_p,): + eight_p.multiply_small(8) + with owned(ceiling_log(eight_p)) as (minimum,): + need(compare(self.u, minimum) >= 0, "production tensor logarithmic concentration") + with owned(Count.product(self.u, self.d), Count(self.w)) as (weighted, separated): + separated.multiply_small(4) + separated.increment() + separated.increment() + need(compare(weighted, self.p) <= 0 and compare(self.d, separated) > 0, + "production tensor similarity and cell separation") + with owned(Count.product(self.d, self.halo)) as (needed,): + needed.multiply_small(64) + need(compare(self.L, needed) >= 0, "production tensor source-padding room") + # F <= 2^A*(D*p^2+32+2D). This guard bounds the restored + # approximation error by 1/256 before narrowing to the disk format. + with owned(Count.product(self.p, self.p)) as (square,): + with owned(Count.product(self.dimensions, square), Count(self.dimensions), Count.literal(32)) as (bound, twice_d, constant): + twice_d.multiply_small(2) + bound.add(twice_d) + bound.add(constant) + with owned(ceiling_log(bound), Count(self.gamma), Count.literal(8)) as (logarithm, required, guard): + required.add(self.outer_bits) + required.add(logarithm) + required.add(guard) + need(compare(self.p, required) >= 0, "production restored tensor error margin") + + def axis(self, index): + self.axis_rows.rewind() + try: + need(compare(index, self.dimensions) < 0, "existing tensor axis") + for _ in indices(index): + with owned(AxisRow(self.axis_rows)): + pass + return AxisRow(self.axis_rows) + finally: + self.axis_rows.rewind() + + def close(self): + for tape in (self.sources, self.flags, self.axis_rows): + if tape is not None: + tape.clear() + self.sources = self.flags = self.axis_rows = None + super().close() diff --git a/research/native-coprime-grid/source_guard.py b/research/native-coprime-grid/source_guard.py new file mode 100644 index 0000000000..48c446f7f2 --- /dev/null +++ b/research/native-coprime-grid/source_guard.py @@ -0,0 +1,50 @@ +"""Execute only the pinned production_axis AST, with host Count semantics. +This is not a replay of the encoded physical-tape implementation. +Following ToikY's PR4029 source-binding method; new adapter by Dugongue. +Apache-2.0; substantial OpenAI Codex assistance. +""" +import ast +from contextlib import contextmanager +from pathlib import Path +from types import SimpleNamespace +from hashlib import sha256 + +PIN='474730f42fcd2bd24720af4e08c71fb51cc374c3e16b8b6d7e565900f1a9e7c3' + +def need(ok,msg): + if not ok:raise ValueError(msg) + +class Count: + def __init__(self,x):self.value=x.value if isinstance(x,Count) else int(x) + @classmethod + def literal(cls,x):return cls(x) + @classmethod + def product(cls,a,b):return cls(a.value*b.value) + def multiply_small(self,n):self.value*=n + def add(self,x):self.value+=x.value + +@contextmanager +def owned(*items):yield items + +def subtract(a,b): + need(a.value>=b.value,'natural subtraction') + return Count(a.value-b.value) + +def compare(a,b):return (a.value>b.value)-(a.value0,'shape') + f=load();d=len(moduli)+1 + obj=SimpleNamespace(d=Count(d),target_halo=Count(halo),w=Count(width)) + for s,t in zip(moduli,targets):f(obj,Count(s),Count(t)) diff --git a/research/native-coprime-grid/verify.py b/research/native-coprime-grid/verify.py new file mode 100644 index 0000000000..eea29d3c0c --- /dev/null +++ b/research/native-coprime-grid/verify.py @@ -0,0 +1,128 @@ +"""Exact independent controls for the coprime-grid construction. Apache-2.0.""" +import hashlib, itertools, json, random +from fractions import Fraction +from math import gcd, prod +from pathlib import Path +import sys +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import grid +import source_guard + +HERE=Path(__file__).resolve().parent + +def need(ok,msg): + if not ok: raise RuntimeError(msg) + +def rejected(fn): + try: fn() + except ValueError: return + raise RuntimeError('negative control accepted') + +def check(): + fixtures=[] + for k,d in [(8,4),(12,8),(16,16),(32,32),(64,64),(128,128)]: + moduli,stats=grid.build(k,d) + need(len(moduli)==d and len(set(moduli))==d,'shape') + need(all(s%2 and 1 (3*(len(moduli)+1)-1)*t and + 4*(len(moduli)+1)*s <= (4*(len(moduli)+1)-1)*t for s,t in zip(moduli,targets)), 'safe intervals') + if squares:need(all(s==a*a and a>1 for s,a in zip(moduli,roots)),'band composite witnesses') + need(2*prod(targets)<3*prod(moduli),'source tensor volume') + source_guard.check(moduli,targets) + band_fixtures.append({'ell':ell,'flags':flags,'squares':squares,'moduli':moduli,**stats}) + rejected(lambda:source_guard.check([255,253],[256,256])) + seen=phase_checks=convolution_checks=0 + rng=random.Random(20261025) + for moduli in [(3,5),(9,25),(9,25,7),(5,7,11)]: + g=grid.CRTGrid(moduli) + forward=list(g.indices(coordinates=True)) + need(g.last_changes < 2*g.size,'odometer bound') + dual=list(g.indices(dual=True,coordinates=True)) + need(g.last_changes < 2*g.size,'dual odometer bound') + need(sorted(a for a,_ in forward)==list(range(g.size)),'input permutation') + need(sorted(a for a,_ in dual)==list(range(g.size)),'output permutation') + for address,digits in forward: + need(all(address%s==x for s,x in zip(moduli,digits)),'input residues') + need(address==g.from_coordinates(digits),'direct input CRT') + for address,digits in dual: + need(address==sum(x*(g.size//s) for s,x in zip(moduli,digits))%g.size,'direct dual CRT') + for _ in range(400): + j,x=rng.choice(forward);k,y=rng.choice(dual) + need((j*k-sum(a*b*(g.size//s) for a,b,s in zip(x,y,moduli)))%g.size==0,'Good-Thomas phase') + phase_checks+=1 + # Independent sparse cyclic convolution versus product-group convolution. + for _ in range(12): + a={rng.randrange(g.size):rng.randrange(-9,10) for _ in range(13)} + b={rng.randrange(g.size):rng.randrange(-9,10) for _ in range(13)} + ordinary={}; tensor={} + for j,v in a.items(): + for k,z in b.items(): + key=(j+k)%g.size;ordinary[key]=ordinary.get(key,0)+v*z + coords=tuple((j%s+k%s)%s for s in moduli) + key=g.from_coordinates(coords);tensor[key]=tensor.get(key,0)+v*z + need(ordinary==tensor,'cyclic convolution') + convolution_checks+=1 + seen+=g.size + # Full exact DFT, including non-prime tensor lengths 9 and 25. + g=grid.CRTGrid([9,25]); prime=1801 + # 11 has order 1800 modulo 1801, and its eighth power has order 225. + root=pow(11,8,prime) + need(pow(root,225,prime)==1 and pow(root,75,prime)!=1 and pow(root,45,prime)!=1,'root order') + values=[rng.randrange(prime) for _ in range(g.size)] + forward=list(g.indices(coordinates=True));dual=list(g.indices(dual=True,coordinates=True)) + for k,coords in dual: + actual=sum(values[j]*pow(root,j*k,prime) for j in range(g.size))%prime + tensor=sum(values[j]*pow(root,sum(a*b*(g.size//s) for a,b,s in zip(digits,coords,g.moduli)),prime) for j,digits in forward)%prime + need(actual==tensor,'complete modular DFT') + # This mutation uses the input CRT permutation on the frequency side. + bad=0 + for j,x in forward[:30]: + for k,y in forward[:30]: + bad+=(j*k-sum(a*b*(g.size//s) for a,b,s in zip(x,y,g.moduli)))%g.size!=0 + need(bad>0,'wrong dual convention must fail') + rejected(lambda:grid.CRTGrid([9,15])) + rejected(lambda:grid.CRTGrid([9,9])) + rejected(lambda:grid.CRTGrid([2,3])) + rejected(lambda:grid.CRTGrid([True,3])) + rejected(lambda:grid.build(8,4,candidate_budget=0)) + rejected(lambda:grid.build(8,4,grid.Words(8))) + rejected(lambda:grid.build(2,2)) + rejected(lambda:grid.build_squares(7,2)) + rejected(lambda:grid.CRTGrid([3,5]).from_coordinates([3,0])) + return {'status':'PASS_NATIVE_COPRIME_GRID','new_kappa_claimed':False, + 'source_bound_band_fixtures':band_fixtures,'grid_fixtures':fixtures,'guaranteed_composite_fixtures':square_fixtures,'permutation_entries_each_direction':seen, + 'phase_checks':phase_checks,'sparse_convolution_cases':convolution_checks, + 'exact_modular_dft_outputs':g.size,'wrong_dual_witnesses':bad, + 'rejecting_controls':10,'scope':'exact reference algorithms; no full multiplier, native instruction trace or Lean audit'} + +def main(): + manifest=HERE/'MANIFEST.json' + if manifest.exists(): + for row in json.loads(manifest.read_text())['files']: + data=(HERE/row['path']).read_bytes() + need(len(data)==row['size'] and hashlib.sha256(data).hexdigest()==row['sha256'],'source drift: '+row['path']) + result=check() + expected=HERE/'RESULT.json' + if expected.exists():need(result==json.loads(expected.read_text()),'receipt mismatch') + print(json.dumps(result,sort_keys=True,indent=2)) + +if __name__=='__main__':main()