diff --git a/docs/ci-verification.md b/docs/ci-verification.md index 63ba3e9aa8..52b62d0481 100644 --- a/docs/ci-verification.md +++ b/docs/ci-verification.md @@ -1,8 +1,25 @@ # CI verification -## Current selected-family replay: #6030 +## Current selected-family replay: #7000 with #7001 The [selected record](../certificates/selected-result.json) binds conditional +κ = 0.00363005817 to the [application review](research/pr-intake-evidence/pr7000-application/PROOF-REVIEW.md), +[validation receipts](research/pr-intake-evidence/pr7000-application/VALIDATION.json), +and [explicit source closure](../certificates/frontier7000-source.json). +`make frontier7000-verify` follows that exact-source selected replay. The review +reuses eleven authenticated preceding executions and records seven fresh serial +application, scalar and complete native-catalogue executions. The earlier +monolithic timeout is retained separately and is not completed coverage. +Consult the receipts for exact commands, source heads and limits. + +The five inherited framework assumptions remain. No complete uniform word, +literal multiplier execution, independent human proof or formal-kernel proof +is asserted. Routine research submissions do not need to rerun this +selected-family replay. The sections below preserve historical checkpoints. + +## Historical selected-family replay: #6030 + +The [historical checkpoint](../certificates/checkpoints/frontier6030.json) binds conditional κ = 0.003125804 to the [proof review](research/pr-intake-evidence/pr6030-audit/PROOF-REVIEW.md), [validation receipts](research/pr-intake-evidence/pr6030-audit/VALIDATION.json), and [explicit source closure](../certificates/frontier6030-source.json). diff --git a/research/frequency-weighted-native-multiplier/FINITE-LOSS.md b/research/frequency-weighted-native-multiplier/FINITE-LOSS.md new file mode 100644 index 0000000000..433a65a282 --- /dev/null +++ b/research/frequency-weighted-native-multiplier/FINITE-LOSS.md @@ -0,0 +1,60 @@ +# Finite price of the physical Gaussian calendar + +Use the installed two Gaussian job types, their weights 1 and 90, and their 51 grade shares. Set the lower band edge to $L=2048$ in the active calendar. The raw trial is $c=17145637167/2^{42}$ and $t=1-c$. For every $M=2^H$ with $H\ge 1024$, let $F$ be the actual number of recursive singleton calls divided by the number $M^{92}$ of productive rows. The bound is + +$$ +F < M^{1-c}2^{65081/524288}. +$$ + +Thus the positive supplier buys any booked rate $b516\ge k/r$. They count the actual singleton axes from a job and the width of the corresponding exterior job. [Linear boundary proof](https://github.com/aliromman/integer-mult-bounds/blob/dfd25d553a843a946ca0b94130a5ff8943e98fdd/research/retimed-native-multiplier/TRANSFER.md#price-of-the-complete-integer-plan) + +For $z=k/r$ set $u=(z-1)/(z+1)$. All occupied cells have $z\ge5/4$. The bound $(z^c-1)/c\ge\log z$ follows from $\exp v\ge1+v$. Integrating $2/(1-v^2)$ on $[0,u]$ gives $\log z\ge2(u+u^3/3+u^5/5)$. The sum of these rational lower bounds on all 51 actual cells is greater than $179021766.8064$. The weighted sum of productive axes is $\sum_k N_k k=135150528$. Therefore + +$$ +d_{\rm fringe}=\frac{10\sum_k N_k k}{t\Psi}<7.579 . +$$ + +On an interior edge the parent issues a prefix of its paid job to a real target. Its remaining suffix has fewer than $10k$ axes. At each bin $e$, type $b$ and actual target port, at most $m[e,b]$ real intervals can arrive. This follows from the per-owner capacity and disjoint receiver ranges. Thus the whole interior suffix count is bounded by $10\sum_{e,b}m[e,b]\sum_i k_{bi}$. The ideal part is at most $10V\sum_k N_k k/(tL^t)$. Dividing by $V L^c\Psi$ gives $d_{\rm fringe}/L$. The excess from the upward-rounded counts is below $20M\cdot105216\cdot258<2^{30}M$ axes. The receipt uses the exact rational upper value of $d_{\rm fringe}$ from the preceding three log terms. [Typed capacity calculation](receipt.py) · [Kernel-checked finite weighted lifting](WeightedNumerical.lean) + +## The lower edge and the integer periods + +Each lower band edge satisfies $e\ge2048>48$. Thus $4(e+2)/5<5e/6$, as required for separate return deadlines. The column count remains $e-8>0$ and is even. At most $4H+1$ simultaneous contexts occur on a causal dependence. With delay radix $2^{19}$, the lifetime of one raw unit is at most $1+2^{19}(U/L)^{77}10$, so $L^t>1024$. The lower edge has no effect on the upper fraction or the physical rank-258 root used for the mandatory ordinary exchange. Its exterior band is above $L$ at all admitted ranks. The integral endpoints remain positive and less than $M$. The original $2^{-64(H+1)}$ grid still gives less than $1/4$ error after the factor $90V/t$. The lower edge also preserves the prior precision, owner, control and high-water estimates. [Physical schedule and resource proof](PROOF.md) · [Original positive data and precision](https://github.com/aliromman/integer-mult-bounds/blob/dfd25d553a843a946ca0b94130a5ff8943e98fdd/research/retimed-native-multiplier/NUMERICAL.md#precision-along-a-real-dependency) + +Set $\delta=2^{-128}$. Every exterior donor starts at a continuous coordinate $x\ge U$. Consequently its receiver coordinate $y=xr/k$ is at least $U/516$. The real per-grade columns $2\lfloor y/2\rfloor-8$ exceed $y-10$. They therefore exceed $(1-\delta)y$, since $U\ge5160/\delta$ even at $H=1024$. Also $U\ge(1-\delta)M/(1024\cdot306)$ since defining the even upper edge loses less than two units. Both inequalities hold at all larger $H$. + +The number of real labels and the unchanged width-two bins give a total floor, ceiling and quadrature loss below $2^{46}M^2$ per time by the source counting proof. The separately bounded suffix count error is below $2^{30}M$. The end-of-calendar loss per birth is at most $(M^{77}/M^{82})\,2V\,2^{19}M=2^{20}V/M^4$. Each is below $2^{-132}V$ for every $H\ge1024$. Thus even their sum fits the $\delta$ allowances in the normalized terminal and exterior bills, since $\Psi>1$ and $L,U>1$. These bounds charge the factor 90 before rounding each individual grant. + +Let $s'$ be an exterior field's actual number of axes and $q=4\lceil M/(4s')\rceil$ its installed period. Then $s'\le258U$, so $q s'/M\le 1+4\cdot258/(1024\cdot306)$. Also $q\le M$ because $s'\ge1$ and $M$ is divisible by four. The $R=M^2$ rounds lose at most the fraction $q/R\le\delta$ to an incomplete period. For $h$ full exterior slots, the real upper count $h\le2M^{82}V\cdot52608\cdot Ra$ give the same per-depth coefficient as in the source. + +There are at most $s+2$ physical depths, with $k\le1030(s+1)$ for the multiplier's admitted packs. The explicit coefficient $M^{220}(1+B_{\rm ord})$ pays the entire sum, including the factor $(s+1)^2$ in the outer rate. This is the predecessor's per-depth proof with the present bound $F (2 : ℝ) * (1 / (2 * i + 1)) * u ^ (2 * i + 1)) + (Real.log z) := by + simpa only [u, show 1 + (z - 1) = z by ring, show z - 1 + 2 = z + 1 by ring] + using Real.hasSum_log_one_add (a := z - 1) (by linarith) + have hp := hs.summable.sum_le_tsum (Finset.range 3) (fun j _ => by positivity) + rw [hs.tsum_eq] at hp + norm_num [Finset.sum_range_succ] at hp + have hl : 2*(u+u^3/3+u^5/5) ≤ Real.log z := by linarith + have he := Real.add_one_le_exp (Real.log z * c) + rw [← Real.rpow_def_of_pos (by linarith : 0 < z) c] at he + apply (le_div_iff₀ hc).2 + change (2*(u+u^3/3+u^5/5)) * c ≤ _ + nlinarith [mul_le_mul_of_nonneg_right hl hc.le] + +/-- The active cost at one depth needs the child-volume bound with ratio one. -/ +theorem activeDepth (M D F x a b : ℝ) (j : ℕ) + (hM : 1 ≤ M) (hD : 0 ≤ D) (hF : 0 ≤ F) (volume : F ≤ M^(1-b)) + (ha : a ≤ 1) (hab : a ≤ b) (hx : 0 ≤ x) (width : x ≤ D / M^j) : + F^j * x^(1-a) ≤ D^(1-a) := by + have hM0 : 0 < M := by linarith + have hp : 0 < M^j := pow_pos hM0 _ + have hv : F ≤ M^(1-a) := + volume.trans (Real.rpow_le_rpow_of_exponent_le hM (by linarith)) + have hj : F^j ≤ (M^j)^(1-a) := by + rw [← Real.rpow_pow_comm hM0.le] + exact pow_le_pow_left₀ hF hv j + calc + _ ≤ (M^j)^(1-a) * (D/M^j)^(1-a) := + mul_le_mul hj (Real.rpow_le_rpow hx width (by linarith)) + (Real.rpow_nonneg hx _) (Real.rpow_nonneg hp.le _) + _ = D^(1-a) := by + rw [← Real.mul_rpow hp.le (div_nonneg hD hp.le)] + congr 1 + field_simp + +#print axioms activeDepth + +#print axioms threeTerms +end GaussianFiniteLoss diff --git a/research/frequency-weighted-native-multiplier/LICENSE b/research/frequency-weighted-native-multiplier/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/research/frequency-weighted-native-multiplier/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/frequency-weighted-native-multiplier/MEASUREMENTS.json b/research/frequency-weighted-native-multiplier/MEASUREMENTS.json new file mode 100644 index 0000000000..ae6f84b100 --- /dev/null +++ b/research/frequency-weighted-native-multiplier/MEASUREMENTS.json @@ -0,0 +1,179 @@ +{ + "sequence": [ + { + "model": "dilation79", + "wall": 6.831931417000305, + "cpu": 6.377187999999999, + "rss_bytes": 253050880, + "python": "3.12.16", + "system": "macOS-27.2-arm64-arm-64bit", + "ranks": [ + [ + 3000, + 3080, + 1024 + ], + [ + 35327, + 559005, + 680000 + ] + ], + "gaussian_grade_cells": 62, + "binary_sha256": "9e7392c52bcf29c0cc58c54c619f95c28f476394c33e8e0a5aa30c9557d31362" + }, + { + "model": "frequency90", + "wall": 6.976833333000286, + "cpu": 6.419596, + "rss_bytes": 258473984, + "python": "3.12.16", + "system": "macOS-27.2-arm64-arm-64bit", + "ranks": [ + [ + 3000, + 3080, + 1024 + ], + [ + 8192, + 129414, + 524288, + 483871 + ] + ], + "gaussian_grade_cells": 51, + "binary_sha256": "9e7392c52bcf29c0cc58c54c619f95c28f476394c33e8e0a5aa30c9557d31362" + }, + { + "model": "frequency90", + "wall": 6.408154208999804, + "cpu": 6.029809, + "rss_bytes": 259883008, + "python": "3.12.16", + "system": "macOS-27.2-arm64-arm-64bit", + "ranks": [ + [ + 3000, + 3080, + 1024 + ], + [ + 8192, + 129414, + 524288, + 483871 + ] + ], + "gaussian_grade_cells": 51, + "binary_sha256": "9e7392c52bcf29c0cc58c54c619f95c28f476394c33e8e0a5aa30c9557d31362" + }, + { + "model": "dilation79", + "wall": 5.480442209000103, + "cpu": 5.382844, + "rss_bytes": 257277952, + "python": "3.12.16", + "system": "macOS-27.2-arm64-arm-64bit", + "ranks": [ + [ + 3000, + 3080, + 1024 + ], + [ + 35327, + 559005, + 680000 + ] + ], + "gaussian_grade_cells": 62, + "binary_sha256": "9e7392c52bcf29c0cc58c54c619f95c28f476394c33e8e0a5aa30c9557d31362" + } + ], + "host": "macOS arm64. Each row uses a separate process. Order was preceding, candidate, candidate, preceding.", + "rounded_peer_sequence": [ + { + "model": "rounded_quarters", + "wall": 85.50279466600023, + "cpu": 85.080657, + "rss_bytes": 306970624, + "python": "3.12.16", + "system": "macOS-27.2-arm64-arm-64bit", + "ranks": [ + [ + 60000, + 960000, + 20000000 + ] + ], + "gaussian_grade_cells": 55, + "binary_sha256": "9e7392c52bcf29c0cc58c54c619f95c28f476394c33e8e0a5aa30c9557d31362" + }, + { + "model": "frequency90", + "wall": 5.205228833000547, + "cpu": 5.196359, + "rss_bytes": 273612800, + "python": "3.12.16", + "system": "macOS-27.2-arm64-arm-64bit", + "ranks": [ + [ + 3000, + 3080, + 1024 + ], + [ + 8192, + 129414, + 524288, + 483871 + ] + ], + "gaussian_grade_cells": 51, + "binary_sha256": "9e7392c52bcf29c0cc58c54c619f95c28f476394c33e8e0a5aa30c9557d31362" + }, + { + "model": "frequency90", + "wall": 5.748198749999574, + "cpu": 5.377325999999999, + "rss_bytes": 278708224, + "python": "3.12.16", + "system": "macOS-27.2-arm64-arm-64bit", + "ranks": [ + [ + 3000, + 3080, + 1024 + ], + [ + 8192, + 129414, + 524288, + 483871 + ] + ], + "gaussian_grade_cells": 51, + "binary_sha256": "9e7392c52bcf29c0cc58c54c619f95c28f476394c33e8e0a5aa30c9557d31362" + }, + { + "model": "rounded_quarters", + "wall": 83.00223966700014, + "cpu": 82.61009, + "rss_bytes": 309903360, + "python": "3.12.16", + "system": "macOS-27.2-arm64-arm-64bit", + "ranks": [ + [ + 60000, + 960000, + 20000000 + ] + ], + "gaussian_grade_cells": 55, + "binary_sha256": "9e7392c52bcf29c0cc58c54c619f95c28f476394c33e8e0a5aa30c9557d31362" + } + ], + "rounded_peer_source": "c5cbef6e558542d6e809aabb6ead89b9e51f7b1c", + "rounded_peer_contract": "Fresh native CPython process. Restore source, install the complete extended peer profile or both candidate profiles, check the ranks and numerical shares, remove temporary output." +} diff --git a/research/frequency-weighted-native-multiplier/NOTICE.md b/research/frequency-weighted-native-multiplier/NOTICE.md new file mode 100644 index 0000000000..0f232c45e7 --- /dev/null +++ b/research/frequency-weighted-native-multiplier/NOTICE.md @@ -0,0 +1,10 @@ +# Attribution + +Ali Romman directed the frequency-weighted Gaussian scheduler, its physical word split, and the signed multiplication integration. This contribution received substantial OpenAI Codex assistance. It builds on the independently reviewable 1-to-79 machine at `7b48187d99525ad59f560de3921ec7e48382484c`. All predecessor source and archived notices retain their Apache 2.0 license. [PR #8055](https://github.com/CrocSwap/integer-mult-bounds/pull/8055) · [Predecessor credits](https://github.com/aliromman/integer-mult-bounds/blob/7b48187d99525ad59f560de3921ec7e48382484c/research/tiered-native-multiplier/NOTICE.md) · [License](LICENSE) + +- SYLforge supplied the K7 binary circuit, journal, physical checks and the two-stage rank family. ToikY supplied the fixed-carrier repricing and the two unsplit physical returns. ToikY’s later quarter-packet rounding gave the leading external comparison at 0.0038982016137. [PR #8052](https://github.com/CrocSwap/integer-mult-bounds/pull/8052) · [PR #8053](https://github.com/CrocSwap/integer-mult-bounds/pull/8053) · [PR #8054](https://github.com/CrocSwap/integer-mult-bounds/pull/8054) · [PR #8056](https://github.com/CrocSwap/integer-mult-bounds/pull/8056) +- Ali Romman's earlier signed retimed machine and quadratic phase producer supply the physical signed path, retimed compiler and fixed setup. Clear1nsight supplied earlier signed funding and competing full prices. DreamingOfClouds and Jerry Chen supplied physical bank, counted-source and verification work. The P104 chart and analytic contributions retain their original credits. The branch contains the exact shared historical CI prerequisite from Jerry Chen. [PR #8042](https://github.com/CrocSwap/integer-mult-bounds/pull/8042) · [PR #8050](https://github.com/CrocSwap/integer-mult-bounds/pull/8050) · [PR #8051](https://github.com/CrocSwap/integer-mult-bounds/pull/8051) · [PR #7257](https://github.com/CrocSwap/integer-mult-bounds/pull/7257) + +The new result changes the actual source birth counts, distribution of every funded individual port and chronological scheduler. The unchanged all-column action, infrastructure and scientific dependencies retain the status documented in the predecessor. [Scientific baseline](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/certificates/selected-result.json) + +The portable setup uses the CPython 3.12 WASI interpreter, the VMware Labs WASI build, and Wasmtime from the Bytecode Alliance. Their externally obtained release artifacts retain their own licenses. [Toolchain provenance and licenses](portable/NOTICE.md) diff --git a/research/frequency-weighted-native-multiplier/PROOF.md b/research/frequency-weighted-native-multiplier/PROOF.md new file mode 100644 index 0000000000..305542103f --- /dev/null +++ b/research/frequency-weighted-native-multiplier/PROOF.md @@ -0,0 +1,49 @@ +# Two physical Gaussian jobs with different production frequencies + +At every even band edge e the machine opens two independent kinds of native job. Type 0 runs the original signed word at f=e−8 columns, and splits the first 1,008 paid unit cuts into two half-width cuts. Type 1 runs the same signed word at 2f columns. Its cut sequence is the original one. The numbers of real openings approximate densities V and 90V. The 90 occurs in the tape loop counts. One type 1 opening still runs exactly one physical copy with its own 52,608 productive owners. The maximum physical ambient is 306. The old 1 and 79 construction needs 12,087. Every stored spectator, selected axis and returned field belongs to that particular copy. The retained raw interpreter applies the same signed Pauli circuits, private arithmetic grid, helper transfers, root normalization and restoration on the specified f or 2f physical axes. + +## Fixed source and funding + +Let w₀=1 and w₁=90. Extract each actual rank from the fixed signed source. Denote the number of target labels of grade k in type b by nᵦk and the number of paid labels of grade r in type a by mₐr. Put Nₖ=Σᵦ wᵦ nᵦk and Mᵣ=Σₐ wₐ mₐr. These are masses used by the allocator. Individual native jobs retain exactly 52,608 ordered productive labels and 282,576 or 281,568 paid labels. The weighted numbers are 4,787,328 and 25,623,696. The difference concerns the actual number of openings. The installer derives the two histograms by traversing the unchanged 145 signed role segments. It stores a single copy of each of the 25,621 shared source records. The active calendar generates both real chronological lists from these segments. At each bin the actual calendar visits the whole rounded count for the second type. [Grade producer and calendar construction](grades.py) · [Physical chronological adapter](typed_raw.py) + +Set c=17145637167/2⁴² and t=1−c. Certify on N and M with the predecessor's 112-bit dyadic root calculation. Round target masses downward and paid masses upward. Let T and P be their totals. The margin (T−P)/T exceeds 6.89×10⁻¹³. The ordinary descending greedy transport fills 51 nonempty grade cells with 5r≤4k. It produces a row fraction pᵣₖ. For a particular paid label in either type and a particular target label i with grade k in type b, assign probability π=pᵣₖ wᵦ/Nₖ. Each row sums to one. For each b,i, the paid influx Σₐⱼ wₐ π rⱼᵗ is at most wᵦ kᵗ because the interval allocation scales each target mass exactly by P/T. A positive individual probability exceeds 2⁻²⁶. The 51 installed grade fractions have at most 261 bits per numerator and denominator. At active entry the type allocation expands them into 88 type-specific shares. Their constant-size type and port factors remain in the charged incidence calculation. At multiplicity 91 the signed total remains positive by more than 0.03. But every paid grade with $5r>8$ must go to a target of grade $k>2$. The sum of *upper* target capacities there is smaller than the corresponding *lower* compulsory paid sum by more than 1,515. At multiplicity 90 the same cut has more than 494 units of certified slack. The negative control at 91 permits arbitrary utilization of the target capacities. [Independent grade and cut calculation](receipt.py) + +The 112 to 258 cell has fraction one, and its external rotated root has probability 1/624. At e=2⌊3U/8⌋ the parent interval [258e/112,258(e+2)/112] is strictly exterior. For M≥2¹⁰²⁴ all its endpoints are between U and M. The weighted directed integral times 1/624 exceeds one with strict room for the descending enclosure. A quick lower bound is 90V times the interval length divided by 624M². The physical size 258(e−8) has period 1620, with first tickets 0, 324, 648. To verify for all sizes, use |e−3M/(4096·306)|<4 and hence |258(e−8)−3·258M/(4096·306)|<3096. The inequalities 1616s′3240 for M≥10¹³, so the first three ticket ordinals have quotients 0,324,648. The first call to ComplexRaw.align swaps the full selected slot at 324 with slot 1. The placement check uses the exact type-proportional shares from the installed recipe at both actual ranks. [Source-bound exchange](check_placement.py) · [All-size placement proof](WeightedNumerical.lean) This supplies the positive-to-ordinary witness. + +## Calendar, stock and cost + +Use M=2ᴴ for H≥1024, L=2048, U=2⌊M/(2048·306)⌋, V=M⁶, K=M⁸² and R=M². Use M⁹² real productive fields. The count at e in type a is the ceiling of an upper enclosure of wₐV∫ₑᵉ⁺² x⁻¹⁻ᵗ dx. The count sent by a particular paid/target pair to each qualifying interior or exterior interval is the floor of a lower enclosure for wₐVπ∫x⁻¹⁻ᵗ dx. The destination relation is y=xr/k. Its change of density introduces (r/k)ᵗ. Together with the weighted column inequality this proves that no type-b target receives more than its true bin count. The probability row supplies the outgoing bound for the source type. Exterior intervals carry the weight of the proposed parent's type even when the true source enters a child of the other type. Integer allocations use disjoint ranges per parent and per recipient type, bin and individual port. An unused target gets an independent zero. An unused parent loan takes the primitive service for its whole field. A matched parent issues the surplus suffix and lends its exact prefix. The column choices give 0≤r c(x)−k c(y)<10k since 8k≥10r. + +Number the birth frames by type, physical e, birth tick and replica. A type a closes at time birth+QₐD[e], with its own real paid count Qₐ≤282,576<2¹⁹. Use the common delay radix 2¹⁹ and the original 6/5 levels. Every recipient's band d is at most 4(e+2)/5<5e/6. Thus its local cut and its return precede the next cut of every providing parent, including a parent of the other kind. Process due closes first, then the two kinds at each decreasing e. There are no same-band loans. A pending prefix is indexed by recipient type as well as bin, owner and port. The unchanged decoder consumes each descriptor exactly once. Its positive even column argument stores the physical type in the spare low bit. The physical adapter recovers the width and kind before opening. On close it clears the zeros and releases the original owners. This preserves the actual active and suspended state. The number of time levels is at most $1+H/\log_2(6/5)$. Since $Q_a<2^{19}$ and $19/\log_2(6/5)<73$, even the endpoint factor from the two integer levels fits $M^{77}$ for $H\ge1024$. Along one dependency chain each interior edge reduces the band by at least a factor $6/5$. Its depth is at most $4H+1$. Sibling births and pending returns remain on their physical tapes. [Typed clock, producer and receiver events](typed_transport.py) + +Here k≤258, r≥1/2 and k/r≤516. All endpoints in the integral error estimate are positive and at most M, and all rounded inverse bases stay above 1/(2M). There are at most 42 square roots and 43 product stages for the exact dyadic trial. The proof uses 43 as a common depth bound. At a square root the interval width multiplies by at most √(2M)/2 before two units of the grid 2⁻⁶⁴⁽ᴴ⁺¹⁾ are added. Product errors in the unit interval add. A bound for one endpoint is 2(4√(2M))⁴³ grid units. Even after subtracting two endpoints and multiplying by 90V/t, the absolute error is below 2³¹⁰M⁻³⁶ < 1/4. Hence each ceiling or grant costs fewer than two replicas. The number of pairs of real label types is still below 2²⁰·2¹⁷. Each has one external and at most two interior intervals per source bin. Each real or ideal interval has at most M axes. The rounding error is below 2⁴⁶M² per time. The total number of openings at one tick satisfies + + Σₐ,ₑ count[e,a] ≤ 91V/(t Lᵗ) + 2U < 2V. + +The last inequality follows from t>.996 and Lᵗ>2¹⁰. Thus even the conservative full-weight density leaves the earlier 2V bound available for the active banks and the terminal-cut loss. The latter is at most (M⁷⁷/K)·2V·2¹⁹M < 2⁻¹³² V. The rounding loss also fits 2⁻¹³² V. + +For each directed pair use the measure wₐπ. The ideal terminal and exterior axis counts per tick are V Lᶜ Ψ and V Uᶜ Ψ. A rational lower sum over the 51 actual cells gives Ψ>179021766.8064. The weighted linear target sum is 135150528. The resulting suffix factor is below 7.579/L. Every exterior physical width lies above (1−δ) times its continuous width, for δ=2⁻¹²⁸. Incomplete copy groups cost at most 1+1/M. The period factor is at most 1+4·258/(1024·306). These inequalities hold at H=1024 and above. They permit the real calendar to start at 2,048 columns. The positive recursive clock pays for each physical depth individually. It funds the complete singleton and stopped costs at a finite debit below 65081/524288 while retaining Z=M²²⁰(1+B) and the previous grid. The ordinary same-stage recursion keeps its separate contraction reserve. [All-size proof with the changed cutoff](FINITE-LOSS.md) · [Exact finite-price calculation](positive_debit.py) + +The comparison uses the outward 112-bit root enclosures. The direct preparation visits the same number of true chronological labels as the 1 and 79 construction. Across both types there are fewer than 2²⁰ distinct paid and 2¹⁷ target labels. Every receiver can meet at most 518 parent bands per source type and paid grade, fewer than the old 20,384. The four possible type pairs fit two more bits per candidate loop. Two extra type loops per band, and a seven-bit exact multiplicity on the interval numerator, fit the numerical calendar bound of 2⁸¹M⁹³ structural comparisons before axis expansion. Opening count and external-group bounds above pay all independently live cohorts, including every real factor of 90. Each axis expansion costs at most M visits. Factoring, enumerating and executing the fixed raw source still fits M⁹⁶ total visits; every expanded owner keeps the previous bound of M⁹⁶ control bits. Pricing the full sequential sweep at every visit, with rewriting, scratch and cleanup, stays below M⁷⁰⁰ per actual preparation. This is less than its input field volume 2ᴹ. The actual moving-payload coefficient is below M¹⁹³(1+B), including the 4M⁹² per-visit row traversal and all live and suspended owners. The 148 fixed dyadic positions and at most 436 extra mass bits per raw context are inherited from the common literal word. The larger 2f columns are divisible by four, so there are no extra second-copy phase passes from the modulo-four scalar phase. All physical whole-field gates remain charged. The stopped budget still fits 2⁴⁵M⁹² and the two-moment sum consequently fits Z=M²²⁰(1+B). + +The terminal installation uses three ordinary heights 8,192, 129,414 and 524,288 and a numerical height 483,871. The booked complete rate is 0.00389821 with stopping gap 10⁻¹⁸. After the new debit the numerical margin above κ+5g is 1143237735274919989/1623601656627200000000000000000. Both tiers pass 54 strict and four functional outer inequalities. The public signed controller retains the input scans, both normalized forward transforms, pointwise multiplication, opposite transform, recovery, carry and bank restoration of the signed predecessor. The following accounting uses this exact combination of heights and the same five research premises. + +## Complete signed invoice and fixed setup + +The input consists of two independent signed binary magnitudes. Use the scanned significant length $n$ and $p=6\lceil\log_2 n\rceil$. For noncanonical byte intervals charge the complete scan and head restoration, or count their declared length in $n$. Use $n=2$ for the empty, zero and unit cases. The public header selects the terminal installation at the first admissible $p=2^{1146239}+4$. It uses the entry installation below that point. A rank is $2^H$ throughout this statement. At either selection, the positive and ordinary suppliers come from the same fixed source and use the listed rank recipes. [Exact price and stock](RESULT.json) · [Changes to the signed supplier and profile](runtime.patch) + +The ordinary graph has 2,796 moves, 3,426 dirty clears, 18,906 independent productive ports and 104,652 paid ports. The independently generated K7 moments and 24-cell transfer pass at $c_B=4391986206293/2^{50}$. The ordinary recursion pays the same child factor $47/20$ and finite prologue of $11/8$ bits at each stage. Starting with $b_0=0$, each booked $b_i$ is strictly below $[249(c_B-11/(8H_i))+b_{i-1}]/250$ and 0.0039. The last booked rate in each tier is $\kappa+5g$ for $g=10^{-18}$. The 54 strict, four functional and independent positive finance inequalities all hold. The terminal ordinary clock uses $\log_2 B\le128+320(8192+129414+524288)=211806208$. The entry ordinary clock includes the original 25,818,582-bit variable-setup surcharge and has $\log_2 B\le125433359$. The sharper high-stage estimate pays for every traversal and weighted lift by the true exposed fibre. It requires $H\ge8192$ at each terminal stage. Each local clock is at most $N_i^{320}(1+B_{i-1})$. Starting from the cold coefficient $2^{100}$, three applications give a log ceiling at most $100+3+320\sum H_i$ and hence the displayed bound. The third receiver uses the same clipped predecessor stage and the same contraction. The intermediate booked rates are listed in the exact receipt. The two entry stages keep the original price for that reason. [Ordinary, variable and stopped clocks](https://github.com/aliromman/integer-mult-bounds/blob/7b48187d99525ad59f560de3921ec7e48382484c/research/tiered-native-multiplier/CLOCK.md) + +The exterior performs both input CRT conversions, normalized forward transforms, pointwise multiplication, the opposite transform, extraction at original coordinates, normalization, integer rounding, inverse CRT and carry. An operand sign is recovered separately, and the input heads and all temporary files return to their required state. The price enters as a change of the Gaussian job supplier and the installed ordinary heights. Its contract returns the same linear operator on the original coordinates and all spectators. Along an active dependence it uses the same raw word, scalar denominator and rational signs at each physical stage. The inherited widening and rounding bound, including both source-size factors, applies to either operand and each recovered coefficient under the same analytic and precision premises. [Physical transform and exact signed recovery](https://github.com/aliromman/integer-mult-bounds/blob/dfd25d553a843a946ca0b94130a5ff8943e98fdd/research/retimed-native-multiplier/OUTER-CLOCK.md) + +At the terminal rank the three signed ordinary cuts are 8,290, 137,768 and 662,120. At entry they are 3,077 and 6,221 with heights (3000, 3080, 1024). Write $s=\lceil\log_2(p+2)\rceil$. The actual exterior ticket established above gives a full-slot interchange on at least $2^{s-100}/s^7$ true windows. The sufficient condition $s-7\lceil\log_2s\rceil\ge H_M+a_{\rm last}+102$ passes at $s=7438$ or $1146240$, respectively, and past the next dyadic jump. The post-jump minima then increase. The paying last ordinary invocation reaches a real singleton and eventually enters a stopped weighted pair. At each lower stage the prior cut plus two is smaller than the next height, and its prefix meets the prior stock bound. Induction gives genuine activation of all three terminal ordinary bodies and the positive supplier. The entry tier uses both its ordinary bodies. The per-stage private address overhead is 1,968 log units in the three-stage tier and 1,964 at entry. The historical stripe reserve, not just this logical descent, must hold. Its initial and cofinal margins are (1,701, 1,635) at entry and (571,066, 553,239) in the terminal tier. The changing thresholds do not allocate both tiers' large runtime banks together. In the same live-data regime, all arbitrary rows, high data, temporary zero families, suspended owners and cleanup satisfy $6.2pT<297.6n$ bits. [Historical stock and cleanup proof](https://github.com/aliromman/integer-mult-bounds/blob/dfd25d553a843a946ca0b94130a5ff8943e98fdd/research/retimed-native-multiplier/ACTIVATION.md) + +The normalized cofinal clock has log ceiling $1602+220H_M+\log_2 B$. The finite exterior prefix has log ceiling 84,500,001. The resulting entry and terminal ceilings are 125,660,241 and 318,259,430. On the whole entry interval $1+\log_2 n\le2^{1146239}$. Its price at the terminal rate therefore adds only $\lceil(.00389821-.00345)1146239\rceil=514$ bits. One further bit pays the selector. This gives $2^{318259431} n(1+\log_2 n)^{1-.00389821}$ individual tape transitions after fixed installation for all $n\ge2$. The lower rate on the early interval is fully charged in this inequality. The predecessor priced its fixed installation at $2^{228}$ after changing the phase compiler and specifying the serial arithmetic. In this machine the fixed compiler creates five binary recipes and two Gaussian recipes. Both Gaussian recipes share the same signed word and 51 grade fractions. The active tiers pay separately for the 88 type-specific shares and every source band, live owner list and cleanup. [Preceding fixed compiler](https://github.com/aliromman/integer-mult-bounds/blob/7b48187d99525ad59f560de3921ec7e48382484c/research/tiered-native-multiplier/SERIAL-SETUP.md) + +The portable fixed installation uses a pinned CPython WASI image and a deterministic file service. It generates the complete fixed directory, transfers it, and starts a fresh receiving interpreter. The receiver reads all 2,407,819 records, installs the seven original data getters, and binds both Gaussian job sources to the signed caller. Its linked image has 110 files and 38,671,319 bytes. The two entry ordinary recipes, three terminal ordinary recipes and both Gaussian recipes reach the caller. The compiler-state conversion preserves dictionary order, exact fractions, shared objects and the original instruction-generator arguments. A separate installation through Git and native CPython gives a byte-identical directory. The setup clock pays for the interpreter, source, library, storage, movement, both runs, transfer and scratch cleanup. A complete instruction census bounds every unpaid straight run at 274 instructions. The serial interpreter parks its stack heads at the active suffix. It charges an operand that is discarded at a return against its earlier push. Every complete file operation, initialization and final high-water cleanup keeps its original bill. The resulting two-run upper sum is 8,788,853,932,655,975,457,155,330,527,461,376 tape transitions, below $2^{113}$. On these same runs, charging a whole-store sweep at every instruction gives a looser ceiling below $2^{142}$. The archived instruction measurements use Wasmtime. They supply finite evidence for these fixed bytes. The sequential interpreter and its transition pricing are written arguments. The dynamic calendar still pays for its expanded lists and every input-dependent operation. [Portable fixed construction](portable/README.md) · [Complete-store tape clock](portable/TRACE-CLOCK.md) · [Stack-head and code-clock proof](portable/STACK-LOCALITY.md) + +The identities and inequalities above are new conditional implications for the source given here. They retain five research premises for all-column native operators, owned erasure, uniform mixed compilation, fixed-tape precision and movement, and analytic recovery. Finite tests and the partial formal proofs have the scope given in [Verification](VERIFICATION.md). + +## What still forces large ranks + +Fix this K7 trial, its finite ordinary debit $11/8$, the Gaussian debit $65081/524288$, and the five-unit terminal stopping margin. Allow any finite number of ordinary stages and any positive heights. If all ordinary heights are at most $h$, their local prices are at most $c_B-11/(8h)$. Each funded next price is at most the convex combination of the local price and the previous booked price with weights $249/250$ and $1/250$. Starting from zero, induction bounds every price by the maximum of zero and the local ceiling. Thus the same rules require some ordinary height of at least 517,430. The exact dividing value is $1181116006400000000000000000/2282661773688558548329$. The numerical debit requires a Gaussian height of at least 483,870. The installed Gaussian height is one bit above that floor. The maximum installed height of 524,288 is within 1.33% of the ordinary floor. These bounds apply to these funding inequalities. A better word, a new physical exchange price, or a sharper finite loss can change them. [Kernel-checked convexity and endpoint tests](WeightedNumerical.lean) · [Exact stage invoice](receipt.py) diff --git a/research/frequency-weighted-native-multiplier/README.md b/research/frequency-weighted-native-multiplier/README.md new file mode 100644 index 0000000000..1cd388aa58 --- /dev/null +++ b/research/frequency-weighted-native-multiplier/README.md @@ -0,0 +1,37 @@ +# Frequency-weighted Gaussian calls in a signed multiplier + +One signed binary multiplier attains conditional $\kappa=0.00389821$. Its largest native rank is $2^{524288}$, against $2^{20000000}$ for the previous highest-rate peer and $2^{680000}$ for the previous compact high-rate machine. The portable fixed setup costs fewer than $2^{113}$ individual tape transitions, and the complete all-input recurring coefficient is at most $2^{318259431}$. The exact gain over the rounded-packet peer is $83863/10^{13}$. The new complete rate also exceeds that peer's raw trial $4286126377/2^{40}$. [Written construction](PROOF.md) · [Numerical finite cost](FINITE-LOSS.md) · [Exact receipt](RESULT.json) · [Source bindings](SOURCES.json) + +| Complete claim | κ | Terminal ordinary heights | Gaussian height | First full A | Terminal A | Ceiling for log₂ S | Ceiling for log₂ C | +|---|---:|---|---:|---:|---:|---:|---:| +| Rounded quarter packets in PR #8056 | .0038982016137 | 60,000 and 960,000 | 20,000,000 | 21,020,646 | 21,020,646 | 513 | 21,111,681,659 | +| Physical dilation 79 in PR #8055 | .0038982 | 35,327 and 559,005 | 680,000 | 7,437 | 1,274,851 | 228 | 339,787,971 | +| Frequency-weighted jobs | **.00389821** | **8,192, 129,414 and 524,288** | **483,871** | **7,437** | **1,146,239** | **113** | **318,259,431** | + +Each height $H$ denotes an actual native rank $2^H$. The sufficient input length for exponent $A$ is $2^{\lceil2^A/6\rceil-1}+1$ significant bits. Compared with the rounded-packet machine, the maximum rank exponent falls 38.15-fold and the terminal threshold exponent falls 18.34-fold. The inexpensive complete tier enters 2,826-fold earlier in $A$. Its local rate is .00345. The all-length bill pays the full 514-bit cost to use it at the global rate. The earlier one-stage, lower-rate machine enters at $A=6913$ with maximum $H=5610$ at $\kappa=.00363005817$. A two-stage compact machine uses heights 9,100, 144,000 and 8,500 at $A=161992$ and $\kappa=.00387992803556$. The first tier here still requires $2^{7412}$ true outer axes. [Highest-rate peer](https://github.com/CrocSwap/integer-mult-bounds/pull/8056) · [Compact high-rate predecessor](https://github.com/CrocSwap/integer-mult-bounds/pull/8055) · [Other K7 configurations](https://github.com/CrocSwap/integer-mult-bounds/pull/8052) + +An earlier working configuration of this same research is a useful scale comparison. It reached .00389820002 with maximum $H=559011$, terminal $A=1137207$ and $\log_2 C\le309506891$. The final form lowers its maximum $H$ by 34,723 and raises the complete rate above the rounded-packet peer. It adds 9,032 to that working configuration's terminal $A$ and 8,752,540 to its $\log_2 C$ ceiling. The comparison with PR #8055 in the table uses the smaller published high-rate predecessor. [Earlier weighted receipt](https://github.com/aliromman/integer-mult-bounds/blob/776d432ddaaf9edd8f11f1b8e6933abfd82a63b7/research/frequency-weighted-native-multiplier/RESULT.json) + +The producer runs physical jobs at $f$ and $2f$ columns with relative birth weights 1 and 90. Each opening has 52,608 true productive owners. Both types issue and return their own loans. At frequency 91 the total signed moment still has slack, yet the compulsory flows to grades above two exceed the available capacity. The new finite price uses all 51 installed shares and permits the calendar to begin at 2,048 columns. At execution the calendar constructs 88 typed shares and the real chronological lists. A third terminal ordinary stage lowers the maximum required rank. It also adds an intermediate rank and a suspended call. Both appear in the clock and stock. At the same raw K7 trial and finite debit, any number of ordinary stages requires some height of at least 517,430. The installed maximum is within 1.33% of that floor. [Calendar and stage proof](PROOF.md) · [Exact fringe and depth accounting](FINITE-LOSS.md) + +The portable installer generates a typed directory of 36,094,602 bytes and a cold receiver connects its seven recipe objects to the signed caller. Its sequential clock pays for the entire interpreter, generated sources, transfer, both runs, every live tape and cleanup. The explicit setup bound uses a separate head for each data stack and charges discarded data as the interpreter pops it. The terminal private control envelope is $2^{536870915}$ bits. The active Gaussian cohort alone has $2^{44516132}$ independent rows. The measured installation and finite physical tests have a different scale from the full active machine. [Portable setup and reproducible receipts](portable/README.md) · [Sequential locality proof](portable/STACK-LOCALITY.md) · [Signed execution and limits](VERIFICATION.md) + +Five inherited premises cover all-column native action, owned erasure, uniform compiler closure, fixed-tape movement and precision, and analytic decomposition and recovery. The complete theorem has the same research contract as the two peers. Lean checks the weighted per-owner capacities, physical placement, finite price conversion, rate gain and rank floors. [Weighted funding in Lean](WeightedNumerical.lean) · [Finite Gaussian loss in Lean](GaussianFiniteLoss.lean) · [Canonical assumption record](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/certificates/selected-result.json) + +## Reproduce + +Use Git and CPython 3.12 with assertions. The declared inputs include the exact preceding multiplier on this branch. + +```sh +python3.12 -IB scripts/research_package.py --package research/frequency-weighted-native-multiplier +python3.12 -IB research/frequency-weighted-native-multiplier/bootstrap.py /tmp/frequency-machine +python3.12 -B /tmp/frequency-machine/band_product.py -741503 466013 +``` + +The last command returns −345550037539 through the public small-input base. The registered suite exercises the complete Fourier product at a supplied finite geometry and the weighted physical production bodies separately. [Evidence and limitations](VERIFICATION.md) · [Attribution](NOTICE.md) + +## Open next questions + +- Can a different ordinary graph or a cheaper quotient exchange reduce the 517,430 floor for the present ordinary price? +- Can a different Gaussian word or transfer rule pass the upper-capacity cut that rejects a second-type frequency of 91 in this source at its funded trial? +- Can the outer controller and its true reserves run at tractable bit lengths? No crossover against a practical multiplier has been measured. diff --git a/research/frequency-weighted-native-multiplier/RESULT.json b/research/frequency-weighted-native-multiplier/RESULT.json new file mode 100644 index 0000000000..c7ed01eff9 --- /dev/null +++ b/research/frequency-weighted-native-multiplier/RESULT.json @@ -0,0 +1,155 @@ +{ + "gaussian": { + "trial": "17145637167/4398046511104", + "weights": [ + 1, + 90 + ], + "real_targets": [ + 52608, + 52608 + ], + "real_loans": [ + 282576, + 281568 + ], + "weighted_targets": 4787328, + "weighted_loans": 25623696, + "directed_margin": "2482376821822769941457432782/3600175653438683568314686428627268310425", + "grade_cells": 51, + "typed_cells": 88, + "min_individual_share": "25290615062637780010577697466743506026987874985828825071781589853404561/854265695345809624059507944639574456284113407212140972617470570470989933411600", + "raw_loss": "65081/524288", + "finite_loss": { + "debit": "65081/524288", + "lower_band": 2048, + "weighted_target_axes": 135150528, + "fringe": "32642264398770442661770629828025379509079856783215612937097949695118765130704354640723022281556881880684083266203536611314667574497763627821511459223801440416467092702689201078317529079701013898496002359064546014240048586736970821862758366036238960818316511482366221911627663487974861871704121840703848636213869704607515564177367148348791926786835535860295888404989448387666791056138672879850287608498523826346931410402595873123112312256372592325847600566120989031105701606970822248225557104059548822858466906332987392000000000/4306971313109778552846671079867282687416082775224288129533052962849014701068131296500682200612759775524888730861526498501072249271044745214390799393228329479800904040588652184265244829014918295127915130010247198920674577777325324452085037437916566652160768925195037813256995690156329031774231216344274700537713290788940276507081192862208241848488209362964875914393753469134157967920813431076206526638628282442873269779006130503157504931906957328953087563739014269220165342800989319101215983649305937727765352141564628884983229", + "psi_lower": "6881872030278219850868560284542904293487737654084100232699916837836034011177352473054141194907969817705905758995759818765586297874208681140501592336291219785264804676927791172958451341348658531733847990638411969659859963891492617435963308437067744298991561790631315043447555229671580832460745631300250661306313964132136105321494869475266714221564299319663785265983421280144687728466236313300070932901072174743956654852609245040365393339619243136307408096757695913718793775695735872424431223391310344258661264719419/38441537881352112612024389082547889346795204213477773235616356964580136458047906884248099741183755358974068270961899984988852419645417078980143958438787540355636525704140072247228746078967009818951030740581112744318307781922933808021355792233593442759218239173849532466988073751822539622960221567774250221378163398178556776787374182637146286836409715011611734181919095920221673282464325489788957820670144180783018472642983200817988743284268984660147607039846403952306606031135306155233211424387891200000000", + "upper_factor": "1069907057549017308067324398329850591066813050428089154191929788467267287601195666044534220798977922403476075189752872085612648744728472484895420187893272719564133859339539514191650094973236800696649245313930705081256257277547790009699821252727159500688534228653325030108145048410709335976957044343674548105110656548535123189314574684884222767974549340578743114862917268607323487458733143192891945781676055181154344619441148488192569471384478072225274048495617860886509667148642211465613928959533752623674520857816807592902587724907174860144088845325618530774308896711295440832671668790760817394473858526361907563974352421481136956763015671245307423127530534721873377066381354205184/981699750141125676331618335696637015745854699741901847851154455659793315449989382880025238594330163351693856122249504326746324634616155396166214179549284976044753335196668269397013884103579849759817912537942344880530713981384792669621636779350676168554027959248901840263049966159117520955326571935618826585221557367150688876557013303214139499095823272082876811362667409289645626073704122375648004506242013054642936728120593088577395370817160099749789734842421734183142711112904220488304858904736723947982037711400174918776331613958377585797125520160393170417787605693200546568318337879576218491095489176197615025033061211509690462063821288393545196060624794038910866718349462858125" + }, + "capacity_cut": { + "90": [ + "160534949783530073773261795162075101/324518553658426726783156020576256", + "40133737445882518443315448932550083/81129638414606681695789005144064" + ], + "91": [ + "-491919194256701957600730157813641411/324518553658426726783156020576256", + "-122979798564175489400182539309808557/81129638414606681695789005144064" + ] + } + }, + "entry": { + "kappa": "69/20000", + "ordinary_H": [ + 3000, + 3080 + ], + "numerical_H": 1024, + "ordinary_rates": [ + "3428763898577864693/1000000000000000000000", + "690000000000001/200000000000000000" + ], + "gaussian_rate": "16612493615/4398046511104", + "signed": { + "strict": 54, + "functional": 4, + "smallest_margin": "1/10000000000000000000", + "ordinary_margin": "1/1000000000000000000", + "positive_margin": "1098047753670637519659/3355443200000000000000000" + }, + "stock": { + "binary_cuts": [ + 3077, + 6221 + ], + "public_exponent_A": 7437, + "first_public_offset": 4, + "initial_s": 7438, + "stage_and_outer_fixed_log_overhead": 1964, + "retimed_first_stripe_margin": 1701, + "retimed_all_size_margin_floor": 1635, + "absolute_log2_private_control_envelope": 3153922, + "storage_upper": "6.2 p T < 297.6 n bits" + }, + "geometry": { + "public_offset_above_2_to_A": 4, + "first_extent_bits_minus_b": -7433, + "last_extent_bits_minus_b": -7432, + "minimum_width": 3809536, + "log2_axis_count": 7412, + "largest_axis_width": 5592406, + "private_clock_log2_upper": 5734316302, + "actual_dense_root_entry_log2": 11184812 + }, + "binary_surcharges": [ + 0, + 25818582 + ], + "log2_B": 125433359, + "log2_C": 125660241 + }, + "terminal": { + "kappa": "389821/100000000", + "ordinary_H": [ + 8192, + 129414, + 524288 + ], + "numerical_H": 483871, + "ordinary_rates": [ + "3718088605609114693/1000000000000000000000", + "3889553935785780311/1000000000000000000000", + "779642000000001/200000000000000000" + ], + "gaussian_rate": "8295730662636209/2128087163374403584", + "signed": { + "strict": 54, + "functional": 4, + "smallest_margin": "1/10000000000000000000", + "ordinary_margin": "1/1000000000000000000", + "positive_margin": "1143237735274919989/1623601656627200000000000000000" + }, + "stock": { + "binary_cuts": [ + 8290, + 137768, + 662120 + ], + "public_exponent_A": 1146239, + "first_public_offset": 4, + "initial_s": 1146240, + "stage_and_outer_fixed_log_overhead": 1968, + "retimed_first_stripe_margin": 571066, + "retimed_all_size_margin_floor": 553239, + "absolute_log2_private_control_envelope": 536870915, + "storage_upper": "6.2 p T < 297.6 n bits" + }, + "geometry": { + "public_offset_above_2_to_A": 4, + "first_extent_bits_minus_b": -1146235, + "last_extent_bits_minus_b": -1146234, + "minimum_width": 586876160, + "log2_axis_count": 1146207, + "largest_axis_width": 715827883, + "private_clock_log2_upper": 734182716800, + "actual_dense_root_entry_log2": 1431655766 + }, + "binary_surcharges": [], + "log2_B": 211806208, + "log2_C": 318259430 + }, + "previous_rate": "38982016137/10000000000000", + "rate_delta": "83863/10000000000000", + "complete_log2_C": 318259431, + "entry_price_surcharge": 514, + "fixed_funding_height_floors": [ + 517430, + 483870 + ], + "log2_fixed_setup_upper": 113, + "log2_portable_setup_guard": 146, + "log2_full_store_setup_upper": 142, + "portable_setup_transition_upper": "8788853932655975457155330527461376", + "max_native_H": 524288 +} diff --git a/research/frequency-weighted-native-multiplier/SOURCES.json b/research/frequency-weighted-native-multiplier/SOURCES.json new file mode 100644 index 0000000000..2edf3073fc --- /dev/null +++ b/research/frequency-weighted-native-multiplier/SOURCES.json @@ -0,0 +1,195 @@ +{ + "schema_version": 1, + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "files": [ + { + "path": "AGENTS.md", + "git_blob": "ff81117fca368042f6092964d1f54eb4e6e08fb9", + "sha256": "fece32cdec9c1572ddce354a0b623459cb2c4ca162125d36d36262a92e3caa83", + "usage": "provenance" + }, + { + "path": "autoresearch.md", + "git_blob": "2fe84a7b30b1e26e60ce0ec4775894eb1831c5d6", + "sha256": "d16f0d3bb4d4b213d06c128db6d6460b0fe9ec1ac5a6c1ea1febf1db40e7b60d", + "usage": "provenance" + }, + { + "path": "CONTRIBUTING.md", + "git_blob": "5185786f2ec00f215019fb5777d70979429690a9", + "sha256": "fcd1a8d0e52342a23b8ffa9e905e85ccc539fb084145ef016dfc93cedfb3d924", + "usage": "provenance" + }, + { + "path": "certificates/selected-result.json", + "git_blob": "75d77b328ea02ded535e7f23aee5b1e55d0bb1a8", + "sha256": "154c3d30455d778fd3343b6b4851f0fa4665f0f7625b0adb3675e2bafbbf6bf1", + "usage": "provenance" + }, + { + "path": "docs/research/agent-task-catalog.json", + "git_blob": "3404fbdd5e7529a0674eef26114b5071e4586cec", + "sha256": "ead6cdc9d0af6d58e8a49744d8ec8c7c15e13d2ba93c276c434bcf9b51b93a81", + "usage": "provenance" + }, + { + "path": "research/unconditional-batched-crt/CRT.md", + "git_blob": "d98dd8e368431cac33d5fc1c8c336696663641d6", + "sha256": "02c3a1e38cbee25aefe2640cc72676da62ba10eb7519fbcb9adb9d48b74eff2b", + "usage": "provenance" + }, + { + "path": "research/delayed-cover-physical-batch-routing/PROOF.md", + "git_blob": "af919b5ba2257c07ea17180f9b8c9fd457556079", + "sha256": "1c3dcd294d327a16fa081b7ea27497941ac6480d352f53e55e8b9e87f45d1454", + "usage": "provenance" + }, + { + "path": "notes/compact-control-movement.tex", + "git_blob": "06b6a9ef24245ac7b724c53a204635415b402357", + "sha256": "b963c3d2f4e1b7059aa289bb4b4ac89b688920bcf42f5b20d7698cdef0132cc6", + "usage": "provenance" + }, + { + "path": "research/tiered-native-multiplier/SOURCES.json", + "usage": "input", + "pin": "head:7b48187d99525ad59f560de3921ec7e48382484c:research/tiered-native-multiplier/SOURCES.json", + "git_blob": "9d532ab36fa256de90128e3d795ffa62771053e6", + "sha256": "7a10012734132909e99b0c6160d68d0b8647e1607d25679efb1f5315cf8e23de" + }, + { + "path": "research/tiered-native-multiplier/bootstrap.py", + "usage": "input", + "pin": "head:7b48187d99525ad59f560de3921ec7e48382484c:research/tiered-native-multiplier/bootstrap.py", + "git_blob": "89c6726b374c74abe86c56f1463678d9a0f0d03f", + "sha256": "74ac8f1d3af21f86cda48a3d50084d6fa5faf84b44ec2e5929b587f40f5bcfd1" + }, + { + "path": "research/tiered-native-multiplier/grades.py", + "usage": "input", + "pin": "head:7b48187d99525ad59f560de3921ec7e48382484c:research/tiered-native-multiplier/grades.py", + "git_blob": "18b3041f682ba8ae06cebf0f701af6200ebb8b85", + "sha256": "340684fdd5ca0e611836b0e7301f1c339282ba532bf9e3ec8055944d8981f3c8" + }, + { + "path": "research/tiered-native-multiplier/installations.py", + "usage": "input", + "pin": "head:7b48187d99525ad59f560de3921ec7e48382484c:research/tiered-native-multiplier/installations.py", + "git_blob": "9bc60df559399566f15ea910dfadc66eb472ac89", + "sha256": "1c6978b8c7d136ef87191512d9ab9eb3dda8a818844244b96cb165d46d97b1df" + }, + { + "path": "research/tiered-native-multiplier/runtime.patch", + "usage": "input", + "pin": "head:7b48187d99525ad59f560de3921ec7e48382484c:research/tiered-native-multiplier/runtime.patch", + "git_blob": "cd895f6240fcba916047013240e68046adece6d0", + "sha256": "6c93961841be2abc3629928074e2c7917d264e94187276fc88a33f922a3c62e4" + }, + { + "path": "research/tiered-native-multiplier/source/INSTALLER-NOTICE.md", + "usage": "input", + "pin": "head:7b48187d99525ad59f560de3921ec7e48382484c:research/tiered-native-multiplier/source/INSTALLER-NOTICE.md", + "git_blob": "5299fe7196dff94d7ec0c4fb0baff504f341e0ac", + "sha256": "c6b1753ad6ebda2a2143b1a9efc80fadad6c1b27552c3ec8bc7bfdb431fb8eeb" + }, + { + "path": "research/tiered-native-multiplier/source/K7-NOTICE.md", + "usage": "input", + "pin": "head:7b48187d99525ad59f560de3921ec7e48382484c:research/tiered-native-multiplier/source/K7-NOTICE.md", + "git_blob": "d1a9e0924d384bef8bd4878559c3974f0ce5dc79", + "sha256": "9c5ae9750012d305d917e625d14a33cc880e810e801e73364725bcdc24bffdb5" + }, + { + "path": "research/tiered-native-multiplier/source/K7-STACK-LEDGER.json", + "usage": "input", + "pin": "head:7b48187d99525ad59f560de3921ec7e48382484c:research/tiered-native-multiplier/source/K7-STACK-LEDGER.json", + "git_blob": "2add885cf9c2f4df54761833e0fb2e2e41f125ce", + "sha256": "a0c0d5b241e6861a5c49a287617e48fba56b09824f5ef4fcb7f03152edf37e8e" + }, + { + "path": "research/tiered-native-multiplier/source/activation.py", + "usage": "input", + "pin": "head:7b48187d99525ad59f560de3921ec7e48382484c:research/tiered-native-multiplier/source/activation.py", + "git_blob": "20525c7fa39de6300e0a01b1e0155dbc324d6940", + "sha256": "6e7f89d40a4d10ecd40a50e5b96334dfc64db90841ece7e3ef12eeca5ee5093b" + }, + { + "path": "research/tiered-native-multiplier/source/check_binary_k7.py", + "usage": "input", + "pin": "head:7b48187d99525ad59f560de3921ec7e48382484c:research/tiered-native-multiplier/source/check_binary_k7.py", + "git_blob": "5d5d9173f47ae608b150a6870c1b08d3ac97c7b8", + "sha256": "5eeb8f818725249cbabf215c323c3f8351b1c4ed3c127119341e6ed09f490dd6" + }, + { + "path": "research/tiered-native-multiplier/source/installer.tar.gz", + "usage": "input", + "pin": "head:7b48187d99525ad59f560de3921ec7e48382484c:research/tiered-native-multiplier/source/installer.tar.gz", + "git_blob": "2595a83633ea02c658a0e0c4f0989a4be6e3c04e", + "sha256": "6696459e2e3552f802e7caaaf93dc86c9bb6b62ee38631702bff2e3a8a9a481a" + }, + { + "path": "research/tiered-native-multiplier/source/ordinary_clock.py", + "usage": "input", + "pin": "head:7b48187d99525ad59f560de3921ec7e48382484c:research/tiered-native-multiplier/source/ordinary_clock.py", + "git_blob": "87c72664af8f888a7b6f8892d51b609685f1471a", + "sha256": "91dcf0ef72dddbde998b80f3d8b30c8036de9ce97e06e2bbd9c4159bf292020d" + }, + { + "path": "research/tiered-native-multiplier/source/outer_budget.py", + "usage": "input", + "pin": "head:7b48187d99525ad59f560de3921ec7e48382484c:research/tiered-native-multiplier/source/outer_budget.py", + "git_blob": "35dd5cf836431661bcd306eadcd1da36cccca669", + "sha256": "ca4438db28a447ed5c43d87d43f0ac10a0cb2b4e183342ac93139d517b9d4d02" + }, + { + "path": "research/tiered-native-multiplier/source/outer_clock.py", + "usage": "input", + "pin": "head:7b48187d99525ad59f560de3921ec7e48382484c:research/tiered-native-multiplier/source/outer_clock.py", + "git_blob": "3c4fa183a077c1d9782753cbe1410fe4b161c15e", + "sha256": "63363c3da673365f3ac5e1b7e318c6938005f1e9c9896799504cc598efbf96fa" + }, + { + "path": "research/tiered-native-multiplier/source/strong-bit-k7.json.gz", + "usage": "input", + "pin": "head:7b48187d99525ad59f560de3921ec7e48382484c:research/tiered-native-multiplier/source/strong-bit-k7.json.gz", + "git_blob": "f334b505e60189e00a39a02a22279d579bcc2e7f", + "sha256": "9e7392c52bcf29c0cc58c54c619f95c28f476394c33e8e0a5aa30c9557d31362" + }, + { + "path": "research/tiered-native-multiplier/TierCost.lean", + "usage": "input", + "pin": "head:7b48187d99525ad59f560de3921ec7e48382484c:research/tiered-native-multiplier/TierCost.lean", + "git_blob": "716dec61d18f87b6195c1bb9620c9f98caaba5a0", + "sha256": "668a248d1060dd4fe97a0edb6652cb3782b8ba4ccc0d00ec73ee6ae253eb9945" + } + ], + "predecessor": "7b48187d99525ad59f560de3921ec7e48382484c", + "local_sources": { + "runtime.patch": "f35d37cc1746b5a7ac137a3f6de6de887a24f3af578283c24a64c8a25ccc584b", + "typed_raw.py": "0c268432c9d48798c17d927f2d900b5e69dfc6585166cd71f253913e389c3b47", + "typed_transport.py": "b76b9ad3dc0dd91473026c079585f830387eaa3c34c25a7820ee5057d5cbf941", + "grades.py": "8d2e3d14ac2149f985d7f6a75bf36182d7f68aadf8df6595fc0774224d4951ac" + }, + "runtime_images": { + "installations.py": { + "before": "1c6978b8c7d136ef87191512d9ab9eb3dda8a818844244b96cb165d46d97b1df", + "after": "376c45a08f24daafc628c0f7c9d95f631a0283a4b0c5aea41caf0f155a6ec71b" + }, + "retimed_supplier.py": { + "before": "9c89e67dcc480f2a3664f15446159701c98ef9d7518dbd175baf9a76453eb82f", + "after": "2a87c2781ca93fa854aee098dcb7c50a65f2a46267ba926e3997b442e5a25f2c" + }, + "grades.py": { + "before": "340684fdd5ca0e611836b0e7301f1c339282ba532bf9e3ec8055944d8981f3c8", + "after": "8d2e3d14ac2149f985d7f6a75bf36182d7f68aadf8df6595fc0774224d4951ac" + } + }, + "live_peer_comparison": { + "pr": "https://github.com/CrocSwap/integer-mult-bounds/pull/8056", + "head": "c5cbef6e558542d6e809aabb6ead89b9e51f7b1c", + "result": "research/p104-gaussian-rounded-partitions/RESULT.json", + "kappa": "38982016137/10000000000000", + "gaussian_trial": "4286126377/1099511627776", + "usage": "Comparison only. The new physical job types use equal half cuts in the first job. The rounded quarter packets belong to the peer." + } +} diff --git a/research/frequency-weighted-native-multiplier/TASK.json b/research/frequency-weighted-native-multiplier/TASK.json new file mode 100644 index 0000000000..d8e5e0093e --- /dev/null +++ b/research/frequency-weighted-native-multiplier/TASK.json @@ -0,0 +1,95 @@ +{ + "schema_version": 1, + "task_id": "selected-stock-envelope", + "priority_revision": 8, + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "original_card": { + "id": "selected-stock-envelope", + "question": "What explicit uniform stock envelope does the actual selected stopped producer supply at one bootstrap stage?", + "starting_points": [ + "research/selected-bootstrap-stock-audit/README.md", + "research/bootstrap-cutoff-time-space-split/README.md", + "certificates/selected-result.json", + "docs/research/community-efficient1000-review.md", + "research/stock-margin-chain/README.md" + ], + "methods": [ + "Derive a source-bound reserve recurrence at the actual selected atom widths, separating parent stock from completed inner borrowing.", + "Find an exact missing implication or counterexample to a proposed selected-stage stock envelope." + ], + "acceptance_gate": "Bind every coefficient and depth factor to the selected producer and state the width domain. Compare a proved envelope with the sufficient cutoff guard; a large numerical headroom or a historical m=120 coefficient is not a selected m=73 proof.", + "first_step": { + "command": [ + "python3", + "-B", + "scripts/research_selected_baseline.py" + ], + "expected": "PASS_RESEARCH_BASELINE_BINDINGS_ONLY", + "inspect": "Resolve the current selected review, separate complex/ordinary BIT/admitted BIT/outer budgets, and compare the card against live handoffs before starting. Historical ceilings require exact source/model equivalence.", + "scope": "Source-binding orientation only; not a scientific replay or all-size proof. Materialize selected inputs if this checkout is sparse." + }, + "first_experiment": "Choose one actual selected producer/stage and derive its parent reserve and depth coefficient from source. Check whether newer handoffs already cover that exact obligation. Stop with the missing implementation lemma if it cannot be bounded; do not rerun #2972 cutoff/headroom arithmetic as a new contribution.", + "bottleneck_link": "This reduces a concrete inherited implementation obligation without confusing unchanged kappa arithmetic with a completed theorem.", + "allowed_variations": [ + "One stage or one explicit reserve/depth implication.", + "An independently checked same-domain proof repair, retaining all remaining assumptions." + ], + "scope_change_triggers": [ + "Importing the historical 57604 or 252 allowance without a selected-producer binding.", + "Calling a conditional fit lemma a full outer-proof adoption.", + "Replacing an actual selected stock coefficient with cutoff comparisons or a conditional fit inequality." + ], + "overlap_terms": [ + "selected stock", + "stock envelope", + "bootstrap cutoff", + "1956", + "1965", + "1990", + "2972", + "stock-margin-chain", + "actual_stock_coefficient" + ], + "existing_checks": [ + { + "scope": "Retained stock audit identifies missing actual selected-stage coefficients; later cutoff-chain arithmetic does not supply them.", + "evidence": "docs/research/research-family-status.md#revision-6-handoffs-source-archives-awaiting-independent-validation", + "remaining": "Derive one actual reserve/depth coefficient from the selected producer.", + "status": "reviewed", + "source_commit": "836b19bfa309ceafbc8ee32a15e8c4b10dde7e11", + "selected_record_sha256": "bb2eaa58647b353f88d0aec2eafb9d30df1be53589231b23e12ceef3e4bad129" + } + ] + }, + "claim": "https://github.com/CrocSwap/integer-mult-bounds/discussions/8039#discussioncomment-19819530", + "related": [ + "https://github.com/CrocSwap/integer-mult-bounds/pull/8027", + "https://github.com/CrocSwap/integer-mult-bounds/pull/8030", + "https://github.com/CrocSwap/integer-mult-bounds/pull/8035", + "https://github.com/CrocSwap/integer-mult-bounds/pull/8042", + "https://github.com/CrocSwap/integer-mult-bounds/pull/8050", + "https://github.com/CrocSwap/integer-mult-bounds/pull/8051", + "https://github.com/CrocSwap/integer-mult-bounds/pull/8052", + "https://github.com/CrocSwap/integer-mult-bounds/pull/8053", + "https://github.com/CrocSwap/integer-mult-bounds/pull/8054", + "https://github.com/CrocSwap/integer-mult-bounds/pull/8055", + "https://github.com/CrocSwap/integer-mult-bounds/pull/8056" + ], + "scope_status": "changed", + "actual_scope": "Execute two independently weighted Gaussian job types, prove the actual-edge finite loss at lower band 2048, and fund the two ordinary entry stages and three terminal stages. Generate the fixed machinery and initialize its cold receiver, including the complete tape-transition cost.", + "scope_change_reason": "The 1-to-79 construction needs a large physical column dilation. Different birth frequencies can supply the needed observations at widths f and 2f.", + "bottleneck_link": "The directed grade-two capacity limits the relative birth frequency. The funded ordinary debit sets the remaining floor of 517430, even if the number of stages grows.", + "stop_rule": "Require independent charged calendar execution, true Gaussian jobs, both signed tiers, exact rate, all stage cuts and the complete recurring and fixed clocks.", + "evidence": "RESULT.json, PROOF.md, registered physical and arithmetic checks, WeightedNumerical.lean and independent kernel replay. The portable two-flight proof, generated directory identity and signed receiver are in portable/.", + "author": "Ali Romman", + "ai_assistance": "Substantial OpenAI Codex assistance on the construction, proofs and adversarial checks.", + "outcome": "completed", + "open_questions": [ + { + "question": "Can a different ordinary word or quotient exchange reduce the 517430 lower bound on maximum H for this funding rule?", + "why_it_matters": "The maximum installed height 524288 is within 1.33% of this ordinary floor.", + "first_step": "Construct a lower-cost real quotient receiver or a binary word with greater paid capacity and reprice the two complete stages.", + "blocked_by": "The present binary raw moment and paid quotient exchanges determine both finite stage debits." + } + ] +} diff --git a/research/frequency-weighted-native-multiplier/VERIFICATION.md b/research/frequency-weighted-native-multiplier/VERIFICATION.md new file mode 100644 index 0000000000..525fde62f9 --- /dev/null +++ b/research/frequency-weighted-native-multiplier/VERIFICATION.md @@ -0,0 +1,37 @@ +# Evidence and limits + +The registered replay rebuilds the producer on the pinned K7 and signed multiplier images. It verifies the predecessor's immutable archive and before/after file hashes, then verifies and applies the frequency-weighted overlay. Both Gaussian recipes refer to the same installed circuit and grade shares. [Bootstrap](bootstrap.py) · [Registration](VERIFY.json) + +| Evidence | What was checked | +|---|---| +| Directed numerical and complete price | Recount the literal labels from the raw graph. Check all per-type row sums, individual owner capacities, actual placements, both ordinary savings, the complete signed gates, stock and clock. The unscaled grade-two cut rejects frequency 91 despite positive aggregate mass. [Receipt program](receipt.py) · [Exact numbers](RESULT.json) · [Separate 192-bit weighted and peer check](independent_price.py) | +| Calendar and ownership | The full finite two-type chart run uses 2,048 dirty independent rows, issues 951,040 elementary actions, frees 37,152 temporary zero owners and matches an independent noncommuting action at each output. A second interpreter checks the typed chronology at 1:90 on 25,120 frames and 39,040 distinct exterior rows. It observes 16,848 simultaneous frames, 862,608 paid axes and 12,344 child returns exactly at the next lender event. [Chart execution](check_calendar.py) · [Independent event accounting](check_ownership.py) | +| Signed physical words | The actual Gaussian interpreter runs both full words on nonzero product-state witnesses at 2 and 4 columns. The jobs have 52,608 true productive owners each and 282,576 or 281,568 ordered loans. Each executes 71,808 owner writes and returns every private handle. The witnesses use a tensor representation. The all-column operator identity and its numerical hypotheses are written mathematics. [Physical source check](check_raw.py) | +| Exterior to physical jobs | On the single test bin [10,12), all productive funding is exterior. The test regenerates the two first independent replicas' true source fractions, disjoint row ordinals and cycles. It executes both complete Gaussian words through the installed event emitter and ordinary decoder. It charges 4,456,224 elementary axes, including 234 on nonzero rays, and matches both independent expected outputs. The projection covers two births. The calculated full bin counts are 4,735,181,960,750 and 426,166,376,467,422. [Projection and physical return](check_exterior.py) | +| Interior nonzero field | At band 24 the 16-column parent delivers an eight-axis prefix from its actual paid cut 3,418 to the type-one helper at owner ordinal 9,841. The other eight axes are paid on the parked parent. Two child loans and the returned parent carry nonzero data. Both entire Gaussian words finish, their states match independent tensor actions, and scratch returns to zero after 118,692 peak handles. This fixture selects one of the 899,557,645 genuine grants at that edge. [Nested physical witness](check_nested.py) | +| Complete signed caller | The public entry checks zero, signs, padded byte intervals, both input heads and independent magnitudes. The finite physical Fourier control returns −345550037539 for −741503 × 466013, with the expected base-256 coefficients 11811, 10996, 4152, 868, 77. The supplied rank-two geometry uses 138 shuttles, 157,248 H calls and 633,744 padded bytes. The controller's normal small-input branch uses its scalar base at those operand lengths. [Product and installation checks](verify.py) | + +A public product at the proved fast threshold and a performance crossover remain outside executable evidence. At the entry bound the controller needs $2^{7412}$ true axes. The setup timings measure fixed compilation. The upper bound on $C$ counts worst-case tape transitions. + +## Matched fixed installation + +Four fresh CPython 3.12.16 processes on macOS 27.2 arm64 restored the authenticated program, built both complete tiers, checked all recipe ranks and common K7 bytes, and removed the temporary tree. Order was dilation, weighted, weighted, dilation. The two dilation-79 runs took 6.832 and 5.480 seconds. The two frequency-weighted runs took 6.977 and 6.408 seconds. Their respective means were 6.16 and 6.69 seconds. Peak compiler RSS ranged from 253,050,880 to 259,883,008 bytes. This sample covers an actual third ordinary stage and provides no evidence of an additional installation speedup. In the preceding study a newly published unsplit-return peer took 94.90 seconds against 5.06 seconds for the quadratic-compiler predecessor. The actual work saved at installation came primarily from the quadratic phase compiler and shared role lists. Moving from 62 to 51 installed grade cells is offset in active compilation by 88 type-specific shares. [Weighted observations and contracts](MEASUREMENTS.json) · [Measurement code](measure_setup.py) · [Earlier matched installation](https://github.com/aliromman/integer-mult-bounds/blob/7b48187d99525ad59f560de3921ec7e48382484c/research/tiered-native-multiplier/SETUP.md) + +A second matched run compared the current rounded-quarter peer directly with this multiplier under the same source-to-ready contract. The peer installed its complete extended profile in 85.503 and 83.002 seconds. The new native compiler installed both tiers in 5.205 and 5.748 seconds. The mean fell from 84.25 to 5.48 seconds (15.38-fold). Peak resident sizes in these four runs ranged from 273,612,800 to 309,903,360 bytes. The ordinary circuit digest matched on all runs. These wall times include complete generation and removal of the temporary tree. They measure native CPython installation on this host. The portable two-run setup ceiling and full multiplication time have separate evidence. To reproduce, run the following two commands in separate fresh processes in peer, candidate, candidate, peer order. The first argument below names a checkout of the peer package at its pinned revision. [Rounded-quarter peer](https://github.com/CrocSwap/integer-mult-bounds/pull/8056) · [Raw observations](MEASUREMENTS.json) + +```sh +python3.12 -IB research/frequency-weighted-native-multiplier/measure_setup.py --quarter-peer /path/to/research/p104-gaussian-rounded-partitions +python3.12 -IB research/frequency-weighted-native-multiplier/measure_setup.py +``` + +## Portable fixed installation + +The portable initializer runs the actual compiler, emits a directory and connects it to the original signed operator in a fresh receiver. Its two invocations used 802,083,502,514 and 132,344,680,603 Wasmtime fuel units. Their final linear memories were 331,808,768 and 153,878,528 bytes. WebAssembly memory can only grow during these runs. Fuel measures the metered guest. The proof includes all zero-fuel instruction sequences, suspended stack movement, the virtual file service, serial seeks, floating-point arithmetic and the complete transfer to the receiver. The registered price check recomputes the invoice from the saved finite evidence. The separate release replay regenerates that evidence from the pinned public inputs. Wasmtime and CPython execution and their correspondence with the written interpreter are outside Lean. The smaller setup ceiling can also reflect tighter accounting than that available for another machine. [Replay and receipts](portable/README.md) · [Tape transition proof](portable/TRACE-CLOCK.md) · [Whole-store and active-stack prices](portable/STACK-LOCALITY.md) + +## Formal coverage + +Lean 4.34.1 with Mathlib revision d13f23b723b8a846827a245b89c10fc7d3f11612 builds the weighted row and column implications, the integer placement and ticket fences, the 514-bit finite-prefix charge, the two height floors under the fixed funding rules, and the strict gain over PR #8056. The additional Gaussian proof verifies the logarithmic lower sum for every eligible edge and the active-depth volume inequality for every recursion depth. The separate leanchecker accepts all proof objects. [Gaussian finite-loss theorems](GaussianFiniteLoss.lean) The reported axioms are propext, Classical.choice and Quot.sound. The dependency on the assumptions of the complete multiplication theorem and the relation between the physical program and the finite matrices are outside Lean. [Formal statements](WeightedNumerical.lean) · [Written proof](PROOF.md) + +```sh +python3.12 -IB research/frequency-weighted-native-multiplier/check_lean.py LEAN_ROOT MATHLIB_ROOT +``` diff --git a/research/frequency-weighted-native-multiplier/VERIFY.json b/research/frequency-weighted-native-multiplier/VERIFY.json new file mode 100644 index 0000000000..95b558182b --- /dev/null +++ b/research/frequency-weighted-native-multiplier/VERIFY.json @@ -0,0 +1,92 @@ +{ + "schema_version": 1, + "status": "ready", + "python": "3.12", + "requirements": [], + "inputs": [ + "research/tiered-native-multiplier/SOURCES.json", + "research/tiered-native-multiplier/bootstrap.py", + "research/tiered-native-multiplier/grades.py", + "research/tiered-native-multiplier/installations.py", + "research/tiered-native-multiplier/runtime.patch", + "research/tiered-native-multiplier/source/INSTALLER-NOTICE.md", + "research/tiered-native-multiplier/source/K7-NOTICE.md", + "research/tiered-native-multiplier/source/K7-STACK-LEDGER.json", + "research/tiered-native-multiplier/source/activation.py", + "research/tiered-native-multiplier/source/check_binary_k7.py", + "research/tiered-native-multiplier/source/installer.tar.gz", + "research/tiered-native-multiplier/source/ordinary_clock.py", + "research/tiered-native-multiplier/source/outer_budget.py", + "research/tiered-native-multiplier/source/outer_clock.py", + "research/tiered-native-multiplier/source/strong-bit-k7.json.gz", + "research/tiered-native-multiplier/TierCost.lean" + ], + "commands": [ + { + "argv": [ + "{python}", + "-I", + "-B", + "{package}/verify.py", + "price" + ], + "timeout_seconds": 140, + "checks": "Build all seven recipes. Check every weighted row, both complete prices, activation, the frequency-91 cut, and the two portable tape invoices from the recorded runs." + }, + { + "argv": [ + "{python}", + "-I", + "-B", + "{package}/verify.py", + "calendar" + ], + "timeout_seconds": 160, + "checks": "Run the two-type clock on opaque charts and independently trace loans, distinct owners and every deadline." + }, + { + "argv": [ + "{python}", + "-I", + "-B", + "{package}/verify.py", + "raw" + ], + "timeout_seconds": 170, + "checks": "Run both native Gaussian job types with nonzero exact rays and restore all physical owners." + }, + { + "argv": [ + "{python}", + "-I", + "-B", + "{package}/verify.py", + "exterior" + ], + "timeout_seconds": 190, + "checks": "Generate the first two actual exterior births in a finite bin, execute their complete signed operations and return all owners." + }, + { + "argv": [ + "{python}", + "-I", + "-B", + "{package}/verify.py", + "nested" + ], + "timeout_seconds": 200, + "checks": "Borrow the actual nonzero eight-axis prefix at paid ordinal 3418 across two complete signed physical kernels and verify both returns." + }, + { + "argv": [ + "{python}", + "-I", + "-B", + "{package}/verify.py", + "product" + ], + "timeout_seconds": 220, + "checks": "Run the signed public entry and a complete finite Fourier product with independent coefficient and restoration checks." + } + ] +} diff --git a/research/frequency-weighted-native-multiplier/WeightedNumerical.lean b/research/frequency-weighted-native-multiplier/WeightedNumerical.lean new file mode 100644 index 0000000000..ad5bdf9401 --- /dev/null +++ b/research/frequency-weighted-native-multiplier/WeightedNumerical.lean @@ -0,0 +1,88 @@ +import TierCost + +namespace WeightedNumerical + +/-- A grade share is distributed in proportion to each owner's positive frequency. -/ +theorem rowLift {K : Type*} [Fintype K] (I : K → Type*) [∀ k, Fintype (I k)] + (p : K → ℚ) (w : ∀ k, I k → ℚ) (row : (∑ k, p k) = 1) + (mass : ∀ k, 0 < ∑ i, w k i) : + (∑ k, ∑ i, p k * w k i / (∑ j, w k j)) = 1 := by + calc + _ = ∑ k, p k := by + apply Finset.sum_congr rfl + intro k _ + calc + _ = ∑ i, (p k / (∑ j, w k j)) * w k i := by + apply Finset.sum_congr rfl + intro i _ + ring + _ = (p k / (∑ j, w k j)) * (∑ i, w k i) := by rw [Finset.mul_sum] + _ = p k := by field_simp [ne_of_gt (mass k)] + _ = 1 := row + +/-- The aggregate grade bound implies the service capacity of each physical owner. -/ +theorem columnLift {R : Type*} [Fintype R] (source share : R → ℚ) + (w n k : ℚ) (owner : 0 ≤ w) (mass : 0 < n) + (available : (∑ j, source j * share j) ≤ n * k) : + (∑ j, source j * (share j * w / n)) ≤ w * k := by + calc + _ = ∑ j, (w / n) * (source j * share j) := by + apply Finset.sum_congr rfl + intro j _ + ring + _ = (w / n) * ∑ j, source j * share j := by rw [Finset.mul_sum] + _ ≤ (w / n) * (n * k) := mul_le_mul_of_nonneg_left available (div_nonneg owner mass.le) + _ = w * k := by field_simp [ne_of_gt mass] + +def upper (M : ℕ) := 2*(M/(2048*306)) +def band (M : ℕ) := 2*((3*upper M)/8) +def actualSize (M : ℕ) := 258*(band M-8) + +/-- The external parent interval and the integral period satisfy the physical size bounds. -/ +theorem placement (M : ℕ) (large : 10^13 ≤ M) : + (32768 < band M) ∧ (112 * upper M < 258 * band M) ∧ + ((band M+2)*258 < 112*M) ∧ (1616 * actualSize M < M) ∧ + (M+6000 < 1620*actualSize M) := by + simp only [upper, band, actualSize] + omega + +theorem tickets (M : ℕ) (large : 10^13 ≤ M) : + 3240 < 5 * ((1620*actualSize M - M)/4) ∧ 1620/5 = 324 ∧ 3240/5 = 648 := by + have h := (placement M large).2.2.2.2 + omega + +/-- The complete controller pays for all low-tier inputs at the high-tier rate. -/ +theorem prefixInvoice (x : ℝ) (hx : 0 < x) (bound : x ≤ (2:ℝ)^(1146239:ℝ)) : + x^(1-(345:ℝ)/100000) ≤ x^(1-(389821:ℝ)/100000000) * (2:ℝ)^(514:ℝ) := by + apply (TierCost.finitePrefix x 1146239 (345/100000) (389821/100000000) hx bound (by norm_num)).trans + apply mul_le_mul_of_nonneg_left _ (Real.rpow_nonneg hx.le _) + exact Real.rpow_le_rpow_of_exponent_le (by norm_num) (by norm_num) + +theorem strictIncrease : + (389821:ℚ)/100000000 - 38982016137/10000000000000 = 83863/10000000000000 := by norm_num + +/-- Adding ordinary stages cannot exceed the maximum funded local price. -/ +theorem boundedStages (b price : ℕ → ℚ) (cap : ℚ) (start : b 0 ≤ cap) + (localBound : ∀ i, price i ≤ cap) + (funded : ∀ i, b (i+1) ≤ (249 * price i + b i) / 250) : ∀ i, b i ≤ cap := by + intro i + induction i with + | zero => exact start + | succ i ih => linarith [localBound i, funded i] + +/-- Both thresholds use the same ordinary and numerical costs as the signed caller. -/ +theorem priceFloors : + ((4391986206293:ℚ)/2^50 - 11/(8*517429) < + 389821/100000000 + 5/(10^18)) ∧ + ((17145637167:ℚ)/2^42 - 65081/(2^19*483869) < + 389821/100000000 + 5/(10^18)) := by norm_num + +#print axioms boundedStages +#print axioms priceFloors +#print axioms prefixInvoice +#print axioms strictIncrease +#print axioms rowLift +#print axioms columnLift +#print axioms placement +#print axioms tickets +end WeightedNumerical diff --git a/research/frequency-weighted-native-multiplier/bootstrap.py b/research/frequency-weighted-native-multiplier/bootstrap.py new file mode 100644 index 0000000000..46de56ff40 --- /dev/null +++ b/research/frequency-weighted-native-multiplier/bootstrap.py @@ -0,0 +1,42 @@ +"""Install the frequency-weighted producer in the authenticated signed multiplier.""" + +from argparse import ArgumentParser +from hashlib import sha256 +import json +from pathlib import Path +from shutil import copyfile +from subprocess import run +import sys + +HERE = Path(__file__).resolve().parent +PREDECESSOR = HERE.parent / "tiered-native-multiplier" + + +def install(destination): + path = Path(destination).resolve() + pins = json.loads((HERE / "SOURCES.json").read_bytes()) + for name, digest in pins["local_sources"].items(): + if sha256((HERE / name).read_bytes()).hexdigest() != digest: + raise ValueError(f"Unexpected weighted producer input: {name}") + run( + [sys.executable, "-IB", str(PREDECESSOR / "bootstrap.py"), str(path)], + check=True, + ) + for phase in ("before", "after"): + for name, digests in pins["runtime_images"].items(): + if sha256((path / name).read_bytes()).hexdigest() != digests[phase]: + raise ValueError(f"Unexpected {phase} image for {name}") + if phase == "before": + run( + ["git", "apply", "--no-index", str(HERE / "runtime.patch")], + cwd=path, + check=True, + ) + for name in ("grades.py", "typed_raw.py", "typed_transport.py"): + copyfile(HERE / name, path / name) + + +if __name__ == "__main__": + parser = ArgumentParser(description=__doc__) + parser.add_argument("destination", type=Path) + install(parser.parse_args().destination) diff --git a/research/frequency-weighted-native-multiplier/check_calendar.py b/research/frequency-weighted-native-multiplier/check_calendar.py new file mode 100644 index 0000000000..51f810a105 --- /dev/null +++ b/research/frequency-weighted-native-multiplier/check_calendar.py @@ -0,0 +1,89 @@ +"""Exercise cross-type loans on real dirty finite chart records.""" + +from fractions import Fraction as Q +from random import Random +from pathlib import Path +import sys + +RUNTIME = Path(sys.argv[1]).resolve() +sys.path.insert(0, str(RUNTIME)) +from upstream import install + +install() +from check_band import Chart, ChartJob +from periodic import Rule +from typed_transport import NativeType, TypedPlan + + +def run(): + a = Rule(2, (2,), (1, 1)) + b = Rule(2, (2, 2), (1, 1, 1, 1)) + types = tuple(NativeType(s.targets, s.paid, m) for s, m in ((a, 1), (b, 2))) + shares = {(0, 1, 1, 2): Q(1), (1, 1, 0, 2): Q(1, 4), (1, 1, 1, 2): Q(3, 4)} + p = TypedPlan( + 192, + types, + shares, + Q(1), + 10, + 30, + 1200, + 5, + 16, + delay_base=4, + scale_step=Q(2), + padding=1, + ) + # Each side of the funding exchange must have at least one real loan. + edges = {(kind, r.kind) for (e, kind, j), xs in p.send.items() for r in xs} + assert (0, 1) in edges and (1, 0) in edges + ca = Chart(a, ((1, 1),), p.n) + cb = Chart(b, ((1, 1), (1, 1)), p.n) + cb.data, cb.chart = ca.data, ca.chart + + class Machine: + zero = staticmethod(ca.zero) + leaf = staticmethod(ca.leaf) + retire_zero = staticmethod(ca.retire_zero) + + @staticmethod + def native(ports, tagged): + return (ca, cb)[tagged % 2].native(ports, tagged - tagged % 2) + + rand = Random(8582) + rows = [] + initial = {} + for i in range(p.width): + row = ChartJob(i, tuple(rand.sample(range(p.n), p.n)), 0) + rows.append(row) + initial[i] = [rand.randrange(17) for _ in range(p.n)] + ca.data[i] = initial[i].copy() + ca.chart[i] = 0 + p.run(rows, Machine()) + assert ca.data == {i: [(4 * x) % 17 for x in row] for i, row in initial.items()} + assert ( + not any(ca.chart.values()) + and ca.freed == ca.serial + and ca.raw + and cb.raw + and ca.noncommuting + and cb.noncommuting + ) + z = -(-p.width // p.source_width) + assert ca.leaves == z * p.rounds * p.leaves_per_epoch + assert p.width != p.source_width + print( + "PASS_TWO_NATIVE_TYPES", + p.width, + p.source_width, + z, + (ca.raw, cb.raw), + ca.leaves, + (ca.noncommuting, cb.noncommuting), + ca.freed, + edges, + ) + + +if __name__ == "__main__": + run() diff --git a/research/frequency-weighted-native-multiplier/check_exterior.py b/research/frequency-weighted-native-multiplier/check_exterior.py new file mode 100644 index 0000000000..c96ed69d00 --- /dev/null +++ b/research/frequency-weighted-native-multiplier/check_exterior.py @@ -0,0 +1,211 @@ +"""Run the two first independent exterior births through the actual typed decoder and Raw48.""" + +from collections import Counter, defaultdict +from functools import cache +from fractions import Fraction as Q +from pathlib import Path +import sys + +RUNTIME = Path(sys.argv[1]).resolve() +sys.path.insert(0, str(RUNTIME)) +from upstream import install + +install() +from band_product import production_supplier +from periodic import Job +from transport import Measure, Source, ceil, axes +from unpowered_price import certify +from typed_transport import TypedPlan +from typed_raw import TypedRaw + +sys.path.append(str(Path(__file__).resolve().parent)) +from check_raw import Axes, WitnessRaw, RayField, basis, final_ray, rot + + +def run(): + M = 8192 + L = 10 + U = 12 + V = 2**48 + R = M + K = 1 + c = Q(17145637167, 2**42) + dens = Measure(1 - c, V, 64 * M.bit_length()) + producer = production_supplier(1024, 10**18) + a, w = producer.physical, producer.word + types = producer.recipe.types() + hist_t = Counter() + hist_p = Counter() + ids = defaultdict(list) + for t, spec in enumerate(types): + for i, k in enumerate(spec.targets): + hist_t[k] += spec.multiplicity + ids[t, k].append(i) + for r in spec.paid: + hist_p[r] += spec.multiplicity + _, cells = certify(c, (hist_t, hist_p)) + assert cells == producer.recipe.cells + # All true interior intervals are empty in [10,12). Every incoming replica + # considered below is a real exterior occurrence or an original blank. + assert 4 * U < 5 * L + + # Reconstruct the installed source-width prefix by paid occurrence. Identical + # grades have identical grant sizes, but different occurrences own separate rows. + class FirstReplicas(TypedPlan): + """Project two independent exterior births from the single test bin.""" + + def __init__(self): + self.n, self.types, self.ticks, self.rounds, self.bands = ( + M, + types, + K, + R, + range(L, U, 2), + ) + self.delay = {L: 1} + self.count = {(L, 0): 1, (L, 1): 1} + self.sources, self.receive, self.send = {}, {}, {} + + p = FirstReplicas() + full_counts = tuple(ceil(spec.multiplicity * dens.mass(L, U)[1]) for spec in types) + first = set() + base = 0 + for kind, spec in enumerate(types): + chunks = {r: [] for r in set(spec.paid)} + for (r, k), share in cells.items(): + if r not in chunks: + continue + left = max(U, Q(L * k, r)) + right = Q(U * k, r) + mass = dens.mass(left, right)[0] + for b, other in enumerate(types): + if not ids[b, k]: + continue + grant = int( + spec.multiplicity * mass * share * other.multiplicity / hist_t[k] + ) + size = (L - 8) * k + period = 4 * ceil(Q(M, 4 * size)) + if grant: + chunks[r].append((b, k, grant, period)) + sizes = { + r: sum(len(ids[b, k]) * grant * (R // period) for b, k, grant, period in cs) + for r, cs in chunks.items() + } + for r in spec.paid: + if any((b, k) not in first for b, k, grant, period in chunks[r]): + current = base + for b, k, grant, period in chunks[r]: + for i in ids[b, k] if (b, k) not in first else (): + p.sources[L, b, i] = [Source(0, grant, current, period)] + current += grant * (R // period) + if (b, k) in first: + current += len(ids[b, k]) * grant * (R // period) + first.add((b, k)) + assert current == base + sizes[r] + base += sizes[r] + assert len(p.sources) == sum(len(s.targets) for s in types) + p.source_width = base + p.width = 1 << (4096 * base - 1).bit_length() + # All other true replicas are independent at this width since there are no + # interior edges. Their omission renumbers frame identifiers only. + assert min(full_counts) > 1 + clock, call = next( + (i, row[1]) for i, row in enumerate(a.instructions()) if row[0] == "NATIVE" + ) + pawn = next( + i for i, tag in enumerate(w.targets) if tag.tag == ("helper", clock, call, 1544) + ) + true = {} + stock = [0, 0] + fields = {} + for kind, s in enumerate(types): + for i, k in enumerate(s.targets): + [ext] = p.sources[L, kind, i] + owner = ext.base + assert owner not in fields + fields[owner] = RayField(stock) + true[owner] = (2 * k, ext.period) + + @cache + def placement(size, period): + # Exercise the permitted bijection of the caller's physical row axes. + # This choice makes the two known nonzero stabilizer tensors canonical. + seq = tuple(axes(M, size, period, 0)) + claimed = set(seq) + assert len(claimed) == size + reverse = [0] * M + for j, q in enumerate(seq): + reverse[q] = j + pos = size + for q in range(M): + if q not in claimed: + reverse[q] = pos + pos += 1 + assert pos == M + return tuple(reverse) + + class Rows: + def __getitem__(self, i): + return Job(i, placement(*true[i])) + + expected = {} + for kind, s in enumerate(types): + cols = 2 * (1 + kind) + [e] = p.sources[L, kind, pawn] + origins = tuple((37 * i + 11 + 17 * kind) % 512 for i in range(cols)) + z = ((3 if not kind else -7) << 2048, (5 if not kind else 2) << 2048) + fields[e.base].data = z, tuple(basis(i) for i in origins) + output = tuple(final_ray(i) for i in origins) + z = rot(z, sum(phase for v, phase in output)) + expected[e.base] = ( + (z[0] // 16**cols, z[1] // 16**cols), + tuple(v for v, phase in output), + ) + physical = WitnessRaw(a, fields, Axes(), low=0, bundle=1, slots=M) + adapter = TypedRaw(w, physical) + bills = [0, 0] + + class Machine: + native = staticmethod(adapter.native) + + def leaf(self, job): + (i,) = job.axes + bills[0] += 1 + f = fields[job.owner] + if f.data is not None: + f.paid(i) + bills[1] += 1 + + @staticmethod + def zero(exemplar): + raise AssertionError( + "All tested genuine first replicas received exterior fields" + ) + + retire_zero = staticmethod(physical.retire) + + p.decode(Rows(), 0, 0, Machine(), p.events()) + assert ( + bills[0] == p.leaves_per_epoch + and {i: f.data for i, f in fields.items() if f.data is not None} == expected + ) + assert len(fields) == sum(len(s.targets) for s in types) and all( + f.writes and f.live for f in fields.values() + ) + for f in fields.values(): + f.retire() + assert stock[0] == 0 + print( + "PASS_EXTERIOR_TYPED_RAW", + full_counts, + p.source_width.bit_length(), + len(fields), + sum(len(s.paid) for s in types), + bills, + stock, + ) + + +if __name__ == "__main__": + run() diff --git a/research/frequency-weighted-native-multiplier/check_lean.py b/research/frequency-weighted-native-multiplier/check_lean.py new file mode 100644 index 0000000000..8a3d583dfb --- /dev/null +++ b/research/frequency-weighted-native-multiplier/check_lean.py @@ -0,0 +1,37 @@ +"""Build the inherited price lemma and kernel-check the weighted construction.""" + +from pathlib import Path +import os +from shutil import copyfile +from subprocess import run +import sys +from tempfile import TemporaryDirectory + +package = Path(__file__).resolve().parent +lean_bin = Path(sys.argv[1]).resolve() / "bin" +mathlib = Path(sys.argv[2]).resolve() +with TemporaryDirectory(prefix="tier-lean-") as temp: + dst = Path(temp) + paths = [ + dst, + mathlib / ".lake/build/lib/lean", + *sorted((mathlib / ".lake/packages").glob("*/.lake/build/lib/lean")), + ] + env = os.environ | { + "LEAN_PATH": os.pathsep.join(map(str, paths)), + "PATH": str(lean_bin) + os.pathsep + os.environ["PATH"], + } + for source in ( + package.parent / "tiered-native-multiplier" / "TierCost.lean", + package / "WeightedNumerical.lean", + package / "GaussianFiniteLoss.lean", + ): + name = source.stem + copyfile(source, dst / (name + ".lean")) + run( + [lean_bin / "lean", "-o", name + ".olean", name + ".lean"], + cwd=dst, + env=env, + check=True, + ) + run([lean_bin / "leanchecker", "-v", name], cwd=dst, env=env, check=True) diff --git a/research/frequency-weighted-native-multiplier/check_nested.py b/research/frequency-weighted-native-multiplier/check_nested.py new file mode 100644 index 0000000000..c4797dc5dc --- /dev/null +++ b/research/frequency-weighted-native-multiplier/check_nested.py @@ -0,0 +1,316 @@ +"""Execute an actual weighted interior loan of a nonzero Raw48 field across both native types.""" + +from pathlib import Path +from collections import Counter +from functools import cache +from fractions import Fraction as Q +import sys + +sys.path.insert(0, str(Path(sys.argv[1]).resolve())) +from upstream import install + +install() +from band_product import production_supplier +from periodic import Job +from raw48 import ComplexRaw +from check_nonzero_eight import Field, rot, times +from typed_raw import TypedRaw +from transport import Measure +from unpowered_price import certify +from installations import GAUSSIAN_C + +lanes = 8 +bits = 18 +dim = 1 << bits +ALL = (1 << dim) - 1 +# Each bit in a phase mask is one computational basis address. +ONES = tuple(ALL // ((1 << (1 << i)) + 1) << (1 << i) for i in range(bits)) +unit = ((1, 0), (0, 1), (-1, 0), (0, -1), (0, 0)) + + +@cache +def initial(x): + return (1 << x, 0, 0, 0) + + +def norm(v): + """Strip the phase of the first nonzero basis amplitude.""" + active = v[0] | v[1] | v[2] | v[3] + first = active & -active + pivot = next(j for j, s in enumerate(v) if s & first) + return tuple(v[(j + pivot) % 4] for j in range(4)), pivot + + +def flip(s, t, ctrl): + low = s & (ALL ^ ONES[t]) & ctrl + high = s & ONES[t] & ctrl + return (s ^ low ^ high) | (low << (1 << t)) | (high >> (1 << t)) + + +@cache +def affine(v, target, control): + ctrl = ALL if control < 0 else ONES[control] + return norm(tuple(flip(s, target, ctrl) for s in v)) + + +@cache +def diagonal_masks(alpha, cross): + low = high = 0 + for i, g in enumerate(alpha): + m = ONES[i] + if g & 1: + high ^= low & m + low ^= m + if g & 2: + high ^= m + for i, j in cross: + high ^= ONES[i] & ONES[j] + return ALL ^ (low | high), low & (ALL ^ high), high & (ALL ^ low), low & high + + +@cache +def phases(v, alpha, cross): + masks = diagonal_masks(alpha, cross) + return norm( + tuple( + (masks[0] & v[j]) + | (masks[1] & v[(j - 1) % 4]) + | (masks[2] & v[(j - 2) % 4]) + | (masks[3] & v[(j - 3) % 4]) + for j in range(4) + ) + ) + + +@cache +def kernel(v, target): + """Apply the numerator (1+i)I+(1−i)X on one exact 18-bit factor.""" + masks = (*v, ALL ^ (v[0] | v[1] | v[2] | v[3])) + others = tuple(flip(s, target, ALL) for s in masks) + buckets = {} + nz = 0 + for j, s in enumerate(masks): + if not s: + continue + a, b = unit[j] + for k, w in enumerate(others): + v2 = s & w + if not v2: + continue + c, d = unit[k] + z = a - b + c + d, a + b + d - c + if z == (0, 0): + continue + buckets[z] = buckets.get(z, 0) | v2 + nz |= v2 + first = nz & -nz + pivot = next(z for z, s in buckets.items() if s & first) + result = tuple(buckets.get(rot(pivot, i), 0) for i in range(4)) + assert sum(q.bit_count() for q in result) == nz.bit_count() + return result, pivot + + +def axis(i): + v, j = divmod(i, lanes) + if v >= bits: + raise ValueError( + "The live stabilizer reached a qubit outside its declared group" + ) + return v, j + + +class ProductField(Field): + """A shared Gaussian scalar times eight independent 18-bit stabilizer factors.""" + + def blank(self): + return ProductField(self.stock) + + def affine(self, t, s): + if self.data is None: + return + i, j = axis(t) + v = -1 + if s is not None: + v, k = axis(s) + assert k == j + z, vs = self.data + w, h = affine(vs[j], i, v) + self.data = rot(z, h), vs[:j] + (w,) + vs[j + 1 :] + + def paid(self, t): + if self.data is None: + return + i, j = axis(t) + z, vs = self.data + w, h = kernel(vs[j], i) + new = times(z, h) + assert not (new[0] % 2 or new[1] % 2) + self.data = (new[0] // 2, new[1] // 2), vs[:j] + (w,) + vs[j + 1 :] + + def phase(self, fn, suffix): + if self.data is None: + return + z, vs = self.data + base = fn(0) % 4 + z = rot(z, base) + # Every literal I, S and CZ on a complete set of 8 or 16 columns is + # diagonal quadratic and preserves the residue class modulo 8. + loc = [1 << (i * lanes) for i in range(bits)] + alpha = tuple((fn(x) - base) % 4 for x in loc) + cross = [] + for i in range(bits): + for j in range(i): + coeff = (fn(loc[i] | loc[j]) - base - alpha[i] - alpha[j]) % 4 + assert coeff in (0, 2) + if coeff: + cross.append((i, j)) + cross = tuple(cross) + outs = [] + probe = 0 + measured = base + for j, v in enumerate(vs): + local = sum(loc[i] << j for i in range(bits) if (5 * i + j) % 7 < 3) + assert (fn(local) - base) % 4 == (fn(local >> j) - base) % 4 + measured += fn(local) - base + probe |= local + w, h = phases(v, alpha, cross) + outs.append(w) + z = rot(z, h) + assert fn(probe) % 4 == measured % 4 + self.data = z, tuple(outs) + + +class Axes: + window = 1 + offset = suffix = 0 + swap = None + + def row(self, f, targets, sources=None): + if f.data is None: + return + for j, t in enumerate(targets): + f.affine(t, None if sources is None else sources[j]) + + +def test(): + system = production_supplier(1024, 10**18) + art, word = system.physical, system.word + types = system.recipe.types() + t, p = Counter(), Counter() + n = 8192 + for v in types: + for k in v.targets: + t[k] += v.multiplicity + for r in v.paid: + p[r] += v.multiplicity + C = GAUSSIAN_C + _, cells = certify(C, (t, p)) + grant = ( + Measure(1 - C, 2**48, 64 * n.bit_length()).mass(24, 26)[0] + * cells[1, 2] + * 90 + / t[2] + ) + child_count = system.recipe.targets.variants[1].histogram[2] + share = system.recipe.typed_cells()[0, 1, 1, 2] / child_count + assert ( + share == cells[1, 2] * 90 / t[2] + and grant.numerator // grant.denominator == 899557645 + ) + assert cells[1, 2] > Q(99, 100) and 24 * 1 == 12 * 2 + clock, call = next( + (i, row[1]) for i, row in enumerate(art.instructions()) if row[0] == "NATIVE" + ) + pawn = next( + i for i, k in enumerate(word.targets) if k.tag == ("helper", clock, call, 1544) + ) + child = next( + i + for i, k in enumerate(word.targets) + if k.rank == 1 and k.tag[:3] == ("helper", clock, call) + ) + stock = [0, 0] + fields = {i: ProductField(stock) for i in range(2 * len(word.targets))} + big = types[0] + small = types[1] + P = 16 + S = 8 + rows = [Job(i, range(P * r)) for i, r in enumerate(big.targets)] + x0 = 0 + for b in range(9): + x0 |= ((11 >> b) & 1) << (2 * b) + x0 |= ((73 >> b) & 1) << (2 * b + 1) + z = (3 << 8192, 5 << 8192) + fields[pawn].data = z, (initial(x0),) * lanes + expected = fields[pawn].copy() + for i in range(8 * P): + expected.paid(i) + physical = ComplexRaw(art, fields, Axes(), low=0, bundle=1, slots=n) + method = TypedRaw(word, physical) + op = method.native(rows, P) + uses = [0, 0] + for j, r in enumerate(big.paid): + job = next(op) + f = fields[job.owner] + assert len(job.axes) == r * P + if j != 3418: + for axis_ in job.axes: + f.paid(axis_) + continue + assert r == 1 and f.data is not None and tuple(job.axes) == tuple(range(P)) + # The actual parent pays every suffix axis before it lends its prefix. + for axis_ in job.axes[S:]: + f.paid(axis_) + prefix = job.select(range(S)) + due = f.copy() + for axis_ in prefix.axes: + due.paid(axis_) + cr = [ + Job(i + len(word.targets), range((S // 2) * k)) + for i, k in enumerate(small.targets) + ] + unused = cr[child].owner + assert fields[unused].data is None + cr[child] = prefix + call2 = method.native(cr, S // 2 + 1) + for grade in small.paid: + loan = next(call2) + owned = fields[loan.owner] + assert len(loan.axes) == (S // 2) * grade + if owned.data is not None: + uses[1] += 1 + for axis_ in loan.axes: + owned.paid(axis_) + uses[0] += 1 + assert next(call2, None) is None and f.data == due.data + due.retire() + assert all( + fields[i + len(word.targets)].data is None for i in range(len(word.targets)) + ) + print( + "real nested transfer completed", + j, + word.targets[child].tag, + uses, + flush=True, + ) + assert next(op, None) is None and fields[pawn].data == expected.data + assert all(f.data is None for i, f in fields.items() if i != pawn) + assert set(fields) == set(range(2 * len(word.targets))) + expected.retire() + for f in fields.values(): + f.retire() + assert stock[0] == 0 and uses[1] > 0 + print( + "PASS_NONZERO_INTERIOR", + len(big.paid), + len(small.paid), + child, + int(grant), + uses[1], + stock, + ) + + +if __name__ == "__main__": + test() diff --git a/research/frequency-weighted-native-multiplier/check_ownership.py b/research/frequency-weighted-native-multiplier/check_ownership.py new file mode 100644 index 0000000000..ef51ecfa33 --- /dev/null +++ b/research/frequency-weighted-native-multiplier/check_ownership.py @@ -0,0 +1,153 @@ +"""Check independent source numbering, deadlines and return of all borrowed owners.""" + +from fractions import Fraction as Q +from collections import Counter +import json +from pathlib import Path +import sys + +RUNTIME = Path(sys.argv[1]).resolve() +sys.path.insert(0, str(RUNTIME)) +from upstream import install + +install() +from typed_transport import TypedPlan, NativeType + + +def run(freq, ticks, lower, upper, volume, n, rounds, delay): + types = (NativeType((2,), (1, 1), 1), NativeType((2, 2), (1, 1, 1, 1), freq)) + shares = { + (0, 1, 1, 2): Q(1), + (1, 1, 0, 2): Q(1, 2 * freq), + (1, 1, 1, 2): 1 - Q(1, 2 * freq), + } + p = TypedPlan( + n, + types, + shares, + Q(1), + lower, + upper, + volume, + ticks, + rounds, + delay_base=delay, + scale_step=Q(2), + padding=1, + ) + M = max(p.count.values()) + bands = len(p.bands) + + def frame_info(ident): + packed, rep = divmod(ident, M) + packed, typ = divmod(packed, 2) + birth, offset = divmod(packed, bands) + band = lower + 2 * offset + assert rep < p.count[(band, typ)] + return typ, birth, band, rep + + # Half-open source blocks have no alias even when their integer periods differ. + ext = sorted( + (src.base, src.base + src.count * ticks * (rounds // src.period), src) + for group in p.sources.values() + for src in group + if rounds // src.period + ) + end = 0 + for lo, hi, src in ext: + assert lo == end and lo < hi + end = hi + assert end == p.source_width + opened = {} + borrowers = {} + serials = {} + kinds = Counter() + transfers = Counter() + flats = external = zero = last = peak = depth = close_on_due = child_tail = 0 + periods = Counter() + for rec in p.events(): + op, ident, *xs = rec + kind, birth, e, rep = frame_info(ident) + w = types[kind] + step = p.delay[e] + if op == 0: + assert ident not in opened and xs[0] == e - 8 + kind + tick = birth + it = iter(xs[1:]) + origins = [] + d = 1 + for k in w.targets: + tag = next(it) + if tag == 1: + par, expected, t0, pkind = serials.pop(next(it)) + assert ( + t0 == tick and par not in borrowers and expected == k * (e - 8) + ) + borrowers[par] = ident + origins.append(par) + d = max(d, opened[par][2] + 1) + transfers[pkind, kind] += 1 + elif tag == 2: + base, size, period = next(it), next(it), next(it) + assert size == k * (e - 8) and period == 4 * (-(-n // (4 * size))) + assert 0 <= base <= base + rounds // period <= p.source_width + if rounds >= period: + external += 1 + periods[period] += 1 + else: + assert tag == 0 and next(it) == k * (e - 8) + zero += 1 + assert next(it, None) is None + opened[ident] = [0, origins, d] + peak = max(peak, len(opened)) + depth = max(depth, d) + elif op == 1: + j, parents, d = opened[ident] + tick = birth + step * j + assert ident not in borrowers + serial, size, sel = xs + assert size == (e - 8) * w.paid[j] and sel <= size + if sel: + serials[serial] = (ident, sel, tick, kind) + flats += size - sel + if tick >= ticks: + child_tail += int(sel != 0) + opened[ident][0] += 1 + else: + j, parents, d = opened.pop(ident) + assert j == len(w.paid) and ident not in borrowers + tick = birth + step * j + for par in parents: + assert borrowers.pop(par) == ident + pk, pb, pe, pr = frame_info(par) + assert p.delay[pe] >= step + due = pb + opened[par][0] * p.delay[pe] + assert tick <= due + close_on_due += int(tick == due) + kinds[kind] += 1 + assert tick >= last, (tick, last, op, e, kind) + last = tick + assert flats == p.leaves_per_epoch and not ( + opened or borrowers or serials or child_tail + ) + assert kinds == Counter( + {a: ticks * sum(v for (e, b), v in p.count.items() if b == a) for a in range(2)} + ) + assert depth <= 1 + max(b.bit_length() for b in p.bands) + return dict( + frequency=freq, + raw_frames=sum(kinds.values()), + directed_bindings={str(k): v for k, v in transfers.items()}, + depth=depth, + peak_simultaneous_frames=peak, + external_opens=external, + zeros=zero, + external_rows=end, + positive_periods=sorted(periods), + leaf_axes=flats, + same_tick_return_before_next_loan=close_on_due, + ) + + +out = [run(3, 12, 10, 82, 1700, 1024, 96, 4), run(90, 8, 10, 42, 450, 384, 32, 4)] +print(json.dumps(out, indent=2)) diff --git a/research/frequency-weighted-native-multiplier/check_placement.py b/research/frequency-weighted-native-multiplier/check_placement.py new file mode 100644 index 0000000000..08dfdc96bf --- /dev/null +++ b/research/frequency-weighted-native-multiplier/check_placement.py @@ -0,0 +1,88 @@ +"""Check the true weighted Gaussian exterior owner at both installed ranks.""" + +from fractions import Fraction as Q +from itertools import islice +import json +from pathlib import Path +import sys + +RUNTIME = Path(sys.argv[1]).resolve() +sys.path.insert(0, str(RUNTIME)) +from upstream import install + +install() +from upstream import HERE + +_, _, _, source = install() +from strong_complex import artifacts +from clock_ports import clock_word +from grades import numerical_recipe, WEIGHTS +from installations import ENTRY, TERMINAL, GAUSSIAN_C +from unpowered_price import certify +from periodic import Job +from raw48 import ComplexRaw +from transport import axes, ceil + +A = artifacts(source / "research/grade14-native-realization", HERE / "inputs") +w = clock_word(A) +recipe = numerical_recipe(TERMINAL.complex_log) +targets, paid = recipe.targets, recipe.paid +c = GAUSSIAN_C +margin, flows = certify(c, (targets.histogram, paid.histogram)) +assert margin > 0 and flows == recipe.cells and flows[112, 258] == 1 +assert paid.variants[0].histogram[112] == 0 and paid.variants[1].histogram[112] > 0 +assert ( + targets.variants[0].histogram[258] == 0 + and targets.variants[1].histogram[258] == 624 +) +pi = flows[112, 258] * WEIGHTS[1] / targets.histogram[258] +assert pi == Q(1, 624) +roots = tuple( + p.tag for p in w.targets if p.rank == 129 and p.tag[:2] == ("root", "rotated") +) +assert len(roots) == 384 + + +class Column: + window = 1 + swap = None + + +class Field: + def __init__(self): + self.swaps = [] + + def swap(self, l, r, n, service): + self.swaps.append((l, r, n)) + + +out = [] +for H in (ENTRY.complex_log, TERMINAL.complex_log): + M = 1 << H + U = 2 * (M // (2048 * 306)) + e = 2 * (3 * U // 8) + lo, hi = Q(e * 258, 112), Q((e + 2) * 258, 112) + assert U < lo < hi < M + assert 90 * (hi - lo) * M * pi > 4 + size = 258 * (e - 8) + period = 4 * ceil(Q(M, 4 * size)) + tickets = tuple(islice(axes(M, size, period, 0), 3)) + f = Field() + raw = ComplexRaw(A, {}, Column(), low=0, bundle=1, slots=M) + # The alignment performs these first three iterations before seeing any + # other slot. The full physical job is exponentially larger. + raw.align(f, Job(0, tickets), tuple(range(3))) + assert period == 1620 and tickets == (0, 324, 648) and f.swaps[0] == (1, 324, 1) + out.append( + dict( + H=H, + cell=[1, 112, 1, 258], + share=str(pi), + rotated_roots=len(roots), + first_root=roots[0], + period=period, + tickets=tickets, + first_swap=f.swaps[0], + ) + ) +print(json.dumps(out, indent=2)) diff --git a/research/frequency-weighted-native-multiplier/check_raw.py b/research/frequency-weighted-native-multiplier/check_raw.py new file mode 100644 index 0000000000..959078287d --- /dev/null +++ b/research/frequency-weighted-native-multiplier/check_raw.py @@ -0,0 +1,107 @@ +"""Execute both physical Gaussian words on finite nonzero product states.""" + +from pathlib import Path +import sys + +RUNTIME = Path(sys.argv[1]).resolve() +sys.path.insert(0, str(RUNTIME)) +from upstream import install + +install() +from check_nonzero_eight import ( + Axes, + WitnessRaw, + Field, + addresses, + basis, + diagonal, + final_ray, + rot, +) +from band_product import production_supplier +from periodic import Job +from typed_raw import TypedRaw + + +class RayField(Field): + def blank(self): + return RayField(self.stock) + + def phase(self, op, suffix): + if self.data is None: + return + z, rays = self.data + n = len(rays) + base = op(0) % 4 + z = rot(z, base) + single = tuple((op(x) - base) % 4 for x in addresses(0, n)) + after = [] + for i, v in enumerate(rays): + other = addresses(i, n) + assert all((op(x) - base) % 4 == y for x, y in zip(other, single)) + y, p = diagonal(v, single) + after.append(y) + z = rot(z, p) + self.data = z, tuple(after) + + +def run(): + producer = production_supplier(1024, 10**18) + a, w = producer.physical, producer.word + types = producer.recipe.types() + for kind, (spec, cols) in enumerate(zip(types, (2, 4))): + stock = [0, 0] + fields = {j: RayField(stock) for j in range(len(spec.targets))} + jobs = [Job(i, range(2 * k)) for i, k in enumerate(spec.targets)] + clock, call = next( + (i, row[1]) for i, row in enumerate(a.instructions()) if row[0] == "NATIVE" + ) + key = ("helper", clock, call, 1544) + owner = next(i for i, p in enumerate(w.targets) if p.tag == key) + assert w.targets[owner].rank == 8 + origins = tuple((37 * i + 11 + 17 * kind) % 512 for i in range(cols)) + initial = ((3 if not kind else -7) << 2048, (5 if not kind else 2) << 2048) + fields[owner].data = initial, tuple(basis(i) for i in origins) + exact = tuple(final_ray(i) for i in origins) + z = rot(initial, sum(p for v, p in exact)) + assert all(x % (16**cols) == 0 for x in z) + after = (z[0] // 16**cols, z[1] // 16**cols), tuple(v for v, p in exact) + raw = WitnessRaw(a, fields, Axes(), low=0, bundle=1, slots=2 * 306) + it = TypedRaw(w, raw).native(jobs, 2 + kind) + nonzero = 0 + for r in spec.paid: + job = next(it) + assert len(job.axes) == 2 * r + f = fields[job.owner] + if f.data is not None: + nonzero += 1 + for axis in job.axes: + f.paid(axis) + assert next(it, None) is None and set(fields) == set(range(len(spec.targets))) + assert {i: f.data for i, f in fields.items() if f.data is not None} == { + owner: after + } + assert all(f.writes and f.live for f in fields.values()) and nonzero > 0 + writes = sum(f.writes for f in fields.values()) + for f in fields.values(): + f.retire() + assert stock[0] == 0 + print( + "PASS_TYPED_RAW48", + kind, + "columns", + cols, + "paid", + len(spec.paid), + "nonzero", + nonzero, + "writes", + writes, + "peak", + stock[1], + flush=True, + ) + + +if __name__ == "__main__": + run() diff --git a/research/frequency-weighted-native-multiplier/grades.py b/research/frequency-weighted-native-multiplier/grades.py new file mode 100644 index 0000000000..82b8edb655 --- /dev/null +++ b/research/frequency-weighted-native-multiplier/grades.py @@ -0,0 +1,140 @@ +"""Install two weighted rank streams and materialize real labels at an active calendar.""" + +from collections import Counter +from fractions import Fraction as Q +from functools import cache +from typed_transport import NativeType, TypedPlan + +WEIGHTS = (1, 90) +SCALES = (1, 2) +SPLITS = 1008 +LOWER = 2048 + + +class GradeVariant: + def __init__(self, ports, raw, scale, splits): + self.ports, self.scale, self.splits = ports, scale, splits + self.histogram = Counter({scale * r: n for r, n in raw.items()}) + if splits: + if not (scale == 1 and raw[1] >= splits): + raise ValueError("A fixed split lacks a physical rank-one loan") + self.histogram[1] -= splits + self.histogram[Q(1, 2)] += 2 * splits + + def __iter__(self): + left = self.splits + for r in self.ports.ranks(): + if r == 1 and left: + left -= 1 + yield Q(1, 2) + yield Q(1, 2) + else: + yield self.scale * r + + def __len__(self): + return len(self.ports) + self.splits + + +class WeightedGrades: + def __init__(self, ports, splits=0): + raw = Counter() + counts = {} + for prefix, entries in ports.segments: + key = id(entries) + if key not in counts: + counts[key] = ( + Counter(p.rank for p in entries) + if prefix is None + else Counter(r for _, r in entries) + ) + raw.update(counts[key]) + self.variants = ( + GradeVariant(ports, raw, 1, splits), + GradeVariant(ports, raw, 2, 0), + ) + self.histogram = Counter() + for w, var in zip(WEIGHTS, self.variants, strict=True): + for r, n in var.histogram.items(): + self.histogram[r] += w * n + + +@cache +def numerical_source(): + from upstream import HERE, install + from strong_complex import artifacts + from clock_ports import clock_word + from installations import GAUSSIAN_C + from unpowered_price import certify + + _, _, _, source = install() + atlas = artifacts(source / "research/grade14-native-realization", HERE / "inputs") + word = clock_word(atlas) + targets, paid = WeightedGrades(word.targets), WeightedGrades(word.paid, SPLITS) + margin, cells = certify(GAUSSIAN_C, (targets.histogram, paid.histogram)) + if cells is None or margin <= 0: + raise ArithmeticError("The two native types cannot fund their real loans") + return atlas, word, targets, paid, cells + + +class WeightedRecipe: + def __init__(self, rank_log, ambient, targets, paid, cells, trial): + if rank_log < 1024: + raise ValueError("The complete numerical schedule requires H at least 1024") + self.rank_log, self.ambient, self.targets, self.paid = ( + rank_log, + ambient, + targets, + paid, + ) + self.cells, self.trial, self.width_log = cells, trial, 92 * rank_log + + @property + def width(self): + return 1 << self.width_log + + def types(self): + return tuple( + NativeType(tuple(t), tuple(p), w) + for t, p, w in zip( + self.targets.variants, self.paid.variants, WEIGHTS, strict=True + ) + ) + + def typed_cells(self): + shares = {} + for (r, k), p in self.cells.items(): + for a, src in enumerate(self.paid.variants): + if r not in src.histogram: + continue + for b, dst in enumerate(self.targets.variants): + if k not in dst.histogram: + continue + shares[a, r, b, k] = ( + p * WEIGHTS[b] * dst.histogram[k] / self.targets.histogram[k] + ) + return shares + + def open(self): + types, shares = self.types(), self.typed_cells() + M = 1 << self.rank_log + return TypedPlan( + M, + types, + shares, + 1 - self.trial, + LOWER, + 2 * (M // (2048 * self.ambient)), + M**6, + M**82, + M**2, + width=self.width, + delay_base=1 << 19, + ) + + +@cache +def numerical_recipe(rank_log): + from installations import GAUSSIAN_C + + _, word, targets, paid, cells = numerical_source() + return WeightedRecipe(rank_log, 2 * word.ambient, targets, paid, cells, GAUSSIAN_C) diff --git a/research/frequency-weighted-native-multiplier/independent_price.py b/research/frequency-weighted-native-multiplier/independent_price.py new file mode 100644 index 0000000000..5bf74e6a68 --- /dev/null +++ b/research/frequency-weighted-native-multiplier/independent_price.py @@ -0,0 +1,108 @@ +"""Check both actual transport prices on an independent 192-bit dyadic grid.""" + +from collections import Counter +from fractions import Fraction as Q +from math import ceil, isqrt +from pathlib import Path +import sys + +IMAGE = Path(sys.argv[1]).resolve() +sys.path.insert(0, str(IMAGE)) +from upstream import install + +install() +from band_product import prepare_native +from installations import BINARY_C, TERMINAL +from strong_complex import load_changed, word + +GRID = 1 << 192 + + +def powers(base, exponent): + assert base > 0 and 0 < exponent < 1 + assert exponent.denominator.bit_count() == 1 + number = Q(base) * GRID + low, high = number.__floor__(), ceil(number) + lower_result = upper_result = GRID + for bit in range(exponent.denominator.bit_length() - 2, -1, -1): + low = isqrt(low * GRID) + high = isqrt(high * GRID - 1) + 1 + if exponent.numerator >> bit & 1: + lower_result = lower_result * low // GRID + upper_result = ceil(Q(upper_result * high, GRID)) + return Q(lower_result, GRID), Q(upper_result, GRID) + + +def weighted(): + recipe = prepare_native(TERMINAL)[-1] + c = recipe.trial + psi = sum( + recipe.paid.histogram[r] * share * r * (powers(Q(k, r), c)[0] - 1) / c + for (r, k), share in recipe.cells.items() + ) + axes = sum(k * n for k, n in recipe.targets.histogram.items()) + fringe = 10 * axes / ((1 - c) * psi) + assert psi > Q("184971191.2157") and fringe < Q("7.335168") + delta = Q(1, 2**128) + upper = ( + (1 + delta) + * (1 + Q(4 * 258, 1024 * 306)) + * powers(1024 * 306 * 2048, c)[1] + * (1 + fringe / 2048 + delta) + / (1 - delta) ** 4 + ) + lower = powers(2, Q(65081, 524288))[0] + assert lower - upper > Q("0.00012957") + + +def rounded_peer(): + raw = word(*load_changed(IMAGE / "inputs")) + + def scales(ports): + single = Counter(port.rank for port in ports) + combined = single.copy() + combined.update({8 * rank: count for rank, count in single.items()}) + return combined + + targets, paid = scales(raw.targets), scales(raw.paid) + paid[1] -= 1006 + paid[Q(1, 4)] += 1006 + paid[Q(3, 4)] += 1006 + assert (targets.total(), paid.total()) == (105216, 564142) + c = Q(4286126377, 2**40) + endpoints = {r: powers(r, 1 - c) for r in (targets | paid)} + + def mass(rows, index): + return sum(n * endpoints[r][index] for r, n in rows) + + tlo, thi = (mass(targets.items(), i) for i in (0, 1)) + plo, phi = (mass(paid.items(), i) for i in (0, 1)) + assert tlo > phi and plo / thi > Q(99, 100) + for rank in sorted(paid)[1:]: + load = mass(((r, n) for r, n in paid.items() if r >= rank), 1) + cap = mass(((k, n) for k, n in targets.items() if 5 * rank <= 4 * k), 0) + assert load <= cap * plo / thi + delta, lower = Q(1, 2**128), 32768 + factor = ( + Q(256, 255) + * Q(4097, 4096) + * Q(1028, 1024) + * powers(1024 * 1224 * lower, c)[1] + * (1 + Q(64, lower) + delta) + / ((1 - Q(10, lower)) * (1 - delta) ** 3) + ) + assert factor**256 < 2**39 + peer = Q(".0038982016137") + first = 249 * (BINARY_C - Q(11, 8 * 60000)) / 250 + booked = Q((first * 10**18).__floor__() - 1, 10**18) + second = (249 * (BINARY_C - Q(11, 8 * 960000)) + booked) / 250 + assert peer + Q(5, 10**18) < min(second, c - Q(39, 256 * 20000000)) + assert TERMINAL.kappa - peer == Q(83863, 10**13) and TERMINAL.kappa > c + + +if __name__ == "__main__": + if not __debug__: + raise ValueError("Run with assertions enabled") + weighted() + rounded_peer() + print("PASS_INDEPENDENT_WEIGHTED_AND_QUARTER_PRICES") diff --git a/research/frequency-weighted-native-multiplier/measure_setup.py b/research/frequency-weighted-native-multiplier/measure_setup.py new file mode 100644 index 0000000000..5d78daa0ae --- /dev/null +++ b/research/frequency-weighted-native-multiplier/measure_setup.py @@ -0,0 +1,98 @@ +"""Measure fixed setup through all native recipes of the selected signed multiplier.""" + +from argparse import ArgumentParser +from hashlib import sha256 +import json +from pathlib import Path +import platform +import resource +import runpy +import sys +from tempfile import TemporaryDirectory +from time import perf_counter + +HERE = Path(__file__).resolve().parent + + +def cpu(): + times = [ + resource.getrusage(who) + for who in (resource.RUSAGE_SELF, resource.RUSAGE_CHILDREN) + ] + return sum(t.ru_utime + t.ru_stime for t in times) + + +def measure(preceding, peer=None): + package = HERE.parent / "tiered-native-multiplier" if preceding else HERE + start, used = perf_counter(), cpu() + with TemporaryDirectory(prefix="fixed-weighted-") as tmp: + path = Path(tmp) / "program" + if peer is not None: + loader = peer / "prepare.py" + if sha256(loader.read_bytes()).hexdigest() != ( + "1a4d885677ba9bd435927d5c400f598dc35c6a793686389a1fb84a1f49d6096e" + ): + raise ValueError( + "Use the rounded-packet source at c5cbef6e558542d6e809aabb6ead89b9e51f7b1c" + ) + package = Path(tmp) / "peer" + runpy.run_path(str(loader))["materialize"]( + peer / "peer8054", peer / "round370", package + ) + runpy.run_path(str(package / "bootstrap.py"))["install"](path) + sys.path.insert(0, str(path)) + from band_product import prepare_native + from installations import PROFILES + + if peer is None: + recipes = prepare_native() + terminal = ( + [35327, 559005, 680000] if preceding else [8192, 129414, 524288, 483871] + ) + expected = [[3000, 3080, 1024], terminal] + assert recipes[0][-1].cells is recipes[1][-1].cells + model = "dilation79" if preceding else "frequency90" + expected_cells = 62 if preceding else 51 + else: + recipes = (prepare_native(PROFILES["extended"]),) + expected = [[60000, 960000, 20000000]] + gaussian = recipes[0][-1] + assert (len(gaussian.targets), len(gaussian.paid)) == (105216, 564142) + model, expected_cells = "rounded_quarters", 55 + ranks = [[item.rank_log for item in row] for row in recipes] + assert ranks == expected + cells = len(recipes[0][-1].cells) + assert cells == expected_cells + graph = sha256((path / "strong-bit.json.gz").read_bytes()).hexdigest() + assert ( + graph == "9e7392c52bcf29c0cc58c54c619f95c28f476394c33e8e0a5aa30c9557d31362" + ) + rss = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + print( + json.dumps( + dict( + model=model, + wall=perf_counter() - start, + cpu=cpu() - used, + rss_bytes=rss if sys.platform == "darwin" else 1024 * rss, + python=platform.python_version(), + system=platform.platform(), + ranks=ranks, + gaussian_grade_cells=cells, + binary_sha256=graph, + ) + ) + ) + + +if __name__ == "__main__": + options = ArgumentParser(description=__doc__) + group = options.add_mutually_exclusive_group() + group.add_argument("--preceding", action="store_true") + group.add_argument( + "--quarter-peer", + type=Path, + help="Path to the source-bound PR 8056 research package", + ) + args = options.parse_args() + measure(args.preceding, args.quarter_peer.resolve() if args.quarter_peer else None) diff --git a/research/frequency-weighted-native-multiplier/portable/EVIDENCE.json b/research/frequency-weighted-native-multiplier/portable/EVIDENCE.json new file mode 100644 index 0000000000..f956035d24 --- /dev/null +++ b/research/frequency-weighted-native-multiplier/portable/EVIDENCE.json @@ -0,0 +1,173 @@ +{ + "clock": { + "compiled_bytes": 2573226, + "compiled_files": 106, + "compiled_sha256": "594661d65b3022ba679c29b193800813ed0c41d8f3a8c691e46a7a20ea38229f", + "directory": { + "bytes": 36094602, + "dictionary_set_keys": 312178, + "edges": 5174419, + "largest_integer_bits": 261, + "largest_key_bytes": 28, + "largest_record": 418608, + "records": 2407819, + "tag_counts": { + "0": 1, + "10": 142614, + "11": 2, + "12": 2, + "13": 1, + "14": 2, + "15": 5, + "16": 4, + "17": 2, + "2": 497434, + "3": 357436, + "4": 97608, + "5": 1085156, + "6": 84173, + "7": 143372, + "8": 6, + "9": 1 + } + }, + "directory_sha256": "045c482b6d32fc58bae8e047e22d519f9269e0124fe3cb1695e930e4f472f2a8", + "exponent": 146, + "full_store_bound": "3838475198494975007767119415723957847851008", + "full_store_trace_exponent": 142, + "installer": { + "fuel": 802083502514, + "host_calls": 28244, + "linear_bytes": 331808768, + "maxima": { + "dirrows": 64, + "entries": 298, + "fd": 500, + "file": 36094602, + "io": 2220706, + "iov": 1, + "joined_path": 120, + "live_fds": 5, + "path": 119 + }, + "operations": { + "args_get": 1, + "args_sizes_get": 1, + "clock_time_get": 2, + "environ_get": 9404, + "environ_sizes_get": 9404, + "fd_close": 497, + "fd_fdstat_get": 1006, + "fd_filestat_get": 578, + "fd_prestat_dir_name": 1, + "fd_prestat_get": 3, + "fd_read": 424, + "fd_readdir": 35, + "fd_seek": 587, + "fd_tell": 113, + "fd_write": 4513, + "path_create_directory": 232, + "path_filestat_get": 726, + "path_open": 539, + "path_readlink": 1, + "path_remove_directory": 22, + "path_unlink_file": 125, + "random_get": 30 + }, + "result": "directory_records 2407819", + "source_seed_bytes": 6094160, + "transferred": 51780723 + }, + "linked_bytes": 38671319, + "linked_files": 110, + "linked_sha256": "3b4c1c8ae6b15cf97c49f801f3b0059da0eaefb2db2aae79d52957e651eaee30", + "max_depth": 284, + "max_free_segment": 274, + "module": { + "bytes": 26267204, + "functions": 11448, + "max_body_bytes": 106184, + "max_locals": 187, + "max_params": 18, + "max_results": 1, + "sha256": "e5dc5a398b07b54ea8fdb503bf68fb583d533f10ec3f930963e02b9505f7a763" + }, + "opcodes": 2665134, + "receiver": { + "fuel": 132344680603, + "host_calls": 24212, + "linear_bytes": 153878528, + "maxima": { + "dirrows": 68, + "entries": 279, + "fd": 356, + "file": 36094602, + "io": 1083296, + "iov": 1, + "joined_path": 119, + "live_fds": 6, + "path": 118 + }, + "operations": { + "args_get": 1, + "args_sizes_get": 1, + "clock_time_get": 2, + "environ_get": 8060, + "environ_sizes_get": 8060, + "fd_close": 353, + "fd_fdstat_get": 723, + "fd_filestat_get": 398, + "fd_prestat_dir_name": 1, + "fd_prestat_get": 3, + "fd_read": 4600, + "fd_readdir": 34, + "fd_seek": 441, + "fd_tell": 76, + "fd_write": 132, + "path_create_directory": 126, + "path_filestat_get": 624, + "path_open": 399, + "path_readlink": 1, + "path_remove_directory": 22, + "path_unlink_file": 125, + "random_get": 30 + }, + "result": "seven received getters, two physical suppliers, 88 typed cells per profile", + "source_seed_bytes": 42314119, + "transferred": 44886562 + }, + "trace_exponent": 113, + "transition_bound": "8788853932655975457155330527461376" + }, + "environment": { + "machine": "arm64", + "python": "3.12.16", + "system": "macOS-27.2-arm64-arm-64bit", + "wasmtime": "38.0.0" + }, + "independent": { + "bytes": 36094602, + "native_directory_sha256": "045c482b6d32fc58bae8e047e22d519f9269e0124fe3cb1695e930e4f472f2a8", + "records": 2407819, + "typed_cells_per_recipe": 88 + }, + "signed": { + "finite_tensor": { + "H_calls": 157248, + "bits": [ + 20, + 19 + ], + "coefficients_prefix": [ + 11811, + 10996, + 4152, + 868, + 77 + ], + "product": "-345550037539", + "seconds": 106.1817 + }, + "public_signed_product": -345550037539 + } +} diff --git a/research/frequency-weighted-native-multiplier/portable/NOTICE.md b/research/frequency-weighted-native-multiplier/portable/NOTICE.md new file mode 100644 index 0000000000..0e09e92a4e --- /dev/null +++ b/research/frequency-weighted-native-multiplier/portable/NOTICE.md @@ -0,0 +1,7 @@ +# Sources and licenses + +The scientific compiler and signed multiplier come from CrocSwap/integer-mult-bounds and its credited predecessors. The weighted installer retains the ordinary circuit, the Gaussian operators, exact chart and role generators, and both public profiles. This package binds them to a finite portable interpreter. The original authors and source hashes are listed in the parent package. [Scientific attribution](../NOTICE.md) · [Source manifest](../SOURCES.json) + +The two external files are from VMware Labs' `python/3.12.0+20231211-040d5a6` release. The VMware Labs packaging repository uses Apache-2.0. CPython and its standard library carry the Python Software Foundation license and included component notices. The interpreter and library are fetched directly from upstream. The module and archive each have their own digest in the replay driver. [Standalone executable](https://github.com/vmware-labs/webassembly-language-runtimes/releases/download/python/3.12.0%2B20231211-040d5a6/python-3.12.0.wasm) · [Library distribution](https://github.com/vmware-labs/webassembly-language-runtimes/releases/download/python/3.12.0%2B20231211-040d5a6/python-3.12.0-wasi-sdk-20.0.tar.gz) · [Packaging license](https://github.com/vmware-labs/webassembly-language-runtimes/blob/main/LICENSE) · [CPython 3.12.0 license](https://github.com/python/cpython/blob/v3.12.0/LICENSE) + +The Bytecode Alliance publishes the Wasmtime Python binding under Apache-2.0 with the LLVM exception. The tested binding is 38.0.0. Its matching Cranelift source distribution records Git commit `399f857f28ee8845d0cfd4ec71680912b5375831`. Its fuel rules are an explicit dependency of the trace proof. [Python release](https://pypi.org/project/wasmtime/38.0.0/) · [Matching compiler crate](https://crates.io/crates/wasmtime-internal-cranelift/38.0.0) · [Fuel translation](https://github.com/bytecodealliance/wasmtime/blob/399f857f28ee8845d0cfd4ec71680912b5375831/crates/cranelift/src/func_environ.rs#L368-L398) diff --git a/research/frequency-weighted-native-multiplier/portable/README.md b/research/frequency-weighted-native-multiplier/portable/README.md new file mode 100644 index 0000000000..9106405e5c --- /dev/null +++ b/research/frequency-weighted-native-multiplier/portable/README.md @@ -0,0 +1,43 @@ +# Portable fixed installation + +The frequency-weighted signed multiplier has an alternative fixed installer with $S<2^{113}$ individual tape reads, writes and moves on the complete fixed trace. The full-store price for the same tape computation gives $2^{142}$, with a coarse $2^{146}$ ceiling for both invocations. The smaller price uses the actual standalone interpreter head positions and the longest sequence of zero-fuel instructions. It generates the 106 runtime files and a 36,094,602-byte directory from the pinned source. A fresh interpreter receives those exact outputs, initializes both Gaussian suppliers and all five binary recipes across the two tiers, and writes the linked multiplier. Its stages have heights (3,000, 3,080, 1,024) and (8,192, 129,414, 524,288, 483,871). The equations for $\kappa$, the active-data bill and the five inherited research premises are those of the parent construction. [Local stack and control proof](STACK-LOCALITY.md) · [Complete tape-machine proof](TRACE-CLOCK.md) · [Whole multiplication construction](../README.md) + +The fixed phase has no operand input. Its two deterministic executions cover every installation of this specified machine. The multiplier receives its signed integer tapes afterwards. The setup bound applies to the same installation at every operand length. The two portable interpreter runs, explicit file services, archive recovery, complete directory transfer, final startup, copying and cleanup are charged. After setup the original algorithms read the restored typed records. The setup reduction is a certified ceiling for a different fixed installer. The comparison with the prior $2^{228}$ ceiling gives no measured speedup. The additional public interpreter is 26,267,204 bytes, even before library and output storage. [Resource proof](TRACE-CLOCK.md) · [Reproducible clock calculation](run.py) + +| Complete fixed operation | Guest fuel | Guest linear memory | Virtual file bytes transferred | +| --- | ---: | ---: | ---: | +| Produce both profiles and their whole directory | 802,083,502,514 | 331,808,768 | 51,780,723 | +| Open the emitted source and directory, bind both receivers | 132,344,680,603 | 153,878,528 | 44,886,562 | + +The output directory contains 2,407,819 records and 5,174,419 references. The 110-file linked installation occupies 38,671,319 bytes, including this directory. The conservative tape model permits up to $2^{64}$ scratch cells during lowering. These are explicit construction costs. Host measurements and the mathematical tape allowance price different operations. [Complete recorded evidence](EVIDENCE.json) + +## Replay + +Use CPython 3.12, Git and Wasmtime for Python version 38.0.0. From the repository root run these commands in a shell. The driver requires an empty output directory. Both downloads are public fixed inputs. The driver checks their SHA-256 digests before using them. + +```sh +work=$(mktemp -d) +python3.12 -m venv "$work/venv" +"$work/venv/bin/python" -m pip install wasmtime==38.0.0 +release='https://github.com/vmware-labs/webassembly-language-runtimes/releases/download/python/3.12.0%2B20231211-040d5a6' +curl -fL "$release/python-3.12.0.wasm" -o "$work/python.wasm" +curl -fL "$release/python-3.12.0-wasi-sdk-20.0.tar.gz" -o "$work/library.tar.gz" +portable=research/frequency-weighted-native-multiplier/portable +"$work/venv/bin/python" -B "$portable/run.py" --wasm "$work/python.wasm" \ + --archive "$work/library.tar.gz" --work "$work/output" +"$work/venv/bin/python" -B "$portable/compare.py" . "$work/output/installed-native.dag" +``` + +The separately downloaded module has SHA-256 `e5dc5a398b07b54ea8fdb503bf68fb583d533f10ec3f930963e02b9505f7a763`. The library archive has SHA-256 `6c1cddbb69ae09e87eee2906bdc70539bff5f2969818a6f8457d4e6a6eb67d4d`. The driver takes its three library members. The archive also contains a different interpreter binary. The release links and original licenses are listed in the component notice. [External components](NOTICE.md) + +For the arithmetic replay alone, run `python3 -B research/frequency-weighted-native-multiplier/portable/verify_receipt.py`. It checks the archived invoices and identities through standard-library integer operations. + +The driver writes `clock.json`, `signed.json`, the complete typed directory and the linked `machine/` tree. The machine executes $(-741503)\cdot466013=-345550037539$ at a finite tensor geometry. The independent check starts a clean instance through the usual Git-based installer. It compares each variant's chronological grades and histogram, both type descriptors, every typed transport share, and the full emitted byte stream. Production positive and ordinary ranks exceed the size of these finite product tests. [Fixed receipts](EVIDENCE.json) · [Finite signed test](signed.py) · [Independent original compiler](compare.py) + +## What is trusted + +The bit-level tape simulation and clock are written mathematics. The finite witness uses the byte-pinned guest, the Wasmtime 38 Cranelift meter with canonical NaN handling, the listed Python host reader and the specified preview1 file service. The checker parses every instruction in the guest. It checks the control depth, signatures, operand and record bounds, archive and directory identity, fuel cap and the total using Python integers. The portable setup proof has no Lean component. The regenerated executable and typed directory are checked independently of the tape simulation. [Opcode parser](guest_opcodes.py) · [Archive reconstruction](source_image.py) · [Directory and key checker](record_census.py) + +## Open next questions + +Can a smaller self-contained compiler remove the 26 MB CPython image while keeping the same verified output? A comparison against an alternative would need its own complete file, arithmetic, movement and receiving clock. The current physical product test leaves the first production-scale execution and performance crossover open. diff --git a/research/frequency-weighted-native-multiplier/portable/STACK-LOCALITY.md b/research/frequency-weighted-native-multiplier/portable/STACK-LOCALITY.md new file mode 100644 index 0000000000..90da9f1e36 --- /dev/null +++ b/research/frequency-weighted-native-multiplier/portable/STACK-LOCALITY.md @@ -0,0 +1,30 @@ +# A smaller clock for the same fixed compiler + +The ordinary WebAssembly instructions operate on the current activation, linear memory and fixed code. The interpreter in the preceding proof already parks its other stack heads beyond the current suffix. Pricing this placement removes the scan of every suspended activation from the coefficient for an ordinary instruction. The full high-water allowance remains in the cleanup term. Both the producer and the fresh receiving initializer use this placement. [Preceding complete-store price](TRACE-CLOCK.md) · [Two invoices](verify_receipt.py) + +## Cost-free instructions within one function + +In the pinned Cranelift translation a conditional or unconditional branch and every call cost fuel. The free forms are `nop`, `drop`, `block`, `loop`, `else`, `end`, `return` and `unreachable`. The last traps. Returning to a caller ends an interval within the current function. A new interval may start at any instruction after that return. All other free steps within a function move strictly forward. + +Index the instructions in a single decoded body by their positions. For every `else` use the structured block stack to find its matching `end`. Compute a suffix table $R$ in decreasing position order. Give a paid instruction and the one-past-end position value zero. Give a return or trap value one. For a free fallthrough instruction use $1+R(i+1)$. For an `else` at position $i$ with matching end $j$ use $1+\max(R(j),R(j+1))$. This includes an accounting convention that counts the matching end separately. Every free successor lies in the listed forward set. Backward induction bounds every consecutive unpaid interval within that function. A function-ending `end` has value one by the zero sentinel. + +The byte parser consumes every immediate before adding its opcode to that body's instruction sequence. It checks all 2,665,134 operators. The greatest $R$ is 274. An independent forward scan found the same value in function 9176. All 116,086 block, loop and if signatures have no parameters. Their single-byte types are empty (111,485), i32 (4,388), i64 (123), f64 (87) and f32 (3). The complete decoder rejects every other block-type encoding for this image. Thus a branch to a loop transfers zero parameters and all other branch targets have at most one result. There are at most $F$ paid instructions in an execution with $F$ fuel. The number of exits to other functions is at most $F+2$. Splitting at the paid instructions and exits leaves at most $2F+3$ unpaid intervals. Thus the whole execution has at most $(2F+4)275$ guest steps, including paid instructions and transfers. This bound admits arbitrary mixtures of nested calls and loop branches. [Complete decoder and suffix calculation](guest_opcodes.py) + +## Active and suspended spans + +Keep the call frames, label records and operand values on separate stack tapes. Their heads remain at the top between instructions. Code, fixed metadata, globals, the indirect table and linear memory together require less than $2^{37}$ cells, as priced in the original bill. A frame contains at most 205 local and parameter slots in total, 284 labels and five fixed descriptors, each using at most 512 cells. An operator addresses locals in its own frame. A branch can read its target label by scanning the current function's part of the label tape. A call appends a new frame adjacent to the suspended one. It transfers at most 18 arguments and stores the absolute bytecode return and operand height. A return drops the current frame and exposes the immediately preceding frame at the stack head. Rewinding a bytecode or memory head on a call transition uses only the fixed code or bounded linear-memory tape. A table-indirect call uses the same frame operation after its index lookup. + +A separate static estimate bounds the complete operand span of any current activation. In a validated function each reachable instruction has the height prescribed by its structured type derivation. Labels restore their entry height and their declared continuation arguments. A loop back-edge cannot accumulate additional live values. In a forward type check, each parsed instruction increases the abstract height by at most 19: the maximal function parameter arity is 18 and every result arity is at most one. Reopening an else arm or ending a scope first returns to the known enclosing height. The parser checks all block signatures have no incoming parameters. The stack floor at an unreachable point is its enclosing label height. Starting with at most 18 entries, even $19\cdot106184+18$ value records occupy less than $2^{30}$ cells. + +Integer and floating arithmetic read a bounded suffix of the operand stack. Keep its current logical height in a small binary counter. Save a height at every label and function entry. A branch or return that transfers a result copies that single top value to a short temporary. It can then walk down to the saved operand height, erasing intervening records before it restores the preserved result. Charge the bounded top-result movement within the ordinary per-instruction charge. Each additional erased operand record represents a true decrease in logical value count. A free block or loop preserves its parameters already on the stack. An end or return preserves at most its one existing result. No unpaid operator creates an additional live operand. Each paid instruction increases total operand count by at most one, across all open frames; parameters entering a function move to locals. The whole trace can therefore discard at most $F+2$ operand records in addition to the one local result handled at each transfer. This also pays a long discarded suffix reached from a single branch. At 512 cells per record allow $2^{14}$ transitions per cell for reverse movement, clearing, height decrements, tests and returning the short result. This gives a separate global charge $E=(F+2)512\,2^{14}$. + +With this extra operand charge, a single non-host instruction can access at most two adjacent frame spans, the current activation’s operand span, and the $2^{37}$ cells on the ordinary fixed and memory tapes. Four copies of the combined allowance, including the entire bounded operand span, fit below $A=2^{40}$ cells. The previously proved maximum of 256 passes with 4096 transitions per cell applies to this accessible range. An instruction does not scan the suspended frame stack or the virtual filesystem. File operations use their full separate $2^{92}$ price per host call. Initialization and final erasure still apply to the complete $L=2^{64}$ high-water allowance. Dynamic stack growth, large file writes, memory growth and final restoration thus enter the bill at their respective extents. + +For one invocation with $D$ host calls a sufficient total is + +$$ + 2^{111}+(2F+4)275(2^{20}A+2^{58})+E+D2^{92}+2^{110} + +4L2^{12}. +$$ + +The sum for the two actual runs is 8,788,853,932,655,975,457,155,330,527,461,376 transitions. The sum for the producer and receiver fits below $2^{113}$, even if each used $F=2^{40}$ and $D=2^{16}$. The accepted executions satisfy both inequalities strictly. This sharpens a transition upper bound for the same emitted scientific program. Source generation, directory contents, inputs to the signed multiplier, finite runs and the inherited proof obligations are shared with the complete-store calculation. [Exact witnessed charges](EVIDENCE.json) · [Integer replay](verify_receipt.py) diff --git a/research/frequency-weighted-native-multiplier/portable/TRACE-CLOCK.md b/research/frequency-weighted-native-multiplier/portable/TRACE-CLOCK.md new file mode 100644 index 0000000000..9d51cde34f --- /dev/null +++ b/research/frequency-weighted-native-multiplier/portable/TRACE-CLOCK.md @@ -0,0 +1,36 @@ +# Tape clock of the fixed WebAssembly installation + +This argument concerns the deterministic fixed installation defined by `run.py`, its public interpreter image, the pinned source and the directory receiver. It prices a sequential interpreter for that image. The Wasmtime execution checks the finite instruction budget. The JIT time is a separate measurement. The guest emits the scientific data after checking the source digests and deriving all the chart, coefficient, grade and recipe data. The initial image contains the ordinary CPython 3.12.0 interpreter for WASI. Installing and reading those 26,267,204 bytes, its 3.4 MiB zipped library, the compiler source, and clearing the transient state are part of the price. + +## Exact finite trace + +The host supplies a fixed clock, a fixed deterministic byte generator, fixed argv/environment, a private file namespace, and specified error codes. CPython runs with a fixed hash seed and no bytecode writes. Set Cranelift canonical NaN mode. The module has one linear memory with a $2^{30}$-byte cap and a function table with at most $2^{20}$ entries. File and directory counts and maximum field widths are checked separately. `source_image.py` restores the nested archives from their stated hashes, checks the preimage of every edit, applies every patch in order and checks the postimage. The independent source comparison uses the normal bootstrap. The fixed calculation calls exactly the constructors which `band_product.prepare_native()` dispatches. The producer checks both parameter rows before it emits the root. `compiler_state.py` extracts the single native instruction generator's four existing bindings. `tape_directory.py` emits each reachable data record once. It numbers each record after all its children. The data include the original maps, sequential roles, instruction order, true physical atlas and fractions. [Metered source and output](run.py) · [Virtual file operations](bounded_wasi.py) · [Exact source reader](source_image.py) · [Typed directory](tape_directory.py) + +Let $F$ be the finite fuel cost of this invocation, including the archive reader and emitter. The pipeline caps fuel at $2^{42}$ and its verified run uses $F<2^{40}$. The Cranelift 38 translation charges each reachable branch, call and numerical opcode. It assigns zero to `drop`, `nop`, `block`, `loop`, `else`, `end`, `return` and `unreachable`. In a successful invocation a zero-cost operator in one function falls through or advances to a larger code offset. A zero-cost return may transfer to the caller. There are at most $F+2$ such function exits, counting the initial entry and an optional module start. Partition at charged instructions and exits. There are fewer than $(2F+4)(106184+1)<2^{58}$ guest instructions because the longest body has 106,184 bytes. The parser checks every code body and every local declaration in the installed image. It finds 2,665,134 instructions, a maximum structured nesting depth of 284, at most 187 declared locals, at most 18 parameters, and at most one result. The actual instruction list has scalar integer and floating-point instructions, local/global/linear-memory operations, structured branches, direct and indirect calls, and memory growth. [Fuel translation in the matching source distribution](https://github.com/bytecodealliance/wasmtime/blob/399f857f28ee8845d0cfd4ec71680912b5375831/crates/cranelift/src/func_environ.rs#L368-L398) · [Full opcode parser](guest_opcodes.py) + +## Sequential interpreter + +Use separate binary work tapes for the bytecode, linear memory, table and globals, call frames with local and label records, operand stack, file catalogue, file bodies, and fixed argument scratch. The number of tapes is constant. Store the remaining code offset and type, local and operand base, frame flags and return location in five 512-bit records per activation. A local or argument needs one such record. One control record carries the block kind, code start/end/else offsets, operand restoration depth and result arity, with room for delimiters. A branch to a loop discards the intervening controls before executing that loop again. Thus at most the static maximum of 284 labels live in each frame. Function calls are charged. The occupied part of all frames has at most $(F+2)\cdot512(187+18+284+5)$ cells. The operand stack can gain at most one value per charged instruction. Branches preserve at most one result, or re-expose an existing value. The uncharged controls have no additional value result above the previous stack height. The operand stack needs at most $512(F+2)$ cells. The code, globals, data segments, function metadata, table, linear memory and fixed buffer descriptors occupy less than $2^{37}$ cells. The private file bound below is less than $2^{50}$ cells. Four full copies of this combined allowance fit in $L=2^{64}$ cells. This includes the current layout, a rewrite stream, output and restoration work. Data-dependent numerical multiplication uses its own tapes after installation. + +The interpreter keeps the active head on the top of each stack between instructions. All stored offsets fit 64 bits. A full pass includes an arbitrary sequential seek, copy, or restoration of up to $L$ cells. Allow 4096 transitions per cell. A pass uses at most two 128-bit counters. A counter update, comparison to a bound, and reset of its head require at most eight transitions per bit for each of two traversals. Reading, copying or clearing the current symbol and moving the source and destination heads fit the remaining steps by using the 64-bit offsets, or by using separate passes for the two counters. The following limits are expressed in complete passes. They include backing up and clearing each traversed scratch area. + +- Fetch the opcode and immediate from the code tape, or fetch a module descriptor from its directory. Up to 20 passes cover the code offset, function/type/global addresses, an indirect table index and the return to the initial heads. A branch-table immediate is one sequential list of LEB words. The same pass can count delimiters and stop at the requested entry. To find a structural end or else target, scan forward within the function, maintaining the current static depth. Ignore immediate bytes as in the checked opcode decoder. No branch requires a second search per scanned opcode. +- A scalar memory operation reads or writes at most eight aligned or unaligned bytes and performs bounds checks. A successful `memory.grow` initializes the entire new interval. Rewriting a complete linear memory and restoring the head takes at most 12 passes. Constants, selection, `local.get`, `local.set`, `local.tee`, `global.get`, and `global.set` require a bounded number of record scans on their named tapes. +- A call has at most 18 arguments. Even saving, moving, writing and restoring each through six complete sweeps costs at most 108 passes. An activation initializes its contiguous segment of at most 187 local slots in one pass. The return moves at most one value, scans back to the saved operand base and clears the discarded frame. A branch compares its depth with the marker stack in one pass, clears the selected suffix and restores the operand height. Up to 32 additional passes suffice for these frame, stack and branch transfers. Instructions with no operands also fit these allowances. +- Allow another 64 passes for copying output tags, saving offsets and scrubbing temporary buffers. The sum of these alternatives is below 256 passes per instruction. There is no table bulk-copy opcode, SIMD, concurrent memory, continuations, exceptions or garbage-collected reference instruction in the parsed image. The total non-arithmetic transition cost per interpreted instruction is at most $2^{20}L$. + +For scalar arithmetic store exact binary integers on separate work tapes. Addition, shifts, schoolbook multiplication and a shift/subtract unsigned division of $h$ bits cost at most $2^{16}(h+4)^2$ transitions each including copying and returns. For binary32 and binary64 use explicit special cases for signed zero, NaN, infinity, overflow, integer conversion and trap conditions. Finite values are signed integers with at most 53 significant bits times powers of two with exponents between $-1074$ and $971$. Keep exact addends, products, ratios, and midpoint tests as integer numerators and positive denominators. All need less than 16,384 bits, even after squaring a midpoint for a square-root comparison. For example, scaling one finite binary64 number by $2^{1074}$ gives an integer of less than 2099 bits. A product of two such integers has less than 4198 bits, and one more product to cross-multiply an exact quotient or a squared midpoint is less than 8396 bits. Include the common powers of two in this bound or cancel them before multiplication. Binary search the ordered finite encodings of the required sign, allowing 64 steps. At the two adjacent encodings compare their exact midpoint and use the even endpoint on a tie. Handle overflow at the last endpoint and subnormals at the zero endpoint. For a positive square root compare the input with the square of each candidate and the square of their midpoint. Integer-conversion tests use exact numerator shifts and division. Reinterpretation, signed zeros, signs and canonical NaNs use the instruction's bit rule. $128\cdot64\cdot2^{16}(2^{14}+4)^2<2^{58}$ local transitions cover the comparisons, products, quotient, sign and scratch erasure for any instruction. The basic operations per candidate are at most 16. The larger allowance also covers the final rounding and exact special cases. This cost is additional to tape movement. + +## Host calls, fixed receiver and cleanup + +The run has fewer than $2^{16}$ host calls. Source files and all initially seeded names fit in $2^{16}$ entries. A directory creation checks the entire entry count against $2^{16}$. Between directory creations there can be fewer than $2^{16}$ successful new file creations since each needs a distinct host call. Seed files and every generated file are shorter than $2^{29}$ bytes. Thus a full file-body tape, record tags and the pathname catalogue together fit below $2^{50}$ cells. Keep descriptor metadata and names on a separate tape from file contents. Every pathname has at most 4095 bytes. Normalizing a path and looking it up can use 4096 passes over the metadata, with a component stack and sequential path comparisons. Directory enumeration can select names in sorted order with one metadata scan per candidate and a separate mark tape. Its name-only catalogue has fewer than $2^{17}$ rows with names and metadata of fewer than $2^{16}$ bits each, so even $2^{18}$ complete selection passes fit $2^{64}$ transitions. No data files are traversed within those name comparisons. Each scatter/gather vector actually has one segment. Even with $2^{16}$ segments, each can locate both offsets, rewrite or read the complete body, copy contiguous bytes, update the descriptor, return and erase in 32 sweeps of the file or memory tape. At 4096 transitions per cell this costs at most $2^{83}$ transitions. The byte generator uses one elementary 32-bit recurrence for each byte requested and writes sequentially. The source file flags, seeks, reads, writes, stats, clock, bounded argument/environment copying and closes lie within $2^{92}$ per host call. These costs are separate from the guest `call` itself. Repeated readback, deleting a virtual file and preserving a still-open output charge the actual length or the complete prefix traversed. [Implemented service](bounded_wasi.py) + +The receiver can take the produced output tape directly. A record has a one-byte domain tag, a four-byte body length, and scalar bytes or four-byte backward child numbers. The 18 tags distinguish each named compiler data type. The last record is the root with all recipe handles. A streaming pass numbers records in order. To materialize the predecessor's indexed representation emit one named entry per scalar or outgoing reference and preserve each dictionary's insertion order. A compound key takes at most 28 bytes of expanded structural representation on the generated image, verified by induction on backward references. There are fewer than $2^{23}$ references in all. For sets and maps, the same ordered numerical, string and tuple comparison applies to each actual key. Reconstructing a structural key of this length takes at most 28 prior-record locates. Bounded-rational construction uses the generated canonical numerator and denominator, each with fewer than 4096 bits on this image. The full directory has fewer than $2^{26}$ bytes. Even allowing $2^{10}$ records of 4096 bits per reference, followed by $2^{10}$ complete record-store sweeps at 4096 transitions per cell per reference, uses fewer than $2^{90}$ transitions. The ordinary operator methods, immutable sharing, closures, signs, ordered labels and exact rational semantics are those exercised in the independently rehydrated consumer. The physical active fields remain in the original recurring calculation. When a fresh consumer needs the fixed source, ship the generated source from the same guest alongside the tape directory. A separate metered invocation reads the exact generated source and directory. It executes the real nested dependency installer, links the seven scientific getters, loads the full object graph and initializes both ordinary and Gaussian source bindings. The linked source and directory are copied to the final tapes. [Tape reader and emitter](tape_directory.py) · [Complete record check](record_census.py) · [Actual consumer bindings](consumer.py) + +Allow $2^{111}$ transitions per initialization. This includes reading the literal guest and library, scanning the module header and data sections, global/table initializers, writing the code with its offsets, seeding the virtual source files, and clearing their scratch. The program uses no host compiler in this serial execution. Fewer than $2^{27}$ initial code or file octets can each scan a $2^{64}$-cell tape with the same $2^{20}$ allowance, with the actual tapes below their cap during initialization. Code decoding can instead be done at fetch, as charged above. Allow a second $2^{110}$ for the output directory, linking the three fixed modules, installing the 106 generated sources and restoring input heads. Clear all remaining scratch and discarded guest state in four scans of $L$ cells, at 4096 transitions per cell. For $U=(2F+4)(106184+1)$ and $D$ actual host calls the complete fixed price is + +$$2^{111}+ U(2^{20}L+2^{58})+D\,2^{92}+2^{110}+4\,L\,2^{12}<2^{145}.$$ + +On the actual two fixed traces the sum is exactly 3,838,475,198,494,975,007,767,119,415,723,957,847,851,008 under this invoice. Its bit length is 142. The complete-store price therefore gives $S<2^{142}$. The loop and stack refinement gives the stronger integrated price $S<2^{113}$. [Accessible-span proof](STACK-LOCALITY.md) [Independent integer replay](verify_receipt.py) · [The two finite traces](EVIDENCE.json) + +The producer and the receiving initializer each have the stated conservative bound. Adding them proves $S<2^{146}$ for the complete fixed installation. Source and table output cross the boundary by content, including the complete directory and every generated runtime module. The byte lengths include the larger second input. The standard library archive can be decoded once by serial DEFLATE. Its complete uncompressed tar is under $2^{25}$ bytes. Even one complete scan of that extent for every output byte, at $2^{20}$ transitions per visited byte, fits the initialization allowance. The separate pinned standalone WebAssembly image is the interpreter used in both runs. The archive’s other interpreter is counted in archive extraction and never executed. It prices this particular portable fixed producer. It changes neither the root-rate proof nor the dynamic multiplication clock. Applying the same interpreter to a competitor could improve that competitor's ceiling as well. diff --git a/research/frequency-weighted-native-multiplier/portable/bounded_wasi.py b/research/frequency-weighted-native-multiplier/portable/bounded_wasi.py new file mode 100644 index 0000000000..bd5f95b5ad --- /dev/null +++ b/research/frequency-weighted-native-multiplier/portable/bounded_wasi.py @@ -0,0 +1,271 @@ +"""A private deterministic preview1 file system for a fixed setup flight.""" + +import posixpath +import struct +from collections import Counter + + +class FileService: + def __init__(self, argv, env): + self.strings = {"args": argv, "environ": env} + self.maximum = Counter() + self.files = {"/": None, "/tmp": None} + self.ino = {k: i for i, k in enumerate(self.files, 1)} + self.descriptors = { + 0: ["/stdin", 0, 0], + 1: ["/stdout", 0, 0], + 2: ["/stderr", 0, 0], + 3: ["/", 0, 0], + } + for name in ("/stdin", "/stdout", "/stderr"): + self.create(name, bytearray()) + self.cursor = 4 + self.rng = 0 + self.calls = Counter() + self.bytecount = 0 + + def create(self, path, data): + path = posixpath.normpath(path) + if path in self.files: + return + parent = posixpath.dirname(path) + if parent not in self.files: + self.create(parent, None) + self.files[path] = data + self.meta("joined_path", len(path.encode())) + self.meta("entries", len(self.files)) + if data is not None: + self.meta("file", len(data)) + self.ino[path] = max(len(self.ino) + 1, getattr(self, "inode", 0) + 1) + self.inode = self.ino[path] + + def meta(self, k, v): + self.maximum[k] = max(self.maximum[k], v) + assert ( + self.maximum[k] + < { + "path": 4096, + "joined_path": 4096, + "iov": 2**16, + "io": 2**28, + "entries": 2**16, + "dirrows": 2**16, + "file": 2**29, + "fd": 2**20, + "live_fds": 2**16, + }[k] + ) + + def handler(self, name): + def call(c, *args): + try: + return self.service(name, c, *args) + except BaseException as e: + print("failed syscall", name, args, repr(e), flush=True) + raise + + return call + + def service(self, name, caller, *x): + self.calls[name] += 1 + mem = caller["memory"] + + def get(p, n): + assert 0 <= n < 2**29 + return mem.read(caller, p, p + n) + + def put(p, data): + if data: + mem.write(caller, bytes(data), p) + + def number(p, n, fmt="I"): + put(p, struct.pack("<" + fmt, n)) + + def path(fd, p, n): + self.meta("path", n) + raw = get(p, n).decode() + parent = self.descriptors.get(fd, ("/badfd",))[0] + full = posixpath.normpath(posixpath.join(parent, raw)) + self.meta("joined_path", len(full.encode())) + return full + + def ftype(file): + return 3 if self.files[file] is None else 4 + + def filestat(file, p): + if file not in self.files: + return 44 + data = self.files[file] + put( + p, + struct.pack( + "> 24) + put(p, raw) + return 0 + if name == "proc_exit": + raise RuntimeError(f"WASI exit {x[0]}") + if name in ("fd_prestat_get", "fd_prestat_dir_name"): + if x[0] != 3: + return 8 + put(x[1], struct.pack("= n: + break + raw = raw[:n] + put(p, raw) + number(stored, len(raw)) + return 0 + if name in ("fd_seek", "fd_tell"): + if name == "fd_seek": + delta, whence = x[1:3] + desc[1] = [0, offset, len(data)][whence] + delta + number(x[-1], desc[1], "Q") + return 0 + if name in ("fd_read", "fd_write", "fd_pread", "fd_pwrite"): + writing = name.endswith("write") + explicit = name.startswith("fd_p") + if explicit: + offset = x[3] + if data is None: + return 31 + self.meta("iov", x[2]) + nbytes = 0 + for i in range(x[2]): + p, n = struct.unpack("= 0 and (depth or code.i == len(code.raw)) + assert depth == 0 + free = max(free, max_free_segment(ops)) + return counts, max_depth, free + + +if __name__ == "__main__": + c, d, f = census((Path(__file__).parent / "python-3.12.0.wasm").read_bytes()) + print( + json.dumps( + { + "instructions": sum(v for k, v in c.items() if "." not in k), + "max_control_depth": d, + "max_free_segment": f, + "opcode_counts": c, + }, + indent=2, + sort_keys=True, + ) + ) diff --git a/research/frequency-weighted-native-multiplier/portable/module_census.py b/research/frequency-weighted-native-multiplier/portable/module_census.py new file mode 100644 index 0000000000..97726c78ef --- /dev/null +++ b/research/frequency-weighted-native-multiplier/portable/module_census.py @@ -0,0 +1,80 @@ +"""Read code-body lengths and expanded local declarations from the guest binary.""" + +import json +from hashlib import sha256 +from pathlib import Path + + +class Reader: + def __init__(self, raw): + self.raw = raw + self.i = 0 + + def byte(self): + self.i += 1 + return self.raw[self.i - 1] + + def uint(self): + value = shift = 0 + while True: + b = self.byte() + value |= (b & 127) << shift + if b < 128: + return value + shift += 7 + assert shift < 35 + + def take(self, n): + self.i += n + assert self.i <= len(self.raw) + return Reader(self.raw[self.i - n : self.i]) + + +def catalogue(raw): + rd = Reader(raw) + assert bytes(rd.take(8).raw) == b"\x00asm\x01\x00\x00\x00" + maximum_local = maximum_body = maximum_params = maximum_results = functions = 0 + while rd.i < len(rd.raw): + kind = rd.byte() + body = rd.take(rd.uint()) + if kind == 1: + for _ in range(body.uint()): + assert body.byte() == 0x60 + p = body.uint() + body.take(p) + r = body.uint() + body.take(r) + maximum_params = max(maximum_params, p) + maximum_results = max(maximum_results, r) + assert body.i == len(body.raw) + if kind == 10: + functions = body.uint() + for _ in range(functions): + size = body.uint() + code = body.take(size) + loc = 0 + for _ in range(code.uint()): + loc += code.uint() + typ = code.byte() + assert typ in {0x7F, 0x7E, 0x7D, 0x7C, 0x7B, 0x70, 0x6F} + maximum_local = max(maximum_local, loc) + maximum_body = max(maximum_body, size) + assert body.i == len(body.raw) + return { + "bytes": len(raw), + "sha256": sha256(raw).hexdigest(), + "functions": functions, + "max_locals": maximum_local, + "max_body_bytes": maximum_body, + "max_params": maximum_params, + "max_results": maximum_results, + } + + +if __name__ == "__main__": + print( + json.dumps( + catalogue((Path(__file__).parent / "python-3.12.0.wasm").read_bytes()), + indent=2, + ) + ) diff --git a/research/frequency-weighted-native-multiplier/portable/producer.py b/research/frequency-weighted-native-multiplier/portable/producer.py new file mode 100644 index 0000000000..4e612d888b --- /dev/null +++ b/research/frequency-weighted-native-multiplier/portable/producer.py @@ -0,0 +1,21 @@ +"""Generate both finite native profiles and emit their fixed directory.""" + +import sys +from pathlib import Path + +from compiler_state import construct +from source_image import write_image + + +def run(): + write_image("/sources", "/machine", "/weighted") + sys.path.insert(0, "/machine") + from tape_directory import dump + + state = construct() + assert [[recipe.rank_log for recipe in layer] for layer in state[0]] == [ + [3000, 3080, 1024], + [8192, 129414, 524288, 483871], + ] + with Path("/tmp/compiled.dag").open("wb") as dest: + print("directory_records", dump(dest, state), flush=True) diff --git a/research/frequency-weighted-native-multiplier/portable/record_census.py b/research/frequency-weighted-native-multiplier/portable/record_census.py new file mode 100644 index 0000000000..71f0589105 --- /dev/null +++ b/research/frequency-weighted-native-multiplier/portable/record_census.py @@ -0,0 +1,62 @@ +"""Read all directory records, check backward edges and size semantic dictionary keys.""" + +import json +import struct +import sys +from array import array +from collections import Counter +from pathlib import Path + + +def inspect(path): + # One finite key has a self-delimiting type plus one reference for each atom. + cap = 2**31 - 1 + size = array("I") + counts = Counter() + keys = largest = largest_key = edges = scalar = 0 + with path.open("rb") as f: + assert f.read(8) == b"IMBDAG1\0" + while raw := f.read(5): + t, n = struct.unpack(" 100 and all(len(op) == 2 for op in operators) + cfg = Config() + cfg.consume_fuel = True + cfg.strategy = "cranelift" + _bindings.wasmtime_config_cranelift_nan_canonicalization_set(cfg.ptr(), True) + eng = Engine(cfg) + module = Module(eng, blob) + common = ("compiler_state.py", "tape_directory.py") + service, producer = flight( + eng, + module, + lib, + sources(root), + "producer", + (*common, "source_image.py", "producer.py"), + ) + raw = bytes(service.files["/tmp/compiled.dag"]) + verified(raw, DIRECTORY) + compiled = machine_files(service) + assert signature(compiled) == SOURCE_IMAGE and len(compiled) == 106 + del service + dag = work / "installed-native.dag" + dag.write_bytes(raw) + c = inspect(dag) + assert ( + c["largest_key_bytes"] <= 28 + and c["largest_integer_bits"] < 4096 + and c["edges"] < 2**23 + and c["bytes"] < 2**26 + ) + seeds = {"/machine/" + k: v for k, v in compiled.items()} + seeds["/machine/installed-native.dag"] = raw + service, consumer = flight( + eng, + module, + lib, + seeds, + "consumer", + (*common, "fixed_directory.py", "consumer.py"), + ) + linked = machine_files(service) + del service + assert len(linked) == 110 + write_tree(work / "machine", linked) + assert ( + signature(linked) + == "3b4c1c8ae6b15cf97c49f801f3b0059da0eaefb2db2aae79d52957e651eaee30" + ) + full_store = time_bound(producer, code, depth) + time_bound(consumer, code, depth) + bound = local_time_bound(producer, code, depth, free) + local_time_bound( + consumer, code, depth, free + ) + assert bound < 2**113 and full_store < 2**142 + evidence = { + "installer": producer, + "receiver": consumer, + "opcodes": sum(operators.values()), + "module": code, + "max_depth": depth, + "max_free_segment": free, + "directory": c, + "directory_sha256": DIRECTORY, + "compiled_sha256": signature(compiled), + "linked_sha256": signature(linked), + "compiled_files": len(compiled), + "compiled_bytes": sum(map(len, compiled.values())), + "linked_files": len(linked), + "linked_bytes": sum(map(len, linked.values())), + "transition_bound": str(bound), + "exponent": 146, + "full_store_bound": str(full_store), + "full_store_trace_exponent": full_store.bit_length(), + "trace_exponent": bound.bit_length(), + } + (work / "clock.json").write_text( + json.dumps(evidence, sort_keys=True, indent=2) + "\n" + ) + print( + f"fixed setup < 2^{bound.bit_length()} transitions on this trace; receipts at", + work / "clock.json", + flush=True, + ) + result = subprocess.run( + [sys.executable, "-B", str(HERE / "signed.py"), str(work / "machine")], + check=True, + capture_output=True, + text=True, + ) + (work / "signed.json").write_text(result.stdout) + print(result.stdout, flush=True) + + +if __name__ == "__main__": + main() diff --git a/research/frequency-weighted-native-multiplier/portable/signed.py b/research/frequency-weighted-native-multiplier/portable/signed.py new file mode 100644 index 0000000000..cc0df84109 --- /dev/null +++ b/research/frequency-weighted-native-multiplier/portable/signed.py @@ -0,0 +1,32 @@ +"""Run the linked signed operator and check every finite convolution coefficient.""" + +import json +import sys +from pathlib import Path + + +def main(): + sys.path.insert(0, str(Path(sys.argv[1]).resolve())) + from band_product import Product, multiply, prepare_native, production_supplier + from check_product import one + from fixed_directory import data + from installations import PROFILES + + links = data() + for left, right in zip(prepare_native(), links[0], strict=True): + assert all(a is b for a, b in zip(left, right, strict=True)) + for profile, tier in zip(PROFILES.values(), links[0], strict=True): + instance = production_supplier( + profile.complex_log, profile.positive_stop_denominator + ) + assert instance.recipe is tier[-1] and instance.physical is links[5][0] + answer = multiply(-741503, 466013) + assert answer == -345550037539 + row = one(Product((3, 5), 8, 136), -741503, 466013) + assert row["product"] == str(answer) + assert row["coefficients_prefix"] == [11811, 10996, 4152, 868, 77] + print(json.dumps({"public_signed_product": answer, "finite_tensor": row})) + + +if __name__ == "__main__": + main() diff --git a/research/frequency-weighted-native-multiplier/portable/source_image.py b/research/frequency-weighted-native-multiplier/portable/source_image.py new file mode 100644 index 0000000000..638b591ea9 --- /dev/null +++ b/research/frequency-weighted-native-multiplier/portable/source_image.py @@ -0,0 +1,173 @@ +"""Restore the public fixed compiler with a sequential unified-diff reader.""" + +import json +import re +import tarfile +from hashlib import sha256 +from io import BytesIO +from pathlib import Path + + +def verify(data, digest): + if sha256(data).hexdigest() != digest: + raise ValueError("incorrect source digest") + return data + + +def source_tar(data, manifest): + files = {} + with tarfile.open(fileobj=BytesIO(data), mode="r|gz") as archive: + for rec in archive: + key = rec.name + if ( + not rec.isfile() + or key not in manifest + or key in files + or Path(key).is_absolute() + or ".." in Path(key).parts + ): + raise ValueError("invalid archive member") + files[key] = verify(archive.extractfile(rec).read(), manifest[key]) + if files.keys() != manifest.keys(): + raise ValueError("incomplete source archive") + return files + + +def apply(files, diff): + lines = diff.splitlines(keepends=True) + i = 0 + header = re.compile(rb"@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") + while i < len(lines): + if lines[i].startswith( + (b"diff --git ", b"index ", b"new file mode ", b"old mode ", b"new mode ") + ): + i += 1 + continue + old = lines[i].split()[1] + new = lines[i + 1].split()[1] + assert ( + lines[i].startswith(b"--- ") + and lines[i + 1].startswith(b"+++ ") + and new.startswith(b"b/") + ) + name = new[2:].decode() + assert old == b"/dev/null" or old == b"a/" + new[2:] + rows = files.get(name, b"").splitlines(keepends=True) + i += 2 + cursor = 0 + output = [] + while i < len(lines) and lines[i].startswith(b"@@ "): + m = header.match(lines[i]) + assert m is not None + start = m[1] + old_count = int(m[2] or 1) + new_count = int(m[4] or 1) + pos = int(start) - (1 if old_count else 0) + assert cursor <= pos <= len(rows) + output.extend(rows[cursor:pos]) + cursor = pos + i += 1 + old_used = new_used = 0 + while old_used < old_count or new_used < new_count: + opcode = lines[i][:1] + value = lines[i][1:] + i += 1 + if i < len(lines) and lines[i].startswith( + b"\\ No newline at end of file" + ): + value = value.removesuffix(b"\n") + i += 1 + assert opcode in (b"+", b"-", b" ") + if opcode != b"+": + assert rows[cursor] == value + cursor += 1 + old_used += 1 + if opcode != b"-": + output.append(value) + new_used += 1 + assert old_used == old_count and new_used == new_count + output.extend(rows[cursor:]) + files[name] = b"".join(output) + + +def image(root): + meta = json.loads((root / "SOURCES.json").read_bytes()) + source = { + s: verify((root / s).read_bytes(), h) + for s, h in meta["archive_and_overlay_sha256"].items() + } + a = source_tar(source["source/installer.tar.gz"], meta["installer_files"]) + amid = json.loads(a["SOURCES.json"]) + b = source_tar( + verify(a["retimed-source.tar.gz"], amid["precursor_archive_sha256"]), + amid["precursor_files"], + ) + bmid = json.loads(b["predecessor/SOURCES.json"])["offline_predecessor"] + fs = source_tar( + verify(b["predecessor/" + bmid["archive"]], bmid["archive_sha256"]), + {k: r["sha256"] for k, r in bmid["files"].items()}, + ) + for name, r in json.loads(b["predecessor/OVERLAY.json"]).items(): + text = verify(fs[name], r["old_sha256"]).decode() + for old, new in r["edits"]: + assert text.count(old) == 1 + text = text.replace(old, new) + fs[name] = verify(text.encode(), r["new_sha256"]) + apply(fs, b["machine.patch"]) + apply(fs, b["receiver.patch"]) + for stem in ( + "five_exchange", + "installations", + "raw_binary_stage", + "retimed_supplier", + "transport", + "unpowered_price", + "fiscal_scans", + "check_nonzero_eight", + ): + fs[stem + ".py"] = b[stem + ".py"] + for name, r in amid["runtime_patch_sha256"].items(): + verify(fs[name], r["before"]) + apply(fs, verify(a["production.patch"], amid["production_patch_sha256"])) + for name, r in amid["runtime_patch_sha256"].items(): + verify(fs[name], r["after"]) + for name in ( + "gauss_phase.py", + "phase_atlas.py", + "sparse_helpers.py", + "clock_ports.py", + ): + fs[name] = a[name] + for name, r in meta["runtime"].items(): + verify(fs[name], r["before"]) + apply(fs, source["runtime.patch"]) + fs["strong-bit.json.gz"] = source["source/strong-bit-k7.json.gz"] + for name in ("installations.py", "grades.py"): + fs[name] = source[name] + for name, r in meta["runtime"].items(): + verify(fs[name], r["after"]) + return fs + + +def write_image(archive, destination, weighted=None): + dest = Path(destination) + files = image(Path(archive)) + if weighted is not None: + root = Path(weighted) + pins = json.loads((root / "SOURCES.json").read_bytes()) + assert pins["predecessor"] == "7b48187d99525ad59f560de3921ec7e48382484c" + source = { + key: verify((root / key).read_bytes(), digest) + for key, digest in pins["local_sources"].items() + } + for key, row in pins["runtime_images"].items(): + verify(files[key], row["before"]) + apply(files, source["runtime.patch"]) + for key in ("typed_raw.py", "typed_transport.py", "grades.py"): + files[key] = source[key] + for key, row in pins["runtime_images"].items(): + verify(files[key], row["after"]) + for key, data in files.items(): + path = dest / key + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data) diff --git a/research/frequency-weighted-native-multiplier/portable/tape_directory.py b/research/frequency-weighted-native-multiplier/portable/tape_directory.py new file mode 100644 index 0000000000..bc50cff23d --- /dev/null +++ b/research/frequency-weighted-native-multiplier/portable/tape_directory.py @@ -0,0 +1,136 @@ +"""Emit and restore an ordered native directory with child-before-parent references.""" + +import struct +import sys +from array import array +from collections import Counter +from fractions import Fraction + + +def types(): + import grades + from clock_ports import Ports + from powered import Port, PoweredWord + from raw_binary_stage import BinaryWord + from transport import Recipe + + base = ( + type(None), + bool, + int, + str, + Fraction, + tuple, + list, + dict, + Counter, + set, + Port, + Ports, + PoweredWord, + BinaryWord, + ) + if hasattr(grades, "WeightedGrades"): + return base + ( + grades.WeightedGrades, + Recipe, + grades.GradeVariant, + grades.WeightedRecipe, + ) + return base + (grades.Grades, Recipe) + + +def ref_bytes(ids): + words = array("I", ids) + assert words.itemsize == 4 + if sys.byteorder != "little": + words.byteswap() + return words.tobytes() + + +def dump(out, roots): + cls = types() + codes = {t: i for i, t in enumerate(cls)} + ids = {} + w = out.write + w(b"IMBDAG1\x00") + + def visit(obj): + k = id(obj) + if k in ids: + return ids[k] + tag = codes[type(obj)] + if tag == 0: + body = b"" + elif tag == 1: + body = bytes([obj]) + elif tag == 2: + body = int(obj).to_bytes( + max(1, (obj.bit_length() + 8) // 8), "little", signed=True + ) + elif tag == 3: + body = obj.encode("utf8") + elif tag == 4: + body = ref_bytes((visit(obj.numerator), visit(obj.denominator))) + elif tag in (5, 6, 9): + body = ref_bytes(visit(v) for v in (sorted(obj) if tag == 9 else obj)) + elif tag in (7, 8): + body = ref_bytes(visit(v) for pair in obj.items() for v in pair) + else: + body = ref_bytes((visit(vars(obj)),)) + rid = len(ids) + ids[k] = rid + w(struct.pack(" 0 and 5 * r <= 4 * k for (r, k), w in cells.items()) + assert all(sum(w for (p, k), w in cells.items() if p == r) == 1 for r in paid) + + # The first three positive terms of log(k/r) suffice for each real edge. + psi = Q(0) + for (r, k), share in cells.items(): + u = Q(k - r, k + r) + log_lower = 2 * (u + u**3 / 3 + u**5 / 5) + psi += paid[r] * share * r * log_lower + target_axes = sum(count * k for k, count in targets.items()) + fringe = 10 * target_axes / (t * psi) + assert target_axes == 135150528 + assert psi > Q(1790217668064, 10000) + assert fringe < Q(7579, 1000) + + # All bounds below improve as H grows. Check their smallest eligible H. + M = 2**1024 + upper = 2 * (M // (2048 * recipe.ambient)) + assert 5160 <= DELTA * upper + assert (1 - DELTA) * M <= 1024 * recipe.ambient * upper + assert upper > 516 * lower and M * DELTA >= 1 + assert t > Q(996, 1000) and 11 * t > 10 + assert 91 / (t * 2**10) + Q(2, M**5) < 2 + assert 2**46 < Q(M**4, 2**132) + assert 2**20 < Q(M**4, 2**132) + assert 2 * 52608 < M + assert 4 * (lower + 2) * 6 < 5 * lower * 5 + assert 2**19 * (upper + lower) ** 77 + lower**77 < (M * lower) ** 77 + + # Keep the upper physical period, complete group padding, both endpoint + # roundings, and the endpoint of the integral's chosen upper band. + finite_factor = ( + (1 + DELTA) + * (1 + Q(4 * max(targets), 1024 * recipe.ambient)) + * Q(power_interval(1024 * recipe.ambient * lower, c)[1], UNIT) + * (1 + fringe / lower + DELTA) + / (1 - DELTA) ** 4 + ) + assert UNIT * finite_factor < power_interval(2, POSITIVE_DEBIT)[0] + return { + "debit": str(POSITIVE_DEBIT), + "lower_band": lower, + "weighted_target_axes": target_axes, + "fringe": str(fringe), + "psi_lower": str(psi), + "upper_factor": str(finite_factor), + } diff --git a/research/frequency-weighted-native-multiplier/receipt.py b/research/frequency-weighted-native-multiplier/receipt.py new file mode 100644 index 0000000000..6c2b0e918d --- /dev/null +++ b/research/frequency-weighted-native-multiplier/receipt.py @@ -0,0 +1,267 @@ +"""Compute both signed invoices from the installed frequency-weighted source.""" + +from collections import Counter, defaultdict +from fractions import Fraction as Q +import json +from pathlib import Path +import sys + +HERE = Path(__file__).resolve().parent +runtime = Path(sys.argv[1]).resolve() +sys.path.insert(0, str(runtime)) +from upstream import HERE as RAW_DIR, install + +install() +sys.path.append(str(HERE.parent / "tiered-native-multiplier" / "source")) +sys.path.append(str(HERE / "portable")) +from activation import resource_receipt +from band_product import prepare_native +from grades import LOWER, SCALES, WEIGHTS +from independent_binary_price import raw_moments +from installations import BINARY_C, GAUSSIAN_C, ENTRY, TERMINAL, activation, at_public +from linear_geometry import entrance_geometry +from ordinary_carrier import stage_for_width_log +from ordinary_clock import first_stage_bound, polynomial_to_fibre_bound +from outer_budget import qualify +from outer_clock import financial_checks +from strict_moment import UNIT, power_interval +from staged_carriers import entrance_logs +from strong_binary import graph, caller +from strong_complex import load_changed, word +from transport import ceil +from unpowered_price import certify, intervals +from verify_receipt import verify as fixed_installation + +sys.path.append(str(HERE)) +from positive_debit import certify_loss + +DEBIT = Q(65081, 2**19) + + +def tape_factor(ambient, rate): + delta, lower = Q(1, 2**128), 32768 + return ( + Q(256, 255) + * Q(4097, 4096) + * Q(1028, 1024) + * Q(power_interval(1024 * ambient * lower, rate)[1], UNIT) + * (1 + Q(64, lower) + delta) + / ((1 - Q(10, lower)) * (1 - delta) ** 3) + ) + + +def raw_counts(base, multiplicity): + targets = Counter(port.rank for port in base.targets) + paid = Counter(port.rank for port in base.paid) + t, p = targets.copy(), paid.copy() + for grade, number in targets.items(): + t[2 * grade] += multiplicity * number + for grade, number in paid.items(): + p[2 * grade] += multiplicity * number + p[1] -= 1008 + p[Q(1, 2)] += 2016 + return t, p + + +def total_interval(counts): + ends = [0, 0] + for grade, count in counts.items(): + for i, value in enumerate(intervals(grade, 1 - GAUSSIAN_C)): + ends[i] += count * value + return tuple(Q(value, UNIT) for value in ends) + + +def check_numerical(recipe): + assert SCALES == (1, 2) and WEIGHTS == (1, 90) + base = word(*load_changed(RAW_DIR / "inputs")) + t, p = raw_counts(base, 90) + assert (recipe.targets.histogram, recipe.paid.histogram) == (t, p) + types = recipe.types() + for variant, target, paid in zip( + types, recipe.targets.variants, recipe.paid.variants, strict=True + ): + assert Counter(variant.targets) == target.histogram + assert Counter(variant.paid) == paid.histogram + t_lo, t_hi = total_interval(t) + p_lo, p_hi = total_interval(p) + assert t_lo > p_hi and p_lo / t_hi > Q(99, 100) and p_lo > 10 + assert 1 - GAUSSIAN_C > Q(996, 1000) and Q( + power_interval(max(t), GAUSSIAN_C)[1], UNIT + ) < Q(106, 100) + margin, cells = certify(GAUSSIAN_C, (t, p)) + assert margin > Q(689, 10**15) and cells == recipe.cells and len(cells) == 51 + prices = recipe.typed_cells() + rows, loads = defaultdict(Q), defaultdict(Q) + min_share = 1 + for (a, r, b, k), share in prices.items(): + count = recipe.targets.variants[b].histogram[k] + unit_share = share / count + assert 5 * r <= 4 * k + rows[a, r] += share + loads[b, k] += ( + WEIGHTS[a] + * recipe.paid.variants[a].histogram[r] + * unit_share + * Q(intervals(r, 1 - GAUSSIAN_C)[1], UNIT) + ) + min_share = min(min_share, unit_share) + assert all( + rows[a, r] == 1 for a, v in enumerate(recipe.paid.variants) for r in v.histogram + ) + for b, variant in enumerate(recipe.targets.variants): + for k in variant.histogram: + assert ( + 0 < loads[b, k] <= WEIGHTS[b] * Q(intervals(k, 1 - GAUSSIAN_C)[0], UNIT) + ) + assert min_share > Q(1, 2**26) + assert prices[1, 112, 1, 258] / recipe.targets.variants[1].histogram[258] == Q( + 1, 624 + ) + assert ( + max( + max(v.numerator.bit_length(), v.denominator.bit_length()) + for v in cells.values() + ) + <= 261 + ) + assert recipe.ambient == 306 and LOWER == 2048 + finite_loss = certify_loss(recipe, LOWER) + assert Q(finite_loss["debit"]) == DEBIT + cuts = {} + for weight in (90, 91): + chosen, required = raw_counts(base, weight) + cap = total_interval({k: n for k, n in chosen.items() if k > 2}) + load = total_interval({r: n for r, n in required.items() if 5 * r > 8}) + net = total_interval(chosen)[0] - total_interval(required)[1] + if weight == 90: + assert cap[0] - load[1] > 494 + else: + assert cap[1] - load[0] < -1515 and net > Q(3, 100) + cuts[weight] = [str(cap[0] - load[1]), str(cap[1] - load[0])] + return dict( + trial=str(GAUSSIAN_C), + weights=list(WEIGHTS), + real_targets=[len(w.targets) for w in types], + real_loans=[len(w.paid) for w in types], + weighted_targets=t.total(), + weighted_loans=p.total(), + directed_margin=str(margin), + grade_cells=len(cells), + typed_cells=len(prices), + min_individual_share=str(min_share), + raw_loss=str(DEBIT), + finite_loss=finite_loss, + capacity_cut=cuts, + ) + + +def bank(profile): + heights = profile.rank_logs + booked, rates = Q(0), [] + for stage, height in enumerate(heights): + assert height >= 3000 + upper = min(profile.eta, (249 * (BINARY_C - Q(11, 8 * height)) + booked) / 250) + selected = ( + profile.ordinary + if stage + 1 == len(heights) + else Q(int(upper * 10**21) - 1, 10**21) + ) + assert booked < selected < upper + rates.append(str(selected)) + booked = selected + gaussian = GAUSSIAN_C - DEBIT / profile.complex_log + signed = qualify( + profile.kappa, + Q(1, profile.positive_stop_denominator), + profile.ordinary, + gaussian, + ) + stock = resource_receipt(profile) + assert activation(profile) == stock["public_exponent_A"] + cuts = tuple(stock["binary_cuts"]) + assert entrance_logs(heights) == cuts + for i, cut in enumerate(cuts, 1): + assert stage_for_width_log(cut - 1, len(heights), heights) == i - 1 + assert stage_for_width_log(cut, len(heights), heights) == i + assert stage_for_width_log(cut, i - 1, heights) == i - 1 + if min(heights) >= 8192: + assert 1 <= len(heights) <= 7 + bound = 128 + 320 * sum(heights) + additions = [] + else: + assert heights == ENTRY.rank_logs + costs = (first_stage_bound(profile.eta), polynomial_to_fibre_bound()) + additions = [ + max(0, e - 944 * h) for e, h in zip(costs, profile.rank_logs, strict=True) + ] + bound = 40 + 17 + 16384 * sum(heights) + sum(additions) + expense = max(84500001, 1602 + 220 * profile.complex_log + bound) + return dict( + kappa=str(profile.kappa), + ordinary_H=list(heights), + numerical_H=profile.complex_log, + ordinary_rates=rates, + gaussian_rate=str(gaussian), + signed=signed, + stock=stock, + geometry=entrance_geometry(activation(profile)), + binary_surcharges=additions, + log2_B=bound, + log2_C=expense, + ) + + +def check(): + low, high = prepare_native() + assert low[-1].cells is high[-1].cells and low[-1].targets is high[-1].targets + assert ( + low[0].cells is high[0].cells and low[-1].trial == high[-1].trial == GAUSSIAN_C + ) + target, paid = raw_moments(graph(), caller()) + for profile, recipes in zip((ENTRY, TERMINAL), (low, high), strict=True): + assert tuple(v.rank_log for v in recipes) == ( + *profile.rank_logs, + profile.complex_log, + ) + for ordinary in recipes[:-1]: + assert ordinary.ambient == 134 and ordinary.trial == BINARY_C + assert (Counter(ordinary.targets), Counter(ordinary.paid)) == (target, paid) + bit_margin, bit_cells = certify(BINARY_C, (target, paid)) + assert bit_margin > 0 and high[0].cells == bit_cells + assert (tape_factor(134, BINARY_C) * Q(47, 20)) ** 8 < 2**11 + gaussian = check_numerical(high[-1]) + early, late = bank(ENTRY), bank(TERMINAL) + A = activation(TERMINAL) + threshold = (1 << A) + (-pow(2, A, 6)) % 6 + assert at_public(threshold - 6) is ENTRY and at_public(threshold) is TERMINAL + premium = ceil((TERMINAL.kappa - ENTRY.kappa) * A) + cost = 1 + max(early["log2_C"] + premium, late["log2_C"]) + assert cost == 318259431 and premium == 514 + ordinary_floor = Q(11, 8) / (BINARY_C - TERMINAL.ordinary) + positive_floor = DEBIT / (GAUSSIAN_C - TERMINAL.ordinary) + assert (ceil(ordinary_floor), ceil(positive_floor)) == (517430, 483870) + older = Q(".0038982016137") + gain = TERMINAL.kappa - older + assert gain == Q(83863, 10**13) + assert TERMINAL.kappa > Q(4286126377, 2**40) + assert financial_checks()["early_log2_C_bound"] == 84500000 + setup = fixed_installation() + return dict( + gaussian=gaussian, + entry=early, + terminal=late, + previous_rate=str(older), + rate_delta=str(gain), + complete_log2_C=cost, + entry_price_surcharge=premium, + fixed_funding_height_floors=[ceil(ordinary_floor), ceil(positive_floor)], + log2_fixed_setup_upper=setup["trace_exponent"], + log2_portable_setup_guard=setup["conservative_exponent"], + log2_full_store_setup_upper=setup["full_store_trace_exponent"], + portable_setup_transition_upper=setup["transitions"], + max_native_H=max(*TERMINAL.rank_logs, TERMINAL.complex_log), + ) + + +if __name__ == "__main__": + print(json.dumps(check(), indent=2)) diff --git a/research/frequency-weighted-native-multiplier/runtime.patch b/research/frequency-weighted-native-multiplier/runtime.patch new file mode 100644 index 0000000000..e63a600acc --- /dev/null +++ b/research/frequency-weighted-native-multiplier/runtime.patch @@ -0,0 +1,84 @@ +--- a/installations.py ++++ b/installations.py +@@ -4,7 +4,7 @@ + from fractions import Fraction as Q + + BINARY_C = Q(4391986206293, 2**50) +-GAUSSIAN_C = Q(2143194013, 2**39) ++GAUSSIAN_C = Q(17145637167, 2**42) + + + @dataclass(frozen=True) +@@ -21,7 +21,7 @@ + + + ENTRY = Profile((3000, 3080), 1024, Q(".00345")) +-TERMINAL = Profile((35327, 559005), 680000, Q(".0038982")) ++TERMINAL = Profile((8192, 129414, 524288), 483871, Q(".00389821")) + PROFILES = {"entry": ENTRY, "terminal": TERMINAL} + + +--- a/retimed_supplier.py ++++ b/retimed_supplier.py +@@ -1,4 +1,4 @@ +-"""Run two column scales of the tagged 48-call word in the signed positive receiver.""" ++"""Run two independently funded column scales of the tagged 48-call word in the signed positive receiver.""" + + + from upstream import HERE, install +@@ -8,44 +8,8 @@ + from periodic import Job + from raw48 import ComplexRaw + from spool import scratch, snapshot, transfer +-from grades import SCALES, SPLITS, numerical_source, numerical_recipe +- +- +-class Raw: +- def __init__(self, tagged, physical): +- self.tagged = tagged +- self.physical = physical +- +- def native(self, ports, columns): +- if columns <= 0 or columns % 2: +- raise ValueError("Each split needs a positive even column count") +- if len(ports) != len(SCALES) * len(self.tagged.targets): +- raise ValueError("Each true target needs one complete owner") +- if len({job.owner for job in ports}) != len(ports): +- raise ValueError("Every productive port needs its own live owner") +- source = iter(ports) +- for scale in SCALES: +- width = columns * scale +- inputs = [] +- for label in self.tagged.targets: +- job = next(source) +- if len(job.axes) != label.rank * width: +- raise ValueError("A target has the wrong number of physical axes") +- inputs.append((label.tag, job)) +- actual = self.physical.raw(inputs, width) +- splits = 0 +- for label in self.tagged.paid: +- tag, job = next(actual) +- if tag != label.tag or len(job.axes) != label.rank * width: +- raise ArithmeticError("The physical cut differs from the installed word") +- if scale == 1 and label.rank == 1 and splits < SPLITS: +- yield job.select(range(width // 2)) +- yield job.select(range(width // 2, width)) +- splits += 1 +- else: +- yield job +- if next(actual, None) is not None or (scale == 1 and splits != SPLITS): +- raise ArithmeticError("The numerical word did not close at its final loan") ++from grades import numerical_source, numerical_recipe ++from typed_raw import TypedRaw + + + class Positive(RetainedPositive): +@@ -87,7 +51,7 @@ + physical = ComplexRaw( + self.physical, fields, columns, low=low, bundle=bundle, slots=n + ) +- adapter = Raw(self.word, physical) ++ adapter = TypedRaw(self.word, physical) + outer = self + + class Machine: diff --git a/research/frequency-weighted-native-multiplier/typed_raw.py b/research/frequency-weighted-native-multiplier/typed_raw.py new file mode 100644 index 0000000000..1797e260bb --- /dev/null +++ b/research/frequency-weighted-native-multiplier/typed_raw.py @@ -0,0 +1,34 @@ +"""Generate both raw types from the signed target tags and restore their independent owners.""" + + +class TypedRaw: + def __init__(self, word, physical): + self.word, self.physical = word, physical + + def native(self, ports, header): + kind = header % 2 + columns = header - kind + if columns <= 0 or len(ports) != len(self.word.targets): + raise ValueError("Every raw type needs a complete positive even-width job") + if len({p.owner for p in ports}) != len(ports): + raise ValueError("Two productive ports share a live field") + width = columns * (1 + kind) + bound = [] + for tag, p in zip(self.word.targets, ports, strict=True): + if len(p.axes) != tag.rank * width: + raise ValueError("A productive job has the wrong physical rank") + bound.append((tag.tag, p)) + actual = self.physical.raw(bound, width) + remaining = 1008 if kind == 0 else 0 + for tag in self.word.paid: + name, p = next(actual) + if name != tag.tag or len(p.axes) != tag.rank * width: + raise ArithmeticError("A raw loan differs from its source") + if remaining and tag.rank == 1: + yield p.select(range(width // 2)) + yield p.select(range(width // 2, width)) + remaining -= 1 + else: + yield p + if next(actual, None) is not None or remaining: + raise ArithmeticError("The raw tape did not close") diff --git a/research/frequency-weighted-native-multiplier/typed_transport.py b/research/frequency-weighted-native-multiplier/typed_transport.py new file mode 100644 index 0000000000..c58740b3b0 --- /dev/null +++ b/research/frequency-weighted-native-multiplier/typed_transport.py @@ -0,0 +1,269 @@ +"""Generate a retimed physical program for two independently weighted native words.""" + +from collections import defaultdict +from dataclasses import dataclass +from fractions import Fraction as Q +from transport import Plan, Source, Measure, ceil + + +@dataclass(frozen=True) +class NativeType: + targets: tuple + paid: tuple + multiplicity: int + + +@dataclass(frozen=True) +class TypedLink: + start: int + count: int + band: int + kind: int + port: int + other: int + + +def column_header(columns, kind): + """Write the type in the low bit of a positive even column count.""" + if columns < 2 or columns % 2 or kind not in (0, 1): + raise ValueError("Invalid two-type column descriptor") + return columns + kind + + +class TypedPlan(Plan): + """Interleave the two raw jobs at each physical column scale.""" + + def __init__( + self, + n, + types, + cells, + t, + lower, + upper, + volume, + ticks, + rounds, + *, + delay_base, + scale_step=Q(6, 5), + padding=4096, + width=None, + ): + if min(ticks, rounds, padding, volume) <= 0 or scale_step <= 1: + raise ValueError("Use positive clock sizes and an increasing scale step") + if len(types) != 2 or lower <= 8 or upper <= lower or lower % 2 or upper % 2: + raise ValueError("Use two raw types and positive even scale endpoints") + if ( + n % 4 + or min(min(w.multiplicity, len(w.paid), len(w.targets)) for w in types) < 1 + or delay_base < max(len(w.paid) for w in types) + ): + raise ValueError( + "The carrier and the temporal base must support each real raw word" + ) + if n < 4 * max(max(w.targets) for w in types) * (upper - 8): + raise ValueError("The productive jobs must fit the carrier") + self.n, self.types, self.ticks, self.rounds = n, types, ticks, rounds + self.bands = range(lower, upper, 2) + self.delay, self.count = {}, {} + self.send, self.receive, self.sources = ( + defaultdict(list), + defaultdict(list), + defaultdict(list), + ) + self.source_width = 0 + measure = Measure(t, volume, max(256, 64 * n.bit_length())) + ids = defaultdict(list) + shares = defaultdict(list) + for b, w in enumerate(types): + for i, k in enumerate(w.targets): + ids[b, k].append(i) + for (a, r, b, k), share in cells.items(): + if not (0 < r and 5 * r <= 4 * k and share > 0 and ids[b, k]): + raise ValueError("A physical funding edge fails strict descent") + owners = ids[b, k] + for i in owners: + shares[a, r].append((b, i, k, share / len(owners))) + for a, w in enumerate(types): + for r in set(w.paid): + if sum(p for b, i, k, p in shares[a, r]) != 1: + raise ValueError("A paid label lacks funding") + headroom = defaultdict(int) + level = 0 + limit = Q(lower) + for e in self.bands: + while limit * scale_step <= e: + level += 1 + limit *= scale_step + self.delay[e] = delay_base**level + for a, w in enumerate(types): + self.count[e, a] = ceil(w.multiplicity * measure.mass(e, e + 2)[1]) + for e in self.bands: + for a, w in enumerate(types): + for j, r in enumerate(w.paid): + used = 0 + for b, i, k, share in shares[a, r]: + left, right = Q(e * r, k), Q((e + 2) * r, k) + low = max(lower, 2 * (left // 2)) + high = min(upper, 2 * ceil(right / 2)) + for d in range(low, high, 2): + if self.delay[d] >= self.delay[e]: + raise ValueError("The child misses its return time") + left_end, right_end = ( + max(e, Q(d * k, r)), + min(e + 2, Q((d + 2) * k, r)), + ) + number = int( + w.multiplicity + * measure.mass(left_end, right_end)[0] + * share + ) + if number: + cap = headroom[d, b, i] + self.send[e, a, j].append( + TypedLink(used, number, d, b, i, cap) + ) + self.receive[d, b, i].append( + TypedLink(cap, number, e, a, j, used) + ) + headroom[d, b, i] += number + used += number + if used > self.count[e, a]: + raise ArithmeticError("More outgoing copies than supplied") + for e in self.bands: + for a, w in enumerate(types): + for j, r in enumerate(w.paid): + for b, i, k, share in shares[a, r]: + left_end, right_end = max(upper, Q(e * k, r)), Q((e + 2) * k, r) + number = int( + w.multiplicity + * measure.mass(left_end, right_end)[0] + * share + ) + if not number: + continue + size = (e - 8) * k + period = 4 * ceil(Q(n, 4 * size)) + base = self.source_width + self.source_width += number * ticks * (rounds // period) + self.sources[e, b, i].append( + Source(headroom[e, b, i], number, base, period) + ) + headroom[e, b, i] += number + for (e, b, i), qty in headroom.items(): + if qty > self.count[e, b]: + raise ArithmeticError("A target owner received two independent fields") + if self.source_width <= 0: + raise ValueError("The epoch has no complete productive period") + self.width = ( + (1 << (padding * self.source_width - 1).bit_length()) + if width is None + else width + ) + if self.width < padding * self.source_width or self.width.bit_count() != 1: + raise ValueError("Too few productive rows") + + def external(self, e, a, i, rep, birth): + size = (e - 8) * self.types[a].targets[i] + for src in self.sources.get((e, a, i), ()): + offset = rep - src.start + if 0 <= offset < src.count: + cycles = self.rounds // src.period + return ( + 2, + src.base + (birth * src.count + offset) * cycles, + size, + src.period, + ) + return (0, size) + + def open_record(self, owner, band, kind, replica, birth, tick, pending): + row = [0, owner, column_header(band - 8, kind)] + for port in range(len(self.types[kind].targets)): + serial = pending.pop((band, kind, replica, port), None) + if serial is not None: + row.extend((1, serial)) + continue + for link in self.receive.get((band, kind, port), ()): + if 0 <= replica - link.start < link.count: + if tick >= link.port * self.delay[link.band]: + raise ArithmeticError( + "The funded source failed to deliver its live owner" + ) + break + row.extend(self.external(band, kind, port, replica, birth)) + return tuple(row) + + def send_prefix(self, band, kind, paid_port, replica, serial, pending): + for link in self.send.get((band, kind, paid_port), ()): + offset = replica - link.start + if 0 <= offset < link.count: + target = (link.band, link.kind, link.other + offset, link.port) + if target in pending: + raise ArithmeticError("Two loans occupied one target") + pending[target] = serial + return self.types[link.kind].targets[link.port] * (link.band - 8) + return 0 + + def events(self): + serial = 0 + maximum = max(self.count.values()) + span = (self.bands.stop - self.bands.start) // 2 + + def frame(e, a, birth, rep): + return ( + (birth * span + (e - self.bands.start) // 2) * 2 + a + ) * maximum + rep + + qmax = max(len(w.paid) for w in self.types) + for tick in range(self.ticks + qmax * max(self.delay.values())): + pending = {} + for e in self.bands: + for a, w in enumerate(self.types): + birth = tick - len(w.paid) * self.delay[e] + if 0 <= birth < self.ticks: + for rep in range(self.count[e, a]): + yield (2, frame(e, a, birth, rep)) + for e in reversed(self.bands): + step = self.delay[e] + for a, w in enumerate(self.types): + first = max(0, (tick - self.ticks) // step + 1) + stop = min(len(w.paid), tick // step + 1) + for j in range(first, stop): + r = w.paid[j] + birth = tick - j * step + for rep in range(self.count[e, a]): + own = frame(e, a, birth, rep) + if j == 0: + yield self.open_record( + own, e, a, rep, birth, tick, pending + ) + selected = ( + self.send_prefix(e, a, j, rep, serial, pending) + if tick < self.ticks + else 0 + ) + size = r * (e - 8) + if size != int(size) or not 0 <= selected <= size: + raise ArithmeticError("The child exceeds its parent") + yield (1, own, serial, int(size), selected) + serial += 1 + if pending: + raise ArithmeticError("An emitted loan lost its receiver") + + @property + def leaves_per_epoch(self): + total = 0 + for e in self.bands: + for a, w in enumerate(self.types): + for j, r in enumerate(w.paid): + spent = self.ticks * self.count[e, a] * r * (e - 8) + routed = max(0, self.ticks - j * self.delay[e]) * sum( + u.count * self.types[u.kind].targets[u.port] * (u.band - 8) + for u in self.send.get((e, a, j), ()) + ) + total += spent - routed + if total != int(total): + raise ArithmeticError("An issued suffix has a fractional axis") + return int(total) diff --git a/research/frequency-weighted-native-multiplier/verify.py b/research/frequency-weighted-native-multiplier/verify.py new file mode 100644 index 0000000000..9d83c2fcff --- /dev/null +++ b/research/frequency-weighted-native-multiplier/verify.py @@ -0,0 +1,103 @@ +"""Restore the signed production program and verify one independent claim.""" + +from io import BytesIO +import json +from pathlib import Path +from subprocess import run +import sys +from tempfile import TemporaryDirectory + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from bootstrap import install + + +def product(runtime): + from band_product import multiply, multiply_tapes, production_supplier + from check_product import physical_product + from installations import ENTRY, TERMINAL + + assert all( + multiply(a, b) == a * b + for a, b in ( + (0, 0), + (-1, 0), + (-1, -1), + (-741503, 466013), + (2**129 - 17, -(2**73) + 3), + (-(2**4096 + 9), 2**41 - 1), + ) + ) + for tier in (ENTRY, TERMINAL): + left = BytesIO(b"abc" + (741503).to_bytes(6, "little") + b"finish") + right = BytesIO(b"xyz" + (466013).to_bytes(5, "little") + b"end") + left.seek(3) + right.seek(3) + destination = BytesIO() + sign, size = multiply_tapes( + left, 6, right, 5, destination, left_negative=True, profile=tier + ) + assert (sign, size, int.from_bytes(destination.getvalue(), "little")) == ( + True, + 5, + 345550037539, + ) + assert left.tell() == right.tell() == 3 + recipe = production_supplier( + tier.complex_log, tier.positive_stop_denominator + ).recipe + assert ( + recipe.rank_log == tier.complex_log + and recipe.ambient == 306 + and len(recipe.cells) == 51 + ) + witness = physical_product(ENTRY) + assert witness["product"] == "-345550037539" and witness["coefficients_prefix"] == [ + 11811, + 10996, + 4152, + 868, + 77, + ] + print(json.dumps(witness, sort_keys=True)) + print("PASS_WEIGHTED_SIGNED_PRODUCT") + + +def main(scope): + if not __debug__: + raise RuntimeError("Enable assertions for the registered checks") + with TemporaryDirectory(prefix="weighted-native-") as temp: + runtime = Path(temp) + install(runtime) + sys.path.insert(0, str(runtime)) + if scope == "product": + product(runtime) + return + files = { + "price": ("receipt.py", "independent_price.py", "check_placement.py"), + "calendar": ("check_calendar.py", "check_ownership.py"), + "raw": ("check_raw.py",), + "exterior": ("check_exterior.py",), + "nested": ("check_nested.py",), + } + for name in files[scope]: + out = run( + [sys.executable, "-IB", str(HERE / name), str(runtime)], + check=True, + capture_output=True, + text=True, + ) + if name == "receipt.py": + assert json.loads(out.stdout) == json.loads( + (HERE / "RESULT.json").read_bytes() + ) + print( + "PASS_WEIGHTED_COMPLETE_PRICE", + json.loads(out.stdout)["complete_log2_C"], + ) + else: + print(out.stdout, end="") + + +if __name__ == "__main__": + main(sys.argv[1]) diff --git a/research/historical-selected-replay-gap/README.md b/research/historical-selected-replay-gap/README.md index 55d8cc3b49..36d9a873ca 100644 --- a/research/historical-selected-replay-gap/README.md +++ b/research/historical-selected-replay-gap/README.md @@ -69,7 +69,11 @@ python3 -B scripts/research_package.py --package research/historical-selected-re The direct command prints `PASS_HISTORICAL_SELECTED_REPLAY_GAP`. A registered replay prints `PASS_REGISTERED_RESEARCH_PACKAGE`. Both require Git history -containing the two inspected commits. +containing the two inspected commits and the source and manifest objects at +`2485805a6d47f36ea83ddde6327d453ac82d44dc`. The verifier uses a temporary +sparse checkout of that commit, checks the declared source digests there, and +uses its planner and manifest inventory. The recorded rejections and selection +therefore remain reproducible after later changes to the live Makefile or CI guide. ## Open next questions diff --git a/research/historical-selected-replay-gap/SOURCES.json b/research/historical-selected-replay-gap/SOURCES.json index c1010eec95..62bb8b3950 100644 --- a/research/historical-selected-replay-gap/SOURCES.json +++ b/research/historical-selected-replay-gap/SOURCES.json @@ -4,13 +4,13 @@ "files": [ { "path": "Makefile", - "usage": "input", + "usage": "provenance", "git_blob": "0d683a06b9e7ee162496108ce9a7c5d2ee94fccf", "sha256": "4f2d4f2dcd15139ec82658a975f85ed300897385f85799218539f4c8d60567da" }, { "path": "certificates/partial-swap-network.json", - "usage": "input", + "usage": "provenance", "git_blob": "eccafa830c16170c36faf93045ddf1f638f7bcd4", "sha256": "4c0b9d37e1034b2076e30a70f8e514416298c462d9ee98bc87fe6556b14df786" }, @@ -22,7 +22,7 @@ }, { "path": "docs/ci-verification.md", - "usage": "input", + "usage": "provenance", "git_blob": "63ba3e9aa8bdc5e942b56e34244b92b16f854085", "sha256": "c7d3027e9ad8bcbff68f07aa9576b30fb2f3c76c44d876d40c7fdbf4a3e2228a" }, @@ -34,163 +34,163 @@ }, { "path": "research/clifford-state-performance/SOURCE.json", - "usage": "input", + "usage": "provenance", "git_blob": "6f98a0061a5104dfab82c9e806f819b41811f684", "sha256": "396d0f08df24952248140d5c65c51b8c902ef1c580892ff7ea182890530f67ee" }, { "path": "research/community-batch1047-audit/CONTENT-COVERAGE.json", - "usage": "input", + "usage": "provenance", "git_blob": "5e0f92af463ec12c5e1dcc3effd44081a88af647", "sha256": "07a9daeaf2bda308a92e9a4684f13d5fc766c7772d74801fceb7f4599fdab226" }, { "path": "research/community-batch1099-audit/CONTENT-COVERAGE.json", - "usage": "input", + "usage": "provenance", "git_blob": "9e13266bf85e627f1b7dc225e9530ea69fd2c7f0", "sha256": "421e1211fb1897c45621dc6801c276e53f2e6f335583c9c9049e535f87c0a3b1" }, { "path": "research/community-batch932-audit/CONTENT-COVERAGE.json", - "usage": "input", + "usage": "provenance", "git_blob": "cc4d03eb59b9ab3f952735f7e88ff18c2d15d7af", "sha256": "184629cac91a5cfaca50330a88596008b824221433867dcf8117539c913c284a" }, { "path": "research/community-batch970-audit/CONTENT-COVERAGE.json", - "usage": "input", + "usage": "provenance", "git_blob": "8b9f4111badf7de5d97684799560b55110e9da79", "sha256": "23188ed920e38a54006cb883e181585620821c63bf7e8b5e05d32719417cc37e" }, { "path": "research/community-frontier741-audit/CONTENT-COVERAGE.json", - "usage": "input", + "usage": "provenance", "git_blob": "a5300d4e7a5381a3f443fc54c768ca6f0f236d68", "sha256": "3c820fb30e1b4d9bcfc6a7ab524375e5b2abd66b940af2c509146104f0bcd79c" }, { "path": "research/community-frontier890-audit/CONTENT-COVERAGE.json", - "usage": "input", + "usage": "provenance", "git_blob": "d7ff6d777b01d69b6ce84caf25d3b7e4a4d2f211", "sha256": "6b185a9902652f893f3ebd8ada92d2f11b6de6533a9a4d11718a8a4496101128" }, { "path": "research/community-hyperplane599-audit/SOURCE.json", - "usage": "input", + "usage": "provenance", "git_blob": "546f37d326d10a99910ae8f908e71ef768524d98", "sha256": "65099d764bfcc39bda5e4d9966783611b094c3522dbdd1435cd498d657a8ef8e" }, { "path": "research/community-k492-audit/SOURCE.json", - "usage": "input", + "usage": "provenance", "git_blob": "e538481e4cb16ed936d3195f2dfb5b5a9ca0a76b", "sha256": "2c0f4fa5bc150d05658af2e7c54c4d2c337dd52b7efd3d69530ae73bcbdf452a" }, { "path": "research/community-reconciliation92-audit/MANIFEST.json", - "usage": "input", + "usage": "provenance", "git_blob": "2a2e93685173d5f13cbb5abe740f5d90352e0228", "sha256": "5f501f3c118131e7d069f30ad77186eb2ad6961f9680a0ef105f4514ed41808a" }, { "path": "research/partial-swap-digest/baseline.py", - "usage": "input", + "usage": "provenance", "git_blob": "a2f0190704db83bd8ef48e46e723c49b925804fe", "sha256": "81e9af92cdf38243a540cdcff2062778e449467848d444da37a9553c12ca4c34" }, { "path": "research/r420-two-sided-basis/SOURCES.json", - "usage": "input", + "usage": "provenance", "git_blob": "5d718e11e62f4bcadecf1e02d6b61f87dbe190b0", "sha256": "d9810b0d139c5a1211fd2c1f0d142187cc1fca30026e1e7bc4f9ecfacf1596d1" }, { "path": "research/skip-clones/SOURCE.json", - "usage": "input", + "usage": "provenance", "git_blob": "8d1bb3b9c8189e35e5d8bfdfa632d7473e8be0d5", "sha256": "0b68e63e35a97ce6b0cdb6e291b88ebaa8f2dd4afb70b2498f10ee89428258dc" }, { "path": "research/split-skip/SOURCE.json", - "usage": "input", + "usage": "provenance", "git_blob": "2ab610b6ea2edd2865fda793ef2168b0c76afb4f", "sha256": "7c2b4646a3ecfef6f881da5c43e4bd0fa9a4d1b00548b8ab458d897e16735134" }, { "path": "scripts/historical-ci-inputs/Makefile", - "usage": "input", + "usage": "provenance", "git_blob": "aff68409021c9d401a6f8013b9dfd7dbcc30f2a8", "sha256": "ea8830dd79da493e2d75baf753d733ff7efbcf2b4794afe41fae0ac8f3055646" }, { "path": "scripts/historical-ci-inputs/ledger-batch932-run_isolated_tests.py", - "usage": "input", + "usage": "provenance", "git_blob": "65db599ab0b1dea0312c4ca048e0bd0f44c3736f", "sha256": "96ea543e6c707424afe247e77bd86c82152f90fc76a0773c4232145da5cdf8d1" }, { "path": "scripts/historical-ci-inputs/ledger-batch932-test_isolated_test_runner.py", - "usage": "input", + "usage": "provenance", "git_blob": "34820a8f24678f918f4d0e7a35380d8013fc3495", "sha256": "628391b6abfbc8674ceec1751867a4392f2cc0b5b66886243e139af86cf355ac" }, { "path": "scripts/historical-ci-inputs/ledger-batch970-verify_selected_result.py", - "usage": "input", + "usage": "provenance", "git_blob": "c755b76e0d44ba4917aa94440ebe54daefce5b2a", "sha256": "d7fd929726b326aeeaf0a3996475adec88eee9aac09ae0bebeeaa0bc1fc8f199" }, { "path": "scripts/historical-ci-inputs/ledger-frontier741-ci-verification.md", - "usage": "input", + "usage": "provenance", "git_blob": "7f3c012504187917a728b9fe87043f0fc8cd006a", "sha256": "a854022e0e1d5d4db4d60e586be3ea56005013ef14a1fc06d02bc06e8529c4b0" }, { "path": "scripts/historical-ci-inputs/partial-swap-context.json", - "usage": "input", + "usage": "provenance", "git_blob": "ad65114886bf34a4fd27e79f3be502389e689faa", "sha256": "833a9642f33aeab2ffea17ec9c6b82e0a953f90192b2c82e10bef21538dccba9" }, { "path": "scripts/historical-ci-inputs/partial-swap-network.json", - "usage": "input", + "usage": "provenance", "git_blob": "52075f2463f60af5e16571347f24274fce73a1ea", "sha256": "f3c4be597b2f2136da4ae2cc80c7454f63c90aa01f84e5b8131cee4dd55de815" }, { "path": "scripts/partial_swap/shared.py", - "usage": "input", + "usage": "provenance", "git_blob": "44a0e454c70f9c4b98e258b8443612e6a119904b", "sha256": "5a0646a50b9f3e8ea55168620a78e8853b0ab810517cefc8cfb8696aedee278a" }, { "path": "scripts/replay_historical_check.py", - "usage": "input", + "usage": "provenance", "git_blob": "1e92fff2782970ef71378f594f2350d245a4db26", "sha256": "5467619c78183d3adc82b0cb55af28e5c1a01fca2b0588677816244b53e2bafd" }, { "path": "scripts/research_package.py", - "usage": "input", + "usage": "provenance", "git_blob": "091b4c8f58bac9a9580d76025b887dc5c873d05f", "sha256": "e1256016e7f51827d04fa2179255989f639ae1d97afaa9c16265f85a0c6abd70" }, { "path": "scripts/run_isolated_tests.py", - "usage": "input", + "usage": "provenance", "git_blob": "a96ab35b315ce492e7fbbfd6c5ae211aa066b541", "sha256": "49eb56dd0fc0d8d8ffdb209970a7adf2176223580646f575d5c22e59543b381c" }, { "path": "scripts/verify_selected_result.py", - "usage": "input", + "usage": "provenance", "git_blob": "6882a4700e410dec569b51ae2eaf1a19cc019195", "sha256": "d6b305eac5b9bdb8172c469ad30a1655a60fa0aceac8b1bf610e1b73f51babd8" }, { "path": "tests/test_isolated_test_runner.py", - "usage": "input", + "usage": "provenance", "git_blob": "343b24abf6719b81805eba5a84c74e57634c8288", "sha256": "3a5470d0b139828b90e19bf9583ddeafcd69f8e34f2824664eb3a2958a52e34d" } diff --git a/research/historical-selected-replay-gap/VERIFY.json b/research/historical-selected-replay-gap/VERIFY.json index 98553e72ed..ab7efa3471 100644 --- a/research/historical-selected-replay-gap/VERIFY.json +++ b/research/historical-selected-replay-gap/VERIFY.json @@ -4,36 +4,7 @@ "python": "3.12", "requirements": [], "inputs": [ - "Makefile", - "certificates/partial-swap-network.json", - "docs/ci-verification.md", - "research/clifford-state-performance/SOURCE.json", - "research/community-batch1047-audit/CONTENT-COVERAGE.json", - "research/community-batch1099-audit/CONTENT-COVERAGE.json", - "research/community-batch932-audit/CONTENT-COVERAGE.json", - "research/community-batch970-audit/CONTENT-COVERAGE.json", - "research/community-frontier741-audit/CONTENT-COVERAGE.json", - "research/community-frontier890-audit/CONTENT-COVERAGE.json", - "research/community-hyperplane599-audit/SOURCE.json", - "research/community-k492-audit/SOURCE.json", - "research/community-reconciliation92-audit/MANIFEST.json", - "research/partial-swap-digest/baseline.py", - "research/r420-two-sided-basis/SOURCES.json", - "research/skip-clones/SOURCE.json", - "research/split-skip/SOURCE.json", - "scripts/historical-ci-inputs/Makefile", - "scripts/historical-ci-inputs/ledger-batch932-run_isolated_tests.py", - "scripts/historical-ci-inputs/ledger-batch932-test_isolated_test_runner.py", - "scripts/historical-ci-inputs/ledger-batch970-verify_selected_result.py", - "scripts/historical-ci-inputs/ledger-frontier741-ci-verification.md", - "scripts/historical-ci-inputs/partial-swap-context.json", - "scripts/historical-ci-inputs/partial-swap-network.json", - "scripts/partial_swap/shared.py", - "scripts/replay_historical_check.py", - "scripts/research_package.py", - "scripts/run_isolated_tests.py", - "scripts/verify_selected_result.py", - "tests/test_isolated_test_runner.py" + "scripts/research_package.py" ], "commands": [ { diff --git a/research/historical-selected-replay-gap/verify.py b/research/historical-selected-replay-gap/verify.py index 83b995941a..9d266c5a4e 100644 --- a/research/historical-selected-replay-gap/verify.py +++ b/research/historical-selected-replay-gap/verify.py @@ -6,8 +6,10 @@ """ import hashlib import importlib.util +import json import subprocess import sys +import tempfile from pathlib import Path ROOT = Path(__file__).resolve().parents[2] @@ -61,31 +63,47 @@ def require(ok, message): raise SystemExit(message) -def load_checker(): - path = ROOT / "scripts/replay_historical_check.py" - spec = importlib.util.spec_from_file_location("historical_selected_replay_gap_checker", path) +def load_module(path): + spec = importlib.util.spec_from_file_location(path.stem, path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module +def checkout_snapshot(snapshot, sources, runner, env): + paths = [runner.canonical_relative_path(row["path"]) for row in sources["files"]] + git = ["git", "-c", "maintenance.auto=false", "-c", "gc.auto=0", + "-c", "core.autocrlf=false"] + subprocess.run([*git, "clone", "--quiet", "--shared", "--no-tags", "--no-checkout", + "--", str(ROOT), str(snapshot)], cwd=ROOT, env=env, check=True) + subprocess.run([*git, "update-ref", "--no-deref", "HEAD", INSPECTED], + cwd=snapshot, env=env, check=True) + # The pinned planner reads omitted manifests from the sparse HEAD/index. + patterns = "".join(f"/{path.as_posix()}\n" for path in paths) + subprocess.run([*git, "sparse-checkout", "set", "--no-cone", "--stdin"], + cwd=snapshot, env=env, input=patterns.encode("utf-8"), check=True) + subprocess.run([*git, "read-tree", "-mu", "HEAD"], cwd=snapshot, env=env, check=True) + for path, row in zip(paths, sources["files"], strict=True): + require(hashlib.sha256((snapshot / path).read_bytes()).hexdigest() == row["sha256"], + "historical checkout source digest changed: " + path.as_posix()) + + def entries(checker): for name, config in checker.CONFIG.items(): for entry in [config, *config.get("additional_inputs", [])]: yield name, entry -def reject(checker, entry): +def reject(root, checker, entry): try: - checker.authenticated_input(ROOT, entry) + checker.authenticated_input(root, entry) except ValueError as exc: return str(exc) raise SystemExit("historical input was admitted: " + entry["path"]) -def main(): - require(not sys.flags.optimize, "assertions must stay enabled") - checker = load_checker() +def check_snapshot(root, env): + checker = load_module(root / "scripts/replay_historical_check.py") selected = [entry for name, entry in entries(checker) if name == "tooling-ledger" and entry["path"] == SELECTED_PATH] require(len(selected) == 1, "selected-result checker overlay is not unique") @@ -94,7 +112,7 @@ def main(): require(entry["accepted_live_sha256"] == [SELECTED_ACCEPTED], "accepted selected-checker successors changed") frozen = (checker.INPUTS / entry["input"]).read_bytes() - live = (ROOT / SELECTED_PATH).read_bytes() + live = (root / SELECTED_PATH).read_bytes() require(hashlib.sha256(frozen).hexdigest() == SELECTED_PIN, "frozen selected checker bytes changed") require(hashlib.sha256(live).hexdigest() == SELECTED_LIVE, "live selected checker digest changed") require(SELECTED_LIVE not in (SELECTED_PIN, SELECTED_ACCEPTED), "live checker was already admitted") @@ -102,7 +120,7 @@ def main(): # live successor, not a broken comparison. require(SELECTED_PIN in (SELECTED_PIN, *entry["accepted_live_sha256"]), "pin membership control failed") - require(reject(checker, entry) == REJECTIONS[SELECTED_PATH][1], + require(reject(root, checker, entry) == REJECTIONS[SELECTED_PATH][1], "selected checker rejection text changed") counts = {path: 0 for path in REJECTIONS} @@ -110,7 +128,7 @@ def main(): for _name, item in entries(checker): if item["path"] not in REJECTIONS: continue - message = reject(checker, item) + message = reject(root, checker, item) counts[item["path"]] += 1 messages.setdefault(item["path"], message) for path, (count, message) in REJECTIONS.items(): @@ -118,20 +136,31 @@ def main(): require(messages[path] == message, "rejection text changed for " + path) require(sum(counts.values()) == 19, "rejection total changed") ci = [item for _name, item in entries(checker) if item["path"] == CI_PATH] - require(len(ci) == 1 and hashlib.sha256((ROOT / CI_PATH).read_bytes()).hexdigest() == CI_LIVE, + require(len(ci) == 1 and hashlib.sha256((root / CI_PATH).read_bytes()).hexdigest() == CI_LIVE, "selected CI note digest changed") diff = subprocess.check_output( - ["git", "diff", "--name-only", PARENT, INSPECTED], cwd=ROOT, text=True) + ["git", "diff", "--name-only", PARENT, INSPECTED], cwd=root, env=env, text=True) changed = sorted(name for name in diff.splitlines() if name) require(changed == CHANGED, "inspected commit diff changed") - sys.path.insert(0, str(ROOT / "scripts")) - from research_package import plan_details - details = plan_details(ROOT, set(changed)) + planner = load_module(root / "scripts/research_package.py") + details = planner.plan_details(root, set(changed)) require([row["package"] for row in details] == PLAN_PACKAGES, "helper plan selection changed") matched = {name for row in details for names in row["causes"].values() for name in names} require(sorted(set(changed) - matched) == UNMATCHED, "unmatched plan paths changed") - require(plan_details(ROOT, set()) == [], "empty change set selected a package") + require(planner.plan_details(root, set()) == [], "empty change set selected a package") + + +def main(): + require(not sys.flags.optimize, "assertions must stay enabled") + sources = json.loads(Path(__file__).with_name("SOURCES.json").read_bytes()) + require(sources["base_commit"] == INSPECTED, "historical checkout base changed") + runner = load_module(ROOT / "scripts/research_package.py") + env = runner.git_source_env() + with tempfile.TemporaryDirectory(prefix="historical-selected-replay-") as temporary: + snapshot = Path(temporary) / "snapshot" + checkout_snapshot(snapshot, sources, runner, env) + check_snapshot(snapshot, env) print("PASS_HISTORICAL_SELECTED_REPLAY_GAP") print("selected_checker_live=" + SELECTED_LIVE) print("rejections=19 distinct_paths=7 plan_packages=9") diff --git a/research/tiered-native-multiplier/CLOCK.md b/research/tiered-native-multiplier/CLOCK.md new file mode 100644 index 0000000000..bbd06a788d --- /dev/null +++ b/research/tiered-native-multiplier/CLOCK.md @@ -0,0 +1,45 @@ +# One complete signed machine and its absolute clock + +Let $n\ge2$ be the larger significant bit length of two canonical signed integers. Count a read, a write or a one-cell move on one fixed-alphabet tape as one transition. The complete recurring upper bound is $2^{339787971}\,n(1+\log_2 n)^{1-0.0038982}$. Fixed installation is billed separately. Short zero and unit inputs fit the same bound with $n=2$. A caller can also supply a longer byte interval with high zeros. In that case the machine scans and restores the entire interval. One may take $n$ to include the declared input lengths in bits, or add the linear charge for these bytes. The placement threshold below refers to significant bits. + +The maintained hypothesis contract has five parts. They cover (1) all-column native operators, spectator and phase conventions, (2) ownership, erasure and suspended fields, (3) uniform chronological compiler closure, (4) the retained physical tape and precision services and (5) the analytic decomposition, fine-prime avoidance and exact recovery. This research proves the changes to the source, its calendar, its clock and its connection to the signed caller under those same premises. The selected application on main and the open K7 application retain their respective status. [Selected hypothesis statements](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/certificates/selected-result.json) · [K7 source application](https://github.com/CrocSwap/integer-mult-bounds/pull/8052) + +## Ordinary funding from the actual K7 circuit + +K7 has 630 independent raw registers, 2,796 transfers and 3,426 dirty clears. The seven retracted returns reduce the grades of seven productive helpers from eight to four in every one of the 36 calls. Both linear totals fall by 1,008. The new totals are 286,098 productive and 284,592 paid over 18,906 and 104,652 labels. The full weighted moment and a chronological coupling of 24 cells, together with the retained physical quotient/weighted receiver, fund the binary trial $c_B=4391986206293/2^{50}$. Each nonempty transport edge has $5r\le4k$. Paid and productive tags are rebuilt from the new graph. The independent binary enclosure and signed register, frame and weighted physical checks operate on these same bytes. [K7 journal](source/K7-STACK-LEDGER.json) · [Whole-machine cost code](receipt.py) + +For ordinary stage $i$, let $N=2^{H_i}$, $J=N^{1024}$, and let $b_0=0$. The raw finite factor times the full physical child factor $47/20$ is below $2^{11/8}$. Its contracting volume ratio is at most $375/376$. Choose $b_i$ strictly below + +$$ +\min\left(0.0039,\ [249(c_B-11/(8H_i))+b_{i-1}]/250\right). +$$ + +The receipt takes the preceding whole $10^{-21}$ tick for the intermediate stage and books exactly $\kappa+5\cdot10^{-18}$ for the last. Both actual receivers have $H_i\ge3000$ and construct an active native recipe. Input, zero, signed returns and boundary calls use the five-exchange/quotient rules from the retimed machine. Each tier passes 54 strict inequalities, four further functional inequalities and its independent positive price check. [Exact margins](RESULT.json) · [Physical ordinary proof](https://github.com/aliromman/integer-mult-bounds/blob/dfd25d553a843a946ca0b94130a5ff8943e98fdd/research/retimed-native-multiplier/ORDINARY-CLOCK.md) + +## Counting tape movement + +Use the inherited per-prefix expression $J^5 X^{20}$, where $X=2^{16} N^4(D+1)(w+1)^{252}$. Here $D$ bounds the number of saved coefficient links, $w$ is the component bound, and $u$ is the width of a balanced digit present on the actual pass. At each admitted root the component geometry is inherited down the same-stage tree. It satisfies $D+1\le256(w+1)$, $w+1\le2^{259}u^{258}$, and $u\ge e^\eta/2$ with $e\ge N$ and $\eta=.0039>1/258$. For $H\ge8192$, $u\ge2^{30}$ and $H\le258(1+\log_2u)$. Substitution gives + +$$ +\log_2(J^5 X^{20}) +\le5200H+480+259\cdot5060+258\cdot5060\log_2u +\le2660000(1+\log_2u)2^u$ distinct cells. Charge one extra transition per cell on that pass. This includes retrieval from the fixed store and all saved coefficient links. Short carry and shift kernels still get their separate $2^{50}$ per-cell allowance. Suspended parent banks remain parked between the lower children of one issuance. Their heads traverse the parent bank at most twice at the two boundaries. [Kernel-checked digit inequality](TierCost.lean) + +The original sweep bound has three counts for a parent field. These are the visits to elementary native sites, the fixed factor or owner scans at one site, and the owner range crossed per opening. Each is at most $N^{96}$ from the actual event and descriptor counts. Owner width is $N^{92}$. Each bounded physical scan includes the complete prefix, packet, spectator gap and suffix it traverses. The remaining $2^{22}(N+1)^6a_1+2$. At the positive root the outer selector supplies at least $2^{s-100}/s^7$ real ordered windows. The actual second ticket on the 10,191-grade group needs a complete slot exchange. When $s-7\lceil\log_2s\rceil\ge H_M+a_2+102$, this creates a genuine ordinary invocation past the second cutoff. The native compiler issues real singleton children. At a populated bin one can take birth at the last tick and paid ordinal one. Delaying it by at least one tick makes this a terminal singleton. The decreasing same-stage coarse width eventually enters the stopped weighted pair. Its two earlier exchanges use the real previous component width at least $2^{a_1}$, so the first binary stage also enters its native recipe. This proof counts the full fields on zero inputs as well. The first satisfying $s$ and the first post-dyadic jump imply all larger $s$, since the successive post-jump minima grow by $2^j-7$. [Physical stock and geometry](https://github.com/aliromman/integer-mult-bounds/blob/dfd25d553a843a946ca0b94130a5ff8943e98fdd/research/retimed-native-multiplier/ACTIVATION.md) · [Stock computations](source/activation.py) + +For the smaller branch $A=7437$. At this threshold the square controller has $2^{7412}$ true axes, with largest axis address width 5,592,406. For the terminal branch $A=1274851$. The first/continuing historical stripe slack is 1,701/1,635 bits in the entry branch and 635,376/615,539 in the terminal branch. The two-stage bound uses 1,964 log units of fixed adapter overhead, plus the depth term. It counts the high-water end of each tape, held pending raw calls, real zero padding, temporary copies, returns and scrubbing. The separate input-dependent control ceiling has logarithm 3,153,922 on entry and 696,320,002 at the terminal ranks. The cofinal live numerical bound is $6.2pT<297.6n$ bits in the predecessor's accounting. True generated positive rows number $2^{94208}$ and $2^{62560000}$ respectively. They contain arbitrary independent data. The construction retains the true high-coordinate and invertible low-matrix terms in its admitted ordinary layout. + +The exterior machine performs both input conversions, normalized forward transforms, pointwise product, opposite transform, the original-coordinate inverse scaling, coefficient rounding, inverse CRT and carry. The native changes return the same H or interchange on the same represented data. The existing radius estimate includes the two operand scales and a strict half-unit rounding margin on the true coefficients. Consequently the rounding and signed output proof transfers under the five stated premises. All independent size factors and double-width root tables in the outer cost remain charged. The early geometry supplied here still exceeds the limits of host-sized lists. The executable evidence therefore includes signed products at finite geometries and separate real raw-source executions. [Signed precision and outer clock](https://github.com/aliromman/integer-mult-bounds/blob/dfd25d553a843a946ca0b94130a5ff8943e98fdd/research/retimed-native-multiplier/OUTER-CLOCK.md) + +For $g=10^{-18}$ use the inherited bound $(17/g)^{16}<2^{1182}$. The cofinal outer coefficient is at most $1602+220H_M+\log_2 B$ in log units. The finite controller, including private geometry and the scalar prefix, has log ceiling 84,500,001. Taking the larger gives 125,660,241 for the entry rate and 339,787,970 for the terminal rate. In the entry branch $1+\log_2 n\le2^{1274851}$. Converting its entire bound from .00345 to .0038982 costs at most $\lceil(.0038982-.00345)1274851\rceil=572$ bits. The resulting 125,660,813 is below the terminal ceiling. One additional bit pays the selector, header restoration and fixed branch control. This proves the stated all-input ceiling on a single machine. [Formal price conversion](TierCost.lean) · [Full receipt](RESULT.json) diff --git a/research/tiered-native-multiplier/LICENSE b/research/tiered-native-multiplier/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/research/tiered-native-multiplier/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/tiered-native-multiplier/MEASUREMENTS.json b/research/tiered-native-multiplier/MEASUREMENTS.json new file mode 100644 index 0000000000..b5cf242025 --- /dev/null +++ b/research/tiered-native-multiplier/MEASUREMENTS.json @@ -0,0 +1,267 @@ +{ + "observations": [ + { + "revision": "8053", + "wall": 83.03838674999997, + "cpu": 82.74014700000001, + "rss_bytes": 309346304, + "python": "3.12.16", + "system": "macOS-27.2-arm64-arm-64bit", + "machine": "arm64", + "installed": [ + [ + [ + 60000, + 18906, + 104652, + 24 + ], + [ + 960000, + 18906, + 104652, + 24 + ], + [ + 20000000, + 105216, + 564144, + 54 + ] + ] + ], + "binary_sha256": "9e7392c52bcf29c0cc58c54c619f95c28f476394c33e8e0a5aa30c9557d31362" + }, + { + "revision": "candidate", + "wall": 5.10587195800008, + "cpu": 5.094125999999999, + "rss_bytes": 277184512, + "python": "3.12.16", + "system": "macOS-27.2-arm64-arm-64bit", + "machine": "arm64", + "installed": [ + [ + [ + 3000, + 18906, + 104652, + 24 + ], + [ + 3080, + 18906, + 104652, + 24 + ], + [ + 1024, + 105216, + 564144, + 62 + ] + ], + [ + [ + 35327, + 18906, + 104652, + 24 + ], + [ + 559005, + 18906, + 104652, + 24 + ], + [ + 680000, + 105216, + 564144, + 62 + ] + ] + ], + "binary_sha256": "9e7392c52bcf29c0cc58c54c619f95c28f476394c33e8e0a5aa30c9557d31362" + }, + { + "revision": "candidate", + "wall": 5.076919667000311, + "cpu": 5.065735000000001, + "rss_bytes": 276201472, + "python": "3.12.16", + "system": "macOS-27.2-arm64-arm-64bit", + "machine": "arm64", + "installed": [ + [ + [ + 3000, + 18906, + 104652, + 24 + ], + [ + 3080, + 18906, + 104652, + 24 + ], + [ + 1024, + 105216, + 564144, + 62 + ] + ], + [ + [ + 35327, + 18906, + 104652, + 24 + ], + [ + 559005, + 18906, + 104652, + 24 + ], + [ + 680000, + 105216, + 564144, + 62 + ] + ] + ], + "binary_sha256": "9e7392c52bcf29c0cc58c54c619f95c28f476394c33e8e0a5aa30c9557d31362" + }, + { + "revision": "8053", + "wall": 82.19959216699999, + "cpu": 81.98890300000001, + "rss_bytes": 309772288, + "python": "3.12.16", + "system": "macOS-27.2-arm64-arm-64bit", + "machine": "arm64", + "installed": [ + [ + [ + 60000, + 18906, + 104652, + 24 + ], + [ + 960000, + 18906, + 104652, + 24 + ], + [ + 20000000, + 105216, + 564144, + 54 + ] + ] + ], + "binary_sha256": "9e7392c52bcf29c0cc58c54c619f95c28f476394c33e8e0a5aa30c9557d31362" + } + ], + "serial_setup": { + "integer_pairs": 4071, + "rational_cases": 7396, + "max_datum_bits": 274877906944, + "lookup": 170141183460469231731687303715884105728, + "local_arithmetic": 297105609434291902295870930944, + "all_setup": 217364570380528137475793294892811967875864032914108887556978854854656, + "setup_exponent": 228 + }, + "subsequent_8054_pair": [ + { + "revision": "8054", + "wall": 94.90161866700055, + "cpu": 91.768531, + "rss_bytes": 324567040, + "python": "3.12.16", + "system": "macOS-27.2-arm64-arm-64bit", + "machine": "arm64", + "installed": [ + [ + [ + 60000, + 18906, + 104652, + 24 + ], + [ + 960000, + 18906, + 104652, + 24 + ], + [ + 20000000, + 105216, + 564142, + 54 + ] + ] + ], + "binary_sha256": "9e7392c52bcf29c0cc58c54c619f95c28f476394c33e8e0a5aa30c9557d31362" + }, + { + "revision": "candidate", + "wall": 5.059486707999895, + "cpu": 5.052404, + "rss_bytes": 277331968, + "python": "3.12.16", + "system": "macOS-27.2-arm64-arm-64bit", + "machine": "arm64", + "installed": [ + [ + [ + 3000, + 18906, + 104652, + 24 + ], + [ + 3080, + 18906, + 104652, + 24 + ], + [ + 1024, + 105216, + 564144, + 62 + ] + ], + [ + [ + 35327, + 18906, + 104652, + 24 + ], + [ + 559005, + 18906, + 104652, + 24 + ], + [ + 680000, + 105216, + 564144, + 62 + ] + ] + ], + "binary_sha256": "9e7392c52bcf29c0cc58c54c619f95c28f476394c33e8e0a5aa30c9557d31362" + } + ] +} diff --git a/research/tiered-native-multiplier/NOTICE.md b/research/tiered-native-multiplier/NOTICE.md new file mode 100644 index 0000000000..71759b91e8 --- /dev/null +++ b/research/tiered-native-multiplier/NOTICE.md @@ -0,0 +1,7 @@ +# Attribution and license + +Ali Romman directed the dilation, charged physical transport, rank choices, tier selection, and integration of this signed multiplier. This work received substantial OpenAI Codex assistance. The contribution includes new calendar bounds, placement and transition proofs, and the independent checks of the changed construction. All archived source retains its Apache 2.0 license and notices. [License](LICENSE) · [Source manifest](SOURCES.json) + +- SYLforge supplied the seven exact K7 return retractions, binary word, chart and register checks, and the two-stage extended and compact comparisons. This package consumes the K7 graph and journal at `baaec65bf8e4c7e92be110a00d5b06522177931f`. ToikY repriced the earlier Gaussian coupling at `e25494616bf149217644ce08d949181ea3600e13` and supplied the live two-return change at `40940734cf582ded0896833b3dc93880299cf927`. ToikY also contributed earlier outer and binary work. [K7 notice](source/K7-NOTICE.md) · [PR #8052](https://github.com/CrocSwap/integer-mult-bounds/pull/8052) · [PR #8053](https://github.com/CrocSwap/integer-mult-bounds/pull/8053) · [PR #8054](https://github.com/CrocSwap/integer-mult-bounds/pull/8054) +- Ali Romman supplied the fixed quadratic phase compiler, sparse derivation of the actual helper data and chronological role segments in PR #8051, and the earlier retimed signed multiplier and connected activation proof in PR #8042. Clear1nsight supplied the competing six-stage and retimed price endpoints. This contribution retains their scientific status and builds on the fixed compiler at `cc21f7040cb3376709b30fc42f289827836d8be5` and retimed machine at `dfd25d553a843a946ca0b94130a5ff8943e98fdd`. [Installer notice](source/INSTALLER-NOTICE.md) · [PR #8051](https://github.com/CrocSwap/integer-mult-bounds/pull/8051) · [PR #8042](https://github.com/CrocSwap/integer-mult-bounds/pull/8042) · [PR #8050](https://github.com/CrocSwap/integer-mult-bounds/pull/8050) +- DreamingOfClouds and Jerry Chen (CubeJerry) supplied physical bank, counted compiler, weighted oracle, and verification work in the source lineage. The numerical graph, grade-14 construction, signed 48-call interpretation, analytic caller, and exact CRT retain their original credits. The archive includes its nested notices. The shared package prerequisite at `0618e75a22cec54d1651394ef83d088551b7f026` comes from Jerry Chen's historical CI repair. [Physical source credits](https://github.com/aliromman/integer-mult-bounds/blob/6285dd829114705862e8d91facaedc1f31d3cfcb/research/single-band-native-carriers/NOTICE.md) · [PR #7257](https://github.com/CrocSwap/integer-mult-bounds/pull/7257) · [Selected record on the canonical base](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/certificates/selected-result.json) diff --git a/research/tiered-native-multiplier/NUMERICAL.md b/research/tiered-native-multiplier/NUMERICAL.md new file mode 100644 index 0000000000..e09739d76c --- /dev/null +++ b/research/tiered-native-multiplier/NUMERICAL.md @@ -0,0 +1,33 @@ +# The numerical word that runs + +The small copy executes the retained signed 48-call Gaussian word on $f$ columns. After it returns, the second copy executes the same word on $79f$ columns. Each copy has its own original owners and all spectator data. On the first copy only, the first 1,008 rank-one child requests issue the two disjoint half-column factors in order. Here $f$ is positive and even. Productive ports stay independent. For a loan at a common rank, both halves act on the original physical job. Their product is the original tensor kernel. The signed caller, fixed odd divisors, absolute Clifford phases, chart reversals, port order, roots and all owner returns run through the retained physical interpreter. The source has 5,674 moves, 6,965 rows, 323,573 donor occurrences per graph call and 1,291 independent roles. The strict physical discharge below uses this source and these copies together. [Physical implementation delta](runtime.patch) · [All-column identity and rational grids](https://github.com/aliromman/integer-mult-bounds/blob/6285dd829114705862e8d91facaedc1f31d3cfcb/research/single-band-native-carriers/STRONG-COMPLEX.md) + +## Directed capacities + +Let $t=1-c$ with $c=2143194013/2^{39}$. Multiply each base grade by the copy's actual column dilation. Replace the 1,008 paid unit grades by 2,016 halves. This gives 105,216 productive labels and 564,144 loans. For each productive grade $k$ use a lower enclosure of $T_k=n_k k^t$. For each paid grade $r$ use an upper enclosure of $P_r=m_r r^t$. Write $T,P$ for their respective sums. The receipt has $(T-P)/T>5.97\cdot10^{-11}$. Assign paid mass in descending order to capacities $T_k P/T$. Each nonempty edge obeys $5r\le4k$. The 62 edge shares are exact rationals. The shares of each paid grade sum to one. The aggregate assigned to grade $k$ is its entire specified capacity. The smallest nonempty share per individual productive label exceeds $2^{-64}$. The independent log/exp enclosure checks the sign again. For the previous physical dilations 1 and 8, it gives a negative margin below $-0.17$ at the new complete rate. Differentiating the signed sum after division by $16^t$ and bounding its derivative on sixteen rational subintervals proves uniqueness of each crossing, including the new peer with 1,006 splits, on $0\le t\le1$. Price headroom in the new construction comes from changing the paid jobs that execute. [Numerical receipt](RESULT.json) · [Second interval calculation](independent_price.py) + +## Finite calendar and honest boundary loss + +Put $M=2^H$, $H\ge1024$, $L=32768$, $U=2\lfloor M/(2048\cdot12087)\rfloor$, $K=M^{82}$, $V=M^6$, $R=M^2$. Keep $M^{92}$ productive rows. A bin $[e,e+2)$ runs $e-8$ real base columns. The large job therefore runs $79(e-8)$ columns. Transport density is $V x^{-1-t}$. Under $y=xr/k$, the change of variables gives the factor $(r/k)^t$ used by the capacity invoice. The prefix fits by $8k\ge10r$, and the lost suffix has fewer than $10k$ axes. The same 6/5 clock levels and delay base $2^{20}$ respect all 564,144 cuts. Their lifetime is below $M^{77}$ and a path through one activation has at most $4H+1$ open raw contexts. The path can enter only one of the two disjoint native copies. All supplied axes carry real data. Padding jobs start at zero and retire through the same phases. [Chronological and boundary proof](https://github.com/aliromman/integer-mult-bounds/blob/dfd25d553a843a946ca0b94130a5ff8943e98fdd/research/retimed-native-multiplier/TRANSFER.md) + +For the new largest grade, $k/r\le20382$ and $k\le12087$. At an exterior integration point $x\le Uk/r.99$, $t>.996$, $\max(k)^c<1.06$ and common boundary mass $\Psi>.19P$. The retained fringe account therefore gives $64/L$. We have $U\ge(1-2^{-128})M/(1024\cdot12087)$. The external productive width lies strictly between $KVM/2$ and $M^{91}$. Thus $M^{92}$ holds at least 4,096 whole productive widths. The final partial group contributes a factor at most $4097/4096$. With $\delta=2^{-128}$ the complete finite multiplier on the raw leaf ratio, including the recursive summation reserve, is bounded by + +$$ +\frac{256}{255}\frac{4097}{4096}\frac{1028}{1024} +(1024\cdot12087 L)^c +\frac{1+64/L+\delta}{(1-10/L)(1-\delta)^3}<2^{43/256}. +$$ + +The executable check proves the inequality with outward integer roots. This buys $ba$ gives $Z=M^{220}(1+B_{\rm ord})$. Every active rank, installed stream and root-factor choice here is the one used for the reported signed product. [Control construction](grades.py) · [Per-use control bound](https://github.com/aliromman/integer-mult-bounds/blob/dfd25d553a843a946ca0b94130a5ff8943e98fdd/research/retimed-native-multiplier/INSTALLATION.md) diff --git a/research/tiered-native-multiplier/README.md b/research/tiered-native-multiplier/README.md new file mode 100644 index 0000000000..694dbf5f33 --- /dev/null +++ b/research/tiered-native-multiplier/README.md @@ -0,0 +1,33 @@ +# A tiered signed multiplier with smaller native ranks + +One signed multitape multiplier attains conditional κ = 0.0038982 for arbitrary binary inputs. It uses the K7 ordinary word, a Gaussian word with physical dilations 1 and 79, and two complete sets of native ranks. The public input header selects the set. Both sets run the same CRT, signed Fourier, product and recovery algorithm. The largest rank is $2^{680000}$. The complete recurring coefficient is at most $2^{339787971}$ tape transitions in the normalization below. [Machine quantities](RESULT.json) · [Sources and exact hashes](SOURCES.json) + +| Complete construction | κ | Ordinary log₂ ranks | Gaussian log₂ rank | Sufficient connected A | Ceiling for log₂ C | +|---|---:|---:|---:|---:|---:| +| Two unsplit K7 returns, PR #8054 | .0038981730255 | 60,000 and 960,000 | 20,000,000 | 21,020,646 | 21,111,681,659 | +| Entry branch | .00345 local | 3,000 and 3,080 | 1,024 | 7,437 | 125,660,241 at its local rate | +| Terminal branch | .0038982 | 35,327 and 559,005 | 680,000 | 1,274,851 | 339,787,970 | +| Single machine | **.0038982** | both sets above | at most 680,000 | **7,437** for a complete native path, **1,274,851** for the terminal path | **339,787,971 at all lengths** | + +For each A the sufficient input length is $2^{\lceil 2^A/6\rceil-1}+1$ significant bits. Here $N_i=2^{H_i}$ and $M=2^{H_M}$ are internal ranks. The price pays for arbitrary inputs, numeric recovery, the smaller branch, every parked bank and every cell traversed. Complete fixed installation falls from a published ceiling of $2^{513}$ to $2^{228}$ tape transitions. Two matched fresh-process observations per version of the preceding fixed-carrier compiler and this complete compiler took 82.62 and 5.09 seconds on average. Input-dependent preparations have their own charge. [Fixed setup and measurements](SETUP.md) [Numerical source, precision and movement](NUMERICAL.md) · [Complete product, clocks and activation](CLOCK.md) + +The complete gain over ToikY’s 1,006-split result is exactly 53949/2000000000000. Its 1-to-8 raw ceiling is below .003898180942173. The previous version with 1,008 splits has a raw crossing below .0038981803447950341293615589, which is already below the new complete rate. [Leading comparison](https://github.com/CrocSwap/integer-mult-bounds/pull/8054) · [Independent interval proof](independent_price.py) + +A lower-rate one-stage configuration in the same source family activates at A = 6,913 with H = 5,610 and numerical H = 1,024. The lower-rate two-stage compact configuration uses 9,100 and 144,000, with numerical H = 8,500 and A = 161,992. At κ = .003893947 the K7 configuration has A = 1,056,618 and numerical H = 36,000. These are smaller in one or more dimensions than the terminal branch above. The 7,437 threshold is for both actual ordinary stages and the numerical supplier. The finite price conversion also applies when an earlier machine has a suitable smaller connected profile. The independently significant terminal comparison is the 29.41-fold reduction in the largest rank exponent and the 16.49-fold reduction in the terminal threshold exponent against K7 extended. [K7 configurations](https://github.com/CrocSwap/integer-mult-bounds/pull/8052) + +## Reproduce + +Use Git and CPython 3.12 with assertions enabled. + +```sh +python3.12 -IB scripts/research_package.py --package research/tiered-native-multiplier +python3.12 -IB research/tiered-native-multiplier/bootstrap.py /tmp/tier-install +python3.12 -B /tmp/tier-install/band_product.py -741503 466013 +``` + +The last command prints `-345550037539` at the ordinary small-input base. The registered replay also runs an explicit physical Fourier geometry, the changed Gaussian source and the K7 interpreter. Open both Lean files with Mathlib and Lean 4.34.1, or run `check_lean.py LEAN_ROOT MATHLIB_ROOT`. [Verification scope](VERIFICATION.md) · [Attribution](NOTICE.md) + +## Open next questions + +- Can a different numerical word or weighted ordinary exchange reduce the terminal exponents by another order of magnitude? The old Gaussian source fails the strict raw moment before finite costs at the new complete rate. +- Can the outer controller generate and serve its enormous sides on physical inputs at an attainable scale? The first full execution proved here still requires at least $2^{7412}$ axes at the certified entry geometry. A production-scale timing comparison remains open. diff --git a/research/tiered-native-multiplier/RESULT.json b/research/tiered-native-multiplier/RESULT.json new file mode 100644 index 0000000000..0254672701 --- /dev/null +++ b/research/tiered-native-multiplier/RESULT.json @@ -0,0 +1,136 @@ +{ + "binary": { + "targets": 18906, + "paid": 104652, + "margin": "55321779883482082595639/244544123725211460862213013703178693829", + "transport_cells": 24, + "physical_factor_upper_millionths": 1101878 + }, + "gaussian": { + "targets": 105216, + "paid": 564144, + "margin": "26805012692229413055189664863/448259604423667117305978754355871799892", + "transport_cells": 62, + "physical_factor_upper_millionths": 1121328 + }, + "entry": { + "kappa": "69/20000", + "binary_H": [ + 3000, + 3080 + ], + "gaussian_H": 1024, + "width_exponents": [ + 276000, + 283360, + 94208 + ], + "rates": [ + "3428763898577864693/1000000000000000000000", + "690000000000001/200000000000000000" + ], + "positive_rate": "2053016477/549755813888", + "signed": { + "strict": 54, + "functional": 4, + "smallest_margin": "1/10000000000000000000", + "ordinary_margin": "1/1000000000000000000", + "positive_margin": "119292388218992043473/419430400000000000000000" + }, + "stock": { + "binary_cuts": [ + 3077, + 6221 + ], + "public_exponent_A": 7437, + "first_public_offset": 4, + "initial_s": 7438, + "stage_and_outer_fixed_log_overhead": 1964, + "retimed_first_stripe_margin": 1701, + "retimed_all_size_margin_floor": 1635, + "absolute_log2_private_control_envelope": 3153922, + "storage_upper": "6.2 p T < 297.6 n bits" + }, + "geometry": { + "public_offset_above_2_to_A": 4, + "first_extent_bits_minus_b": -7433, + "last_extent_bits_minus_b": -7432, + "minimum_width": 3809536, + "log2_axis_count": 7412, + "largest_axis_width": 5592406, + "private_clock_log2_upper": 5734316302, + "actual_dense_root_entry_log2": 11184812 + }, + "variable_cost_surcharges": [ + 0, + 25818582 + ], + "log2_B": 125433359, + "log2_C": 125660241 + }, + "terminal": { + "kappa": "19491/5000000", + "binary_H": [ + 35327, + 559005 + ], + "gaussian_H": 680000, + "width_exponents": [ + 3250084, + 51428460, + 62560000 + ], + "rates": [ + "1923248757962185099/500000000000000000000", + "779640000000001/200000000000000000" + ], + "positive_rate": "22769993547549/5841155522560000", + "signed": { + "strict": 54, + "functional": 4, + "smallest_margin": "1/10000000000000000000", + "ordinary_margin": "1/1000000000000000000", + "positive_margin": "1329962864739041/7130316800000000000000000" + }, + "stock": { + "binary_cuts": [ + 35534, + 594603 + ], + "public_exponent_A": 1274851, + "first_public_offset": 4, + "initial_s": 1274852, + "stage_and_outer_fixed_log_overhead": 1964, + "retimed_first_stripe_margin": 635376, + "retimed_all_size_margin_floor": 615539, + "absolute_log2_private_control_envelope": 696320002, + "storage_upper": "6.2 p T < 297.6 n bits" + }, + "geometry": { + "public_offset_above_2_to_A": 4, + "first_extent_bits_minus_b": -1274847, + "last_extent_bits_minus_b": -1274846, + "minimum_width": 652725504, + "log2_axis_count": 1274819, + "largest_axis_width": 715827883, + "private_clock_log2_upper": 734314544100, + "actual_dense_root_entry_log2": 1431655766 + }, + "variable_cost_surcharges": [], + "log2_B": 190186368, + "log2_C": 339787970 + }, + "old_rate": ".0038981730255", + "rate_delta": "53949/2000000000000", + "entry_premium": 572, + "complete_log2_C": 339787971, + "prefix": { + "small_stop_tail_factor_log2": 1591, + "private_prefix_log2": 126082079, + "controls_prefix_log2": 5081414, + "private_prefix_after_input_log2": 84484466, + "early_log2_C_bound": 84500000, + "tail_log2_fixed_factor_including_b_to_n": 1434, + "tail_unit": "(1 + B + Z) * n * (1 + log2(n))^(1-kappa)" + } +} diff --git a/research/tiered-native-multiplier/SERIAL-SETUP.md b/research/tiered-native-multiplier/SERIAL-SETUP.md new file mode 100644 index 0000000000..b9b8b3f1e2 --- /dev/null +++ b/research/tiered-native-multiplier/SERIAL-SETUP.md @@ -0,0 +1,19 @@ +# Serial arithmetic in fixed installation + +With the fixed indexed-action and width bounds of the quadratic installer, the complete two-tier setup takes fewer than $2^{228}$ individual tape reads, writes and moves. This includes the original $2^{32}$ multiplier for parsing, hashing, initialization and cleanup. The improved price comes from the arithmetic implementation and a sharper sum of the existing charges. It does not give an elapsed-time ratio. [Predecessor fixed census](https://github.com/aliromman/integer-mult-bounds/blob/cc21f7040cb3376709b30fc42f289827836d8be5/research/quadratic-native-installation/COST.md) + +Store a magnitude as a delimited binary word, most significant digit first. Zero is the one digit `0`. Store a sign separately. Use separate work tapes for the operands, output, quotient, alignment and temporary sums. In the reference program a forward or backward word iterator is one sequential traversal. Reverse emission uses a separate tape. Removing leading zeros, concatenation, and making a copy with the last digit omitted each use one or two sequential passes. The last operation uses one symbol of lookahead. A temporary tape is rewound and cleared. The comparison of equal-length digit strings reads both tapes from the same end. The reference uses this representation for all unbounded arithmetic. Its only primitive division, `divmod(digit, 2)`, acts on a carry and two one-bit digits. [Serial operations](serial_setup.py) + +**Division.** Let the two positive magnitudes have bit lengths $a\ge b$. Scan their inputs together for the first $b$ digits. For each of the $a-b$ remaining dividend digits, write a zero on a separate tape. Append these zeros to a copy of the divisor. This aligns its high digit with the high digit of the dividend. The dividend is initially less than twice the aligned divisor since both have $a$ digits. Emit one quotient digit per alignment. Compare the entire remainder to this divisor, then subtract it if the result is nonnegative. Shift a copy of the divisor one position to the right for the next iteration. After a comparison the remainder is below the old aligned divisor. Before the next comparison it is below twice the new aligned divisor. The last comparison uses the original divisor. This proves the quotient and remainder identity with remainder strictly smaller than the divisor. A shorter dividend returns quotient zero and restores a copy of the dividend. A zero divisor is rejected. + +Let $h$ bound the two input lengths. The setup, copies and final truncation need fewer than 16 whole-word passes. One quotient digit needs fewer than 16 passes over words of at most $h+4$ tape symbols. This includes comparison, two rewinds, subtraction, the backward and forward output copies, shifting the divisor, resetting both argument heads, advancing the unary loop and clearing or reusing the bounded scratch. Moving to the opposite end before a reverse scan counts as a pass. In one such pass allow 64 transitions per position. The local state reads at most four current symbols, writes at most three and moves at most four heads per symbol. End tests, delimiters, the sign, carry, and a constant number of shifts fit the allowance. Thus $2^{11}(h+4)(a-b+3)$ suffices for division with clear work tapes and the quotient and remainder returned. The short and zero cases use fewer transitions. + +**Euclid and signed operations.** The sign-normalized first division has $a\ge b$. Write $a_i,b_i$ for the successive bit lengths and $k$ for the number of nonzero divisors. At every nonfinal step $a_{i+1}=b_i$, so $\sum_i(a_i-b_i)\le h$. In two steps a positive divisor falls below half its previous value or the procedure finishes, which gives $k\le 2h+2$. The sum of all alignment lengths is therefore at most $h+k$. This counts quotients with one bit, including consecutive such quotients near the Fibonacci worst case. + +The program also computes both Bézout coefficients. Their recurrence takes each of the two columns $(u,v)$ to $(v,u-qv)$. It preserves each remainder as the signed combination of the two inputs. The nonzero signs of each column alternate from the initial pair of unit rows, allowing a zero at the start. After the initial terms, the magnitudes are nondecreasing, since $q\ge1$ and $|u-qv|=|u|+q|v|$ when $u$ and $v$ have opposite signs or one is zero. The final zero row is a primitive integer relation because every Euclid row replacement has determinant $-1$. For positive inputs $A,B$, its two magnitudes are $B/g,A/g$ for $g=\gcd(A,B)$. This bounds every intermediate coefficient by $\max(A,B,1)$. It includes the product $q|v|$ as well. A zero original operand uses the unit row directly. Swapping inputs or restoring their signs changes neither bound. + +To multiply $v$ by $q$, process the quotient from its high end. Double the accumulated magnitude, then add $|v|$ if the next digit is one. Every prefix product is at most $q|v|$. One quotient digit requires fewer than 16 passes of the same $h+4$ symbols, including leading-zero deletion, addition and scratch release. The two signed additions following the two products each take fewer than 16 passes. The quotient has at most $a_i-b_i+1$ digits. The divider, both products, the two updates and the row and input copies fit $2^{16}(h+4)(a_i-b_i+3)$ per Euclid division. The full Bézout result, including the initial swap, sign handling, final copy and cleanup, costs at most $2^{16}(h+4)(7h+9)$. The three extra units include these boundary passes. [Quotient and Bézout implementation](serial_setup.py) + +**Whole installer.** Use $w=2^{38}$ for the length of an individual indexed datum. Both scalar operands can have this full width. Signed rational addition uses two cross-products and a sum in its numerator and one product in its denominator. Multiplication and division use two products. All unreduced magnitudes have at most $h=2w+2$ bits. Reduction uses the preceding Euclid implementation followed by two exact unsigned divisions. In addition to the Euclid term, $8\cdot2^{16}(h+4)^2$ suffices for all products, signed sums, exact divisions, normalization and erasure. Thus one complete rational operation takes fewer than $2^{110}$ local steps. Long serialized strings may occupy the whole $w$-bit field during lookup or parsing. The scalar proof permits the same width for the numerators and denominators. It does not assume that they have the smaller sizes seen in timing runs. + +With $2^{68}$ actions and records of up to $4w$ cells, every old value and every new value fit in $2^{108}$ cells together. The original complete lookup costs $8\cdot2^{108}\cdot512\cdot128=2^{127}$ transitions with the rewrite stream, cursor and key restoration. Let $E=2^{16}(h+4)(7h+9)+8\cdot2^{16}(h+4)^2$. The setup bill is $(2^{68}+1)(2^{127}+E+2^{120})2^{32}<2^{228}$. The $2^{120}$ allowance and the parsing and cleanup multiplier remain charged. The input-dependent calendar construction and every active numerical tape keep their separate recurring price. The code checks the exact integer inequality together with 4,071 quotient or Bézout inputs and 7,396 rational operations. This finite test supplements the proof for all operand lengths. [Independent arithmetic and exact budget checks](check_serial_setup.py) diff --git a/research/tiered-native-multiplier/SETUP.md b/research/tiered-native-multiplier/SETUP.md new file mode 100644 index 0000000000..9512c6724c --- /dev/null +++ b/research/tiered-native-multiplier/SETUP.md @@ -0,0 +1,30 @@ +# Fixed installation and measurements + +The complete two-tier installation takes fewer than $2^{228}$ single-tape reads, writes and moves on the stated multitape machine. The fixed store, including old value versions and scratch for the indexed representation, is bounded as in the source by $2^{108}$ record cells, with separate constant-many local arithmetic tapes of length $O(2^{38})$. The incumbent reports $2^{513}$ transitions. The quadratic installer already had a $2^{241}$ bound on its earlier configuration. The last reduction from 241 to 228 comes from sequential arithmetic and a tighter tape accounting. The incumbent can also use that lowering after its own scalar-action and width census. The distinct changes in actual work are the quadratic phase generation, shared chronological roles, and removal of numbered grade materialization at installation. [Serial arithmetic proof and exact integer bill](SERIAL-SETUP.md) · [Quadratic installer and source](https://github.com/aliromman/integer-mult-bounds/blob/cc21f7040cb3376709b30fc42f289827836d8be5/research/quadratic-native-installation/COST.md) + +## Installed sources and active work + +The binary constructor authenticates and replays the K7 source. Removing seven terminal moves reduces the number of charged operations and operational chart pairs from the earlier binary graph. The Gaussian producer authenticates the 48-call graph, builds the 60,206 shared rational coefficients, and compiles each chart and its absolute phase by a binary quadratic form. The original single-width caller used 334,176 typed roles. The shared source keeps 25,621 distinct records and 145 chronological segments. Those changes were made in PR #8051. The two new grades objects compute one histogram for each distinct segment and concatenate the chronological rank streams at the required dilations. They add both halves at each of the first 1,008 unit loans in the first stream. The dense prior implementation constructed 105,216 productive and 564,144 paid grade entries during fixed preparation. The new implementation instantiates these 669,360 ordinal entries at each active calendar construction and shares the installed grades and coupling across the two tiers. [Installed representation](grades.py) · [Physical calendar and charge](NUMERICAL.md) + +The same scalar-action bound of $2^{68}$ and individual width $w=2^{38}$ bits apply to the changed sources. The original $2^{64}$ allowance for numeric preparation covers the quadratic compiler and the full pair of words. K7 needs fewer binary operations and a subset of the earlier graph's used frame pairs. There are fewer than $2^{20}$ Gaussian roles. The two dilations and the signed split add at most a constant number of fixed operations per role. The two immutable Gaussian grade streams and their histograms serve both tiers. A single Gaussian price constructs 62 cells. It uses at most 39 root and 40 product steps per endpoint for fewer than $2^8$ distinct grades. All resulting cell numerators and denominators have fewer than 512 bits. The extra recipes contain only references to the same words and couplings, finite rank exponents, rational stops and the two price profiles. All these additions, including the 39-step directed enclosure, fit $2^{32}$ further indexed operations. This is within the original $2^{68}$ bill, which bounded the numerical generation by $2^{64}$ and both 36-call and 48-call compilers together with spare capacity. Reading and restoring the new package and both archived sources uses the charged fixed parsing, comparison, hash, decompression, initialization and cleanup allowance. Active geometry, coefficient precision, full-rank control files and the reconstruction of the two grade sequences receive the separate recurring price in the clock. [Pinned complete predecessor census](https://github.com/aliromman/integer-mult-bounds/blob/dfd25d553a843a946ca0b94130a5ff8943e98fdd/research/retimed-native-multiplier/INSTALLATION.md) · [Installed source bindings](SOURCES.json) + +## Observed host installation + +Four serial fresh-process observations used CPython 3.12.16 on macOS 27.2 arm64. Order was incumbent, candidate, candidate, incumbent. Each process restored the authenticated source, installed the complete fixed program, built all recipes delivered by that multiplier, checked the installed dimensions and common K7 digest, then removed its private temporary directory. The comparison uses ToikY's extended multiplier and the complete two-tier candidate. CPU includes the process and its children. Peak resident bytes refer to the compiler process. The runs share the host filesystem cache and ordinary machine load. [Raw observations](MEASUREMENTS.json) · [Measurement entry](measure_setup.py) + +| Fixed installation | Wall seconds | CPU seconds | Peak resident bytes | +|---|---|---|---| +| Fixed-carrier K7 in PR #8053 | 83.0384, 82.1996 | 82.7401, 81.9889 | 309,346,304 and 309,772,288 | +| Both tiers of this multiplier | 5.1059, 5.0769 | 5.0941, 5.0657 | 277,184,512 and 276,201,472 | + +The ratio of the mean elapsed times is 16.23. The same K7 source digest appears in all four records. The incumbent installed three rank recipes with 54 Gaussian coupling cells. The candidate installed six recipes for two profiles, with shared banks and 62 Gaussian cells. These observations apply to fixed compilation. No comparable production-size multiplication timing is available. [Pinned competitor verifier](https://github.com/ToikY/integer-mult-bounds/blob/e25494616bf149217644ce08d949181ea3600e13/research/p104-gaussian-fixed-carrier/verify.py) + +A subsequent matched pair ran the newly published 1,006-split PR #8054 and the candidate in fresh processes. The peer took 94.902 seconds elapsed, 91.769 seconds CPU and 324,567,040 peak resident bytes. The candidate took 5.059 seconds elapsed, 5.052 seconds CPU and 277,331,968 bytes. This is one paired observation. The peer produced 564,142 numerical loans. The candidate produced 564,144. [Two-unsplit-return source](https://github.com/ToikY/integer-mult-bounds/blob/40940734cf582ded0896833b3dc93880299cf927/research/p104-gaussian-unsplit-returns/prepare.py) + +Given an exact checkout of PR #8053, pass its package directory as the argument to the first command. Run each command in a new process. + +```sh +python3.12 -IB research/tiered-native-multiplier/measure_setup.py --peer-8054 /path/to/research/p104-gaussian-unsplit-returns +python3.12 -IB research/tiered-native-multiplier/measure_setup.py --peer-8053 /path/to/research/p104-gaussian-fixed-carrier +python3.12 -IB research/tiered-native-multiplier/measure_setup.py +``` diff --git a/research/tiered-native-multiplier/SOURCES.json b/research/tiered-native-multiplier/SOURCES.json new file mode 100644 index 0000000000..9d532ab36f --- /dev/null +++ b/research/tiered-native-multiplier/SOURCES.json @@ -0,0 +1,130 @@ +{ + "schema_version": 1, + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "files": [ + { + "path": "AGENTS.md", + "git_blob": "ff81117fca368042f6092964d1f54eb4e6e08fb9", + "sha256": "fece32cdec9c1572ddce354a0b623459cb2c4ca162125d36d36262a92e3caa83", + "usage": "provenance" + }, + { + "path": "autoresearch.md", + "git_blob": "2fe84a7b30b1e26e60ce0ec4775894eb1831c5d6", + "sha256": "d16f0d3bb4d4b213d06c128db6d6460b0fe9ec1ac5a6c1ea1febf1db40e7b60d", + "usage": "provenance" + }, + { + "path": "CONTRIBUTING.md", + "git_blob": "5185786f2ec00f215019fb5777d70979429690a9", + "sha256": "fcd1a8d0e52342a23b8ffa9e905e85ccc539fb084145ef016dfc93cedfb3d924", + "usage": "provenance" + }, + { + "path": "certificates/selected-result.json", + "git_blob": "75d77b328ea02ded535e7f23aee5b1e55d0bb1a8", + "sha256": "154c3d30455d778fd3343b6b4851f0fa4665f0f7625b0adb3675e2bafbbf6bf1", + "usage": "provenance" + }, + { + "path": "docs/research/agent-task-catalog.json", + "git_blob": "3404fbdd5e7529a0674eef26114b5071e4586cec", + "sha256": "ead6cdc9d0af6d58e8a49744d8ec8c7c15e13d2ba93c276c434bcf9b51b93a81", + "usage": "provenance" + }, + { + "path": "research/unconditional-batched-crt/CRT.md", + "git_blob": "d98dd8e368431cac33d5fc1c8c336696663641d6", + "sha256": "02c3a1e38cbee25aefe2640cc72676da62ba10eb7519fbcb9adb9d48b74eff2b", + "usage": "provenance" + }, + { + "path": "research/delayed-cover-physical-batch-routing/PROOF.md", + "git_blob": "af919b5ba2257c07ea17180f9b8c9fd457556079", + "sha256": "1c3dcd294d327a16fa081b7ea27497941ac6480d352f53e55e8b9e87f45d1454", + "usage": "provenance" + }, + { + "path": "notes/compact-control-movement.tex", + "git_blob": "06b6a9ef24245ac7b724c53a204635415b402357", + "sha256": "b963c3d2f4e1b7059aa289bb4b4ac89b688920bcf42f5b20d7698cdef0132cc6", + "usage": "provenance" + } + ], + "canonical_main": "e54523517d0f03e58352e647c403a5af3e525a57", + "retimed": "dfd25d553a843a946ca0b94130a5ff8943e98fdd", + "quadratic_installer": "cc21f7040cb3376709b30fc42f289827836d8be5", + "k7": "baaec65bf8e4c7e92be110a00d5b06522177931f", + "installer_files": { + "bootstrap.py": "17229a98e1da1c03fcc95accdfa7f804667f9c983f768cd3b53c24b611ae901f", + "retimed-source.tar.gz": "3d30e35c5a77f43372e94ccca7aaa38ce706631fc5b4601293bbd8619dfb2775", + "SOURCES.json": "0c5d1999cf744db7c71b29fbd0601e18fa50c7fa134c172ff713ddad65fadff1", + "production.patch": "54a5be1f9a9961fbbf23df7fb874194bc208ea6b87ca01742f87ec8027f0ca7e", + "gauss_phase.py": "a087d0dd5f448d39e6a2dfdc876be7238b75a55b8f9c350eda3907a1865bcb56", + "phase_atlas.py": "6425300f5d3d984290496df0ff411aca6879869b285298e553cd4d94ba02faa7", + "clock_ports.py": "7d67eb9db9c50fec056440ef17acc6566cdcac740f44d74790213a5179d34b1e", + "sparse_helpers.py": "823144823a54b0e79ee9891ed0bc7ba6fb7ecd846fbc1d0d287f19b3a046ecbd", + "LICENSE": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4", + "NOTICE.md": "c6b1753ad6ebda2a2143b1a9efc80fadad6c1b27552c3ec8bc7bfdb431fb8eeb" + }, + "runtime": { + "band_product.py": { + "before": "98595de1aa89a158cfddeb462f9a87bad4a8d59c0d1eb01f24790cb46050044d", + "after": "0a2a243378ced624fa94100d7743bab5209edacda1e3b5a5c2fda6fd0a66791b" + }, + "binary_receiver.py": { + "before": "670c500573ef35b5faba27af4e1ec62922db96877dc1af1db337f82ff362d0ca", + "after": "a7cc759e9a88e60dbcd59ca314ae5b9d39a33b5c642b56e680bbab775b0f06c5" + }, + "independent_binary_price.py": { + "before": "1936595a79fbfa14ec74af3b4e521216740d00bd45f379b5e97a1440e5a2aaf9", + "after": "05f77dd77baff30ff241744901769b952de43859e00afb0739c8b4e18dc30dd2" + }, + "installations.py": { + "before": "2244e7e27f7348575944eb652a741861a0a04d77b18c297db221ef74b3116a16", + "after": "1c6978b8c7d136ef87191512d9ab9eb3dda8a818844244b96cb165d46d97b1df" + }, + "ordinary_carrier.py": { + "before": "e2d07d8136bda5b6a74160e3625cb8c1a0deef2c42bdb4e8cfd7a8d7e3922394", + "after": "aa1a64d48daf22f3918922481899a460dfe8e70268388e41f133279bc78f141d" + }, + "retimed_supplier.py": { + "before": "a50112eb4ee9e56532f54b79bc68f6c2b395be3c717b1e9a0e4178a5b76d846e", + "after": "9c89e67dcc480f2a3664f15446159701c98ef9d7518dbd175baf9a76453eb82f" + }, + "strong-bit.json.gz": { + "before": "74e93daf2b7acf794ffb51f92f03f51556f68126d41ee13a8969bddb4cbe6326", + "after": "9e7392c52bcf29c0cc58c54c619f95c28f476394c33e8e0a5aa30c9557d31362" + }, + "strong_binary.py": { + "before": "dddbfa0a3ae6ee1fc847c24b9b1e2115809d126acafbea988e5331cee3bbb0a4", + "after": "64673cce85c94f90c498ca01bfda138bb98e08b56ad3777c6565be86bde09020" + }, + "transport.py": { + "before": "98bdb540233794338b426d1b0d0e72cff7fcbbd08be702af0d81e237dbecaae9", + "after": "9eb8f0d77a4c53fc4fddffdfe198cab930b6d1f49e2b6d43c970397051bb7818" + }, + "unpowered_price.py": { + "before": "c273f2bcd46a114595ee669021aa6cd7223488f87cee0fe10bd762bc92177424", + "after": "a6c80d4605065889bb49144c034965a6bf33d8fad7f73ef97dcf1089e48316b4" + } + }, + "archive_and_overlay_sha256": { + "source/INSTALLER-NOTICE.md": "c6b1753ad6ebda2a2143b1a9efc80fadad6c1b27552c3ec8bc7bfdb431fb8eeb", + "source/K7-NOTICE.md": "9c5ae9750012d305d917e625d14a33cc880e810e801e73364725bcdc24bffdb5", + "source/K7-STACK-LEDGER.json": "a0c0d5b241e6861a5c49a287617e48fba56b09824f5ef4fcb7f03152edf37e8e", + "source/activation.py": "6e7f89d40a4d10ecd40a50e5b96334dfc64db90841ece7e3ef12eeca5ee5093b", + "source/check_binary_k7.py": "5eeb8f818725249cbabf215c323c3f8351b1c4ed3c127119341e6ed09f490dd6", + "source/installer.tar.gz": "6696459e2e3552f802e7caaaf93dc86c9bb6b62ee38631702bff2e3a8a9a481a", + "source/ordinary_clock.py": "91dcf0ef72dddbde998b80f3d8b30c8036de9ce97e06e2bbd9c4159bf292020d", + "source/outer_budget.py": "ca4438db28a447ed5c43d87d43f0ac10a0cb2b4e183342ac93139d517b9d4d02", + "source/outer_clock.py": "63363c3da673365f3ac5e1b7e318c6938005f1e9c9896799504cc598efbf96fa", + "source/strong-bit-k7.json.gz": "9e7392c52bcf29c0cc58c54c619f95c28f476394c33e8e0a5aa30c9557d31362", + "runtime.patch": "6c93961841be2abc3629928074e2c7917d264e94187276fc88a33f922a3c62e4", + "grades.py": "340684fdd5ca0e611836b0e7301f1c339282ba532bf9e3ec8055944d8981f3c8", + "installations.py": "1c6978b8c7d136ef87191512d9ab9eb3dda8a818844244b96cb165d46d97b1df" + }, + "live_comparator": "40940734cf582ded0896833b3dc93880299cf927", + "repriced_fixed_carrier": "e25494616bf149217644ce08d949181ea3600e13", + "live_comparator_replay_head": "f6f4ecd5dd717ce2b155dd564469e9693ac90f6d" +} diff --git a/research/tiered-native-multiplier/ScaledEntrance.lean b/research/tiered-native-multiplier/ScaledEntrance.lean new file mode 100644 index 0000000000..0823ea46fc --- /dev/null +++ b/research/tiered-native-multiplier/ScaledEntrance.lean @@ -0,0 +1,28 @@ +import Mathlib.Tactic + +namespace ScaledEntrance + +def upper (M : ℕ) := 2*(M/(2048*12087)) +def band (M : ℕ) := 2*((3*upper M)/8) +def actualSize (M : ℕ) := 10191*(band M-8) + +/-- All integer rounding in the changed physical entrance, including the period fences. -/ +theorem placement (M : ℕ) (large : 10^13 ≤ M) : + (32768 < band M) ∧ + (4424 * upper M < 10191 * band M) ∧ + ((band M+2)*10191 < 4424*M) ∧ + (1616 * actualSize M < M) ∧ + (M+6000 < 1620*actualSize M) := by + simp only [upper, band, actualSize] + omega + +/-- Both following tickets belong to the five-hit prefix and differ from slot one. -/ +theorem tickets (M : ℕ) (large : 10^13 ≤ M) : + 3240 < 5 * ((1620*actualSize M - M)/4) ∧ + 1620/5 = 324 ∧ 3240/5 = 648 := by + have h := (placement M large).2.2.2.2 + omega + +#print axioms placement +#print axioms tickets +end ScaledEntrance diff --git a/research/tiered-native-multiplier/TASK.json b/research/tiered-native-multiplier/TASK.json new file mode 100644 index 0000000000..0c085c2bab --- /dev/null +++ b/research/tiered-native-multiplier/TASK.json @@ -0,0 +1,93 @@ +{ + "schema_version": 1, + "task_id": "selected-stock-envelope", + "priority_revision": 8, + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "original_card": { + "id": "selected-stock-envelope", + "question": "What explicit uniform stock envelope does the actual selected stopped producer supply at one bootstrap stage?", + "starting_points": [ + "research/selected-bootstrap-stock-audit/README.md", + "research/bootstrap-cutoff-time-space-split/README.md", + "certificates/selected-result.json", + "docs/research/community-efficient1000-review.md", + "research/stock-margin-chain/README.md" + ], + "methods": [ + "Derive a source-bound reserve recurrence at the actual selected atom widths, separating parent stock from completed inner borrowing.", + "Find an exact missing implication or counterexample to a proposed selected-stage stock envelope." + ], + "acceptance_gate": "Bind every coefficient and depth factor to the selected producer and state the width domain. Compare a proved envelope with the sufficient cutoff guard; a large numerical headroom or a historical m=120 coefficient is not a selected m=73 proof.", + "first_step": { + "command": [ + "python3", + "-B", + "scripts/research_selected_baseline.py" + ], + "expected": "PASS_RESEARCH_BASELINE_BINDINGS_ONLY", + "inspect": "Resolve the current selected review, separate complex/ordinary BIT/admitted BIT/outer budgets, and compare the card against live handoffs before starting. Historical ceilings require exact source/model equivalence.", + "scope": "Source-binding orientation only; not a scientific replay or all-size proof. Materialize selected inputs if this checkout is sparse." + }, + "first_experiment": "Choose one actual selected producer/stage and derive its parent reserve and depth coefficient from source. Check whether newer handoffs already cover that exact obligation. Stop with the missing implementation lemma if it cannot be bounded; do not rerun #2972 cutoff/headroom arithmetic as a new contribution.", + "bottleneck_link": "This reduces a concrete inherited implementation obligation without confusing unchanged kappa arithmetic with a completed theorem.", + "allowed_variations": [ + "One stage or one explicit reserve/depth implication.", + "An independently checked same-domain proof repair, retaining all remaining assumptions." + ], + "scope_change_triggers": [ + "Importing the historical 57604 or 252 allowance without a selected-producer binding.", + "Calling a conditional fit lemma a full outer-proof adoption.", + "Replacing an actual selected stock coefficient with cutoff comparisons or a conditional fit inequality." + ], + "overlap_terms": [ + "selected stock", + "stock envelope", + "bootstrap cutoff", + "1956", + "1965", + "1990", + "2972", + "stock-margin-chain", + "actual_stock_coefficient" + ], + "existing_checks": [ + { + "scope": "Retained stock audit identifies missing actual selected-stage coefficients; later cutoff-chain arithmetic does not supply them.", + "evidence": "docs/research/research-family-status.md#revision-6-handoffs-source-archives-awaiting-independent-validation", + "remaining": "Derive one actual reserve/depth coefficient from the selected producer.", + "status": "reviewed", + "source_commit": "836b19bfa309ceafbc8ee32a15e8c4b10dde7e11", + "selected_record_sha256": "bb2eaa58647b353f88d0aec2eafb9d30df1be53589231b23e12ceef3e4bad129" + } + ] + }, + "claim": "https://github.com/CrocSwap/integer-mult-bounds/discussions/8039#discussioncomment-19819246", + "related": [ + "https://github.com/CrocSwap/integer-mult-bounds/pull/8027", + "https://github.com/CrocSwap/integer-mult-bounds/pull/8030", + "https://github.com/CrocSwap/integer-mult-bounds/pull/8035", + "https://github.com/CrocSwap/integer-mult-bounds/pull/8042", + "https://github.com/CrocSwap/integer-mult-bounds/pull/8050", + "https://github.com/CrocSwap/integer-mult-bounds/pull/8051", + "https://github.com/CrocSwap/integer-mult-bounds/pull/8052", + "https://github.com/CrocSwap/integer-mult-bounds/pull/8053", + "https://github.com/CrocSwap/integer-mult-bounds/pull/8054" + ], + "scope_status": "changed", + "actual_scope": "Construct one signed multiplier with a higher complete rate and smaller fixed ranks, setup and connected activation. Give an absolute recurring tape clock.", + "scope_change_reason": "The donor assigned joint construction scale and complete rate. The live K7 binary word moved the bottleneck to the Gaussian transport.", + "bottleneck_link": "Two identical grade supports at dilations one and eight have insufficient signed capacity at the new rate. The last ordinary stage and the numerical rank set the required outer precision.", + "stop_rule": "Require a strict comparison with the current open leader, one complete all-input clock, two connected execution thresholds, a literal physical source replay and signed numerical recovery.", + "evidence": "RESULT.json, NUMERICAL.md, CLOCK.md, SETUP.md, MEASUREMENTS.json, ScaledEntrance.lean, TierCost.lean, and the registered replay.", + "author": "Ali Romman", + "ai_assistance": "Substantial OpenAI Codex assistance on the construction, proofs and adversarial checks.", + "outcome": "completed", + "open_questions": [ + { + "question": "Can a new Gaussian source and a cheaper weighted ordinary call reduce the terminal size of both suppliers?", + "why_it_matters": "The terminal numerical rank remains at 2^680000, and the first connected outer geometry requires 2^7412 genuine CRT axes.", + "first_step": "Supply a physical source with a larger directed moment or a cheaper physical child exchange. Reprice both stages and the numerical caller.", + "blocked_by": "The two-copy Gaussian source and the K7 binary word both have finite raw price ceilings." + } + ] +} diff --git a/research/tiered-native-multiplier/TierCost.lean b/research/tiered-native-multiplier/TierCost.lean new file mode 100644 index 0000000000..716dec61d1 --- /dev/null +++ b/research/tiered-native-multiplier/TierCost.lean @@ -0,0 +1,38 @@ +import Mathlib.Tactic + +namespace TierCost + +/-- Each admitted high fibre has enough cells to pay its coefficient clock. -/ +theorem highFibre (k : ℕ) (hk : 30 ≤ k) : 2660000 * (k + 2) < 2 ^ k := by + induction k, hk using Nat.le_induction with + | base => decide + | succ k hk ih => + rw [pow_succ] + omega + +/-- Convert a rate on a finite initial interval to the global rate. -/ +theorem finitePrefix (x A lo hi : ℝ) (hx : 0 < x) (hA : x ≤ (2:ℝ)^A) + (hh : lo ≤ hi) : x^(1-lo) ≤ x^(1-hi) * (2:ℝ)^(A*(hi-lo)) := by + have h := Real.rpow_le_rpow hx.le hA (sub_nonneg.mpr hh) + rw [← Real.rpow_mul (by norm_num : (0:ℝ) ≤ 2)] at h + calc + x^(1-lo) = x^(1-hi) * x^(hi-lo) := by + rw [← Real.rpow_add hx] + congr 1 + ring + _ ≤ _ := mul_le_mul_of_nonneg_left h (Real.rpow_nonneg hx.le _) + +theorem entryPrice (x : ℝ) (hx : 0 < x) (hA : x ≤ (2:ℝ)^(1274851:ℝ)) : + x^(1-(345:ℝ)/100000) ≤ x^(1-(38982:ℝ)/10000000) * (2:ℝ)^(572:ℝ) := by + apply (finitePrefix x 1274851 (345/100000) (38982/10000000) hx hA (by norm_num)).trans + apply mul_le_mul_of_nonneg_left _ (Real.rpow_nonneg hx.le _) + exact Real.rpow_le_rpow_of_exponent_le (by norm_num) (by norm_num) + +theorem strictGain : + (19491:ℚ)/5000000 - 7796346051/2000000000000 = 53949/2000000000000 := by norm_num + +#print axioms highFibre +#print axioms finitePrefix +#print axioms entryPrice +#print axioms strictGain +end TierCost diff --git a/research/tiered-native-multiplier/VERIFICATION.md b/research/tiered-native-multiplier/VERIFICATION.md new file mode 100644 index 0000000000..59f0deac99 --- /dev/null +++ b/research/tiered-native-multiplier/VERIFICATION.md @@ -0,0 +1,25 @@ +# Verification and scope + +The registered check restores the actual signed program from its archived source in a new empty directory for each scope. Each restoration verifies the outer archive, exact member set, individual hashes, input images, patch and output images. It uses Git and CPython 3.12 with assertions. It requires no network connection. [Bootstrap](bootstrap.py) · [Manifest](SOURCES.json) · [Registered commands](VERIFY.json) + +```sh +python3.12 -IB scripts/research_package.py --package research/tiered-native-multiplier +``` + +| Check | Evidence | +|---|---| +| Complete invoice | The checker builds all six installed recipes, compares independently enumerated productive and paid grades, and checks both exact prices. It recomputes 54 strict and four functional signed inequalities per profile, the activation, first physical exchange, stock and complete transition bounds. It compares the full receipt with committed bytes. [Receipt](receipt.py) · [Placement](check_placement.py) | +| Independent numerical price | A second rational logarithm and exponential enclosure bounds both the 1,008- and 1,006-split 1-to-8 signed moments, their derivatives over the whole admissible interval, and the new 1-to-79 moment. Its negative control rejects the old source at the new complete rate. [Interval check](independent_price.py) | +| Binary physical calls | The inherited K7 checker replays all independent registers and every chronological dirty clear and move. It checks all 2,353 chart pairs, all 44,734 frame gates, the 36-call outer word and the weighted physical transfers. [K7 checker](source/check_binary_k7.py) | +| Numerical physical calls | The new raw word executes on two independent, nonzero tensor-product witnesses. The widths are 2 and 158. All 564,144 loans issue, all 105,216 owners receive writes and every handle retires. There are 143,616 owner writes, 119,470,080 requested output axes and 115,056 peak live handles. The individual ray evaluator uses closed tensor products. It does not materialize a dense state of dimension $2^{1422}$. The written all-column argument applies to arbitrary inputs under the retained premises. [Physical replay](check_gaussian.py) · [Numerical proof](NUMERICAL.md) | +| Signed product | The public binary entry handles signs, zero, padded input intervals and head restoration. The two-axis Fourier test uses the physical movement back end and the same signed product class on supplied finite CRT sides. It returns −345550037539 for −741503 and 466013, from coefficients 11811, 10996, 4152, 868, 77. It executes 157,248 H calls and 138 shuttles with 633,744 padded bytes. The ordinary public entry for these two small operands uses its specified scalar base. [Product check](verify.py) · [Complete signed account](CLOCK.md) | + +The fixed-setup replay also checks 4,071 division or Bézout inputs and 7,396 rational arithmetic cases against independent integer and fraction arithmetic. It checks the full explicit bound of $2^{228}$ transitions. The phase census exercises both residue classes on the actual graph and recovers each additional charged field traversal. [Arithmetic proof](SERIAL-SETUP.md) · [Phase check](check_phase_passes.py) + +The Lean proofs cover the integer placement and ticket fences, the high-fibre induction, the finite-interval conversion and the exact comparison with the live complete price. The supplied runner builds both modules with Lean 4.34.1 and Mathlib revision `d13f23b723b8a846827a245b89c10fc7d3f11612`, prints theorem axioms and invokes the standalone `leanchecker` on both objects. The high-fibre statement uses `propext` and `Quot.sound`. The other listed declarations use only `propext`, `Classical.choice` and `Quot.sound`. [Placement](ScaledEntrance.lean) · [Clock](TierCost.lean) · [Kernel replay](check_lean.py) + +```sh +python3.12 -IB research/tiered-native-multiplier/check_lean.py LEAN_ROOT MATHLIB_ROOT +``` + +The full circuit interpretation, charged calendar and tape layout, analytic error and product proof remain written mathematics with exact finite checks. The five inherited scientific premises remain external. The production activation lengths exceed physical execution capacity. The setup measurements cover the compiler itself. No multiplication timing or performance crossover at those lengths is available. [Complete assumptions and clock](CLOCK.md) · [Fixed installation measurements](SETUP.md) diff --git a/research/tiered-native-multiplier/VERIFY.json b/research/tiered-native-multiplier/VERIFY.json new file mode 100644 index 0000000000..4c1d8aadbc --- /dev/null +++ b/research/tiered-native-multiplier/VERIFY.json @@ -0,0 +1,75 @@ +{ + "schema_version": 1, + "status": "ready", + "python": "3.12", + "requirements": [], + "inputs": [], + "commands": [ + { + "argv": [ + "{python}", + "-I", + "-B", + "{package}/verify.py", + "price" + ], + "timeout_seconds": 170, + "checks": "Rebuild and price both complete source profiles, all signed margins, true placement, activation and the all-input transition bound." + }, + { + "argv": [ + "{python}", + "-I", + "-B", + "{package}/verify.py", + "interval" + ], + "timeout_seconds": 150, + "checks": "Bound the old global Gaussian crossing and the changed signed moment with independent log and exp enclosures." + }, + { + "argv": [ + "{python}", + "-I", + "-B", + "{package}/verify.py", + "binary" + ], + "timeout_seconds": 140, + "checks": "Replay K7 on all independent roles, rational charts and weighted physical controls." + }, + { + "argv": [ + "{python}", + "-I", + "-B", + "{package}/verify.py", + "gaussian" + ], + "timeout_seconds": 180, + "checks": "Execute both complete numerical words on independent nonzero witnesses and check all loans, owners and releases." + }, + { + "argv": [ + "{python}", + "-I", + "-B", + "{package}/verify.py", + "product" + ], + "timeout_seconds": 200, + "checks": "Run the signed general entry and compare exact physical Fourier coefficients, product and restored input heads on a finite geometry." + }, + { + "argv": [ + "{python}", + "-I", + "-B", + "{package}/verify.py", + "setup" + ], + "timeout_seconds": 110, + "checks": "Check the serial quotient, signed B\u00e9zout and rational primitives and the absolute fixed-installation tape bill." + } + ] +} diff --git a/research/tiered-native-multiplier/bootstrap.py b/research/tiered-native-multiplier/bootstrap.py new file mode 100644 index 0000000000..89c6726b37 --- /dev/null +++ b/research/tiered-native-multiplier/bootstrap.py @@ -0,0 +1,54 @@ +"""Restore and bind the two signed tiers from the archived research sources.""" + +from argparse import ArgumentParser +from hashlib import sha256 +import json +from pathlib import Path +from shutil import copyfile +from subprocess import run +import sys +import tarfile +from tempfile import TemporaryDirectory + +HERE = Path(__file__).resolve().parent + + +def install(destination): + dest = Path(destination).resolve() + dest.mkdir(parents=True, exist_ok=True) + if any(dest.iterdir()): + raise ValueError("Use an empty installation directory") + pins = json.loads((HERE / "SOURCES.json").read_bytes()) + for name, hex_digest in pins["archive_and_overlay_sha256"].items(): + if sha256((HERE / name).read_bytes()).hexdigest() != hex_digest: + raise ValueError(f"The source differs at {name}") + with TemporaryDirectory(prefix="tier-source-") as temp: + folder = Path(temp) + entries = dict(pins["installer_files"]) + with tarfile.open(HERE / "source/installer.tar.gz") as source: + for member in source: + name = member.name + if name not in entries or Path(name).name != name or not member.isfile(): + raise ValueError("Invalid fixed source entry") + data = source.extractfile(member).read() + if sha256(data).hexdigest() != entries.pop(name): + raise ValueError(f"The fixed source differs at {name}") + (folder / name).write_bytes(data) + if entries: + raise ValueError("The fixed compiler is incomplete") + run([sys.executable, "-IB", str(folder / "bootstrap.py"), str(dest)], check=True) + for phase in ("before", "after"): + for name, hashes in pins["runtime"].items(): + if sha256((dest / name).read_bytes()).hexdigest() != hashes[phase]: + raise ValueError(f"The {phase} image differs at {name}") + if phase == "before": + run(["git", "apply", "--no-index", str(HERE / "runtime.patch")], check=True, cwd=dest) + copyfile(HERE / "source/strong-bit-k7.json.gz", dest / "strong-bit.json.gz") + copyfile(HERE / "installations.py", dest / "installations.py") + copyfile(HERE / "grades.py", dest / "grades.py") + + +if __name__ == "__main__": + cli = ArgumentParser(description=__doc__) + cli.add_argument("destination", type=Path) + install(cli.parse_args().destination) diff --git a/research/tiered-native-multiplier/check_gaussian.py b/research/tiered-native-multiplier/check_gaussian.py new file mode 100644 index 0000000000..e904a06486 --- /dev/null +++ b/research/tiered-native-multiplier/check_gaussian.py @@ -0,0 +1,102 @@ +"""Run both literal scaled copies on independent nonzero Gaussian product states.""" +from argparse import ArgumentParser +from pathlib import Path +from functools import cache +import sys +p=ArgumentParser() +p.add_argument("runtime",type=Path) +args=p.parse_args() +sys.path.insert(0,str(args.runtime.resolve())) +from upstream import HERE,install +_,_,_,source=install() +from raw48 import ComplexRaw +from periodic import Job +from retimed_supplier import Raw +from grades import SCALES, SPLITS +from band_product import production_supplier +from check_nonzero_eight import Field, Axes, WitnessRaw, addresses, basis, diagonal, final_ray, rot + +class RayField(Field): + def blank(self): + return RayField(self.stock) + + def phase(self,fn,suffix): + if self.data is None: + return + z,rays=self.data + n=len(rays) + base=fn(0)%4 + z=rot(z,base) + # The source opcodes I, S and CZ apply the same phase polynomial in + # each of the n physical columns. Evaluate that polynomial on all 512 + # assignments of the first column. Check additional physical addresses + # in every column as well as two mixed whole-register assignments. + single=tuple((fn(x)-base)%4 for x in addresses(0,n)) + after=[] + totals=[base,base] + probes=[0,0] + for i,v in enumerate(rays): + indices=((71*i+93)%512,(11*i+7)%512) + locations=addresses(i,n) + for sample,j in enumerate(indices): + assert (fn(locations[j])-base)%4==single[j] + totals[sample]+=single[j] + probes[sample]|=locations[j] + v2,phase=diagonal(v,single) + after.append(v2) + z=rot(z,phase) + assert all(fn(a)%4==q%4 for a,q in zip(probes,totals)) + self.data=z,tuple(after) + +def check(): + assert SCALES==(1,79) and SPLITS==1008 + producer=production_supplier(1024,10**18) + a,w=producer.physical,producer.word + sizes, paid = producer.recipe.targets, producer.recipe.paid + assert producer.recipe.ambient==153*79 + stock=[0,0] + fields={i:RayField(stock) for i in range(len(sizes))} + jobs=[Job(i,range(2*k)) for i,k in enumerate(sizes)] + clock,call=next((i,row[1]) for i,row in enumerate(a.instructions()) if row[0]=="NATIVE") + key=("helper",clock,call,1544) + pawn=next(i for i,p in enumerate(w.targets) if p.tag==key) + assert w.targets[pawn].rank==8 + exp={} + widths=tuple(2*s for s in SCALES) + for copy,cols in enumerate(widths): + owner=pawn+copy*len(w.targets) + origins=tuple((37*i+11+17*copy)%512 for i in range(cols)) + initial=((3 if not copy else -7)<<2048,(5 if not copy else 2)<<2048) + fields[owner].data=initial,tuple(basis(i) for i in origins) + exact=tuple(final_ray(i) for i in origins) + z=rot(initial,sum(p for _,p in exact)) + assert all(x % (16**cols)==0 for x in z) + exp[owner]=(z[0]//16**cols,z[1]//16**cols),tuple(v for v,_ in exact) + raw=WitnessRaw(a,fields,Axes(),low=0,bundle=1,slots=2*producer.recipe.ambient) + it=Raw(w,raw).native(jobs,2) + completed=0 + nonzero={width:0 for width in widths} + for grade in paid: + job=next(it) + field=fields[job.owner] + completed+=1 + assert len(job.axes)==2*grade + if field.data is not None: + nonzero[len(field.data[1])]+=1 + for axis in job.axes: + field.paid(axis) + assert next(it,None) is None + assert set(fields)==set(range(len(sizes))) and all(f.live and f.writes>0 for f in fields.values()) + assert {i:f.data for i,f in fields.items() if f.data is not None}==exp + assert all(nonzero.values()) + writes=sum(f.writes for f in fields.values()) + for f in fields.values(): + f.retire() + assert stock[0]==0 + print("physical columns",widths,"nonzero cut counts",nonzero,"all paid",completed) + print("owners",len(fields),"owner writes",writes,"sum output axes",2*sum(sizes),"peak handles",stock[1]) + print("exact nonzero output Hilbert log2 dimensions",tuple(9*x for x in widths)) + print("PASS_SCALED_POSITIVE_RAW") + +if __name__=="__main__": + check() diff --git a/research/tiered-native-multiplier/check_lean.py b/research/tiered-native-multiplier/check_lean.py new file mode 100644 index 0000000000..fade224096 --- /dev/null +++ b/research/tiered-native-multiplier/check_lean.py @@ -0,0 +1,20 @@ +"""Kernel-check both proof files against a specified Lean and Mathlib build.""" + +from pathlib import Path +import os +from shutil import copyfile +from subprocess import run +import sys +from tempfile import TemporaryDirectory + +package = Path(__file__).resolve().parent +lean_bin = Path(sys.argv[1]).resolve() / "bin" +mathlib = Path(sys.argv[2]).resolve() +with TemporaryDirectory(prefix="tier-lean-") as temp: + dst = Path(temp) + paths = [dst, mathlib / ".lake/build/lib/lean", *sorted((mathlib / ".lake/packages").glob("*/.lake/build/lib/lean"))] + env = os.environ | {"LEAN_PATH":os.pathsep.join(map(str,paths)), "PATH":str(lean_bin)+os.pathsep+os.environ["PATH"]} + for name in ("ScaledEntrance","TierCost"): + copyfile(package / (name+".lean"),dst / (name+".lean")) + run([lean_bin/"lean","-o",name+".olean",name+".lean"],cwd=dst,env=env,check=True) + run([lean_bin/"leanchecker","-v",name],cwd=dst,env=env,check=True) diff --git a/research/tiered-native-multiplier/check_phase_passes.py b/research/tiered-native-multiplier/check_phase_passes.py new file mode 100644 index 0000000000..616fe10344 --- /dev/null +++ b/research/tiered-native-multiplier/check_phase_passes.py @@ -0,0 +1,119 @@ +"""Count whole-field phase passes added by changing the large-copy dilation.""" + +from argparse import ArgumentParser +from collections import Counter, defaultdict +from pathlib import Path +import json +import sys + +def phase_census(atlas): + """Return signed, occurrence-weighted I instructions for each graph role.""" + counts = defaultdict(Counter) + def visit(label, tape, inverse=False): + for op in tape: + if op[0] == "I": + residue = ((-1 if inverse else 1) * op[1]) % 4 + counts[label][residue] += 1 + calls = [r for r in atlas.instructions() if r[0] == "NATIVE"] + shape = tuple(map(len, atlas.regs)) + assert all(tuple(map(len, r[3])) == shape for r in calls) + for node in atlas.graph["schedule"]: + if node in atlas.moves: + _, right, left = atlas.factors[atlas.moves[node]] + visit("paid, right", right) + visit("paid, left", left) + for i, pair in enumerate(zip(atlas.graph["initial"],atlas.graph["final"],strict=True)): + if i not in atlas.main: + _, right, left = atlas.factors[pair] + visit("helper, inverse right", right, True) + visit("helper, inverse left", left, True) + for p, regs in enumerate(atlas.regs): + move, correct = atlas.contacts[p] + for k in range(len(regs)): + visit("main, contact", move) + visit("main, inverse contact", move, True) + visit("main, correction", correct) + if k % 2 == 0: + visit("main, producer", atlas.port[p][0]) + else: + visit("main, consumer", atlas.port[p][1]) + # The only rank-dependent branch in a chart's phase-dispatch count + # is I. S and CZ always issue once. Multiplicity is independent of + # graph binding; each binding has the same count of each port parity. + per_group = Counter() + by_role = {} + for label, row in sorted(counts.items()): + per_group[label.split(",")[0]] += row[1] + row[3] + by_role[label] = [row[x] for x in range(4)] + return { + "native_graphs_per_copy":len(calls), + "main_slot_counts":dict(sorted(Counter(shape).items())), + "graph_issued_roles":[len(atlas.moves),len(atlas.graph["initial"])-len(atlas.main),len(atlas.main)], + "signed_I_exponents_per_graph":by_role, + "odd_I_by_role_per_graph":dict(per_group), + "all_copy_delta_at_residue_2":len(calls)*sum(per_group.values()), + "all_copy_delta_at_residue_0":0, + } + +def dynamic(atlas, widths): + # Use the unmodified chart and graph generators for one bound call. + # A null payload charges callback invocations. These tests do not price + # the non-phase instructions, field lengths, or the recursive child. + from periodic import Job + from raw48 import ComplexRaw + class Columns: + window = 1 + offset = suffix = 0 + def row(self, *args): pass + class Field: + def __init__(self, counter): self.counter = counter + def copy(self): return Field(self.counter) + blank = copy + def clear(self): pass + def retire(self): pass + def replace(self, other): pass + def scale(self, *args): pass + def scale_add(self, *args): pass + def phase(self, fn, suffix): + self.counter["all_phase_calls"] += 1 + if fn(0) % 4: + self.counter["nonzero_constant_at_zero"] += 1 + class Raw(ComplexRaw): + def align(self, field, job, canonical): return () + def unalign(self, field, route): pass + @staticmethod + def axis_list(cols, axes): return range(cols * len(axes)) + clock,row = next((i,r) for i,r in enumerate(atlas.instructions()) if r[0]=="NATIVE") + _, call, color, bound = row + rows = {} + for cols, bundle in widths: + counts = Counter() + roots={r:Field(counts) for group in bound for r in group} + jobs = {("helper",clock,call,atlas.layout["source_labels"][i]):Job(i,()) + for i in range(len(atlas.graph["initial"])) if i not in atlas.main} + fields = {j.owner:Field(counts) for j in jobs.values()} + machine=Raw(atlas,fields,Columns(),low=0,bundle=bundle,slots=153*cols) + issued=sum(1 for _ in machine.graph(clock,call,color,bound,jobs,roots,cols)) + assert issued == len(atlas.moves) + rows[f"columns={cols},bundle={bundle}"] = dict(counts,returned_paid=issued) + return rows + +def main(): + parser=ArgumentParser() + parser.add_argument("machine", type=Path) + args=parser.parse_args() + sys.path.insert(0,str(args.machine.resolve())) + from upstream import install,HERE + _, _, _, source=install() + from strong_complex import artifacts + atlas=artifacts(source/"research/grade14-native-realization", HERE/"inputs") + report=phase_census(atlas) + assert report["native_graphs_per_copy"]==48 + assert report["odd_I_by_role_per_graph"]=={"paid":3042,"helper":697,"main":200} + probes=dynamic(atlas,[(2*8,1),(2*79,1),(2*79,2)]) + old,large,even_bundle=probes.values() + assert large["all_phase_calls"]-old["all_phase_calls"]==sum(report["odd_I_by_role_per_graph"].values()) + assert large["nonzero_constant_at_zero"]==3939 and even_bundle==old + report["one_real_graph_callbacks"] = probes + print(json.dumps(report,indent=2)) +if __name__ == "__main__": main() diff --git a/research/tiered-native-multiplier/check_placement.py b/research/tiered-native-multiplier/check_placement.py new file mode 100644 index 0000000000..8820fe49b0 --- /dev/null +++ b/research/tiered-native-multiplier/check_placement.py @@ -0,0 +1,50 @@ +"""Reconstruct the first productive row and its true placement exchange at the new ranks.""" +from fractions import Fraction as F +from itertools import islice +from pathlib import Path +from json import dumps +import sys +sys.path.insert(0,str(Path(sys.argv[1]).resolve())) +from upstream import HERE,install +install() +from strong_complex import load_changed,word +from raw48 import ComplexRaw +from periodic import Job +from transport import axes +from unpowered_price import ranks,certify +from installations import GAUSSIAN_C, ENTRY, TERMINAL +from strict_moment import UNIT,power_interval +from retimed_supplier import SCALES +assert SCALES==(1,79) +tar,paid=ranks() +margin,cells=certify(GAUSSIAN_C,(tar,paid)) +assert min(cells.values())/sum(tar.values()) > F(1,2**64) +assert max(max(v.numerator.bit_length(),v.denominator.bit_length()) for v in cells.values())<512 +raw=word(*load_changed(HERE/"inputs")) +roots=[p for p in raw.targets if p.rank==129 and p.tag[:2]==("root","rotated")] +assert len(roots)==384 and tar[10191]==624 and cells[4424,10191]==1 +assert power_interval(10191,GAUSSIAN_C)[1]*100 < UNIT*106 +out={} +class Support: + def __init__(self):self.swaps=[] + def swap(self,a,b,z,s):self.swaps.append((a,b,z)) +class Columns: + window=1 + swap=None +for H in (ENTRY.complex_log,TERMINAL.complex_log): + M=1<624*4 + sz=10191*(band-8) + period=4*(-(-M//(4*sz))) + tickets=tuple(islice(axes(M,sz,period,0),3)) + sup=Support() + unit=ComplexRaw(None,{},Columns(),low=0,bundle=1,slots=M) + route=unit.align(sup,Job(0,tickets),ComplexRaw.axis_list(3,(0,))) + assert sup.swaps[0]==(1,tickets[1],1) + out[H]=dict(period=period,tickets=tickets,first_swap=sup.swaps[0]) +print(dumps(dict(starts=out,root=roots[0].tag,nonempty=len(cells),minimum_probability_lower="2^-64"), + indent=2)) diff --git a/research/tiered-native-multiplier/check_serial_setup.py b/research/tiered-native-multiplier/check_serial_setup.py new file mode 100644 index 0000000000..202f8913be --- /dev/null +++ b/research/tiered-native-multiplier/check_serial_setup.py @@ -0,0 +1,101 @@ +"""Check the serial arithmetic against independent host arithmetic and exact budgets.""" + +from fractions import Fraction +from itertools import product +from math import gcd +from random import Random +import json +from pathlib import Path +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from serial_setup import bezout, quotient_remainder, rational + + +def integer(x): + return (-1 if x < 0 else 1, format(abs(x), "b")) + + +def value(x): + return x[0] * int(x[1], 2) + + +def check_pair(a, b): + if b: + q, r = quotient_remainder(integer(a)[1], integer(b)[1]) + assert (int(q, 2), int(r, 2)) == divmod(abs(a), abs(b)) + else: + try: + quotient_remainder(integer(a)[1], "0") + except ZeroDivisionError: + pass + else: + raise AssertionError("division by zero") + g, x, y = bezout(integer(a), integer(b)) + assert value(x)*a + value(y)*b == int(g, 2) == gcd(a, b) + + +def rat(x): + return integer(x.numerator), format(x.denominator, "b") + + +def check_rational(x, y, op): + if op == "/" and not y: + try: + rational(op, rat(x), rat(y)) + except ZeroDivisionError: + return + raise AssertionError("rational division by zero") + expected = {"+": Fraction.__add__, "-": Fraction.__sub__, + "*": Fraction.__mul__, "/": Fraction.__truediv__}[op](x, y) + assert rational(op, rat(x), rat(y)) == rat(expected) + + +def clock(): + w = 2**38 + h = 2*w + 2 + # The bound for a Euclid step includes both signed coefficient updates. + bezout_cost = 2**16*(h + 4)*(7*h + 9) + elementary = 2**16*(h + 4)**2 + scalar = bezout_cost + 8*elementary + assert scalar < 2**110 + store = 4*w*2**68 + lookup = 8*store*512*128 + assert store == 2**108 and lookup == 2**127 + action = lookup + scalar + 2**120 + assert action < 2**128 + total = (2**68 + 1)*action*2**32 + assert total < 2**228 + return dict(max_datum_bits=w, lookup=lookup, local_arithmetic=scalar, + all_setup=total, setup_exponent=228) + + +def main(): + pairs = list(product(range(-31, 32), repeat=2)) + for width in (1, 2, 11, 31, 63, 127, 256, 512): + a = 2**width - 1 + for b in (1, a, a + 1, 2**(width//2) + 1): + pairs.append((a, b)) + pairs.append((-b, a)) + rng = Random(17813) + for width in (16, 64, 256): + for _ in range(12): + pairs.append((rng.getrandbits(width), -rng.getrandbits(width))) + a, b = 0, 1 + while b.bit_length() < 512: + a, b = b, a + b + pairs.extend(((a, b), (-b, -a))) + for a, b in pairs: + check_pair(a, b) + numbers = sorted({Fraction(a, b) for a in range(-6, 7) for b in range(1, 6)}) + rational_cases = 0 + for x, y in product(numbers, repeat=2): + for op in "+-*/": + check_rational(x, y, op) + rational_cases += 1 + print(json.dumps(dict(integer_pairs=len(pairs), rational_cases=rational_cases, **clock()), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/research/tiered-native-multiplier/grades.py b/research/tiered-native-multiplier/grades.py new file mode 100644 index 0000000000..18b3041f68 --- /dev/null +++ b/research/tiered-native-multiplier/grades.py @@ -0,0 +1,75 @@ +"""Generate the chronological grades of the dilated numerical source.""" + +from collections import Counter +from fractions import Fraction +from functools import cache + +SCALES = (1, 79) +SPLITS = 1008 +HALF = Fraction(1, 2) + + +class Grades: + """Use the fixed role segments for each copy and each chronological split.""" + + def __init__(self, ports, splits=0): + self.ports = ports + self.splits = splits + raw = Counter() + counts = {} + for prefix, entries in ports.segments: + key = id(entries) + if key not in counts: + ranks = (p.rank for p in entries) if prefix is None else (r for _, r in entries) + counts[key] = Counter(ranks) + raw.update(counts[key]) + if raw[1] < splits: + raise ValueError("The base copy has too few rank-one loans") + self.histogram = Counter() + for scale in SCALES: + for rank, count in raw.items(): + self.histogram[scale * rank] += count + if splits: + self.histogram[1] -= splits + self.histogram[HALF] += 2 * splits + + def __len__(self): + return len(SCALES) * len(self.ports) + self.splits + + def __iter__(self): + for scale in SCALES: + remaining = self.splits if scale == 1 else 0 + for rank in self.ports.ranks(): + if remaining and rank == 1: + yield HALF + yield HALF + remaining -= 1 + else: + yield scale * rank + + +@cache +def numerical_source(): + from upstream import HERE, install + _, _, _, source = install() + from clock_ports import clock_word + from installations import GAUSSIAN_C + from strong_complex import artifacts + from unpowered_price import certify + + atlas = artifacts(source / "research/grade14-native-realization", HERE / "inputs") + word = clock_word(atlas) + targets, paid = Grades(word.targets), Grades(word.paid, SPLITS) + margin, cells = certify(GAUSSIAN_C, (targets.histogram, paid.histogram)) + if cells is None or margin <= 0: + raise ArithmeticError("The numerical source cannot pay its physical loans") + return atlas, word, targets, paid, cells + + +@cache +def numerical_recipe(rank_log): + from installations import GAUSSIAN_C + from transport import Recipe + + _, word, targets, paid, cells = numerical_source() + return Recipe(rank_log, max(SCALES) * word.ambient, targets, paid, cells, GAUSSIAN_C) diff --git a/research/tiered-native-multiplier/independent_price.py b/research/tiered-native-multiplier/independent_price.py new file mode 100644 index 0000000000..f3e098a35d --- /dev/null +++ b/research/tiered-native-multiplier/independent_price.py @@ -0,0 +1,95 @@ +"""Check both numerical grade inventories with independent log and exp intervals.""" + +from collections import Counter +from fractions import Fraction as Q +from pathlib import Path +import sys + +sys.path.insert(0, str(Path(sys.argv[1]).resolve())) +from upstream import HERE, install +install() +from independent_binary_price import log_rank, rank_price +from installations import GAUSSIAN_C, TERMINAL +from strong_complex import load_changed, word +from unpowered_price import certify + +raw = word(*load_changed(HERE/"inputs")) +targets = Counter(p.rank for p in raw.targets) +paid = Counter(p.rank for p in raw.paid) + + +def histogram(scale): + h = Counter(targets) + h.subtract(paid) + for r in targets.keys() | paid.keys(): + h[scale*r] += targets[r]-paid[r] + h[1] += 1008 + h[Q(1,2)] -= 2016 + return h + + +def power(r,t): + r = Q(r) + a,b = rank_price(r.numerator,t) + d,e = rank_price(r.denominator,t) + return a/e,b/d + + +def margin(h,c): + lower = upper = 0 + for r,n in h.items(): + a,b = power(r,1-c) + lower += min(n*a,n*b) + upper += max(n*a,n*b) + return lower,upper + + +def doubled(counts): + result = counts.copy() + for grade, count in counts.items(): + result[8*grade] += count + return result + + +old_target, old_paid = doubled(targets), doubled(paid) +old_paid[1] -= 1008 +old_paid[Q(1, 2)] += 2016 +before, old_cells = certify(Q(2092819, 2**29), (old_target, old_paid)) +after, revised_cells = certify(Q(1071523491, 2**38), (old_target, old_paid)) +assert min(before, after) > 0 and old_cells.keys() == revised_cells.keys() +assert len(revised_cells) == 54 and sum(v != revised_cells[k] for k, v in old_cells.items()) == 45 +old = histogram(8) +lo,hi = Q(".0038981803447950341293615588"),Q(".0038981803447950341293615589") +assert margin(old,lo)[0] > 0 and margin(old,hi)[1] < 0 +assert margin(old,TERMINAL.kappa)[1] < -Q(17,100) + + +def certify_derivative(h): + for j in range(16): + # Differentiate sum h_r*(r/16)^t. Bound the signed derivative on the full interval. + derivative = 0 + for r,n in h.items(): + q = Q(r)/16 + a,b = log_rank(q.numerator) + d,e = log_rank(q.denominator) + endpoints = (*power(q,Q(j,16)), *power(q,Q(j+1,16))) + derivative += min(n*z*y for z in (a-e,b-d) for y in (min(endpoints),max(endpoints))) + assert derivative > 300000 + + +certify_derivative(old) +two_returns = old.copy() +two_returns[1] -= 2 +two_returns[Q(1, 2)] += 4 +unsplit_paid = old_paid.copy() +unsplit_paid[1] += 2 +unsplit_paid[Q(1, 2)] -= 4 +peer_margin, peer_cells = certify(Q(133940467, 2**35), (old_target, unsplit_paid)) +assert sum(unsplit_paid.values()) == 564142 and peer_margin > 0 and len(peer_cells) == 54 +assert margin(two_returns,Q(".003898180942171"))[0] > 0 +assert margin(two_returns,Q(".003898180942173"))[1] < 0 +assert margin(two_returns,TERMINAL.kappa)[1] < -Q(17,100) +certify_derivative(two_returns) +assert margin(histogram(79),GAUSSIAN_C)[0] > 0 +assert TERMINAL.kappa > hi +print("PASS_INDEPENDENT_RAW_CROSSING",lo,hi,"and funded 79-column dilation") diff --git a/research/tiered-native-multiplier/installations.py b/research/tiered-native-multiplier/installations.py new file mode 100644 index 0000000000..9bc60df559 --- /dev/null +++ b/research/tiered-native-multiplier/installations.py @@ -0,0 +1,37 @@ +"""Select both complete native stages from the signed controller's public width.""" + +from dataclasses import dataclass +from fractions import Fraction as Q + +BINARY_C = Q(4391986206293, 2**50) +GAUSSIAN_C = Q(2143194013, 2**39) + + +@dataclass(frozen=True) +class Profile: + rank_logs: tuple + complex_log: int + kappa: Q + eta: Q = Q(39, 10000) + positive_stop_denominator: int = 10**18 + + @property + def ordinary(self): + return self.kappa + Q(5, self.positive_stop_denominator) + + +ENTRY = Profile((3000, 3080), 1024, Q(".00345")) +TERMINAL = Profile((35327, 559005), 680000, Q(".0038982")) +PROFILES = {"entry": ENTRY, "terminal": TERMINAL} + + +def activation(profile): + from linear_geometry import connected_exponent + from staged_carriers import entrance_logs + + return connected_exponent(entrance_logs(profile.rank_logs)[-1], profile.complex_log) + + +def at_public(public): + """The magnitude scan and square-side selector have already computed public.""" + return TERMINAL if public.bit_length() > activation(TERMINAL) else ENTRY diff --git a/research/tiered-native-multiplier/measure_setup.py b/research/tiered-native-multiplier/measure_setup.py new file mode 100644 index 0000000000..75bbf0bb33 --- /dev/null +++ b/research/tiered-native-multiplier/measure_setup.py @@ -0,0 +1,73 @@ +"""Measure complete fixed preparation in one fresh process per observation.""" + +from argparse import ArgumentParser +from hashlib import sha256 +from importlib.util import module_from_spec, spec_from_file_location +import json +from pathlib import Path +import platform +import resource +from subprocess import run +import sys +from tempfile import TemporaryDirectory +from time import perf_counter + +HERE = Path(__file__).resolve().parent + + +def load_file(name, path): + spec = spec_from_file_location(name, path) + module = module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def cpu(): + rows = [resource.getrusage(who) for who in (resource.RUSAGE_SELF,resource.RUSAGE_CHILDREN)] + return sum(x.ru_utime+x.ru_stime for x in rows) + + +def measure(peer, revision): + start, used = perf_counter(), cpu() + with TemporaryDirectory(prefix="tier-timing-") as tmp: + work = Path(tmp) + machine = work / "machine" + if peer is None: + load_file("candidate_setup",HERE/"bootstrap.py").install(machine) + else: + src = work / "peer" + if revision == "8054": + wrapper = load_file("unsplit_source", peer/"prepare.py") + wrapper.materialize(peer/"peer8053", src) + else: + wrapper = load_file("fixed_carrier_source",peer/"verify.py") + src.mkdir() + wrapper.restore(src) + wrapper.edit_installation(src) + run([sys.executable,"-IB",str(src/"bootstrap.py"),str(machine)],check=True) + sys.path.insert(0,str(machine)) + from band_product import prepare_native + from installations import PROFILES + if peer is None: + rows = prepare_native() + else: + rows = (prepare_native(PROFILES["extended"]),) + contracts = [[(r.rank_log,len(r.targets),len(r.paid),len(r.cells)) for r in tier] for tier in rows] + loans = 564142 if revision == "8054" else 564144 + assert all(len(tier)==3 and tier[-1][1:3]==(105216,loans) for tier in contracts) + digest = sha256((machine/"strong-bit.json.gz").read_bytes()).hexdigest() + rss = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + print(json.dumps(dict(revision=revision,wall=perf_counter()-start, + cpu=cpu()-used,rss_bytes=rss if sys.platform=="darwin" else rss*1024, + python=sys.version.split()[0],system=platform.platform(),machine=platform.machine(), + installed=contracts,binary_sha256=digest))) + + +if __name__ == "__main__": + args = ArgumentParser(description=__doc__) + group = args.add_mutually_exclusive_group() + group.add_argument("--peer-8053",type=Path) + group.add_argument("--peer-8054",type=Path) + options = args.parse_args() + measure(options.peer_8053 or options.peer_8054, + "8054" if options.peer_8054 else "8053" if options.peer_8053 else "candidate") diff --git a/research/tiered-native-multiplier/receipt.py b/research/tiered-native-multiplier/receipt.py new file mode 100644 index 0000000000..39f2ef7ae8 --- /dev/null +++ b/research/tiered-native-multiplier/receipt.py @@ -0,0 +1,129 @@ +"""Recompute the complete rate, calendar, stock and fixed-tape bounds.""" + +from collections import Counter +from fractions import Fraction as Q +from pathlib import Path +import json +import sys + +PACKAGE = Path(__file__).resolve().parent +sys.path.insert(0, str(Path(sys.argv[1]).resolve())) +from upstream import install +install() +sys.path.append(str(PACKAGE / "source")) +from activation import resource_receipt +from band_product import prepare_native +from grades import SCALES +from independent_binary_price import raw_moments +from installations import BINARY_C, GAUSSIAN_C, ENTRY, TERMINAL, activation, at_public +from linear_geometry import entrance_geometry +from ordinary_clock import first_stage_bound, polynomial_to_fibre_bound +from outer_budget import qualify +from outer_clock import financial_checks +from raw_binary_stage import binary_word +from strong_binary import caller, graph +from strict_moment import UNIT, power_interval +from unpowered_price import certify, intervals + + +def ceil(x): + return -(-x.numerator // x.denominator) + + +def tariff(recipe, target, paid): + c = recipe.trial + margin, cells = certify(c, (target, paid)) + assert cells == recipe.cells and margin > 0 + assert min(cells.values()) / sum(target.values()) > Q(1, 2**64) + assert max(max(v.numerator.bit_length(), v.denominator.bit_length()) for v in cells.values()) < 512 + assert all(5*r <= 4*k for r,k in cells) + t = 1 - c + p = sum(n * Q(intervals(r,t)[0], UNIT) for r,n in paid.items()) + total = sum(n * Q(intervals(k,t)[1], UNIT) for k,n in target.items()) + assert p > 10 and p / total > Q(99,100) + assert t > Q(996,1000) and power_interval(max(target),c)[1] * 100 < 106*UNIT + lower, delta = 32768, Q(1, 2**128) + factor = (Q(256,255)*Q(4097,4096)*Q(1028,1024) + *Q(power_interval(1024*recipe.ambient*lower,c)[1], UNIT) + *(1+Q(64,lower)+delta)/((1-Q(10,lower))*(1-delta)**3)) + if c == BINARY_C: + assert (factor*Q(47,20))**8 < 2**11 and Q(75,32)/Q(47,20) == Q(375,376) + else: + assert recipe.ambient == 12087 and len(cells) == 62 + assert max(Q(k)/r for r, k in cells) == 9 + assert cells[4424,10191] == 1 and target[10191] == 624 + assert factor < Q(power_interval(2,Q(43,256))[0],UNIT) + return dict(targets=target.total(), paid=paid.total(), margin=str(margin), + transport_cells=len(cells), physical_factor_upper_millionths=ceil(factor*10**6)) + + +def bank(profile): + stages = profile.rank_logs + previous = Q(0) + rates = [] + for i, h in enumerate(stages): + funded = min(profile.eta,(249*(BINARY_C-Q(11,8*h))+previous)/250) + rate = (profile.ordinary if i+1==len(stages) + else Q(int(funded*10**21)-1,10**21)) + assert previous < rate < funded + rates.append(str(rate)) + previous = rate + num = profile.complex_log + positive = GAUSSIAN_C-Q(43,256*num) + stock = resource_receipt(profile) + A = activation(profile) + assert A == stock["public_exponent_A"] and min(stages) >= 3000 + signed = qualify(profile.kappa,Q(1,profile.positive_stop_denominator),previous,positive) + if min(stages) >= 8192: + assert 2660000*32 < 2**30 + ordinary = 128+320*sum(stages) + extra = [] + else: + expense = [first_stage_bound(profile.eta), polynomial_to_fibre_bound()] + extra = [max(0,e-944*h) for e,h in zip(expense,stages,strict=True)] + assert Q(376*7,10)**len(stages) < 2**17 + ordinary = 40+17+16384*sum(stages)+sum(extra) + E = max(84500001,1602+220*num+ordinary) + return dict(kappa=str(profile.kappa), binary_H=stages, gaussian_H=num, + width_exponents=[92*h for h in (*stages,num)], rates=rates, + positive_rate=str(positive), signed=signed, stock=stock, + geometry=entrance_geometry(A), variable_cost_surcharges=extra, + log2_B=ordinary, log2_C=E) + + +def verify(): + early_rec, late_rec = prepare_native() + early_bit, _, early_num = early_rec + bit, _, num = late_rec + assert bit.cells is early_bit.cells and num.targets is early_num.targets + assert num.cells is early_num.cells and num.paid is early_num.paid + btarget, bpaid = raw_moments(graph(), caller()) + assert (btarget,bpaid) == (Counter(binary_word().targets),Counter(binary_word().paid)) + assert sum(r*n for r,n in btarget.items()) == 286098 + assert sum(r*n for r,n in bpaid.items()) == 284592 + actual = Counter(num.targets), Counter(num.paid) + assert actual == (num.targets.histogram,num.paid.histogram) + assert (len(num.targets),len(num.paid)) == (105216,564144) and SCALES == (1,79) + b_receipt = tariff(bit,btarget,bpaid) + n_receipt = tariff(num,*actual) + early, late = bank(ENTRY), bank(TERMINAL) + boundary = activation(TERMINAL) + threshold = 1 << boundary + assert at_public(threshold-1) is ENTRY and at_public(threshold) is TERMINAL + # Public precision is a multiple of six. Exercise the last and first such headers. + first_public = threshold + (-threshold)%6 + assert at_public(first_public-6) is ENTRY and at_public(first_public) is TERMINAL + premium = ceil((TERMINAL.kappa-ENTRY.kappa)*boundary) + cost = 1+max(early["log2_C"]+premium,late["log2_C"]) + assert (premium,cost) == (572,339787971) + delta = TERMINAL.kappa-Q(".0038981730255") + assert delta == Q(53949,2*10**12) and delta > 0 + prefix = financial_checks() + return dict(binary=b_receipt,gaussian=n_receipt,entry=early,terminal=late, + old_rate=".0038981730255",rate_delta=str(delta),entry_premium=premium, + complete_log2_C=cost,prefix=prefix) + + +if __name__ == "__main__": + actual = verify() + print(json.dumps(actual,indent=2)) diff --git a/research/tiered-native-multiplier/runtime.patch b/research/tiered-native-multiplier/runtime.patch new file mode 100644 index 0000000000..cd895f6240 --- /dev/null +++ b/research/tiered-native-multiplier/runtime.patch @@ -0,0 +1,239 @@ +--- a/band_product.py ++++ b/band_product.py +@@ -10,7 +10,8 @@ + from retimed_supplier import Positive + from binary_io import magnitude_limbs + from fiscal_scans import magnitude_bits +-from installations import COMPACT, PROFILES ++from installations import ENTRY, PROFILES, at_public ++from grades import numerical_recipe + from inputs.triangular.multiplier import Product as PackProduct, precision + from linear_geometry import parameters, square_sides + from ordinary_carrier import ordinary_swap +@@ -23,17 +24,18 @@ + return Positive(rank_log, stop_denominator) + + +-def prepare_native(profile=COMPACT): ++def prepare_native(profile=None): + """Generate the raw labels, both signed circuits, the atlas and the two grade couplings.""" + from raw_binary_stage import binary_recipe + ++ if profile is None: ++ return tuple(prepare_native(tier) for tier in PROFILES.values()) + binary = tuple(binary_recipe(height) for height in profile.rank_logs) +- positive = production_supplier(profile.complex_log, profile.positive_stop_denominator) +- return (*binary, positive.recipe) ++ return (*binary, numerical_recipe(profile.complex_log)) + + + class Product(PackProduct): +- def __init__(self, sides, b, P, exchange=None, *, engine=None, profile=COMPACT): ++ def __init__(self, sides, b, P, exchange=None, *, engine=None, profile=ENTRY): + self.profile = profile + exchange = partial(ordinary_swap, profile=profile) if exchange is None else exchange + super().__init__(sides, b, P, exchange, engine=engine) +@@ -60,7 +62,7 @@ + left_negative=False, + right_negative=False, + engine=None, +- profile=COMPACT, ++ profile=None, + ): + """Return the sign and length of the product. Restore both input heads.""" + if output is left or output is right: +@@ -77,6 +79,8 @@ + raw = result.to_bytes(max(1, (result.bit_length() + 7) // 8), "little") + output.write(raw) + return bool(negative and all(lengths)), len(raw) ++ if profile is None: ++ profile = at_public(shape.public) + sides = tuple(square_sides(shape)) + machine = Product( + sides, +@@ -89,7 +93,7 @@ + return sign, size + + +-def multiply(left, right, *, profile=COMPACT): ++def multiply(left, right, *, profile=None): + raw = [abs(v).to_bytes((abs(v).bit_length() + 7) // 8, "little") for v in (left, right)] + out = BytesIO() + sign, _ = multiply_tapes( +@@ -110,6 +114,6 @@ + args = ArgumentParser(description=__doc__) + args.add_argument("left", type=lambda x: int(x, 0)) + args.add_argument("right", type=lambda x: int(x, 0)) +- args.add_argument("--profile", choices=PROFILES, default="compact") ++ args.add_argument("--profile", choices=PROFILES) + call = args.parse_args() +- print(multiply(call.left, call.right, profile=PROFILES[call.profile])) ++ print(multiply(call.left, call.right, profile=PROFILES.get(call.profile))) +--- a/binary_receiver.py ++++ b/binary_receiver.py +@@ -1,6 +1,6 @@ + """Run the funded binary graph in the public bank and return every physical loan.""" + +-from installations import COMPACT ++from installations import ENTRY + from raw_binary_stage import binary_recipe, binary_word, run + from module_atoms import chart_width, total_width + from periodic import Job +@@ -13,7 +13,7 @@ + + class Receiver(PhysicalReceiver): + def __init__( +- self, dimension, layout, previous=cold_swap_tape, *, direct=False, profile=COMPACT ++ self, dimension, layout, previous=cold_swap_tape, *, direct=False, profile=ENTRY + ): + if dimension < 2: + raise ValueError("Use a native rank of at least two") +--- a/independent_binary_price.py ++++ b/independent_binary_price.py +@@ -75,7 +75,7 @@ + paid[1] += ports + elif row[0] == "IDLE_ONE": + paid[len(row[2]) * caller["body_rank"]] += ports +- assert targets.total() == 18_906 and paid.total() == 104_904 ++ assert targets.total() == 18_906 and paid.total() == 104_652 + return targets, paid + + +--- a/ordinary_carrier.py ++++ b/ordinary_carrier.py +@@ -7,7 +7,7 @@ + + install() + from binary_receiver import Receiver +-from installations import COMPACT ++from installations import ENTRY + from module_atoms import ceil_root + from ordinary import least_power + from staged_carriers import entrance_logs +@@ -55,7 +55,7 @@ + root_body(source, target, digits, 1, gap, suffix, backend) + + +-def ordinary_swap(source, target, bits, prefix, gap, suffix, *, profile=COMPACT): ++def ordinary_swap(source, target, bits, prefix, gap, suffix, *, profile=ENTRY): + rank_logs = profile.rank_logs + if bits < 0 or min(prefix, gap, suffix) < 1: + raise ValueError("Use a nonnegative width and positive field dimensions") +--- a/retimed_supplier.py ++++ b/retimed_supplier.py +@@ -1,7 +1,5 @@ + """Run two column scales of the tagged 48-call word in the signed positive receiver.""" + +-from fractions import Fraction as F +-from collections import Counter + + from upstream import HERE, install + +@@ -10,15 +8,7 @@ + from periodic import Job + from raw48 import ComplexRaw + from spool import scratch, snapshot, transfer +-from strong_complex import artifacts +-from clock_ports import clock_word +-from transport import Recipe +-from installations import GAUSSIAN_C +-from unpowered_price import certify +- +- +-SCALES = (1, 8) +-SMALL_SPLITS = 1008 ++from grades import SCALES, SPLITS, numerical_source, numerical_recipe + + + class Raw: +@@ -48,45 +38,21 @@ + tag, job = next(actual) + if tag != label.tag or len(job.axes) != label.rank * width: + raise ArithmeticError("The physical cut differs from the installed word") +- if scale == 1 and label.rank == 1 and splits < SMALL_SPLITS: ++ if scale == 1 and label.rank == 1 and splits < SPLITS: + yield job.select(range(width // 2)) + yield job.select(range(width // 2, width)) + splits += 1 + else: + yield job +- if next(actual, None) is not None or (scale == 1 and splits != SMALL_SPLITS): ++ if next(actual, None) is not None or (scale == 1 and splits != SPLITS): + raise ArithmeticError("The numerical word did not close at its final loan") + + +-def source_ranks(tagged): +- targets = tuple(scale*p.rank for scale in SCALES for p in tagged.targets) +- slots = [] +- for scale in SCALES: +- splits = 0 +- for port in tagged.paid: +- if scale == 1 and port.rank == 1 and splits < SMALL_SPLITS: +- slots.extend((F(1, 2), F(1, 2))) +- splits += 1 +- else: +- slots.append(scale * port.rank) +- if scale == 1 and splits != SMALL_SPLITS: +- raise ArithmeticError("The base copy has too few rank-one requests") +- return targets, tuple(slots) +- +- + class Positive(RetainedPositive): +- def __init__(self, rank_log, denominator=10**14): +- atlas = artifacts( +- source / "research/grade14-native-realization", HERE / "inputs" +- ) +- native = clock_word(atlas) ++ def __init__(self, rank_log, denominator): ++ atlas, native, _, _, _ = numerical_source() + super().__init__(native, atlas, 1 << rank_log, denominator) +- +- targets, paid = source_ranks(native) +- margin, cells = certify(GAUSSIAN_C, (Counter(targets), Counter(paid))) +- if cells is None or margin <= 0: +- raise ArithmeticError("The Gaussian word has insufficient column capacity") +- self.recipe = Recipe(rank_log, max(SCALES)*native.ambient, targets, paid, cells, GAUSSIAN_C) ++ self.recipe = numerical_recipe(rank_log) + + @property + def owners(self): +--- a/strong_binary.py ++++ b/strong_binary.py +@@ -15,7 +15,7 @@ + from tagged_sources import BIT_CALLER, BIT_PIN, binary_ports, packed, pinned + + +-SOURCE_SHA256 = "74e93daf2b7acf794ffb51f92f03f51556f68126d41ee13a8969bddb4cbe6326" ++SOURCE_SHA256 = "9e7392c52bcf29c0cc58c54c619f95c28f476394c33e8e0a5aa30c9557d31362" + + + @cache +--- a/transport.py ++++ b/transport.py +@@ -102,6 +102,7 @@ + self.source_width = 0 + t = F(t) + measure = Measure(t, volume, max(256, 64 * n.bit_length())) ++ targets, paid = self.targets, self.paid + ids = defaultdict(list) + for i, k in enumerate(targets): + ids[k].append(i) +--- a/unpowered_price.py ++++ b/unpowered_price.py +@@ -11,13 +11,9 @@ + + + def ranks(): +- graph, layout = load_changed(HERE / "inputs") +- raw = word(graph, layout) +- target = Counter(scale*p.rank for scale in (1, 8) for p in raw.targets) +- paid = Counter(scale*p.rank for scale in (1, 8) for p in raw.paid) +- paid[1] -= 1008 +- paid[F(1, 2)] = 2016 +- return target, paid ++ from grades import numerical_source ++ _, _, targets, paid, _ = numerical_source() ++ return targets.histogram, paid.histogram + + + def intervals(r, t): diff --git a/research/tiered-native-multiplier/serial_setup.py b/research/tiered-native-multiplier/serial_setup.py new file mode 100644 index 0000000000..e3b51bf416 --- /dev/null +++ b/research/tiered-native-multiplier/serial_setup.py @@ -0,0 +1,139 @@ +"""Serial bit operations for the fixed installer's reduced rational arithmetic.""" + +from itertools import zip_longest + + +def canonical(word): + return word.lstrip("0") or "0" + + +def compare(a, b): + """Scan two canonical magnitudes from their high ends.""" + first = 0 + for x, y in zip_longest(a, b): + if x is None: + return -1 + if y is None: + return 1 + if not first: + first = (x > y) - (x < y) + return first + + +def combine(a, b, subtract=False): + """Add two magnitudes, or subtract b from a when a >= b.""" + output = [] + carry = 0 + for x, y in zip_longest(reversed(a), reversed(b), fillvalue="0"): + digit = (x == "1") + carry + (-1 if subtract else 1) * (y == "1") + carry, bit = divmod(digit, 2) + output.append("01"[bit]) + if carry == 1: + output.append("1") + if carry < 0: + raise ArithmeticError("negative magnitude") + return "".join(reversed(output)) + + +def times(a, b): + """Use one shift and at most one addition per digit of b.""" + r = "0" + for digit in b: + r = r + "0" + if digit == "1": + r = combine(r, a) + r = canonical(r) + return r + + +def quotient_remainder(a, b): + """Return the exact quotient and remainder of two canonical magnitudes.""" + if b == "0": + raise ZeroDivisionError + tail = iter(a) + for _ in b: + if next(tail, None) is None: + return "0", a + zero_tail = "".join("0" for _ in tail) + divisor = b + zero_tail + quotient = [] + for _ in "1" + zero_tail: + # The two words retain the dividend width throughout this loop. + take = a >= divisor + quotient.append("1" if take else "0") + if take: + a = combine(a, divisor, subtract=True) + divisor = "0" + divisor[:-1] + return canonical("".join(quotient)), canonical(a) + + +def signed(sign, mag): + return (1 if mag == "0" else sign, mag) + + +def sum_signed(x, y): + sx, a = x + sy, b = y + if sx == sy: + return signed(sx, canonical(combine(a, b))) + if compare(a, b) < 0: + sx, a, b = sy, b, a + return signed(sx, canonical(combine(a, b, subtract=True))) + + +def neg(x): + return signed(-x[0], x[1]) + + +def product_signed(x, y): + return signed(x[0] * y[0], times(x[1], y[1])) + + +def bezout(a, b): + """Return g,u,v with g >= 0 and u*a + v*b = g for signed integers.""" + sa, a = a + sb, b = b + unit, zero = (1, "1"), (1, "0") + rows = ((unit, zero), (zero, unit)) + if compare(a, b) < 0: + a, b = b, a + rows = rows[::-1] + while b != "0": + q, r = quotient_remainder(a, b) + old, current = rows + after = tuple(sum_signed(u, neg(product_signed(v, (1, q)))) + for u, v in zip(old, current)) + rows = current, after + a, b = b, r + x, y = rows[0] + return a, signed(sa * x[0], x[1]), signed(sb * y[0], y[1]) + + +def exact_quotient(a, b): + q, r = quotient_remainder(a, b) + if r != "0": + raise ArithmeticError("inexact division") + return q + + +def reduced(num, den): + if den[1] == "0": + raise ZeroDivisionError + g = bezout(num, den)[0] + return signed(num[0] * den[0], exact_quotient(num[1], g)), exact_quotient(den[1], g) + + +def rational(op, x, y): + """Evaluate a field operation on pairs of signed numerator and positive denominator.""" + a, b = x + c, d = y + if op == "/": + return reduced(product_signed(a, (1, d)), product_signed((1, b), c)) + denominator = product_signed((1, b), (1, d)) + if op == "*": + return reduced(product_signed(a, c), denominator) + if op not in ("+", "-"): + raise ValueError(op) + left = product_signed(a, (1, d)) + right = product_signed(c, (1, b)) + return reduced(sum_signed(left, right if op == "+" else neg(right)), denominator) diff --git a/research/tiered-native-multiplier/source/INSTALLER-NOTICE.md b/research/tiered-native-multiplier/source/INSTALLER-NOTICE.md new file mode 100644 index 0000000000..5299fe7196 --- /dev/null +++ b/research/tiered-native-multiplier/source/INSTALLER-NOTICE.md @@ -0,0 +1,9 @@ +Ali Romman directed this replacement of the fixed Gaussian setup, its binary quadratic path-sum implementation and the integration checks. The work received substantial OpenAI Codex assistance. The source graph, numerical compiler basis convention, physical multiplier and historical proofs retain their original attribution and Apache 2.0 notices. The frozen archive includes the notices for every directly consumed package. + +* Ali Romman's retimed program supplies the binary and numerical words, signed entry, growing precision and resource contracts. Clear1nsight supplied the six-stage comparator and the competing retimed endpoint. This package changes fixed generation and stored role descriptions at the seven-stage source's own price. [Retimed source and credits](https://github.com/aliromman/integer-mult-bounds/blob/dfd25d553a843a946ca0b94130a5ff8943e98fdd/research/retimed-native-multiplier/NOTICE.md) · [PR #8042](https://github.com/CrocSwap/integer-mult-bounds/pull/8042) · [PR #8044](https://github.com/CrocSwap/integer-mult-bounds/pull/8044) · [PR #8050](https://github.com/CrocSwap/integer-mult-bounds/pull/8050) +* The original P104 rational word, its directed helper changes and the 48-call schedule come from the real source consumed by the retimed construction. The sparse journal uses those signed formulas and chronological tie order. [PR #8027](https://github.com/CrocSwap/integer-mult-bounds/pull/8027) · [Physical catalogue and predecessor credit](https://github.com/aliromman/integer-mult-bounds/blob/6285dd829114705862e8d91facaedc1f31d3cfcb/research/single-band-native-carriers/NOTICE.md) +* The grade-14 source supplies the canonical frame construction, reduction to a paid Fourier rank, and the original independent all-column checker. The replacement reuses its signed Pauli arithmetic. Its new part computes the absolute phase by a binary quadratic sum and uses that calculation in the complete factor emitter. [Original grade construction and attribution](https://github.com/CrocSwap/integer-mult-bounds/blob/a7f99a5f5f919dd3ffb2987f90c1e7d6527feb1e/research/grade14-native-realization/NOTICE.md) · [Original Clifford compiler](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/shared-wire-split-composition/frozen/clifford_exact.py) + +Binary quadratic forms are an established representation of Clifford operations. Jeroen Dehaene and Bart De Moor describe that representation. Niel de Beaudrap and Steven Herbert give algorithms for stabilizer simulation with quadratic forms. Here the path sum produces the absolute phase of the repository's individual chart circuits and supplies the installed multiplier. [Dehaene and De Moor](https://arxiv.org/abs/quant-ph/0304125) · [de Beaudrap and Herbert](https://quantum-journal.org/papers/q-2022-09-15-803/) + +The historically selected result remains the authority for main. Peer review of the conditional scientific premises remains open. [Selected record](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/certificates/selected-result.json) diff --git a/research/tiered-native-multiplier/source/K7-NOTICE.md b/research/tiered-native-multiplier/source/K7-NOTICE.md new file mode 100644 index 0000000000..d1a9e0924d --- /dev/null +++ b/research/tiered-native-multiplier/source/K7-NOTICE.md @@ -0,0 +1,18 @@ +# Predecessor Credits and License Notice + +This package inherits code, mathematical constructions, pinned archives, and verification structure from prior work in `CrocSwap/integer-mult-bounds` under the Apache License, Version 2.0 (`LICENSE`). + +## Pinned Predecessor Contributions + +- **Ali Romman** (`PR #8027`, `PR #8030`, `PR #8040`, `PR #8042`): + - Original 111-port strong binary catalogue and word (`#8027`, `fb9b6a7b0d27da1cf98430893a3016bf811e2aa4`), retimed machine and archive baseline (`#8030`, `6285dd829114705862e8d91facaedc1f31d3cfcb`), and unpowered retimed seven-stage native multiplier architecture (`#8042`, `dfd25d553a843a946ca0b94130a5ff8943e98fdd`, including `transport.py`, `unpowered_price.py`, `retimed_supplier.py`, `raw_binary_stage.py`, `five_exchange.py`, `fiscal_scans.py`, `activation.py`, and verifier suite). +- **Clear1nsight** (`PR #8031`–`#8050`): + - Powered 6-stage retimed margin construction (`#8035`, `ea776471bf8ed143a0625cf2d7532f65d15eb5f9`), seven-stage dyadic endpoint refit at `numerical_H = 36000` (`#8050`, `328b858e24709495843abc751fcbf5df35a89da8`, `κ ≥ 0.003890115286594461`), and `binary` vs `Gaussian` sensitivity characterization. +- **ToikY** (`PR #8026`, `PR #8029`): + - Prior outer-caller and binary optimization groundwork feeding into the `strong-bit` construction family. +- **DreamingOfClouds** (`PR #7852`) & **Jerry Chen / CubeJerry** (`PR #7257`, `PR #7914`, `PR #7981`): + - Physical bank machine, 36-call catalogue interpreter, sparse weighted oracle verification (`#7981`), counted compiler (`1ca6b8111297ac2cc2dcfe5da0027656898f7589`), and CI research-package validator harness (`#7257`, `0618e75a22cec54d1651394ef83d088551b7f026`). + +## Present Contribution (`p104-k7-retimed-binary`) + +- Constructive 6-round (`k=2..7`) binary circuit modification `strong-bit-k7.json.gz` reducing `MOVE` instructions (`2803 -> 2796`), dirty private clears (`3433 -> 3426`), and paid linear rank sum (`285,600 -> 284,592`; `104,904 -> 104,652` paid ports) while preserving exact register semantics and unchanged 2-scale Gaussian receiver coupling (`GAUSSIAN_C = 2092819/2^29`). diff --git a/research/tiered-native-multiplier/source/K7-STACK-LEDGER.json b/research/tiered-native-multiplier/source/K7-STACK-LEDGER.json new file mode 100644 index 0000000000..2add885cf9 --- /dev/null +++ b/research/tiered-native-multiplier/source/K7-STACK-LEDGER.json @@ -0,0 +1,230 @@ +{ + "description": "Constructive binary graph reduction steps reaching seed_k7 from PR #8027/#8035 baseline", + "baseline_8027": { + "moves": 2803, + "dirty_clears": 3433, + "frames": 636, + "pairs": 2352, + "frame_gates": 44825, + "n_targets": 18906, + "n_paid": 104904, + "linear_paid_sum": 285600 + }, + "final_k7": { + "moves": 2796, + "dirty_clears": 3426, + "frames": 636, + "pairs": 2353, + "frame_gates": 44734, + "n_targets": 18906, + "n_paid": 104652, + "linear_paid_sum": 284592, + "gz_sha256": "9e7392c52bcf29c0cc58c54c619f95c28f476394c33e8e0a5aa30c9557d31362", + "raw_sha256": "f4a43e4e36ac734dea10a73dca496bf4a4f4a9804b903ea379483d0513d7abc3" + }, + "steps": [ + { + "k": 2, + "method": "quad_toggle_plus_thirdperm", + "details": { + "toggle": { + "D4": 519, + "q": 307, + "d2_cell": 134, + "d6_H": 398, + "d7s": [ + 551, + 546 + ], + "rk0": 7, + "rk_new": 8, + "rk_v1": 504, + "rk_tot": 519 + } + }, + "seed_name": "seed_k2.json.gz", + "gz_sha256": "10eebd653d0725b8229be327ede06cf546b3018d8d3ff6c6c7ad9a2872638fdf", + "raw_sha256": "f47580954b437dfdcef93e271fbbb19a836682a436cb54deaef4d5c4849a48da", + "moves": 2801, + "adds": 30960, + "dirty_clears": 3431, + "charts": { + "frames": 636, + "pairs": 2353, + "frame_gates": 44841 + }, + "n_targets": 18906, + "n_paid": 104832, + "linear_paid_sum": 285312, + "linear_target_sum": 286818, + "raw_c0_float": 0.003893181247910902 + }, + { + "k": 3, + "method": "quad_toggle_plus_thirdperm", + "details": { + "toggle": { + "D4": 522, + "q": 323, + "d2_cell": 213, + "d6_H": 471, + "d7s": [ + 628, + 527 + ], + "rk0": 7, + "rk_new": 8, + "rk_v1": 503, + "rk_tot": 519 + } + }, + "seed_name": "seed_k3.json.gz", + "gz_sha256": "5baf5494c8d073c6ff410b108ad909c2d12ed548479a2ec6e021b8f821f90ea6", + "raw_sha256": "69e7e3e66be4baeec96a8d1090f0037f98df7841323f2389f11690cad2c26669", + "moves": 2800, + "adds": 30899, + "dirty_clears": 3430, + "charts": { + "frames": 636, + "pairs": 2353, + "frame_gates": 44822 + }, + "n_targets": 18906, + "n_paid": 104796, + "linear_paid_sum": 285168, + "linear_target_sum": 286674, + "raw_c0_float": 0.003894716044279911 + }, + { + "k": 4, + "method": "quad_toggle_plus_thirdperm", + "details": { + "toggle": { + "D4": 523, + "q": 322, + "d2_cell": 231, + "d6_H": 453, + "d7s": [ + 631, + 526 + ], + "rk0": 8, + "rk_new": 9, + "rk_v1": 502, + "rk_tot": 519 + } + }, + "seed_name": "seed_k4.json.gz", + "gz_sha256": "8876015ef6c172da589f26e64a818b752feef266244ee49e4232fa8fe7173de8", + "raw_sha256": "f1c159a5d23dc09c9118ffbff957e277a7f3d542c7c3604b4b67783cc34547ac", + "moves": 2799, + "adds": 30961, + "dirty_clears": 3429, + "charts": { + "frames": 636, + "pairs": 2353, + "frame_gates": 44780 + }, + "n_targets": 18906, + "n_paid": 104760, + "linear_paid_sum": 285024, + "linear_target_sum": 286530, + "raw_c0_float": 0.003896252053038069 + }, + { + "k": 5, + "method": "thirdperm_rcv", + "details": { + "D4": 521 + }, + "seed_name": "seed_k5.json.gz", + "gz_sha256": "8dba3630679cdd232bba66234ea843011b097a2dc0cdbf61e4a608aea4099567", + "raw_sha256": "91a70d9c7aeecf56586f6bb63ec27c036294df6824372d6ccac2a7517e31a067", + "moves": 2798, + "adds": 30834, + "dirty_clears": 3428, + "charts": { + "frames": 636, + "pairs": 2353, + "frame_gates": 44769 + }, + "n_targets": 18906, + "n_paid": 104724, + "linear_paid_sum": 284880, + "linear_target_sum": 286386, + "raw_c0_float": 0.003897789275624352 + }, + { + "k": 6, + "method": "simul_quad_toggle", + "details": { + "toggle": { + "D4": 520, + "q": 292, + "d2_cell": 172, + "d6_H": 370, + "d7s": [ + 555, + 607 + ], + "rk0": 8, + "rk_new": 9, + "rk_v1": 499, + "rk_tot": 518 + } + }, + "seed_name": "seed_k6.json.gz", + "gz_sha256": "034cded61ad647b259ecb9f44425102960ae762949512a430dae960b9926bca5", + "raw_sha256": "98710327e4ebd9d4172dcbd0188be9091b1de19096e3fd1e5fea5b18a430126a", + "moves": 2797, + "adds": 30765, + "dirty_clears": 3427, + "charts": { + "frames": 636, + "pairs": 2353, + "frame_gates": 44756 + }, + "n_targets": 18906, + "n_paid": 104688, + "linear_paid_sum": 284736, + "linear_target_sum": 286242, + "raw_c0_float": 0.0038993277134807035 + }, + { + "k": 7, + "method": "simul_quad_toggle_thirdperm", + "details": { + "toggle": { + "D4": 524, + "q": 266, + "d2_cell": 248, + "d6_H": 439, + "d7s": [ + 632, + 629 + ], + "rk0": 8, + "rk_new": 9, + "rk_v1": 498, + "rk_tot": 518 + } + }, + "seed_name": "seed_k7.json.gz", + "gz_sha256": "9e7392c52bcf29c0cc58c54c619f95c28f476394c33e8e0a5aa30c9557d31362", + "raw_sha256": "f4a43e4e36ac734dea10a73dca496bf4a4f4a9804b903ea379483d0513d7abc3", + "moves": 2796, + "adds": 30588, + "dirty_clears": 3426, + "charts": { + "frames": 636, + "pairs": 2353, + "frame_gates": 44734 + }, + "n_targets": 18906, + "n_paid": 104652, + "linear_paid_sum": 284592, + "linear_target_sum": 286098, + "raw_c0_float": 0.0039008673680502896 + } + ] +} diff --git a/research/tiered-native-multiplier/source/activation.py b/research/tiered-native-multiplier/source/activation.py new file mode 100644 index 0000000000..20525c7fa3 --- /dev/null +++ b/research/tiered-native-multiplier/source/activation.py @@ -0,0 +1,80 @@ +"""Check the complete connected activation of a streamed raw-transport installation.""" + +from fractions import Fraction + + +def ceil_log2(n): + return (n-1).bit_length() + + +def binary_entries(rank_logs): + cuts = [] + for h in rank_logs: + minimum = (250*(h+64)+248)//249 + cuts.append(max(minimum,h+64+cuts[-1] if cuts else 0)) + return cuts + + +def full_entrance(last_cut, numerical): + target = last_cut + numerical + 102 + s = max(512,target) + while s - 7*ceil_log2(s) < target: + s = target + 7*ceil_log2(s) + log = ceil_log2(s) + after = 7*(log+1) + target + if (1<=target + assert (1<=target + return s-1 + + +def resource_receipt(profile): + ranks=tuple(profile.rank_logs) + num=profile.complex_log + m=len(ranks) + assert 1<=m<=7 + cuts=binary_entries(ranks) + A=full_entrance(cuts[-1],num) + s=A+1 + assert s>=6000 + # 8E < 33L/s and L <= p/6+3. The remaining excess is <= 34s+8. + # Then 5.5/s <= 11/12000, and p/12000 covers 34s+9 for every s>=6000. + assert (12000*(34*s+9)).bit_length() <= s-2 + for h in (num,*ranks): + assert h>=1024 + assert 68+83*h<92*h + assert 92*h<105*h and 92*h<448*h + assert (700*h).bit_length()<=h and (872*(4*h+1)).bit_length()<=h + assert (30*1024*h+120).bit_length()<=h-1 + for i,h in enumerate(ranks): + assert not i or cuts[i-1]+2=num+cuts[-1]+2 + assert profile.eta1024 and tail>1024 + delta=(-pow(2,A,6))%6 + assert delta in (2,4) + return {"binary_cuts":cuts,"public_exponent_A":A,"first_public_offset":delta, + "initial_s":s,"stage_and_outer_fixed_log_overhead":local, + "retimed_first_stripe_margin":slack,"retimed_all_size_margin_floor":tail, + "absolute_log2_private_control_envelope":job_log, + "storage_upper":"6.2 p T < 297.6 n bits"} diff --git a/research/tiered-native-multiplier/source/check_binary_k7.py b/research/tiered-native-multiplier/source/check_binary_k7.py new file mode 100644 index 0000000000..5d5d9173f4 --- /dev/null +++ b/research/tiered-native-multiplier/source/check_binary_k7.py @@ -0,0 +1,434 @@ +"""Check the constructive k7 binary circuit: replays, charts, sparse oracle, tariff, and #8027 control.""" + +from collections import Counter +from fractions import Fraction +from functools import cache +import gzip +from hashlib import sha256 +import json +from math import lcm +from pathlib import Path +from random import Random +import tarfile + +from installations import BINARY_C +from unpowered_price import certify + +PACKAGE_DIR = Path(__file__).resolve().parent +K7_GZ_SHA256 = "9e7392c52bcf29c0cc58c54c619f95c28f476394c33e8e0a5aa30c9557d31362" +K7_RAW_SHA256 = "f4a43e4e36ac734dea10a73dca496bf4a4f4a9804b903ea379483d0513d7abc3" +OLD_8027_GZ_SHA256 = "74e93daf2b7acf794ffb51f92f03f51556f68126d41ee13a8969bddb4cbe6326" + + +def check_archives_and_ledger(): + gz_bytes = (PACKAGE_DIR / "strong-bit-k7.json.gz").read_bytes() + assert sha256(gz_bytes).hexdigest() == K7_GZ_SHA256 + raw_bytes = gzip.decompress(gz_bytes) + assert sha256(raw_bytes).hexdigest() == K7_RAW_SHA256 + ledger = json.loads((PACKAGE_DIR / "K7-STACK-LEDGER.json").read_text(encoding="utf-8")) + final = ledger["final_k7"] + assert final["moves"] == 2796 + assert final["dirty_clears"] == 3426 + assert (final["frames"], final["pairs"], final["frame_gates"]) == (636, 2353, 44734) + assert (final["n_targets"], final["n_paid"], final["linear_paid_sum"]) == (18906, 104652, 284592) + assert final["gz_sha256"] == K7_GZ_SHA256 and final["raw_sha256"] == K7_RAW_SHA256 + return json.loads(raw_bytes) + + +def run_registers(program, starts, ends, ports): + count = len(starts) + frames = dict(enumerate(starts)) + values = {i: 1 << i for i in range(count)} + dirty = 0 + moves = 0 + for op, dest, *args in program: + if op == "MOVE": + before, after = args + assert frames[dest] == before + frames[dest] = after + moves += 1 + elif op == "ADD": + read, site = args + assert frames[dest] == frames[read] == site + values[dest] ^= values[read] + elif op == "SWAP": + (read,) = args + frames[dest], frames[read] = frames[read], frames[dest] + values[dest], values[read] = values[read], values[dest] + elif op == "INIT": + assert dest >= count and dest not in frames + frames[dest], values[dest] = args[0], 0 + elif op == "CLEAR": + assert dest >= count and frames.pop(dest) == args[0] + dirty += int(bool(values.pop(dest))) + else: + raise ValueError("Unknown graph instruction") + assert frames == dict(enumerate(ends)) + assert len(values) == count == 630 and ports == 111 + for i in range(count): + expected = 1 << i + if ports <= i < 2 * ports: + expected ^= 1 << (i - ports) + assert values[i] == expected + return dirty, moves + + +def check_outer_word(root): + def shift(terms, mask): + return {(role, exponent ^ mask) for role, exponent in terms} + + def stage_mask(stages): + mask = 0 + for stage in stages: + mask ^= 1 << stage + return mask + + head = 1 + words = [{(i, 0)} for i in range(root["roles"])] + for op, *args in root["events"]: + if op == "LOCAL": + stage, x, y = args + body = stage_mask((stage,)) + first, second = words[x], words[y] + words[x] = shift(first, body) + words[y] = shift(first, body ^ head) ^ shift(second, body) + elif op == "IDLE_ONE": + x, stages = args + words[x] = shift(words[x], stage_mask(stages)) + elif op == "QUERY": + x, y = args + words[x] ^= shift(words[y], head) + elif op == "ADD": + x, y = args + words[x] ^= words[y] + elif op == "SWAP": + x, y = args + words[x], words[y] = words[y], words[x] + else: + raise ValueError("Unknown caller instruction") + for i, (answer, diag) in enumerate(zip(words, root["diagonal"], strict=True)): + assert diag["q"] == 1 + assert answer == {(i, head ^ stage_mask(diag["stages"]))} + + +def matrix_product(a, b): + cols = list(zip(*b, strict=True)) + return [[sum(x * y for x, y in zip(u, v, strict=True)) for v in cols] for u in a] + + +def integer_matrix(a): + den = lcm(*(v.denominator for row in a for v in row)) + assert den % 3 + return den, [[int(v * den) for v in row] for row in a] + + +def rational_word(frame): + from factored_frames import inverse_word + from ternary_frames import identity + from vendor.cover import row_program + + word = row_program(frame, 3) + back = tuple(inverse_word(word)) + for program, base, goal in [ + (word, identity(len(frame)), frame), + (back, frame, identity(len(frame))), + ]: + rows = [list(row) for row in base] + for op, i, *args in program: + if op in ("scale", "add"): + q = Fraction(args[-1]) + assert q.denominator % 3 and max(abs(q.numerator), q.denominator) <= 20 + if op == "scale": + assert q.numerator % 3 + for row in rows: + if op == "scale": + row[i] *= q + elif op == "add": + row[i] += row[args[0]] * q + elif op == "swap": + j = args[0] + row[i], row[j] = row[j], row[i] + else: + raise ValueError("Unknown frame instruction") + assert rows == goal + return len(word) + + +def check_charts(data, ports): + from ternary_frames import frame_at_three, identity, projector, transpose + + frames, starts, ends = data["frames"], data["start"], data["final"] + ops = data["program"] + projectors, splits = [], [] + ident = identity(8) + for i in range(len(frames)): + spec = frames[str(i)] + p = projector(transpose(spec["B"] + spec["A"]), spec["dim"]) + projectors.append(p) + den, m = integer_matrix(p) + assert matrix_product(m, m) == [[den * x for x in row] for row in m] + splits.append((den, m)) + pairs = {tuple(row[2:]) for row in ops if row[0] == "MOVE"} + pairs.update(zip(starts[2 * ports :], ends[2 * ports :], strict=True)) + pairs = {tuple(sorted(pair, key=lambda j: frames[str(j)]["dim"])) for pair in pairs} + steps = 0 + for i, j in sorted(pairs): + di, pi = splits[i] + dj, pj = splits[j] + lifted = [[dj * x for x in row] for row in pi] + assert matrix_product(pi, pj) == matrix_product(pj, pi) == lifted + delta = [ + [y - x for x, y in zip(a, b, strict=True)] + for a, b in zip(projectors[i], projectors[j], strict=True) + ] + basis, rank = frame_at_three(delta) + assert rank == frames[str(j)]["dim"] - frames[str(i)]["dim"] + den, m = integer_matrix(delta) + assert matrix_product(m, basis) == [ + [den * v if col < rank else 0 for col, v in enumerate(row)] for row in basis + ] + steps += rational_word(basis) + for i in range(ports): + head, body = projectors[starts[i]], projectors[ends[ports + i]] + assert len(frames[str(starts[i])]["B"]) == 1 + assert projectors[ends[i]] == ident + assert all(x == 0 for row in projectors[starts[ports + i]] for x in row) + assert [ + [x + y for x, y in zip(a, b, strict=True)] for a, b in zip(head, body, strict=True) + ] == ident + basis = transpose(frames[str(starts[i])]["B"] + frames[str(ends[ports + i])]["B"]) + steps += rational_word(basis) + return len(projectors), len(pairs), steps + + +def raw_moments(data, root): + ports = root["ports"] + dims = {int(idx): frame["dim"] for idx, frame in data["frames"].items()} + targets = Counter() + paid = Counter() + local = sum(row[0] == "LOCAL" for row in root["events"]) + for row in root["diagonal"]: + targets[1 + root["body_rank"] * len(row["stages"])] += ports + for src, dst in zip(data["start"][2 * ports :], data["final"][2 * ports :], strict=True): + targets[abs(dims[dst] - dims[src])] += local + for row in data["program"]: + if row[0] == "MOVE": + paid[abs(dims[row[3]] - dims[row[2]])] += local + for row in root["events"]: + if row[0] == "QUERY": + paid[1] += ports + elif row[0] == "IDLE_ONE": + paid[len(row[2]) * root["body_rank"]] += ports + return targets, paid + + +def check_weighted_sparse(data, root): + from check_raw_delta import Sparse, right_columns + from strong_binary import StrongBinarySource + from direct_body import direct_actions, direct_factors + from factored_frames import Frame, inverse_word + from periodic import Job + from raw_binary import Axis, job_frame + from tagged_sources import binary_ports + from ternary_frames import residue + + source = binary_ports(data, root) + seeds = {0, 111, 114, len(source.targets) - 1} + for grade in (4, 8): + seeds.add( + next( + i + for i, port in enumerate(source.targets) + if port.tag[0] == "helper" and port.rank == grade + ) + ) + for modulus, columns in ((3, 1), (9, 2)): + n = source.ambient * columns + ident = tuple(bytes(int(x == y) for x in range(n)) for y in range(n)) + rng = Random(7914) + units = [x for x in range(modulus) if x % 3] + A = [rng.choice(units) for _ in range(n)] + Ai = [pow(a, -1, modulus) for a in A] + + @cache + def scaled_word(word): + out = [] + for op, tail, i, j, coeff in direct_actions(word, 1): + a = residue(coeff, modulus) + if not tail and op == "swap": + a = A[i] * Ai[j] % modulus + elif not tail and op == "add": + a = a * A[j] * Ai[i] % modulus + out.append((op, tail, i, j, a)) + return tuple(out) + + @cache + def factors(word, axis): + u, v = direct_factors(Frame(n, word, (axis,)), modulus) + return bytes(u), bytes(v) + + class DirectSparse(Sparse): + dimension = n + + def route(self, owner, word): + if not self.values[owner]: + return + self.active_routes += 1 + out = set() + for label, h, t in self.values[owner]: + pair = list(h), list(t) + for op, tail, i, j, a in scaled_word(word): + bank = pair[tail] + if op == "swap": + bank[i], bank[j] = ( + a * bank[j] % modulus, + pow(a, -1, modulus) * bank[i] % modulus, + ) + elif op == "scale": + bank[i] = a * bank[i] % modulus + else: + bank[j] = (bank[j] + a * bank[i]) % modulus + out.add((label, bytes(pair[0]), bytes(pair[1]))) + self.values[owner] = out + + def pay(self, job): + if not self.values[job.owner]: + return + self.active_paid += 1 + frame = job_frame(job, n) + out = set() + for label, h, t in self.values[job.owner]: + d = [(y - ai * x) % modulus for x, ai, y in zip(h, Ai, t, strict=True)] + change = [0] * n + for axis in frame.mask: + u, v = factors(frame.word, axis) + coeff = sum(x * y for x, y in zip(v, d, strict=True)) % modulus + if coeff: + change = [ + (x + coeff * y) % modulus for x, y in zip(change, u, strict=True) + ] + self.moved += any(change) + out.add( + ( + label, + bytes( + (x + a * v) % modulus for x, a, v in zip(h, A, change, strict=True) + ), + bytes((y - v) % modulus for y, v in zip(t, change, strict=True)), + ) + ) + self.values[job.owner] = out + + banks = DirectSparse(None, modulus) + entries, expected = [], {} + for i, port in enumerate(source.targets): + owner = banks.zero() + if i in seeds: + g = ( + ("add", 7, 113, Fraction(4, 5)), + ("swap", 0, 126), + ("scale", 4, Fraction(-2)), + ("add", 0, 32, 2), + ("add", 7, 0, i % 4 + 1), + ) + axes = tuple(Axis(g, j) for j in range(port.rank * columns)) + h, t = (bytes(rng.randrange(modulus) for _ in range(n)) for _ in range(2)) + banks.values[i].add((i, h, t)) + data_mat = right_columns(ident, g, modulus) + inv = right_columns(ident, tuple(inverse_word(g)), modulus) + diff = [(y - ai * x) % modulus for x, ai, y in zip(h, Ai, t, strict=True)] + local = [ + sum(col[j] * x for col, x in zip(inv, diff, strict=True)) % modulus + for j in range(port.rank * columns) + ] + change = [ + sum(data_mat[j][k] * entry for j, entry in enumerate(local)) % modulus + for k in range(n) + ] + expected[i] = { + ( + i, + bytes((x + a * v) % modulus for x, a, v in zip(h, A, change, strict=True)), + bytes((y - v) % modulus for y, v in zip(t, change, strict=True)), + ) + } + else: + axes = tuple(range(port.rank * columns)) + entries.append((port.tag, Job(owner, axes))) + count = 0 + for (tag, job), paid in zip( + StrongBinarySource(banks).raw(entries, columns), source.paid, strict=True + ): + assert tag == paid.tag and len(job.axes) == paid.rank * columns + banks.pay(job) + count += 1 + assert count == 104652 and len(banks.values) == len(entries) == 18906 + wrong = [k for k, v in banks.values.items() if v != expected.get(k, set())] + assert not wrong, wrong[:3] + + +def check_predecessor_8027_fails_binary_c(root): + tar_path = PACKAGE_DIR / "predecessor" / "predecessor-8030.tar.gz" + with tarfile.open(tar_path, "r:gz") as archive: + member = archive.getmember("strong-bit.json.gz") + with archive.extractfile(member) as f: + old_gz = f.read() + assert sha256(old_gz).hexdigest() == OLD_8027_GZ_SHA256 + old_data = json.loads(gzip.decompress(old_gz)) + old_targets, old_paid = raw_moments(old_data, root) + assert (old_targets.total(), old_paid.total()) == (18906, 104904) + try: + margin, cells = certify(BINARY_C, (old_targets, old_paid)) + except (AssertionError, ValueError): + return + assert cells is None or margin <= 0, "PR #8027 binary source unexpectedly certified at k7 BINARY_C" + + +def check(): + from strong_binary import caller, graph + + k7_from_pkg = check_archives_and_ledger() + data, root = graph(), caller() + assert data == k7_from_pkg + assert sum(r[0] == "LOCAL" for r in root["events"]) == 36 + dirty, moves = run_registers(data["program"], data["start"], data["final"], root["ports"]) + assert (dirty, moves) == (3426, 2796) + check_outer_word(root) + frames, pairs, steps = check_charts(data, root["ports"]) + assert (frames, pairs, steps) == (636, 2353, 44734) + + targets, paid = raw_moments(data, root) + assert (targets.total(), paid.total()) == (18906, 104652) + linear_t = sum(r * c for r, c in targets.items()) + linear_p = sum(r * c for r, c in paid.items()) + assert (linear_t, linear_p) == (286098, 284592) + signed = {r: targets[r] - paid[r] for r in targets.keys() | paid.keys() if targets[r] != paid[r]} + expected_signed = dict(enumerate((-48720, -45144, -1980, -396, -1296, -2664, -480), 1)) + expected_signed.update({8: 14268, 64: 444, 127: 222}) + for low in range(14, 57, 7): + expected_signed[low] = -444 + expected_signed[low + 1] = 444 + assert signed == expected_signed + + margin, cells = certify(BINARY_C, (targets, paid)) + assert cells is not None and len(cells) == 24 and margin > 0 + + check_weighted_sparse(data, root) + check_predecessor_8027_fails_binary_c(root) + print( + "PASS_K7_BINARY_CIRCUIT", + f"moves={moves}", + f"dirty={dirty}", + f"targets={targets.total()}", + f"paid={paid.total()}", + f"linear_paid={linear_p}", + f"frames={frames}", + f"pairs={pairs}", + f"frame_gates={steps}", + f"cells={len(cells)}", + "control_8027=rejected", + ) + + +if __name__ == "__main__": + check() diff --git a/research/tiered-native-multiplier/source/installer.tar.gz b/research/tiered-native-multiplier/source/installer.tar.gz new file mode 100644 index 0000000000..2595a83633 Binary files /dev/null and b/research/tiered-native-multiplier/source/installer.tar.gz differ diff --git a/research/tiered-native-multiplier/source/ordinary_clock.py b/research/tiered-native-multiplier/source/ordinary_clock.py new file mode 100644 index 0000000000..87c72664af --- /dev/null +++ b/research/tiered-native-multiplier/source/ordinary_clock.py @@ -0,0 +1,49 @@ +"""Check integer envelopes in the ordinary fixed-tape clock proof.""" + +from fractions import Fraction + +RANKS = { + '8030-compact': (260_000, 1_600_000), + '8030-high': (25_000_000, 160_000_000, 1_000_000_000, 6_000_000_000, 36_000_000_000, 224_000_000_000), + '8030-match': tuple(7*x for x in (25_000_000, 160_000_000, 1_000_000_000, 6_000_000_000, 36_000_000_000, 224_000_000_000)), + '8035-near': (6_835_937_536, 109_375_000_000, 1_750_000_000_000, 28_000_000_000_000, 448_000_000_000_000, 7_168_000_000_000_000), + '8035-fixed': (106_811_524, 1_708_984_375, 27_343_750_000, 437_500_000_000, 7_000_000_000_000, 112_000_000_000_000), +} + + +def polynomial_to_fibre_bound(): + # X=2^16 N^4 (D+1)(w+1)^252, D+1<=256(w+1). + # w+1<=2^259*u^258; u^a/3^(u-1)<=3*a^a. + degree = 20 * 253 + a = 258 * degree + return 20 * (16 + 8) + 259 * degree + 2 + a * (a - 1).bit_length() + + +def first_stage_bound(eta): + assert eta >= Fraction(97,25000) and 2*eta > Fraction(1,250) + # u >= ceil(e^eta)/2, hence w+1 <= 9u^2. Bound u^a/3^(u-1) by 3a^a. + degree = 20*253 + a = 2*degree + return 20*(16+8)+4*degree+2+a*(a-1).bit_length() + + +def full_log2_B(ranks): + # B0=2^100, B_i<=J_i^14(1+Bprev); root binary rectangle and digit rounding. + return 40 + 16 * 1024 * sum(ranks) + + +def main(): + extra = polynomial_to_fibre_bound() + assert Fraction(9*16, 15*32) == Fraction(3, 10) + assert Fraction(1,1) / (1-Fraction(3,10)) == Fraction(10,7) + assert all((1+y)**5 <= 2**14 * max(1, 2**(y-1)) for y in range(1, 11)) + assert all((z+1)**5 <= 2**10*3**z for z in range(1, 8)) + assert all((e+1)**5 <= 32*4**e for e in range(1, 8)) + assert all(extra + 80*min(H) < 1024*min(H) for H in RANKS.values()) + print('log2 fixed variable-amortization factor <=', extra, 'plus 80 H') + for name, H in RANKS.items(): + print(name, 'sum H', sum(H), 'log2 B <=', full_log2_B(H)) + + +if __name__ == '__main__': + main() diff --git a/research/tiered-native-multiplier/source/outer_budget.py b/research/tiered-native-multiplier/source/outer_budget.py new file mode 100644 index 0000000000..35dd5cf836 --- /dev/null +++ b/research/tiered-native-multiplier/source/outer_budget.py @@ -0,0 +1,40 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Directed rational outer inequalities for the inherited parameterized signed caller. + +The 54 strict and four functional expressions follow the P104 dual-supplier +gate at 4f7c67ae387cc91580f469aeda4d508b372b9ec1. The positive and ordinary +caps come independently from the actual single-band profiles. +""" +from fractions import Fraction as Q + + +def margins(k,g,ordinary,positive): + a,b,q=k+4*g,k+5*g,k+3*g + ep,be=1-g,1-3*g + r0=g/10 + sigma,tau=1-b,1-a + internal=tau+(1-g)*max(sigma-tau,0) + leaf=sigma+g*(1-sigma) + lam=1-(q+a)/2 + xi=ep*(1+q)-Q(3,32)+g + key=be+1-ep + powers=[ep*q,a,1-ep+q*be,1-ep+a*be,1-ep+be,Q(3,32)+xi-ep, + xi+Q(1,2)-ep,ep,1-(ep+be+48-128+2)] + strict=[ordinary-a,b-a,q,b-q,a-q,g,1-g,(1-g)*b-a,1-internal-q,1-leaf-q, + lam-tau,lam-sigma,lam-internal,1-q-lam,1-q-leaf,ep,1-ep,xi-Q(1,2),ep-xi, + be,ep-be,1-be,1-(2*xi-2)-r0-be,1-(2*xi-2)-be,1-ep-r0,1-ep,r0,1-key, + 1-be-2*(1-ep),128-48-be,g,ep-a,Q(1,32)-b,Q(2**45-7**16),Q(2),2-xi, + Q(5),1-be,1-be,1-ep,powers[2]-powers[0],g,k-Q('.001730970419199163702738'), + 1-ep,Q(11,2)]+[x-k for x in powers] + functional=[1-be,be*(1-Q(3,1000)),128-48-ep-be-1,be*(1-Q(1,250))] + assert len(strict)==54 and len(functional)==4 + return strict,functional,positive-b + + +def qualify(k,g,ordinary,positive): + strict,functional,paid=margins(k,g,ordinary,positive) + if min(*strict,*functional,paid)<=0: + raise ArithmeticError('signed outer budget has an unfunded inequality') + return {'strict':len(strict),'functional':len(functional), + 'smallest_margin':str(min(*strict,*functional,paid)), + 'ordinary_margin':str(ordinary-k-4*g),'positive_margin':str(paid)} diff --git a/research/tiered-native-multiplier/source/outer_clock.py b/research/tiered-native-multiplier/source/outer_clock.py new file mode 100644 index 0000000000..3c4fa183a0 --- /dev/null +++ b/research/tiered-native-multiplier/source/outer_clock.py @@ -0,0 +1,114 @@ +"""Check the finite endpoints and the dyadic induction comparisons for the outer clock.""" + +from fractions import Fraction +from itertools import chain + + +def width_cap(s): + if s < 512: + return 128 * s * s + return 1024 * s + 2560 + + +def private_log(s): + # X=2^64(t+2)(P+2), P<2^20 p, d<=p<2^s. + return s + 1024 * (width_cap(s) + s + 88) + + +def controls_log(s): + # Dense Beneš, inverse modulo the true side, restored left child, and all copies. + return 60 + 16 * (s + 1) + 10 * (width_cap(s) + 1) + + +def exact_shape_check(package): + from pathlib import Path + import sys + + sys.path.insert(0, str(Path(package).resolve())) + import band_product + from linear_geometry import parameters, square_sides + + first = (18508 << 18493) + 1 + assert parameters(first - 1) is None + shape = parameters(first) + assert shape.count == 1 + side, = square_sides(shape) + bits = next(shape.axes()) + assert side.bit_length() == bits + actual_precision = band_product.precision(shape.public, shape.extent_bits, shape.count) + # The production fourier_axis function calls [Fraction(1)] * r. This reproduces + # its host list limit before any large allocation. It is not a Turing lower bound. + try: + [None] * side + except OverflowError as exc: + host = type(exc).__name__ + else: + raise AssertionError("The first side unexpectedly fit a host list") + + # The two-endpoint assertions bind all advertised finite constants to the producer. + return {"first_b": shape.public // 6, "first_L": bits, "first_P": actual_precision, + "first_side_bit_length": side.bit_length(), "host_list": host} + + +def financial_checks(): + # At s>=32 the private setup fits in n. Compare one term with an exponential + # and use (s+2)^2<2(s+1)^2 on the tail. The linear cap only decreases at s=512. + # p=6b, s=ceil(log2(6b+2)), and n>2^(b-1) when n>1. + def prefix_log(s): + lower = max(0, ((1 << (s-1))-2)//6-1) + return private_log(s)-lower + prefix = max(prefix_log(s) for s in range(1,32)) + assert prefix < 84_500_000-1000 and prefix == prefix_log(27) + assert 32 + 1024 * (128 * 32**2 + 32 + 88) < 1 << (32 - 4) + assert max(controls_log(s) for s in range(1, 64)) < 1 << 23 + assert 128 * 63**2 == 508_032 + for s in chain(range(32, 1025), (4096, 8192)): + assert private_log(s) < 1 << (s - 4) + if s >= 64: + # Use p>=2^(s-1)-1 and L>=p/12. The polynomial has its + # maximum relative to the exponential at the first endpoint. + p_min = (1 << (s - 1)) - 1 + L_min = p_min // 12 + G_max = 64 * (width_cap(s) + s) + assert L_min >= 10100 * G_max + assert L_min // (2 * width_cap(s)) >= 51_200 + H_min = L_min // 101 + assert controls_log(s) + 16 < H_min + assert private_log(s) + 16 < H_min + # Scalar fallback is impossible at b >= 2^15. On 2^j<=b<2^(j+1), + # ceil(log2(p+2))<=j+4; L >= 2^j-j-1. Growth closes all later j. + for j in range(15, 128): + assert (1 << j) - j - 1 >= 64 * (j + 4)**2 + assert 2 * (j + 4)**2 >= (j + 5)**2 + for s in (512, 1023, 1024, 4096): + ell = width_cap(s) + h_mixing_class = 80_000 * (ell + 2)**6 + 2048 * s + 2 + pack_pass = 40_000 * (ell + 2)**6 + 4 + assert 3 * h_mixing_class * pack_pass < (1 << 168) * (s + 1)**12 + # Each switch has at most 20 whole swaps, and each tail has two. + K = 64 * 64 * (ell + s) + crt_dispatch = 3 * s * 2 * ell * (1 << 18) * (10 + 32 * K + 4 * K*K) + assert crt_dispatch < (1 << 90) * (s + 1)**4 + g = Fraction(1, 10**17) + assert (Fraction(128, 1) / g)**16 < 1 << 1024 + assert 17**16 * 10**(21*16) < 1 << 1182 + assert 400 + 1182 + 9 + 2 < 1600 + return {"small_stop_tail_factor_log2":1591, "private_prefix_log2": max(private_log(s) for s in range(1, 32)), + "controls_prefix_log2": max(controls_log(s) for s in range(1, 64)), + "private_prefix_after_input_log2": prefix, + "early_log2_C_bound": 84_500_000, + "tail_log2_fixed_factor_including_b_to_n": 1434, + "tail_unit": "(1 + B + Z) * n * (1 + log2(n))^(1-kappa)"} + + +if __name__ == "__main__": + from argparse import ArgumentParser + import json + + command = ArgumentParser(description=__doc__) + command.add_argument("package", nargs="?") + args = command.parse_args() + report = financial_checks() + if args.package: + report.update(exact_shape_check(args.package)) + print(json.dumps(report, sort_keys=True)) diff --git a/research/tiered-native-multiplier/source/strong-bit-k7.json.gz b/research/tiered-native-multiplier/source/strong-bit-k7.json.gz new file mode 100644 index 0000000000..f334b505e6 Binary files /dev/null and b/research/tiered-native-multiplier/source/strong-bit-k7.json.gz differ diff --git a/research/tiered-native-multiplier/verify.py b/research/tiered-native-multiplier/verify.py new file mode 100644 index 0000000000..e87b02c8d9 --- /dev/null +++ b/research/tiered-native-multiplier/verify.py @@ -0,0 +1,90 @@ +"""Replay one scope on a fresh, authenticated signed multiplier.""" + +from pathlib import Path +from tempfile import TemporaryDirectory +from subprocess import run +import json +import sys + +PACKAGE = Path(__file__).resolve().parent +sys.path.insert(0, str(PACKAGE)) +from bootstrap import install + + +def worker(name, target): + cmd = [sys.executable, "-IB", str(PACKAGE / name), str(target)] + return run(cmd, check=True, capture_output=True, text=True).stdout + + +def check_binary(): + from upstream import install as activate + activate() + sys.path.append(str(PACKAGE / "source")) + from check_binary_k7 import check_archives_and_ledger, check_charts, check_outer_word + from check_binary_k7 import check_weighted_sparse, run_registers + from strong_binary import caller, graph + g, root = graph(), caller() + assert g == check_archives_and_ledger() + assert sum(v[0]=="LOCAL" for v in root["events"]) == 36 + assert run_registers(g["program"], g["start"], g["final"], root["ports"]) == (3426,2796) + check_outer_word(root) + assert check_charts(g,root["ports"]) == (636,2353,44734) + check_weighted_sparse(g,root) + print("PASS_K7_ALL_630_ROLES_AND_WEIGHTED_ROUTES") + + +def check_product(): + from band_product import multiply, multiply_tapes + from check_product import physical_product + from installations import ENTRY, TERMINAL + from io import BytesIO + + for a,b in ((0,0),(-1,0),(-1,-1),(-741503,466013),(741503,466013), + (2**127-1,-2**73+3),(-(2**4096+9),2**41-1)): + assert multiply(a,b) == a*b + for profile in (ENTRY,TERMINAL): + left = BytesIO(b"pre"+(741503).to_bytes(6,"little")+b"post") + right = BytesIO(b"pre"+(466013).to_bytes(5,"little")+b"end") + left.seek(3) + right.seek(3) + out = BytesIO() + sign, size = multiply_tapes(left,6,right,5,out,left_negative=True,profile=profile) + assert sign and size == 5 and -int.from_bytes(out.getvalue(),"little") == -345550037539 + assert left.tell()==3 and right.tell()==3 + result = physical_product(ENTRY) + assert result["coefficients_prefix"] == [11811,10996,4152,868,77] + print(json.dumps(result,sort_keys=True)) + print("PASS_SIGNED_PRODUCT_AND_RESTORATION") + + +def main(scope): + if not __debug__: + raise RuntimeError("Enable Python assertions for this replay") + with TemporaryDirectory(prefix="tier-machine-") as name: + dst = Path(name) + install(dst) + sys.path.insert(0, str(dst)) + if scope == "price": + receipt = json.loads(worker("receipt.py",dst)) + assert receipt == json.loads((PACKAGE/"RESULT.json").read_bytes()) + print(worker("check_placement.py",dst),end="") + print("PASS_COMPLETE_RATE_STOCK_AND_CLOCK",receipt["complete_log2_C"]) + elif scope == "binary": + check_binary() + elif scope == "gaussian": + print(worker("check_gaussian.py",dst),end="") + print(worker("check_phase_passes.py",dst),end="") + elif scope == "setup": + measured = json.loads(worker("check_serial_setup.py",dst)) + assert measured == json.loads((PACKAGE/"MEASUREMENTS.json").read_bytes())["serial_setup"] + print("PASS_SERIAL_FIXED_INSTALL", measured["setup_exponent"]) + elif scope == "product": + check_product() + elif scope == "interval": + print(worker("independent_price.py",dst),end="") + else: + raise ValueError("Unknown replay scope") + + +if __name__ == "__main__": + main(sys.argv[1])