From 879fcb8d6a4f63e53a2d19a80efee326ca0d653f Mon Sep 17 00:00:00 2001 From: Chris R Date: Fri, 20 Nov 2026 20:30:07 +1100 Subject: [PATCH 1/2] Prove the exact threshold for fusing two congruent products Include the direct residue and channel proofs, reversible circuit prices and pinned Gaussian caller controls. --- research/recursive-dot-carry/CALLERS.md | 35 ++ research/recursive-dot-carry/PROOF.md | 54 +++ research/recursive-dot-carry/README.md | 39 ++ research/recursive-dot-carry/RESULT.json | 74 ++++ research/recursive-dot-carry/REVIEW.md | 47 ++ research/recursive-dot-carry/SOURCES.json | 18 + research/recursive-dot-carry/TASK.json | 91 ++++ research/recursive-dot-carry/VERIFY.json | 19 + .../recursive-dot-carry/caller-evidence.json | 402 +++++++++++++++++ research/recursive-dot-carry/circuits.py | 117 +++++ .../recursive-dot-carry/diagonal/PROOF.md | 63 +++ .../recursive-dot-carry/diagonal/RESULT.json | 298 +++++++++++++ .../diagonal/independent-twist.json | 119 +++++ .../diagonal/independent_twist.py | 135 ++++++ .../recursive-dot-carry/diagonal/verify.py | 372 ++++++++++++++++ .../recursive-dot-carry/gaussian/PROOF.md | 45 ++ .../gaussian/REGRESSION.json | 126 ++++++ .../gaussian/SOURCE-BLOBS.json | 22 + .../recursive-dot-carry/gaussian/check.py | 417 ++++++++++++++++++ research/recursive-dot-carry/independent.py | 310 +++++++++++++ .../recursive-dot-carry/reference-price.json | 114 +++++ research/recursive-dot-carry/verify.py | 98 ++++ 22 files changed, 3015 insertions(+) create mode 100644 research/recursive-dot-carry/CALLERS.md create mode 100644 research/recursive-dot-carry/PROOF.md create mode 100644 research/recursive-dot-carry/README.md create mode 100644 research/recursive-dot-carry/RESULT.json create mode 100644 research/recursive-dot-carry/REVIEW.md create mode 100644 research/recursive-dot-carry/SOURCES.json create mode 100644 research/recursive-dot-carry/TASK.json create mode 100644 research/recursive-dot-carry/VERIFY.json create mode 100644 research/recursive-dot-carry/caller-evidence.json create mode 100644 research/recursive-dot-carry/circuits.py create mode 100644 research/recursive-dot-carry/diagonal/PROOF.md create mode 100644 research/recursive-dot-carry/diagonal/RESULT.json create mode 100644 research/recursive-dot-carry/diagonal/independent-twist.json create mode 100644 research/recursive-dot-carry/diagonal/independent_twist.py create mode 100644 research/recursive-dot-carry/diagonal/verify.py create mode 100644 research/recursive-dot-carry/gaussian/PROOF.md create mode 100644 research/recursive-dot-carry/gaussian/REGRESSION.json create mode 100644 research/recursive-dot-carry/gaussian/SOURCE-BLOBS.json create mode 100644 research/recursive-dot-carry/gaussian/check.py create mode 100644 research/recursive-dot-carry/independent.py create mode 100644 research/recursive-dot-carry/reference-price.json create mode 100644 research/recursive-dot-carry/verify.py diff --git a/research/recursive-dot-carry/CALLERS.md b/research/recursive-dot-carry/CALLERS.md new file mode 100644 index 0000000000..ed60448505 --- /dev/null +++ b/research/recursive-dot-carry/CALLERS.md @@ -0,0 +1,35 @@ +# Where the two products are consumed + +## Gaussian integer multiplication + +In aliromman's #7834, the pointwise multiplication forms $ac-bd$ and $ad+bc$ before truncating each component. The synthetic ring join similarly forms both signed sums before it decodes the packed limbs, folds the negacyclic output, and drops to the fixed grid. These are genuine sites to change the scalar products while preserving the observations. Moving an individual rounding operation can change the result. For example, at divisor four, the pairs $(3,1)$ and $(4,0)$ have the same sum and different sums of individual truncations. The original implementation also checks the recovered complex residual and the final carry. [Pinned pointwise source](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/fine-prime-gaussian-product/fine_ring.py#L118-L130) · [Packed ring join](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/fine-prime-gaussian-product/fine_ring.py#L332-L390) · [Recovery to the final integer](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/fine-prime-gaussian-product/product.py#L121-L170) + +Two optional source replays exercise the pinned implementation. Their savings overlap at some sites. Each count compares its own variant with the original code. + +* **Direct complex products.** A signed version of the classical three-product identity chooses a sum or difference separately on each input, keeping the largest product operand at or below its original side maximum. For example, on four components equal to $2^{8191}+1$, the conventional sum in $(a+b)(c+d)$ crosses the implementation's 8,192-bit cutoff. The sign choice avoids that extra wide dispatch. In four complete finite multiplications on the emitted $5\times7$ grid, ordinary word-product dispatches fell from **74,655 to 62,284** each. The input widths include a 20-by-19-bit example and a 144-by-144-bit example. Full product, coefficient vector, recorded error, tape movement and cleanup agreed. Both versions made zero wide-worker calls on those four runs. A complete 145-bit run reached its CPU limit before returning. The measured quantity is a count of multiplication dispatches, with extra combinations and branch work in the variant. [Sign choices, added work and scope](gaussian/PROOF.md) · [20-bit receipt](gaussian/REGRESSION.json) +* **Chirp twist.** Equal or nearly equal coefficient components give an ordinary product and a signed correction in each returned component. Exact equal-magnitude coefficients occur at the two diagonal angles of the first payload twist when its power-of-two radix is at least eight. This saves four scalar dispatches per outer tuple at these two positions. On a complete $8\times8$ middle call with the emitted 128-bit precision, applying the guarded edit across the diagonal passes gave **1,728 to 1,664** calls in each transform direction with identical output words. The emitted $32\times32$, 96-bit geometry gave **26,880 to 26,624**. The optional 8,200-bit precision control has a nonzero correction that affects the answer. It is a direct subroutine fixture external to the top-level geometry selector, and substitutes an exact integer oracle at the wide-worker return. [Offset proof and guard costs](diagonal/PROOF.md) · [Phase receipts](diagonal/RESULT.json) + +Both kinds of scalar multiplication enter the ordinary word-arithmetic rows of #7834's invoice. Its certified common exponent for the grouped butterflies and CRT calls is $1-.997\cdot.001737=.998268211$. Removing every multiplication in the examined ordinary rows would still leave those existing terms. The simple modulus-$2^m$ result also omits the wider signed value that the packed ring's centered extraction consumes. [Middle-product cost](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/fine-prime-gaussian-product/MIDDLE.md) · [Complete multiplier invoice](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/fine-prime-gaussian-product/PROOF.md#L63-L83) + +### Replaying the Gaussian cases + +The default package verifier runs without a second checkout. For the two public caller controls, use the exact source commit below. The scripts authenticate their source files, use the Python standard library, and write results to standard output. The short direct-product control runs the original and edited complete integer multiplier. Its full mode adds independently checked signed convolutions, cutoff controls and a charged-wrapper address witness. The phase control replays both transform directions. + +~~~sh +git clone --filter=blob:none --no-checkout https://github.com/CrocSwap/integer-mult-bounds.git gaussian-source +git -C gaussian-source fetch origin pull/7834/head +git -C gaussian-source checkout --detach 4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02 +src=gaussian-source/research/fine-prime-gaussian-product +python3 -I -B research/recursive-dot-carry/gaussian/check.py --source "$src" --regression-only +python3 -I -B research/recursive-dot-carry/diagonal/verify.py --source-dir "$src" +~~~ + +## Charged P104 and BIT returns + +At #7830 head `87fbf4f7b35b0f18ab12b5767775a9a424cf0b15`, rational slots 0 and 3 transform independent owners 1260 and 281 at grades 3 and 5. The first and only consumers of those child returns are distinct productive terminals 156028 and 155049. The impulses $(1,0)$ and $(0,1)$ thus have equal sum and different protected outputs. Even if surrendering both terminals retired both paid calls, the paid and productive grade deltas would each be $\{3:-48,5:-48\}$, for zero net signed credit. On BIT, native clocks 2 and 5 pulse distinct banks 680 and 681. Clocks 11 and 15 consume them into 683 and 684. Their coordinatewise XOR also loses the identity of the pulsed bank. A common incoming carry cannot recover it. [Rational word](https://github.com/CrocSwap/integer-mult-bounds/blob/87fbf4f7b35b0f18ab12b5767775a9a424cf0b15/research/p104-chart306-chain/DOUBLE-CANDIDATE.json.gz) · [Inherited BIT word](https://github.com/CrocSwap/integer-mult-bounds/blob/89a67c404226d51028e135de2b9169e9020d57af/research/p104-iterated-returns/binary/WORD.json.gz) · [Caller review](https://github.com/CrocSwap/integer-mult-bounds/blob/87fbf4f7b35b0f18ab12b5767775a9a424cf0b15/research/p104-mixed-rank-supplier/review/REVIEW.md) + +One same-owner control preserves both blocks by coalescing their coordinates, a different operation from projecting them to a sum. Its grade $R=4^{182}14^{134}21^{164}$ lies between $J=10^{480}$ and $11^{480}$. Putting both slabs through the original complete grade-$R$ job saves $J^{1-\kappa}+(R-J)^{1-\kappa}-R^{1-\kappa}>0$ in the paid moment relative to that split. Even the unsplit raw BIT paid-to-productive moment at the target exceeds 1 at tensor power 480. Coarsening this fixed roster alone cannot clear the target. A new physical schedule would separately need its stock, matching and ordinary checks. [Mixed-rank construction](https://github.com/CrocSwap/integer-mult-bounds/blob/87fbf4f7b35b0f18ab12b5767775a9a424cf0b15/research/p104-mixed-rank-supplier/PROOF.md) · [Native price data](reference-price.json) + +The source-bound coordinate and price checks are included in the [caller receipt](caller-evidence.json). The separate [twist verifier](diagonal/independent_twist.py) restricts the guard to the first payload twist; its [frozen output](diagonal/independent-twist.json) reports that narrower result. + +The research starting point is canonical main `e54523517d0f03e58352e647c403a5af3e525a57`. The four-sibling promises, channel widths and gate savings have the scopes above. Earlier work on rectangular carry-state ranges, individual product bits, fixed-point Gaussian rounding and the mixed supplier supplies the comparison and the protected observations. [Rectangular convolution, #6252](https://github.com/CrocSwap/integer-mult-bounds/pull/6252) · [Single-product channels, #7838](https://github.com/CrocSwap/integer-mult-bounds/pull/7838) · [Selected result record](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/certificates/selected-result.json) diff --git a/research/recursive-dot-carry/PROOF.md b/research/recursive-dot-carry/PROOF.md new file mode 100644 index 0000000000..492b382401 --- /dev/null +++ b/research/recursive-dot-carry/PROOF.md @@ -0,0 +1,54 @@ +# When can one ordinary product return two siblings' sum? + +The parent needs the low $m$ bits of $x_1y_1+x_2y_2+c$, with its incoming integer $c$ available at the parent. All congruences below are promises on admissible inputs. Left encoders see the two $x$'s and right encoders see the two $y$'s. The two individual products have no other consumer in this contract. + +## A sharp congruence threshold + +Let $m\ge 2$ and $1\le a,b\le m$. Write $x_1=x, x_2=x+2^a v, y_1=y, y_2=y+2^b z$. The four parameters are independent subject to their residue widths. Put + +$$ +A=(x_1+x_2)/2,\qquad B=(y_1+y_2)/2,\qquad d=\max(0,m+1-a-b). +$$ + +The half sums are integral. Taking each sum modulo $2^m$ before halving gives the same $A,B$ modulo $2^{m-1}$. + +**Theorem 1.** The full residue admits a representation $F(x_1,x_2)G(y_1,y_2)+U(x_1,x_2)+V(y_1,y_2)+c\pmod {2^m}$ on every admissible input exactly when $a+b\ge m+1$. Each of the four functions may be nonlinear. The product in this representation returns its ordinary residue directly. A separate joint decoder of arbitrary complexity would change the model. + +For every $a,b$ the following implementation is exact: + +$$ +x_1y_1+x_2y_2+c +=2AB+2^{a+b-1}vz+c\pmod {2^m}. +$$ + +Use the low $m-1$ bits of $AB$. When $d>0$, use only the low $d$ bits of the second product. For $d=1$, the correction is a single highest-bit toggle. Its control is the AND of the two difference parities, computed by XORing bit $a$ of the two left inputs and bit $b$ of the two right inputs. When $d=0$, the correction vanishes. + +**Proof.** Expanding $2(x+2^{a-1}v)(y+2^{b-1}z)$ gives the stated identity and sufficiency. For necessity, set $c=0$ and take mixed differences at the zero input, first with a left coordinate increment and then with a right coordinate increment. The one-sided terms cancel. A product of arbitrary separate functions gives the outer product of the two vectors of differences. On the actual target, using unit increments in $(x,v)$ and $(y,z)$, its matrix is + +$$ +\begin{pmatrix}2&2^b\\2^a&2^{a+b}\end{pmatrix}. +$$ + +Subtract $2^{a-1}$ times the first row from the second, then $2^{b-1}$ times the first column from the second. The resulting diagonal entries are $2$ and $2^{a+b-1}$. These operations preserve an outer-product factorization. If the first entry of an outer product equals 2 modulo $2^m$, one of its two factors is odd and hence invertible. The vanishing off-diagonal on that factor's row or column forces the opposite second factor to vanish, so the second diagonal must be zero. This is impossible when $a+b\le m$. In that case $a,b0$, all $v,z\pmod{2^d}$ occur. With $z=1$, the uncorrected main product is always zero and the $2^d$ different values of $v$ give different full outputs. The same holds on the right. Any extra, separately encoded inputs to a decoder that already sees this fixed main return must distinguish at least $2^d$ cases per side. A low $d$-bit multiplication attains that information bound. It is a statement about this residual interface. It does not give a minimum gate count for all algorithms. + +## What changes if the parent asks for only the high bit? + +Take $m\ge3$ and independently odd $x_1,x_2,y_1,y_2\pmod {2^m}$. The required result is bit $m-1$ of the sum of the products, with incoming $c$ known to the decoder. Consider separate, arbitrary encoders into a fixed list of binary polynomial products. Only the returned product coefficients and $c$ reach the decoder. Count every input coordinate across the list, including hardwired coordinates. + +**Theorem 2.** The exact minimum total width is $2m-2$ per side. This is a channel-list result with unrestricted decoding. Its attainable construction sends enough information for the decoder to do the arithmetic. + +**Proof.** It suffices for the lower bound to fix $c=0$. Put $Q=2^{m-1}, H=Q/2$, and $y_i=1+2t_i$. The output row indexed by $x=(x_1,x_2)$ is the indicator of the upper half of $\mathbb{Z}/Q\mathbb{Z}$ evaluated at + +$$ +L_x(t)+b_x,\qquad L_x(t)=x_1t_1+x_2t_2,\quad b_x=(x_1+x_2)/2. +$$ + +Each $L_x$ is surjective. No nonzero translation preserves a half interval. If two rows agree, translating by any member of $\ker L_x$ must leave the other row invariant. Surjectivity gives $\ker L_x\subseteq\ker L_{x'}$; both kernels have the same size. The induced automorphism of the cyclic quotient gives $L_{x'}=uL_x$ for a unit $u$. + +An affine permutation preserving the lower half interval $I=[0,H-1]$ has multiplier $+1$ or $-1$. Indeed, $I$ overlaps $I+1$ in $H-1$ places, and only the two shifts $\pm1$ have that overlap. For multiplier $+1$, the translation must vanish. For multiplier $-1$, the intercept must be $H-1$, by reflection of the endpoints. If $u=-1$, both $x_i+x'_i$ are multiples of $Q$, so $b_x+b_{x'}$ is a multiple of $H$; it cannot equal $H-1\pmod Q$. If $u=1$, each coordinate can differ by $Q$, and the two intercepts agree precisely when both top bits flip or neither does. + +Thus there are exactly $2^{2m-3}$ different rows, all nonconstant. The simultaneous top-bit flip preserves the full dot product for all odd right inputs, since it adds $Q(y_1+y_2)=0\pmod {2^m}$. In a product-only interface an all-zero code on one side gives a constant row at fixed $c$. Hence $2^w-1\ge2^{2m-3}$, forcing $w\ge2m-2$. Symmetry handles the right side. + +For attainment, describe each row class by the $m-2$ inner bits of each odd coordinate and the XOR of the two top bits. Canonicalize by putting the first top bit at zero. Use two channels with respective left/right widths $(2m-3,1)$ and $(1,2m-3)$, hardwiring the shorter operand to one. From these codes and $c$ the decoder can compute the full residue for the two canonicalized pairs, which gives the original output. The construction proves width optimality even when all incoming carries must be served. It makes no single-channel, decoder-time or recursive-price claim. diff --git a/research/recursive-dot-carry/README.md b/research/recursive-dot-carry/README.md new file mode 100644 index 0000000000..9387f0fe4d --- /dev/null +++ b/research/recursive-dot-carry/README.md @@ -0,0 +1,39 @@ +# When two product returns can share a carry + +A parent receives four words and an incoming carry. It needs the low $m$ bits of $x_1y_1+x_2y_2+c$. Suppose the two left words agree on $a$ low bits, and the two right words agree on $b$ low bits. This package proves exactly when a single ordinary multiplication of separately encoded operands, with arbitrary one-sided additive corrections, can supply that return. + +The threshold is **$a+b\ge m+1$**. Below it, multiply the two half sums and add a correction from the low $d=\max(0,m+1-a-b)$ bits of each divided difference. At $a+b=m$ the correction is one AND of two parities, applied to the high bit. For example, with four-bit words, take both sibling pairs to be $(0,4)$. The half-sum product would give 8 after doubling. The correction toggles its top bit, giving the correct $16\bmod16=0$. The proof allows arbitrary incoming carries and hidden differences of either sign. [Theorem 1 and the residual information bound](PROOF.md) + +If all four words are independently odd and the parent asks for just the high bit, a different bound applies. Every fixed list of binary polynomial products with separate encoders and no other operand messages needs **$2m-2$ input coordinates on each side**. Unrestricted decoding attains that width. At six bits there are 512 distinct, nonconstant rows among the 1,024 left pairs. The earlier single-product result has a different input and output contract. [Theorem 2](PROOF.md) · [Single-product predecessor, #7838](https://github.com/CrocSwap/integer-mult-bounds/pull/7838) + +## Two circuits on the same inputs + +Both circuits read four distinct operand ports and one incoming carry, preserve all five words, and write the same low word. The control computes two truncated schoolbook products and adds them. The candidate computes the half sums, a truncated product, the correction and the carry. Both are compiled with the same XOR/AND primitives, zero constant, wire reuse, ripple addition and gate sharing. + +| Word and low-bit promise | Two-product control | Shared-carry circuit | Inputs checked by the primary circuit verifier | +|---|---:|---:|---:| +| $m=4,\ a=b=2$ | 38 AND, 38 XOR | 21 AND, 29 XOR | All 65,536 input and carry combinations | +| $m=8,\ a=b=4$ | 170 AND, 170 XOR | 91 AND, 107 XOR | 4,096 repeatable cases | + +On the eight-bit case, reversible compute, copy and uncompute costs **182 Toffoli and 436 CNOT**, using 198 initially clean scratch bits. The same translation of the control costs **340 Toffoli and 688 CNOT**, using 340 scratch bits. These totals include copying the eight-bit output and restoring every scratch wire. Wires and fan-out are free in the Boolean count. The reversible count assumes unrestricted gate connectivity and charges the forward and inverse gates explicitly. Neither circuit uses a lookup table. [Circuit generators](circuits.py) · [Frozen counts](RESULT.json) · [Independent verification](REVIEW.md) + +## What this buys the integer multiplier + +The Gaussian multiplier in #7834 contains actual sum-only joins. A source-bound control there can reduce ordinary word-product dispatches in a complete finite multiplication while preserving the integer output and the checked intermediate coefficients. The charged P104 and BIT caller in #7830 has a different obligation. Its named child fields may be observed separately. The congruence theorem supplies no signed credit on that caller. The verified conditional reference is $\kappa\ge0.00387992803556$; its fixed-profile directed upper endpoint is $0.003879928046155$. The target in this study is $0.003884928046155$. The reference still needs at least 4.880391089954707 rational and 1.925615290709237 binary price units there. [Source sites and qualifications](CALLERS.md) · [Full reference histograms](reference-price.json) · [Reference PR](https://github.com/CrocSwap/integer-mult-bounds/pull/7830) + +## Reproduction + +From a checkout with Python 3.12, run the two commands below. The first checks the congruence identity on 1,044,944 admissible cases through five bits, large signed representatives, literal odd-dot row classes, the circuits and the independent replay. The second also checks package registration and provenance. The Gaussian source replay has its own pinned checkout instructions. [Caller reproduction](CALLERS.md) + +~~~sh +python3 -I -B research/recursive-dot-carry/verify.py +python3 -B scripts/research_package.py --package research/recursive-dot-carry +~~~ + +## Open next questions + +Can a charged parent accept an invertible representation that exposes a dot-product sum while keeping any independently observed child difference available? Start by pinning the two child activations, the first consumer of each return, the correlation on all legal inputs, and the cost of retaining or restoring the difference. A candidate must move the applicable signed invoice after all of those charges. The explicit ordinary gate savings make a control for that test. [Literal caller witnesses](CALLERS.md) + +## Credit + +Clear1nsight prepared this package with substantial OpenAI Codex assistance. Separate workers traced the Gaussian and mixed-rank callers, tested asymmetric and phase-diagonal corrections, and reviewed the proofs and circuits with a separately implemented verifier. The arithmetic factorization uses the classical difference-of-products identity, and the Gaussian control uses the classical three-product complex multiplication identity. The contribution here is the sharp threshold for arbitrary separate encoders in the stated model, the exact residual and channel bounds, and the source-bound circuit and caller evidence. The Gaussian and mixed-rank implementations and their reported bounds belong to their cited contributors. [Task card and attribution](TASK.json) · [Frozen base sources](SOURCES.json) · [Gaussian implementation by aliromman](https://github.com/CrocSwap/integer-mult-bounds/pull/7834) diff --git a/research/recursive-dot-carry/RESULT.json b/research/recursive-dot-carry/RESULT.json new file mode 100644 index 0000000000..ea49388c5c --- /dev/null +++ b/research/recursive-dot-carry/RESULT.json @@ -0,0 +1,74 @@ +{ + "congruence": { + "exhaustive_congruent_inputs": 1044944, + "signed_large_inputs": 840 + }, + "odd_dot_rows": [ + { + "m": 3, + "rows": 16, + "different": 8, + "minimum_total_coordinates_per_side": 4 + }, + { + "m": 4, + "rows": 64, + "different": 32, + "minimum_total_coordinates_per_side": 6 + }, + { + "m": 5, + "rows": 256, + "different": 128, + "minimum_total_coordinates_per_side": 8 + }, + { + "m": 6, + "rows": 1024, + "different": 512, + "minimum_total_coordinates_per_side": 10 + } + ], + "circuits": [ + { + "m": 4, + "a": 2, + "b": 2, + "cases": 65536, + "two_products": { + "and": 38, + "xor": 38, + "clean_scratch_bits": 76, + "clean_cnot": 156, + "clean_toffoli": 76 + }, + "shared_carry": { + "and": 21, + "xor": 29, + "clean_scratch_bits": 50, + "clean_cnot": 120, + "clean_toffoli": 42 + } + }, + { + "m": 8, + "a": 4, + "b": 4, + "cases": 4096, + "two_products": { + "and": 170, + "xor": 170, + "clean_scratch_bits": 340, + "clean_cnot": 688, + "clean_toffoli": 340 + }, + "shared_carry": { + "and": 91, + "xor": 107, + "clean_scratch_bits": 198, + "clean_cnot": 436, + "clean_toffoli": 182 + } + } + ] +} diff --git a/research/recursive-dot-carry/REVIEW.md b/research/recursive-dot-carry/REVIEW.md new file mode 100644 index 0000000000..f5a5738002 --- /dev/null +++ b/research/recursive-dot-carry/REVIEW.md @@ -0,0 +1,47 @@ +# Independent review of the recursive dot and carry proofs + +**Pass within the stated interfaces.** The frozen proof establishes the direct-product congruence threshold, the information needed by the correction at a fixed main return, and the dense odd channel width. The finite circuits preserve all read-only ports and erase all scratch. Their signed recursive credit is **zero**. + +## Direct residue and residual information + +For $m\ge2$, write $x_2=x_1+2^a v$ and $y_2=y_1+2^b z$. The exact integer identity is $x_1y_1+x_2y_2=2AB+2^{a+b-1}vz$, where $A,B$ are the respective integer half-sums. Changing a representative by $2^m$ changes its half-sum by a multiple of $2^{m-1}$. A nonzero correction uses $d=m+1-a-b$ low bits. Since $a,b\ge1$, this width satisfies $d\le m-a$ and $d\le m-b$, so the needed bits of $v,z$ are independent of the chosen representatives. The identity absorbs every separately known integer carry, including negative lifts. + +For necessity, set any carry and subtract mixed differences over the four points given by the base input and independent unit changes. The one-sided terms cancel and the differences of any separate nonlinear product factor as an outer product. The target gives entries $2,2^b,2^a,2^{a+b}$ in row order. The invertible row and column eliminations in the proof give $\operatorname{diag}(2,2^{a+b-1})$. Since $m\ge2$, a product congruent to $2$ has exactly one odd factor. Its inverse and the two zero off-diagonals force the other diagonal to be zero. For $a+b\le m$, both increments exist and the second diagonal is nonzero. If either side is congruent at all $m$ bits, the correction vanishes because the other promise contributes at least one bit. At $m=2$, $(a,b)=(1,1)$ fails and $(1,2),(2,1),(2,2)$ attain the direct representation. + +Fix both half-sums at zero using opposing pairs, set $z=1$, and vary $v$ through the $2^d$ residues. This fixes the main product and the incoming carry and leaves $2^d$ distinct target outputs. Symmetry gives the same separation for the other side. A decoder seeing the fixed main return and only an extra joint return needs at least $d$ effective bits in that return. A separately conveyed side summary also needs at least $d$ bits per side with the other side fixed. The low $d$-bit residual product attains the return-width bound. These are information bounds for this interface. + +Two exact controls make common simplifications fail. + +- At $m=2,a=b=1$ the diagonal $\operatorname{diag}(2,2)$ has determinant zero modulo $4$. Exhausting all 256 pairs of two-entry vectors modulo $4$ finds no outer-product factorization. +- With $m=5,a=b=1$, left inputs $(0,0)$ and $(-8,8)$ have the same main return and same three-bit $v$ value. Right inputs $(-1,1)$ and carry zero give outputs $0$ and $16$. A three-bit residual cannot serve this four-bit interface. + +The replay checks 1,044,944 congruent pairs of operand pairs at widths 2 through 5 with varied carries, 848 signed lifts through width 1,024, and 156 fixed-main separation families. + +## Dense odd channel width for each fixed carry + +For $m\ge3$, set $Q=2^{m-1}$, $H=Q/2$, and $k=\lfloor c/2\rfloor$. Putting $y_i=1+2t_i$ makes the high bit the upper-half indicator of $x_1t_1+x_2t_2+b_x+k$ modulo $Q$, with $b_x=(x_1+x_2)/2$. Two equal rows give equal kernels of the surjective linear forms because the half interval has no period. The forms differ by a unit and the resulting affine permutation must preserve the half interval. The overlap size of a half interval and its translate by $s$ is $H-\min(s,Q-s)$ for $0\le s> i) & 1) << k + for j, word in enumerate(words): + planes[j*m+i] |= ((word >> i) & 1) << k + for circ, out in circuits: + if circ.evaluate_planes(planes, out) != oracle: + raise ValueError('circuit disagrees with the integer sum') + + +def check(): + rows = [] + rng = random.Random(8016) + for m in (4, 8): + a = b = m // 2 + circuits = [build(m, a, b, flag) for flag in (False, True)] + size = 1 << m + if m == 4: + sides = [(x, u) for x, u in product(range(size), repeat=2) if (x-u) % (1 << a) == 0] + cases = ((x, u, y, v, c) for (x, u), (y, v), c in product(sides, sides, range(size))) + else: + def sample(): + x, y, c = (rng.randrange(size) for _ in range(3)) + return x, x ^ (rng.getrandbits(m-a) << a), y, y ^ (rng.getrandbits(m-b) << b), c + cases = (sample() for _ in range(4096)) + from itertools import islice + total = 0 + while batch := list(islice(cases, 128)): + test_batch(circuits, batch, m) + total += len(batch) + rows.append({'m': m, 'a': a, 'b': b, 'cases': total, + 'two_products': circuits[0][0].invoice(), 'shared_carry': circuits[1][0].invoice()}) + return rows diff --git a/research/recursive-dot-carry/diagonal/PROOF.md b/research/recursive-dot-carry/diagonal/PROOF.md new file mode 100644 index 0000000000..37138f0d0e --- /dev/null +++ b/research/recursive-dot-carry/diagonal/PROOF.md @@ -0,0 +1,63 @@ +# Exact fusion of two scalar returns with a one-sided offset + +Suppose a parent needs bit $m-1$ of $xy+uv+C$, where $x,u,y,v,C$ are signed integers, $m\ge 1$, and $u=x+2^d q$ for $d\ge 0$. The offset $q$ may vary with the operands and may be hidden from the parent. The published carryless observation in #7838 concerned raw product bits without operand-dependent side information. This construction changes the boundary to two ordinary integer products with a relation on one side only. + +## One wide return and the exact correction + +Use the low $m$ bits of the single return $P=x(y+v)$. The ordinary dot product is $P+2^d qv$. If $v\ne 0$, put $s=v_2(v)$ and $\ell=\max(0,m-d-s)$. If $v=0$, take $\ell=0$. For positive $\ell$, let $a=q\bmod 2^\ell$ and $b=(v/2^s)\bmod 2^\ell$. Return + +$$ + \operatorname{bit}_{m-1}\bigl(P+C+2^{d+s}(ab\bmod 2^\ell)\bigr). +$$ + +For $\ell=0$, return the bit of $P+C$. These expressions give the same entire residue modulo $2^m$ as the unfused dot product with the same carry. The decoder needs no division on an unknown integer. It obtains $a$ by subtracting the $\ell$-bit slices of $u$ and $x$ that start at bit $d$. Their lower $d$ bits agree, so this difference gives the low $\ell$ bits of $q$ even when the offset is negative. The division of $v$ by $2^s$ is a shift. The scan that finds the first set bit of $v\bmod 2^m$ also detects the case where the correction vanishes. + +For $\ell=1$, the bit of $P+C$ flips exactly when $q$ is odd. In particular, at $d=m-1$ and for unrestricted $v$, XOR the top bits of $u,x$, AND with the low bit of $v$, then XOR with the selected bit of $P+C$. The final XOR is valid after arbitrary incoming carry because the correction is a multiple of $2^{m-1}$. + +### Sharpness with arbitrary incoming carry + +Fix $x,y,v$ and the wide return $P$. Assume the left input permits the full range of low offset residues. Two offsets $q,q'$ give the same bit for **every** $C$ exactly when $q\equiv q'\pmod{2^\ell}$. The difference of their complete residues is $2^d v(q'-q)$. It vanishes modulo $2^m$ exactly under that congruence. Conversely, write a nonzero residue difference as $0<\delta<2^m$ and set $H=2^{m-1}$. For $\delta\le H$, choose $C$ to send the first residue to $H-\delta$, so the second is $H$. For $\delta>H$, send the first to zero, so the second is already in the upper half. The two bits differ in either case. The wide return stays fixed in both tests. + +Thus freedom to omit all offset-dependent information starts at $d+s\ge m$, with $v=0$ also free. Below that threshold, a side return independent of $C$ needs at least $\ell$ bits when all $2^\ell$ offset residues are admissible. The decoder above attains the bound for this fixed wide return. This bound concerns the specified carrier $P=x(y+v)$. A different wide encoding or a carry fixed in advance has a different contract. + +For $m=8,d=7,x=83,y=117,v=155,C=177$, both $u=83$ and $u=211$ have the same wide residue 48 and give bits 1 and 0 respectively. Omitting the single correction bit gives 1 on both inputs. + +### Ordinary word price + +Compare two separate width-$m$ products with one width-$m$ product. The candidate uses $x\bmod 2^m$ and $(y+v)\bmod 2^m$; a sum crossing the boundary therefore incurs no higher grade. The original and candidate both return a fixed-width product and consume the data before releasing its storage. The candidate additionally reads the two slices for $a$, produces $y+v\bmod 2^m$ and adds the correction to the same carry consumer. A straight shift-add correction scans only the $\ell-j$ surviving bits in row $j=0,\ldots,\ell-1$, using at most $\ell(\ell+1)/2$ partial bit products and the same number of ripple positions. One-bit correction uses the gates stated above. All copying, sign conversion if needed, carry scans, initialization, rewind and erasure take $O(m+\ell^2)$ additional work and $O(m)$ space with a fixed number of sequential banks. An encoded carry longer than $m$ can be consumed according to its interface in both versions. Only its low $m$ bits affect this observation. + +Under a common fixed-width charge $W(m)$, the two-product oracle fee is $2W(m)$ and the fused fee is $W(m)$. The complete comparison is a saving of one fee minus the additional $O(m+\ell^2)$ work. For example, if $W(m)=\omega(m)$ and $\ell^2=o(W(m))$, the replacement is eventually cheaper in that tariff. If a provider trims the widths, compare the actual grades and substitutes for all calls. A cost upper bound for a multiplier alone gives no lower bound on its fee. + +## Exact signed fusion in the pinned Gaussian diagonal + +The #7834 scalar consumer evaluates four real word products for a payload $(x,y)$ and public phase $(u,v)$. It sends $xu-yv$ and $xv+yu$ to the same signed truncation routine. [Pinned scalar consumer](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/fine-prime-gaussian-product/fine_ring.py) + +Choose $\sigma=1$ if $u,v$ have the same sign, and $\sigma=-1$ otherwise. Set $\Delta=u-\sigma v$. The two exact raw outputs are + +$$ + v(\sigma x-y)+\Delta x,\qquad v(x+\sigma y)+\Delta y. +$$ + +This identity is the signed version of the one-sided offset. Small $\Delta$ gives two wide word calls and two short shift-add corrections for both outputs. For $\Delta=\pm1$, the correction uses one signed add per component. All corrections precede the original rounding. Equality holds as signed integers for both normal and conjugated phases and remains exact after any common incoming carry. The path preserves input access order and output cleanup. + +The checked guard requires $|\Delta|\le 2$, equal magnitude widths $w$ for $u,v$, and magnitude widths at most $w$ for both new factors $\sigma x-y,x+\sigma y$. Their sum and difference show that $x,y$ also have width at most $w$. All four old and both new calls therefore have exactly the same width $w$. The guard returns to the original four calls when it fails. + +Let $L$ be the signed record width. Testing signs, forming the difference, inspecting operand widths, and making the new factors use a fixed number of linear signed tape scans. The same bound covers holding the payload until both corrections finish, consuming the complete child returns, and erasing and rewinding the banks. With a correction cap $B_\Delta\le 2^w$, the candidate costs two width-$w$ fees plus $O(L+w(1+\log(B_\Delta+1)))$ movement and arithmetic. The source costs four such fees plus linear adapter work. Extra guard work on a failed record is $O(L)$. On the two exact twist diagonals discussed below, $\Delta=0$ and $L=\Theta(w)$. + +The rounded public chirp product has a natural source of small nonzero offsets. An exact phase on a diagonal of the complex plane would have equal component magnitudes. For $D$ cached rounded factors, the source bounds the root error by three grid units per factor and its multiplication drop by two. All rounded factors have complex modulus at most one, so the product defect is less than $5D$ grid units. On a diagonal the integer component-magnitude difference is therefore less than $5\sqrt{2}D<8D$. The guard uses the actual integer difference on tape and never assumes the error vanishes. + +### Dispatches at reachable geometries + +In the first source twist pass of `chirp_middle`, `make_diagonals` supplies `root_word(k, 2*r, f)` for the fastest coordinate $k=0,\ldots,r-1$. For $r\ge8$, the roots at $k=r/4,3r/4$ lie at angles $\pi/4,3\pi/4$. The symmetric interval recursion gives equal magnitudes for these two stored integer pairs, each of width $f$. The first is obtained by applying the same square-root interval to each component of the half-angle of $\pi/2$, and the second by quadrant rotation. The inward root error is under three units and $f\ge16$, so their magnitudes exceed $2^{f-1}$. The prior normalized phase diagonal preserves the half disk by the modulus bound and truncation toward zero. On that disk $|x\pm y|\le 2^f/\sqrt{2}<2^f$. This guarantees the same-width guard, including when one component of the payload is zero. + +The pass therefore admits two replacements per outer tuple, each removing two width-$f$ word calls. This gives $4T/r$ fewer scalar dispatches in this pass per middle call, where $T$ is the complete tensor volume. The finite top-level first geometry has $r=8$. The fine selector has $r\ge8$ on its Gaussian branch and $f\to\infty$. At widths $f>8192$, each removed call goes to the cold physical word wrapper. [Pinned word dispatcher](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/fine-prime-gaussian-product/word_multiply.py) + +A public fixed block schedule can target these coordinates. The guarded implementation in this receipt tests every supplied phase, so its price includes the linear guard on every failed record too. The resulting count is exact. In the large family $r$ grows faster than a fixed power of the scalar precision, so a per-record guard is not justified by the sparse dispatch count alone. + +The direct nonzero fixture has slopes $(3,7)$, target sides $(8,8)$, $q=8186$, $f=8200$ and index 9. Coordinate $(1,1)$ has exact angle $3\pi/4$. The cached components differ in magnitude by one. The control verifies the coefficient independently using the exact floor square roots for $\cos^2(\pi/8)=(2+\sqrt{2})/4$ and $\sin^2(\pi/8)=(2-\sqrt{2})/4$. Omitting the correction changes a signed truncated result. In both orientations, the original dispatcher sends four width-8200 words and the guarded version sends two width-8200 words. The diagnostic substitutes exact integers at the cold physical worker return. The top-level selector uses different slopes for its finite geometries. Its fine guard $4W < B \le \min t_i$ excludes the direct 8-by-8 fixture. The large-width diagnostic covers the legal `chirp_middle` interface and this literal scalar consumer. + +The #7834 invoice already charges these scalar words as local acyclic work. The width-preserving change gives no P104 or BIT tariff credit, and no complete asymptotic saving is established for the Gaussian construction. + +## Reproduction + +Run `python3 -I -B verify.py --source-dir /path/to/checkout/research/fine-prime-gaussian-product`. The verifier authenticates three source modules at #7834 head `4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02`. The complete middle calls use the source's bounded-base word implementation in both directions. The high-width control uses an exact integer return at the cold worker boundary. [Recorded output](RESULT.json) · [Checkout and replay](../CALLERS.md) diff --git a/research/recursive-dot-carry/diagonal/RESULT.json b/research/recursive-dot-carry/diagonal/RESULT.json new file mode 100644 index 0000000000..e9295843e2 --- /dev/null +++ b/research/recursive-dot-carry/diagonal/RESULT.json @@ -0,0 +1,298 @@ +{ + "emitted_geometry_control": { + "144": { + "alpha": 2, + "batch": 3, + "block": 4, + "digit_bits": 8, + "precision": 128, + "sources": [ + 5, + 7 + ], + "targets": [ + 8, + 8 + ], + "use_caller_page_limit": false, + "window": 24 + }, + "145": { + "alpha": 2, + "batch": 3, + "block": 16, + "digit_bits": 4, + "precision": 96, + "sources": [ + 31, + 29 + ], + "targets": [ + 32, + 32 + ], + "use_caller_page_limit": true, + "window": 7 + }, + "1800": { + "alpha": 2, + "batch": 3, + "block": 16, + "digit_bits": 4, + "precision": 96, + "sources": [ + 31, + 29 + ], + "targets": [ + 32, + 32 + ], + "use_caller_page_limit": true, + "window": 7 + } + }, + "full_unmocked_chirp_controls": [ + { + "fused_fast_words": 0, + "fused_words": 1664, + "geometry": [ + [ + 5, + 7 + ], + [ + 8, + 8 + ], + 128 + ], + "guard_census": { + "0": 32, + "None": 288 + }, + "inverse": false, + "out_sha256": "a3297c95c74f1316460f166eaf00b3b68966202a6dc6024d9c0f77483eb4f411", + "outputs": 64, + "source_fast_words": 0, + "source_words": 1728 + }, + { + "fused_fast_words": 0, + "fused_words": 1664, + "geometry": [ + [ + 5, + 7 + ], + [ + 8, + 8 + ], + 128 + ], + "guard_census": { + "0": 32, + "None": 288 + }, + "inverse": true, + "out_sha256": "7fbd6c23bbf33efdbfbb6b7721f37d9e786c285607a5a1543b9ac1cf4ddfca7a", + "outputs": 64, + "source_fast_words": 0, + "source_words": 1728 + }, + { + "fused_fast_words": 0, + "fused_words": 26624, + "geometry": [ + [ + 31, + 29 + ], + [ + 32, + 32 + ], + 96 + ], + "guard_census": { + "0": 128, + "None": 4992 + }, + "inverse": false, + "out_sha256": "24f5447ff486ccaa70d810875f0b3ff516886260445ac311ff24b60c742e8f54", + "outputs": 1024, + "source_fast_words": 0, + "source_words": 26880 + }, + { + "fused_fast_words": 0, + "fused_words": 26624, + "geometry": [ + [ + 31, + 29 + ], + [ + 32, + 32 + ], + 96 + ], + "guard_census": { + "0": 128, + "None": 4992 + }, + "inverse": true, + "out_sha256": "c508942874553e144c2eb8d7f55fde27e720fcc4a011f9322bb6a8a926836ea9", + "outputs": 1024, + "source_fast_words": 0, + "source_words": 26880 + }, + { + "fused_fast_words": 0, + "fused_words": 1600, + "geometry": [ + [ + 3, + 7 + ], + [ + 8, + 8 + ], + 82 + ], + "guard_census": { + "-1": 16, + "0": 32, + "1": 16, + "None": 256 + }, + "inverse": false, + "out_sha256": "42fadef96da46329469f8db6fd58e1391da71f59da3a9931d2c7c3f1564b5f07", + "outputs": 64, + "source_fast_words": 0, + "source_words": 1728 + }, + { + "fused_fast_words": 0, + "fused_words": 1600, + "geometry": [ + [ + 3, + 7 + ], + [ + 8, + 8 + ], + 82 + ], + "guard_census": { + "-1": 16, + "0": 32, + "1": 16, + "None": 256 + }, + "inverse": true, + "out_sha256": "37a812e96710f0b8bd325826be1b18ae1360f78beec44a8cc5de84692c742de8", + "outputs": 64, + "source_fast_words": 0, + "source_words": 1728 + } + ], + "kappa": null, + "low_bits": { + "explicit_carry_cases": 63280, + "full_residue_cases": 2199512, + "signed_random_cases": 1024 + }, + "matched_dispatch_control": { + "coordinate": [ + 1, + 1 + ], + "correction_changes_truncated_output": true, + "execution": "actual source dispatcher with an exact integer test double for the physical worker", + "f": 8200, + "independent_integer_phase_formula": true, + "index": 9, + "ingress": "legal direct chirp_middle fixture, outside product.choose geometries", + "phase_sha256": "e5ba8130dc9a1e3b22fef5280de8a32cac1beccc0d254f1b29d581c7cb425c8f", + "q": 8186, + "radices": [ + 8, + 8 + ], + "same_grid_results": { + "false": { + "baseline_fast_widths": [ + 8200, + 8200, + 8200, + 8200 + ], + "cleaned_owned_banks": true, + "delta": 1, + "fused_fast_widths": [ + 8200, + 8200 + ] + }, + "true": { + "baseline_fast_widths": [ + 8200, + 8200, + 8200, + 8200 + ], + "cleaned_owned_banks": true, + "delta": 1, + "fused_fast_widths": [ + 8200, + 8200 + ] + } + }, + "sources": [ + 3, + 7 + ] + }, + "phase_raw": { + "cases": 65536, + "signed_carry_checks": 35020, + "width_preserving_fusions": 7004 + }, + "physical_recursive_p104_or_bit_credit": 0, + "sources": { + "#7834_head": "4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02", + "#7838_head": "cd9ce5a555977b469bd848199bc36025bd82fdcb", + "#7838_role": "different carryless channel ABI without side information", + "fine_ring_sha256": "70c639c9c23225acbf5a2165eaad81a8f6a65ec9b3e08bf05df9ecf416a0d313", + "product_sha256": "610fb9c7c0008e477519ce96eea56d7c17e37939d7d98054b14f62c516e5a174", + "word_multiply_sha256": "87bf3512dfab314e26f297678f809bdf0913b5fa28642379ad48ae1b900de481" + }, + "status": "exact_local_scalar_fusion", + "threshold": { + "carry_signatures": 10794, + "fixed_right_rows": 768, + "required_parity_witness": { + "bit_with_correction": 0, + "bit_with_correction_omitted": 1, + "carry": 177, + "d": 7, + "expected_bits": [ + 1, + 0 + ], + "m": 8, + "second_y": 155, + "wide_return_modulo": 48, + "x": 83, + "y": 117 + }, + "same_residue_collisions": 3516 + } +} diff --git a/research/recursive-dot-carry/diagonal/independent-twist.json b/research/recursive-dot-carry/diagonal/independent-twist.json new file mode 100644 index 0000000000..f9a74871a0 --- /dev/null +++ b/research/recursive-dot-carry/diagonal/independent-twist.json @@ -0,0 +1,119 @@ +{ + "kernel_width_control": { + "index": 10, + "mixed_width": 17, + "original_width": 16, + "payload": [ + -25079, + 60547 + ], + "phase": [ + 46340, + 46340 + ] + }, + "middle_controls": [ + { + "inverse": false, + "live_numeric_bits_at_return": 0, + "new_scalar_dispatches": 216, + "original_scalar_dispatches": 224, + "q": 22, + "radices": [ + 4, + 2 + ], + "records_fused": 4, + "sources": [ + 3, + 1 + ] + }, + { + "inverse": true, + "live_numeric_bits_at_return": 0, + "new_scalar_dispatches": 216, + "original_scalar_dispatches": 224, + "q": 22, + "radices": [ + 4, + 2 + ], + "records_fused": 4, + "sources": [ + 3, + 1 + ] + }, + { + "inverse": false, + "live_numeric_bits_at_return": 0, + "new_scalar_dispatches": 1696, + "original_scalar_dispatches": 1728, + "q": 128, + "radices": [ + 8, + 8 + ], + "records_fused": 16, + "sources": [ + 5, + 7 + ] + }, + { + "inverse": true, + "live_numeric_bits_at_return": 0, + "new_scalar_dispatches": 1696, + "original_scalar_dispatches": 1728, + "q": 128, + "radices": [ + 8, + 8 + ], + "records_fused": 16, + "sources": [ + 5, + 7 + ] + }, + { + "inverse": false, + "live_numeric_bits_at_return": 0, + "new_scalar_dispatches": 3360, + "original_scalar_dispatches": 3392, + "q": 63, + "radices": [ + 16, + 8 + ], + "records_fused": 16, + "sources": [ + 11, + 5 + ] + }, + { + "inverse": true, + "live_numeric_bits_at_return": 0, + "new_scalar_dispatches": 3360, + "original_scalar_dispatches": 3392, + "q": 63, + "radices": [ + 16, + 8 + ], + "records_fused": 16, + "sources": [ + 11, + 5 + ] + } + ], + "root_projection_checks": 50, + "source_git_blobs": { + "fine_ring.py": "b18da6275e31ac0bcc4174ec86106532c0cb5958", + "word_multiply.py": "b148a60eac955722520e193f8bde0687635407ee" + }, + "status": "PASS_GUARDED_FIRST_PAYLOAD_TWIST" +} diff --git a/research/recursive-dot-carry/diagonal/independent_twist.py b/research/recursive-dot-carry/diagonal/independent_twist.py new file mode 100644 index 0000000000..5cc478f2f1 --- /dev/null +++ b/research/recursive-dot-carry/diagonal/independent_twist.py @@ -0,0 +1,135 @@ +"""Replay the guarded first-payload-twist substitution on pinned #7834 code.""" + +import argparse +from hashlib import sha1 +import importlib +import json +from math import isqrt, prod +from pathlib import Path +from random import Random +import sys +from unittest.mock import patch + + +SOURCE_BLOBS = { + "fine_ring.py": "b18da6275e31ac0bcc4174ec86106532c0cb5958", + "word_multiply.py": "b148a60eac955722520e193f8bde0687635407ee", +} + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def load_source(directory): + for name, expected in SOURCE_BLOBS.items(): + blob = (directory / name).read_bytes() + actual = sha1(f"blob {len(blob)}\0".encode() + blob).hexdigest() + require(actual == expected, name) + sys.path.insert(0, str(directory)) + return importlib.import_module("fine_ring") + + +def root_checks(ring): + count = 0 + for f in (16, 23, 128, 8192, 8193): + expected = isqrt(1 << (2 * f - 1)) + for r in (4, 8, 16, 64, 256): + for k, sign in ((r // 4, 1), (3 * r // 4, -1)): + sampled = ring.root_word(k, 2 * r, f, ring.Trace()) + require(sampled == (sign * expected, expected) and expected.bit_length() == f, + (r, k, f, "root projection")) + count += 1 + return count + + +def check_middle(ring, sources, radices, q, inverse): + r, volume = radices[0], prod(radices) + rng = Random(r * q + int(inverse)) + bound = 1 << (q - 1) + values = [(bound, 0), (0, -bound)] + [ + (rng.randint(-bound // 2, bound // 2), rng.randint(-bound // 2, bound // 2)) + for _ in range(volume - 2) + ] + old, new = ring.Trace(), ring.Trace() + want = ring.chirp_middle(values, sources, radices, q, inverse=inverse, trace=old) + original = ring.scalar_diagonal + diagonals = fused = 0 + + def replace_second_diagonal(tape, diagonal, size, unit, conjugate=False): + nonlocal diagonals + diagonals += 1 + if diagonals != 2: + return original(tape, diagonal, size, unit, conjugate) + require(not conjugate and size == volume, "first twist ABI") + diagonal.home() + + def substitute(i, record): + nonlocal fused + u, v = diagonal.read() + if i % r not in (r // 4, 3 * r // 4): + return ring.times(record, (u, v), unit, tape.trace) + require(abs(u) == abs(v) > 0 and u.bit_length() == unit.bit_length() - 1, "root guard") + x, y = record + require(x * x + y * y <= unit * unit // 4, "payload radius") + sign = 1 if u == v else -1 + a, b = x - sign * y, y + sign * x + require(max(x.bit_length(), y.bit_length(), a.bit_length(), b.bit_length()) <= u.bit_length(), + "same-width operands") + real = ring.mul(u, a, tape.trace) + imag = ring.mul(u, b, tape.trace) + require((real, imag) == (x * u - y * v, x * v + y * u), "exact raw complex return") + fused += 1 + return ring.tz(real, unit), ring.tz(imag, unit) + + return ring.map_tape(tape, size, substitute) + + with patch.object(ring, "scalar_diagonal", replace_second_diagonal): + result = ring.chirp_middle(values, sources, radices, q, inverse=inverse, trace=new) + require(result == want and old.live == new.live == old.fast_words == new.fast_words == 0, + "completed middle endpoint") + require(diagonals == 5 and fused == 2 * volume // r, "guaranteed first twist count") + require(old.scalar_products - new.scalar_products == 4 * volume // r, "guaranteed dispatch saving") + return { + "sources": sources, "radices": radices, "q": q, "inverse": inverse, "records_fused": fused, + "original_scalar_dispatches": old.scalar_products, "new_scalar_dispatches": new.scalar_products, + "live_numeric_bits_at_return": new.live, + } + + +def kernel_width_control(ring): + f, index = 16, 10 + trace = ring.Trace() + phase, twist = ring.make_diagonals((5, 7), (8, 8), f + 5, f, trace) + x, y = phase.cells[index] + u, v = twist.cells[index] + require(index % 8 == 2 and u == v > 0, "kernel control root") + require(x * x + y * y <= 1 << (2 * f), "kernel disk") + require(max(n.bit_length() for n in (x, y, u, v)) == f and (x - y).bit_length() == f + 1, + "unguarded kernel mix widens") + phase.release() + twist.release() + require(trace.live == 0, "kernel control cleanup") + return {"index": index, "payload": [x, y], "phase": [u, v], "original_width": f, "mixed_width": f + 1} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--source", required=True, type=Path) + ring = load_source(parser.parse_args().source.resolve()) + print(json.dumps({ + "status": "PASS_GUARDED_FIRST_PAYLOAD_TWIST", + "source_git_blobs": SOURCE_BLOBS, + "root_projection_checks": root_checks(ring), + "middle_controls": [ + check_middle(ring, sources, radices, q, inverse) + for sources, radices, q in (((3, 1), (4, 2), 22), ((5, 7), (8, 8), 128), ((11, 5), (16, 8), 63)) + for inverse in (False, True) + ], + "kernel_width_control": kernel_width_control(ring), + }, indent=2, sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/research/recursive-dot-carry/diagonal/verify.py b/research/recursive-dot-carry/diagonal/verify.py new file mode 100644 index 0000000000..3a80d1294d --- /dev/null +++ b/research/recursive-dot-carry/diagonal/verify.py @@ -0,0 +1,372 @@ +#!/usr/bin/env python3 +"""Exact low-bit and signed phase fusion checks with frozen local #7834 sources.""" + +import argparse +import ast +from collections import Counter +from dataclasses import dataclass +from hashlib import sha1, sha256 +import importlib.util +import json +from math import gcd, isqrt, prod +from pathlib import Path +from random import Random +import sys + + +SOURCE_HEAD = "4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02" + + +def check(test, message): + if not test: + raise ArithmeticError(message) + + +def bit(value, position): + return (value >> position) & 1 + + +def shift_add_signed(value, short, width=None): + """Signed shift-add, optionally consuming only a fixed-width low return.""" + multiplier = abs(short) + accumulated = 0 + shift = 0 + mask = None if width is None else (1 << width) - 1 + while multiplier: + if multiplier & 1: + accumulated += value << shift + if mask is not None: + accumulated &= mask + multiplier >>= 1 + shift += 1 + return -accumulated if short < 0 else accumulated + + +def fused_residue(x, second_x, y, second_y, carry, m, d): + mask = (1 << m) - 1 + x &= mask + second_y &= mask + carry &= mask + wide_return = x * (((y & mask) + second_y) & mask) + if d >= m or not second_y: + return (wide_return + carry) & mask + s = (second_y & -second_y).bit_length() - 1 + short_width = m - d - s + if short_width <= 0: + return (wide_return + carry) & mask + short_mask = (1 << short_width) - 1 + q = (((second_x & mask) >> d) - (x >> d)) & short_mask + if short_width == 1: + correction = q # second_y >> s is odd + else: + correction = shift_add_signed((second_y >> s) & short_mask, q, short_width) + return (wide_return + carry + (correction << (d + s))) & mask + + +def check_low_bits(): + residues = checked_carries = 0 + for m in range(1, 6): + size = 1 << m + for d in range(m + 1): + width = 1 << d + for x in range(size): + for second_x in range(x % width, size, width): + for y in range(size): + for second_y in range(size): + source = x * y + second_x * second_y + if fused_residue(x, second_x, y, second_y, 0, m, d) != source % size: + raise ArithmeticError((m, d, x, second_x, y, second_y)) + residues += 1 + if m <= 3: + for carry in range(size): + got = bit(fused_residue(x, second_x, y, second_y, carry, m, d), m - 1) + check(got == bit(source + carry, m - 1), "arbitrary carry") + checked_carries += 1 + rng = Random(1267834) + signed_cases = 1024 + for _ in range(signed_cases): + x, y, second_y, q = (rng.randint(-(1 << 41), 1 << 41) for _ in range(4)) + carry = rng.randint(-(1 << 81), 1 << 81) + m = rng.randint(1, 61) + d = rng.randint(0, m + 2) + second_x = x + (q << d) + got = fused_residue(x, second_x, y, second_y, carry, m, d) + check(got == (x * y + second_x * second_y + carry) % (1 << m), "signed residue") + return {"full_residue_cases": residues, "explicit_carry_cases": checked_carries, + "signed_random_cases": signed_cases} + + +def check_threshold(): + """Compute full carry signatures from the original two products.""" + rows = signatures = collisions = 0 + for m in range(1, 7): + size = 1 << m + for d in range(m + 1): + for second_y in range(size): + x, y = 1, size - 1 + rows += 1 + expected_period = size // gcd(size, second_y << d) + residue_to_signature, signature_to_residue = {}, {} + for q in range(size >> d): + source = x * y + (x + (q << d)) * second_y + signature = sum(bit(source + carry, m - 1) << carry for carry in range(size)) + residue = q % expected_period + previous = residue_to_signature.setdefault(residue, signature) + reverse = signature_to_residue.setdefault(signature, residue) + check(previous == signature and reverse == residue, "hidden offset period") + collisions += (q >= expected_period) + signatures += 1 + check(len(signature_to_residue) == expected_period, "hidden offset census") + # Same wide product and carry. Ignoring the hidden top bit gives a false return. + x, y, second_y, carry, m, d = 83, 117, 155, 177, 8, 7 + values = [bit(x * y + (x + (q << d)) * second_y + carry, m - 1) for q in (0, 1)] + dropped_bit = bit(x * (y + second_y) + carry, m - 1) + q1 = bit(fused_residue(x, x + (1 << d), y, second_y, carry, m, d), m - 1) + check(values == [1, 0] and dropped_bit == 1 and q1 == 0, "no-side-information negative control") + return {"fixed_right_rows": rows, "carry_signatures": signatures, + "same_residue_collisions": collisions, "required_parity_witness": { + "m": m, "d": d, "x": x, "y": y, "second_y": second_y, "carry": carry, + "wide_return_modulo": (x * (y + second_y)) % (1 << m), "expected_bits": values, + "bit_with_correction_omitted": dropped_bit, "bit_with_correction": q1}} + + +def pinned_bytes(path, blob): + raw = path.read_bytes() + actual = sha1(f"blob {len(raw)}\0".encode() + raw).hexdigest() + check(actual == blob, f"source identity for {path.name}") + return raw + + +def load_pinned(name, path, blob): + raw = pinned_bytes(path, blob) + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + exec(compile(raw, str(path), "exec"), module.__dict__) + return module, sha256(raw).hexdigest() + + +def finite_geometries(path): + source = pinned_bytes(path, "94a78b3c297b67b9aa1d07a3c67546ddb0f5ff75") + tree = ast.parse(source) + declarations = {"Geometry", "ceil_log", "prime", "choose"} + tree.body = [node for node in tree.body if getattr(node, "name", None) in declarations] + namespace = dict(dataclass=dataclass, isqrt=isqrt) + exec(compile(tree, str(path), "exec"), namespace) + return {n: namespace["choose"](n) for n in (144, 145, 1800)}, sha256(source).hexdigest() + + +def guarded_phase_raw(payload, phase, multiply, delta_cap): + x, y = payload + u, v = phase + same_sign = (u < 0) == (v < 0) + delta = u - (v if same_sign else -v) + w = v.bit_length() + if abs(delta) <= delta_cap and u.bit_length() == w: + real_factor = (x if same_sign else -x) - y + imag_factor = x + (y if same_sign else -y) + if max(real_factor.bit_length(), imag_factor.bit_length()) <= w: + real = multiply(v, real_factor) + shift_add_signed(x, delta) + imag = multiply(v, imag_factor) + shift_add_signed(y, delta) + return (real, imag), delta + return (multiply(x, u) - multiply(y, v), multiply(x, v) + multiply(y, u)), None + + +def patched_diagonal(fine, counts, delta_cap): + def diagonal(tape, diag, volume, scale, conjugate=False): + diag.home() + + def apply(_, payload): + phase = diag.read() + if conjugate: + phase = fine.conj(phase) + raw, delta = guarded_phase_raw(payload, phase, lambda a, b: fine.mul(a, b, tape.trace), delta_cap) + counts[delta] += 1 + return tuple(fine.tz(value, scale) for value in raw) + + return fine.map_tape(tape, volume, apply) + + return diagonal + + +def check_phase_raw(): + cases = matched = full_carry = 0 + for x in range(-8, 8): + for y in range(-8, 8): + for u in range(-8, 8): + for v in range(-8, 8): + calls = [] + + def counted(a, b): + calls.append(max(a.bit_length(), b.bit_length())) + return a * b + + actual, delta = guarded_phase_raw((x, y), (u, v), counted, 2) + expected = (x * u - y * v, x * v + y * u) + check(actual == expected, "raw signed phase product") + if delta is None: + check(len(calls) == 4, "phase fallback") + else: + original = [max(a.bit_length(), b.bit_length()) for a, b in + ((x, u), (y, v), (x, v), (y, u))] + check(len(set(original + calls)) == 1 and len(calls) == 2, "width guard") + for carry in (-128, -1, 0, 1, 128): + check([bit(t + carry, 4) for t in actual] == + [bit(t + carry, 4) for t in expected], "phase carry") + full_carry += 1 + matched += 1 + cases += 1 + return {"cases": cases, "width_preserving_fusions": matched, "signed_carry_checks": full_carry} + + +def choose_test_payload(q, f, phase, fine): + rng = Random(20261120) + scale = 1 << f + u, v = phase + same_sign = (u < 0) == (v < 0) + for _ in range(32): + x, y = tuple(rng.randrange(-(1 << (q - 2)), 1 << (q - 2)) << (f - q) for _ in range(2)) + dropped = (v * ((x if same_sign else -x) - y), v * (x + (y if same_sign else -y))) + original = (x * u - y * v, x * v + y * u) + if tuple(fine.tz(n, scale) for n in dropped) != tuple(fine.tz(n, scale) for n in original): + return x, y + raise ArithmeticError("missing nonzero correction control") + + +def selected_diagonal(fine, operation, payload, phase, width, scale, conjugate=False): + trace = fine.Trace() + source, diagonal = (fine.Tape(width, trace) for _ in range(2)) + source.append(payload) + diagonal.append(phase) + result = operation(source, diagonal, 1, scale, conjugate) + result.home() + received = result.read() + result.release() + diagonal.release() + check(trace.live == 0, "single-record owned banks") + return received, trace + + +def high_width_fixture(fine, word): + sources, radices, f, q, index = (3, 7), (8, 8), 8200, 8186, 9 + width, scale = f + len(radices) + 3, 1 << f + check(f == q + (radices[1]).bit_length() + 10, "ordinary chirp internal width") + calls = [] + + def integer_return(a, b): + calls.append(max(a.bit_length(), b.bit_length())) + return a * b + + # Keep the actual source dispatcher. Replace only its cold worker return. + prior = word.physical_product + word.physical_product = integer_return + try: + trace = fine.Trace() + phase, twist = fine.make_diagonals(sources, radices, width, f, trace) + coefficient = phase.cells[index] + row_hash = sha256(str(coefficient).encode()).hexdigest() + phase.release() + twist.release() + check(trace.live == 0, "public phase banks") + # cos(pi/8)^2 and sin(pi/8)^2 are (2 +/- sqrt(2))/4. + # Their floors after scaling by 2^(2*f) use exact integer square roots. + radical = isqrt(1 << (4 * f - 3)) + dc = isqrt((1 << (2 * f - 1)) + radical) + ds = isqrt((1 << (2 * f - 1)) - radical - 1) + direct_coefficient = (-((2 * ds * dc) >> f), (dc * dc - ds * ds) >> f) + check(coefficient == direct_coefficient, "independent integer phase formula") + check(tuple(abs(a).bit_length() for a in coefficient) == (f, f), "high phase width") + check(abs(coefficient[0]) - abs(coefficient[1]) == -1, "nonzero rounded phase offset") + payload = choose_test_payload(q, f, coefficient, fine) + check(sum(n * n for n in payload) <= 1 << (2 * f - 2), "admitted half disk") + receipts = {} + for conjugate in (False, True): + counts = Counter() + calls.clear() + want, before = selected_diagonal(fine, fine.scalar_diagonal, payload, coefficient, width, scale, conjugate) + baseline = calls.copy() + calls.clear() + have, after = selected_diagonal(fine, patched_diagonal(fine, counts, 2), payload, coefficient, + width, scale, conjugate) + direct = coefficient if not conjugate else fine.conj(coefficient) + x, y = payload + u, v = direct + exact = (fine.tz(x * u - y * v, scale), fine.tz(x * v + y * u, scale)) + check(have == want == exact, "high phase scaled output") + check(before.fast_words == 4 and after.fast_words == 2 and baseline == [f] * 4 and calls == [f] * 2, + "matched high word grades") + check(sum(counts.values()) == 1 and abs(next(iter(counts))) == 1, "bounded nonzero correction") + receipts[str(conjugate).lower()] = {"baseline_fast_widths": baseline, "fused_fast_widths": calls.copy(), + "delta": next(iter(counts)), "cleaned_owned_banks": True} + return {"sources": sources, "radices": radices, "q": q, "f": f, "index": index, + "coordinate": [1, 1], "phase_sha256": row_hash, "same_grid_results": receipts, + "independent_integer_phase_formula": True, + "correction_changes_truncated_output": True, + "execution": "actual source dispatcher with an exact integer test double for the physical worker", + "ingress": "legal direct chirp_middle fixture, outside product.choose geometries"} + finally: + word.physical_product = prior + + +def complete_chirp(fine, geometry, inverse=False): + sources, radices, q = geometry + scale = 1 << q + values = [(((5 * i + 7) % 19 - 9) * scale // 64, ((11 * i + 5) % 23 - 11) * scale // 64) + for i in range(prod(radices))] + before, after = fine.Trace(), fine.Trace() + want = fine.chirp_middle(values, sources, radices, q, inverse=inverse, trace=before) + counts = Counter() + original = fine.scalar_diagonal + try: + fine.scalar_diagonal = patched_diagonal(fine, counts, 2) + have = fine.chirp_middle(values, sources, radices, q, inverse=inverse, trace=after) + finally: + fine.scalar_diagonal = original + check(have == want and before.live == after.live == 0, "complete chirp and lifetimes") + fused = sum(n for delta, n in counts.items() if delta is not None) + check(before.fast_words == after.fast_words == 0 and fused > 0, "unmocked bounded-base control") + check(before.scalar_products - after.scalar_products == 2 * fused, "whole-middle dispatch census") + return {"geometry": geometry, "inverse": inverse, "outputs": len(have), "source_words": before.scalar_products, + "fused_words": after.scalar_products, "guard_census": {str(delta): n for delta, n in counts.items()}, + "source_fast_words": before.fast_words, "fused_fast_words": after.fast_words, + "out_sha256": sha256(str(have).encode()).hexdigest()} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--source-dir", type=Path, required=True, + help="checkout directory with the three pinned #7834 Python modules") + args = parser.parse_args() + source_dir = args.source_dir.resolve() + word_path = source_dir / "word_multiply.py" + word, word_hash = load_pinned("word_multiply", word_path, + "b148a60eac955722520e193f8bde0687635407ee") + fine, fine_hash = load_pinned("fine_ring_7834", source_dir / "fine_ring.py", + "b18da6275e31ac0bcc4174ec86106532c0cb5958") + emitted, product_hash = finite_geometries(source_dir / "product.py") + first = emitted[144] + check((first.sources, first.targets, first.precision) == ((5, 7), (8, 8), 128), "emitted first geometry") + check((emitted[145].sources, emitted[145].targets) == ((31, 29), (32, 32)), "emitted second geometry") + result = { + "status": "exact_local_scalar_fusion", + "sources": {"#7834_head": SOURCE_HEAD, "fine_ring_sha256": fine_hash, "word_multiply_sha256": word_hash, + "product_sha256": product_hash, + "#7838_head": "cd9ce5a555977b469bd848199bc36025bd82fdcb", + "#7838_role": "different carryless channel ABI without side information"}, + "low_bits": check_low_bits(), "threshold": check_threshold(), "phase_raw": check_phase_raw(), + "emitted_geometry_control": {n: vars(g) for n, g in emitted.items()}, + "full_unmocked_chirp_controls": [complete_chirp(fine, geometry, inverse) + for geometry in ((first.sources, first.targets, first.precision), + (emitted[145].sources, emitted[145].targets, + emitted[145].precision), + ((3, 7), (8, 8), 82)) + for inverse in (False, True)], + "matched_dispatch_control": high_width_fixture(fine, word), + "physical_recursive_p104_or_bit_credit": 0, + "kappa": None, + } + print(json.dumps(result, indent=2, sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/research/recursive-dot-carry/gaussian/PROOF.md b/research/recursive-dot-carry/gaussian/PROOF.md new file mode 100644 index 0000000000..c3a2cd7c41 --- /dev/null +++ b/research/recursive-dot-carry/gaussian/PROOF.md @@ -0,0 +1,45 @@ +# Gaussian product joins and the charged ordinary parent + +Source PR #7834 is pinned at `4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02`. Both component joins admit a three-product replacement with the same signed integers at their normalizers. This saves one ordinary word-product dispatch at each join. The charged recursive layer and the frozen #7830 signed tariff receive zero credit. + +## Literal uses + +| Site | First consumer | +| --- | --- | +| Pointwise Gaussian multiplication | `product.pointwise` reads one record from each bank. `fine_ring.times` combines `ac-bd` and `ad+bc` separately and truncates each toward zero on its existing grid. [Pointwise scan](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/fine-prime-gaussian-product/product.py#L108-L118) · [Signed joins](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/fine-prime-gaussian-product/fine_ring.py#L118-L130) | +| Synthetic ring multiplication | Two separate forward transforms produce the kernel and payload fields. The ring scan reads both, packs two signed components from each, combines four exact word products in the same real and imaginary joins, then decodes each signed packed sum, folds modulo \(Y^r+1\) and truncates once per folded component. The opposite transform consumes that return and restores the factor \(M=T/r\) once. [Packing and ring join](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/fine-prime-gaussian-product/fine_ring.py#L332-L390) · [Middle call and restoration](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/fine-prime-gaussian-product/fine_ring.py#L458-L489) | +| Sparse Gaussian border | `scale` performs each individual grid drop before `multiply_line` adds the record. At divisor 4, raw pairs \((3,1)\) and \((4,0)\) give the same sum and different sums of drops. The checker observes the same issue on actual coefficient pages in each completed finite Gaussian product. [Individual drops and accumulation](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/fine-prime-gaussian-product/sparse_tapes.py#L68-L106) | +| Recovery and final carry | Each component is scaled by \(S^2 2^{2b+4+3\Gamma}\). Real rounding and the separate imaginary residual precede an exact sum of squared errors, the radius comparison and running maximum. Inverse CRT returns coefficients in digit order, followed by low-to-high carry. The entrance disk guard and the final residual check use ordinary scalar square sums. [Recovery](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/fine-prime-gaussian-product/product.py#L121-L144) · [Carry scan](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/fine-prime-gaussian-product/product.py#L156-L170) · [Join through inverse CRT](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/fine-prime-gaussian-product/product.py#L211-L233) | + +## Exact three-product identity + +Use the classical Gauss/Karatsuba three-product identity with sign choices to bound operand widths. Choose \(s,t\in\{-1,1\}\) so that the two sums \(a+sb\) and \(c+td\) cancel magnitudes within each operand. Each is bounded in magnitude by the larger original component on its side. Set \(P=(a+sb)(c+td)\). If \(s=t\), also compute \(A=ac\) and \(B=bd\). The required components are \((A-B,s(P-A-B))\). If \(s=-t\), compute \(A=ad\) and \(B=bc\). The components are \((P-tA-sB,A+B)\). These identities also apply to the signed packed integers in one ring row. + +The two outputs before truncation or centered limb recovery are equal as integers. For any signed incoming carry \(k\) and any positive normalization divisor \(D\), equality of those integers gives the same quotient and remainder of \(z+k\) modulo \(D\), hence the same next carry and signed truncation. Identical packed sums give identical centered extraction, fold and divisional normalization. Identical field values then give the same radius admission, normalized opposite transform, recovered coefficients, inverse CRT and carry. This uses the original numerical proof and does not require a wider grid or a larger radius. [Recovery scaling and admission](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/fine-prime-gaussian-product/PROOF.md#L45-L61) · [Error bounds](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/fine-prime-gaussian-product/ACCURACY.md#L67-L85) + +The two retained products form one of the two matchings between component pairs. If the mixed product crosses the physical cutoff, its wide side has an original wide component, so at least one discarded product crossed it too. The number of physical dispatches weakly decreases. It strictly decreases when all four original calls cross the cutoff. There are also inputs where the physical count ties. The four components \(a=b=c=d=2^{8191}+1\) fit the pointwise disk at grid precision 8,195. All original calls have 8,192-bit operands, while an unconditional \((a+b)(c+d)\) has 8,193-bit operands and launches one physical child. The cancellation rule keeps these inputs below the physical cutoff. + +At component width \(L\), the signs, mixture operands and reconstruction can use a fixed number of scratch words with \(O(L)\) read, write, rewind and erasure work. All intermediate reconstruction sums fit within \(2L+O(1)\) bits. At the packed site this is \(O(rp)\) per ring row. The original field scans, home positions, decoders and releases are retained. The public word interface copies signed operands, consumes the exact child return and restores its word roles. A reduction in recorded dispatches leaves the net finite bit transition difference dependent on the extra signed scans. [Borrowed tape restoration](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/fine-prime-gaussian-product/crt_route.py#L48-L105) · [Word selector and adapter](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/fine-prime-gaussian-product/word_multiply.py#L42-L62) · [Child disposal](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/fine-prime-gaussian-product/word_multiply.py#L93-L118) + +## Charged alternative + +The grouped Hadamard word parks all other owners around each paid `visit`. A CRT swap batch applies one Hadamard, a sign diagonal and the second Hadamard to the resulting bank. Those calls are serial. The two synthetic forward branches are consumed through the ring product. The growing-group funded C word is established through a finite-word existence and search argument. Its literal paid program was not materialized by the source, so the conditional program gives no concrete additional sum-only pair. [Charged parking and return](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/fine-prime-gaussian-product/c_dispatch.py#L138-L188) · [CRT batch](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/fine-prime-gaussian-product/crt_route.py#L140-L162) · [Layer tariff and source scope](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/fine-prime-gaussian-product/BUTTERFLIES.md#L43-L47) + +There is a literal pair of complete charged \(F_I\) roots in the fitted ordinary transpose. On the two body addresses \(H,D\), let \(C_n\) reverse the \(n\) atom positions. The first root after the initial subtraction returns \(X=C_n(D-H)\) and \(Y=C_n H\). The next addition forms \(X+Y=C_nD\). The second root receives \((X,X+Y)\), returning \((D,D-H)\). The final sign and addition produce \((D,H)\). For \(D=e_0\), the legal choices \(H=0\) and \(H=e_0\) give equal \(X+Y=e_{n-1}\) with different \(X\), different second-root inputs and different outputs. The sum alone loses a live lane. Each root has complete padding, restriction and output-disposal passes. [Production adapter](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/fine-prime-gaussian-product/compact_outer.py#L97-L110) · [Two-root loop](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/selected-outer-borrowing-wrapper/outer.py#L91-L116) · [Root endpoint](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/physical-ordinary-interchange/PROOF.md#L38-L52) · [States and restoration](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/physical-ordinary-interchange/PROOF.md#L125-L172) + +The retained body adds and signs target \(D\), so zero roots leave \(H\) unchanged. One root between any atomwise pre- and post-maps makes output atom \(j\) depend on input atom \(n-1-j\). The required swap depends on input atom \(j\). Two roots are necessary at every fitted \(n\ge64\) under the retained body operations. Even allowing a forward pre-scan and forward post-scan with a carry, fix the suffix after the first \(m=\lfloor n/2\rfloor\) input atom pairs. The last \(m\) pre-scan outputs, read first after reversal, depend on that arbitrary prefix only through the midpoint state. The desired first \(m\) output pairs form an injection of the prefix, requiring at least \(2m\log_2(q^w)\) midpoint bits when the modulus of each atom is \(q^w\), with fixed initial state and no other side channel. This statement covers those forward carried passes. Cross-atom routing and rereading retained inputs are outside its scope. [Body updates](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/selected-outer-borrowing-wrapper/outer.py#L29-L79) + +## Tariff + +The word multiply above 8,192 bits uses an acyclic \(O(L\log^2(L+2))\) subroutine. Its calls appear in the additive scalar and packed ring rows. The paid C recurrence has the same \((P/W)N^{-.998263}\) moment and the ordinary wrapper still needs its two roots under the attempted local edit. The #7834 bound under its predecessor premises still has time power \(1-.997\cdot.001737=.998268211\) after deleting all additive scalar and ring work. The #7830 rational and binary invoices price their own native jobs and independent targets. This replacement changes neither signed histogram and supplies zero credit toward either shortfall at \(\kappa=0.003884928046155\). [Word complexity](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/physical-fft-word/PROOF.md#L134-L166) · [Complete #7834 invoice](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/fine-prime-gaussian-product/PROOF.md#L63-L83) · [Comparator #7830](https://github.com/CrocSwap/integer-mult-bounds/pull/7830) + +## Replay + +Place `check.py` and `SOURCE-BLOBS.json` side by side. Use any checkout containing the exact #7834 blobs. + +```sh +python3 -B check.py --source /path/to/checkout/research/fine-prime-gaussian-product --regression-only +python3 -B check.py --source /path/to/checkout/research/fine-prime-gaussian-product +``` + +The first command runs both complete versions of the 20-bit regression, including coefficient recovery, the residual check, inverse CRT and final carry. It yields 74,655 original and 62,284 fused ordinary word-product dispatches. The second runs that regression plus the signed arithmetic, word selector, signed ring, fitted address and additional finite Gaussian controls. The full finite products use the bounded Walsh branch and finish with empty numerical tapes. The selector controls substitute an exact bigint oracle only for the wide child body. The fitted address check models the documented two-root endpoint. diff --git a/research/recursive-dot-carry/gaussian/REGRESSION.json b/research/recursive-dot-carry/gaussian/REGRESSION.json new file mode 100644 index 0000000000..64de646ed2 --- /dev/null +++ b/research/recursive-dot-carry/gaussian/REGRESSION.json @@ -0,0 +1,126 @@ +{ + "complete_finite_products": [ + { + "coefficients": 35, + "fast_words_old_new": [ + 0, + 0 + ], + "fused_parents": { + "ring_products": 24, + "times": 12347 + }, + "input_bits": [ + 20, + 19 + ], + "max_residual_squared_numerator": 31146888301070224773812339651641344, + "path": "gaussian", + "payload_trace": { + "erased": 110070804, + "high_water": 889440, + "live": 0, + "reads": 154925898, + "resets": 8968, + "travel": 759467396, + "writes": 221871024 + }, + "radius_numerator": 33101457261173145600, + "reached_postponed_drop_failure": { + "component": 0, + "line_call": 9, + "nonzero_product_count": 3, + "nonzero_signed_products_hex": [ + "-0xf8423ae9066084534c051561d7573cca7dd47612b86b4e507eed38b31e03abc45795475943f4b14420d8d1bf41ad639df6438c31da5b62006d7ea95f59f7e06a13ac15a631c306bd05a0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "-0x2bcb0cee2546cfa2bacf43b7c1807e4ab565594e19649321800e96247b0ca3336d1ca95066dd2767482ff8ccaf852932c42cfbaf19addb5f7905751f6d03e2ddbd951d933d411b3a8d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "-0x5a1c5ad80862a88a693fbb68c9010591b438dd362e83b546d75d689524eebdbdea87ad2b260100e9f4ebc5acfda54a2b20d101da464c1d0efc671c51b581886d4e6ef4e09a462bd2248e40000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + ], + "row": 0, + "scale_bits": 480, + "sum_of_drops_minus_drop_of_sum": 2 + }, + "sources": [ + 5, + 7 + ], + "targets": [ + 8, + 8 + ], + "word_products_old_new": [ + 74655, + 62284 + ] + } + ], + "source": { + "files": { + "axis_program.py": { + "git_blob": "8a32490a41dfb8e1ee5261f449ce0bce49b6cc17", + "sha256": "0aef16ada64d11a4ce716eb1f78ec1129123ff98cae564c91c1d76a11afd1e18" + }, + "c_dispatch.py": { + "git_blob": "e297420a5913071b88ee097ae1243589affb1b8d", + "sha256": "08784858188a38a94054c61fe80b99618a1be50530269e6db207c3ce96bee5ab" + }, + "catalogue_codec.py": { + "git_blob": "319d6b43bed7728bf8ceae42f91525eb3dc17fae", + "sha256": "ee79eb38eaf7e956b5649f10f759cbfa94541dca735c5822190bb31f8db6062e" + }, + "compact_ordinary.py": { + "git_blob": "a0a496c6cf95af7f972359a0adad103ba81ffb7a", + "sha256": "1f9051b115a5f81fac8c64d004ad6e1bbc8d55e9c655a5a59e426f641ec7474a" + }, + "condensed.py": { + "git_blob": "cae4c0546efe9a7a2dd7e152f58fc10b82b23172", + "sha256": "cbe09376546cf81096d22d40d33ffa916f8b4c975eb66f85f3fd7f25495f4388" + }, + "crt_route.py": { + "git_blob": "6e5cfdd9e8f01448e95ce3e3717b2ba722c75a6d", + "sha256": "e86913fe81444728ed8e13377ec3356ec604f7bfb46264a077887041c1b278a4" + }, + "fine_ring.py": { + "git_blob": "b18da6275e31ac0bcc4174ec86106532c0cb5958", + "sha256": "70c639c9c23225acbf5a2165eaad81a8f6a65ec9b3e08bf05df9ecf416a0d313" + }, + "finite_c_word.py": { + "git_blob": "48036da3b5b271ae7d4e95218fff80bf789ca816", + "sha256": "b4f6ec571406e980c3354ff10f4711de018bd4d87b77077aff528908fd922e51" + }, + "gauged_circulants.py": { + "git_blob": "3d186b386291e1d54b13377ac8e0b9fd5413a60d", + "sha256": "84dd9691f3ae3c0278cc37b543733aaa21dfc456e9d51ab8fc866718123eed18" + }, + "gaussian_pages.py": { + "git_blob": "dfc01e092502bdaca1de99985e1c288204564e0c", + "sha256": "8bf23e4e2c6b09bca2382432970a3a19e8cf1dba03c8bfc767c9f8d49e5d97d0" + }, + "product.py": { + "git_blob": "94a78b3c297b67b9aa1d07a3c67546ddb0f5ff75", + "sha256": "610fb9c7c0008e477519ce96eea56d7c17e37939d7d98054b14f62c516e5a174" + }, + "recovery_radius.py": { + "git_blob": "0a360cbc6834cc38fb2dc5bd63603af9103c15b0", + "sha256": "d9ec4c1d28ddf4a58164f695fc8cf88cc1cbe78323702504278b30895e48c2a3" + }, + "scattered_cnot.py": { + "git_blob": "7941c3ec097f7dd3dc414ef6a45f4f2ea689981d", + "sha256": "15662405c3e4bec16562f0c14df116928b1f793cae761ebf29c2037965d1bc0f" + }, + "selected_h.py": { + "git_blob": "0c088ba350b2fe0cb74256f8a4438da6659476c5", + "sha256": "c73cc6bafbb7cd7fed6157abb5946753bab3459bb8451dd913ffb2f82874a12f" + }, + "sparse_tapes.py": { + "git_blob": "1d2eb9427ab5810e1837b9d506ec099adba7e1e8", + "sha256": "52dd7a2fe6f2d7dc0986a42f0ec101765e0b8d7dcfaaa5d2a60ce4c00ff96ad3" + }, + "word_multiply.py": { + "git_blob": "b148a60eac955722520e193f8bde0687635407ee", + "sha256": "87bf3512dfab314e26f297678f809bdf0913b5fa28642379ad48ae1b900de481" + } + }, + "head": "4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02", + "path": "research/fine-prime-gaussian-product" + } +} diff --git a/research/recursive-dot-carry/gaussian/SOURCE-BLOBS.json b/research/recursive-dot-carry/gaussian/SOURCE-BLOBS.json new file mode 100644 index 0000000000..67be3a5ba9 --- /dev/null +++ b/research/recursive-dot-carry/gaussian/SOURCE-BLOBS.json @@ -0,0 +1,22 @@ +{ + "head": "4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02", + "path": "research/fine-prime-gaussian-product", + "git_blobs": { + "word_multiply.py": "b148a60eac955722520e193f8bde0687635407ee", + "selected_h.py": "0c088ba350b2fe0cb74256f8a4438da6659476c5", + "c_dispatch.py": "e297420a5913071b88ee097ae1243589affb1b8d", + "crt_route.py": "6e5cfdd9e8f01448e95ce3e3717b2ba722c75a6d", + "axis_program.py": "8a32490a41dfb8e1ee5261f449ce0bce49b6cc17", + "sparse_tapes.py": "1d2eb9427ab5810e1837b9d506ec099adba7e1e8", + "compact_ordinary.py": "a0a496c6cf95af7f972359a0adad103ba81ffb7a", + "scattered_cnot.py": "7941c3ec097f7dd3dc414ef6a45f4f2ea689981d", + "finite_c_word.py": "48036da3b5b271ae7d4e95218fff80bf789ca816", + "recovery_radius.py": "0a360cbc6834cc38fb2dc5bd63603af9103c15b0", + "gaussian_pages.py": "dfc01e092502bdaca1de99985e1c288204564e0c", + "catalogue_codec.py": "319d6b43bed7728bf8ceae42f91525eb3dc17fae", + "gauged_circulants.py": "3d186b386291e1d54b13377ac8e0b9fd5413a60d", + "product.py": "94a78b3c297b67b9aa1d07a3c67546ddb0f5ff75", + "fine_ring.py": "b18da6275e31ac0bcc4174ec86106532c0cb5958", + "condensed.py": "cae4c0546efe9a7a2dd7e152f58fc10b82b23172" + } +} diff --git a/research/recursive-dot-carry/gaussian/check.py b/research/recursive-dot-carry/gaussian/check.py new file mode 100644 index 0000000000..e444bdd7d1 --- /dev/null +++ b/research/recursive-dot-carry/gaussian/check.py @@ -0,0 +1,417 @@ +#!/usr/bin/env python3 +"""Check the signed products and charged continuation at the registered #7834 head.""" + +import argparse +from collections import Counter +from contextlib import contextmanager +from functools import cache +from hashlib import sha1, sha256 +from inspect import getsource +from itertools import product as combinations +import json +from math import prod +from pathlib import Path +from random import Random +import sys +from unittest.mock import patch + + +HERE = Path(__file__).resolve().parent + + +def require(condition, message): + if not condition: + raise ArithmeticError(message) + + +def bind_sources(source_path): + pins = json.loads((HERE / "SOURCE-BLOBS.json").read_text()) + files = {} + for name, expected in sorted(pins["git_blobs"].items()): + data = (source_path / name).read_bytes() + git_blob = sha1(f"blob {len(data)}\0".encode() + data).hexdigest() + require(git_blob == expected, f"source blob changed: {name}") + files[name] = {"git_blob": git_blob, "sha256": sha256(data).hexdigest()} + sys.path.insert(0, str(source_path)) + return {"head": pins["head"], "path": pins["path"], "files": files} + + +def signed_mix(first, second): + """Return first+s*second with the sign s that cancels magnitudes.""" + if (first < 0) == (second < 0): + return first - second, -1 + return first + second, 1 + + +def cross_parts(a, b, c, d, mul, trace): + """Exact Gaussian product numerators using three equally bounded products.""" + x, s = signed_mix(a, b) + y, t = signed_mix(c, d) + mixed = mul(x, y, trace) + if s == t: + ac = mul(a, c, trace) + bd = mul(b, d, trace) + cross = mixed - ac - bd + return ac - bd, cross if s == 1 else -cross + ad = mul(a, d, trace) + bc = mul(b, c, trace) + cross = ad - bc if s == 1 else bc - ad + return mixed + cross, ad + bc + + +def trunc_zero(value, divisor): + quotient, remainder = divmod(value, divisor) + return quotient + int(value < 0 and remainder != 0) + + +def raw_checks(): + def check_product(a, b, trace): + return a * b + + cases = 0 + carried = 0 + for a, b, c, d in combinations(range(-4, 5), repeat=4): + actual = cross_parts(a, b, c, d, check_product, None) + exact = a * c - b * d, a * d + b * c + require(actual == exact, "signed numerator mismatch") + x, _ = signed_mix(a, b) + y, _ = signed_mix(c, d) + require(abs(x) <= max(abs(a), abs(b)), "left mixture widened") + require(abs(y) <= max(abs(c), abs(d)), "right mixture widened") + cases += 1 + for divisor, carry in combinations((4, 8, 16), (-23, -7, -1, 0, 1, 7, 23)): + for total, original in zip(actual, exact, strict=True): + quotient, digit = divmod(total + carry, divisor) + expected = original + carry + expected_digit = expected & (divisor - 1) + expected_carry = expected >> (divisor.bit_length() - 1) + require((quotient, digit) == (expected_carry, expected_digit), "integer carry failed") + magnitude = abs(expected) // divisor + signed = -magnitude if expected < 0 else magnitude + require(trunc_zero(total + carry, divisor) == signed, "signed q-grid drop changed") + carried += 1 + separating = { + "scale": 4, + "summands": [[3, 1], [4, 0]], + "common_sum": 4, + "sum_of_signed_drops": [0, 1], + } + return {"quadruples": cases, "carry_and_drop_comparisons": carried, + "individually_dropped_collision": separating} + + +@contextmanager +def candidate(): + """Change just the multiplication joins in memory.""" + import axis_program + import fine_ring + import product + + calls = Counter() + + def parts(a, b, c, d, trace): + calls["ring_products"] += 1 + return cross_parts(a, b, c, d, fine_ring.mul, trace) + + def times(a, b, divisor, trace): + calls["times"] += 1 + real, imag = cross_parts(*a, *b, fine_ring.mul, trace) + return fine_ring.tz(real, divisor), fine_ring.tz(imag, divisor) + + source = getsource(fine_ring.ring_products) + target = "real = mul(a, c, trace) - mul(b, d, trace)\n imag = mul(a, d, trace) + mul(b, c, trace)" + require(source.count(target) == 1, "the two ring joins changed") + rewritten = source.replace(target, "real, imag = _parts(a, b, c, d, trace)") + namespace = dict(fine_ring.__dict__, _parts=parts) + exec(compile(rewritten, "", "exec"), namespace) + with ( + patch.object(fine_ring, "times", times), + patch.object(axis_program, "times", times), + patch.object(product, "times", times), + patch.object(fine_ring, "ring_products", namespace["ring_products"]), + ): + yield calls + + +def word_dispatch_checks(): + """Exercise the actual selector; the expensive child body has an exact oracle.""" + import fine_ring + import word_multiply + + width = word_multiply.BASE_BITS + q = width + 3 + divisor = 1 << q + below = (1 << (width - 1)) + 1 + above = (1 << width) + 1 + endpoint_checks = 0 + fast_transitions = Counter() + + def physical_oracle(a, b): + return a * b + + with patch.object(word_multiply, "physical_product", physical_oracle): + for bits in combinations((0, below, above, -below, -above), repeat=4): + a, b, c, d = bits + radius_sq = ((5 * divisor) // 16 - 1) ** 2 + require(a * a + b * b <= radius_sq and c * c + d * d <= radius_sq, + "test record exceeds the pointwise entrance disk") + old = fine_ring.Trace() + exact = fine_ring.times((a, b), (c, d), divisor, old) + new = fine_ring.Trace() + p, r = cross_parts(a, b, c, d, word_multiply.product, new) + actual = trunc_zero(p, divisor), trunc_zero(r, divisor) + require(actual == exact, "dispatch endpoint changed") + require((old.scalar_products, new.scalar_products) == (4, 3), "word count changed") + require(new.fast_words <= old.fast_words, "avoidable larger dispatch") + require(new.max_scalar_operand <= old.max_scalar_operand, "avoidable width increase") + fast_transitions[f"{old.fast_words}->{new.fast_words}"] += 1 + endpoint_checks += 1 + b = below + naive = fine_ring.Trace() + word_multiply.product(b, b, naive) + word_multiply.product(b, b, naive) + word_multiply.product(b + b, b + b, naive) + require((naive.scalar_products, naive.fast_words) == (3, 1), + "unprotected join should cross the physical cutoff on this input") + require(fast_transitions["4->3"] > 0 and fast_transitions["2->2"] > 0, + "test should see both strict and tied physical counts") + return {"selector": "actual word_multiply.product", + "physical_child": "exact bigint oracle only for selector controls", + "threshold_bits": width, "checks": endpoint_checks, + "fast_word_transitions": dict(sorted(fast_transitions.items())), + "unconditionally_additive_mix_negative_control": { + "component_formula_for_all_four": "2^8191+1", + "pointwise_grid_bits": q, + "original_operand_bits": width, + "mixed_operand_bits": width + 1, + "baseline_fast": 0, + "naive_fast": 1, + }} + + +def ring_expected(first, second, r, divisor): + output = [] + for offset in range(0, len(first), r): + real = [0] * r + imag = [0] * r + for i, (a, b) in enumerate(first[offset:offset + r]): + for j, (c, d) in enumerate(second[offset:offset + r]): + k = (i + j) % r + sign = 1 if i + j < r else -1 + real[k] += sign * (a * c - b * d) + imag[k] += sign * (a * d + b * c) + output.extend((trunc_zero(a, divisor), trunc_zero(b, divisor)) + for a, b in zip(real, imag, strict=True)) + return output + + +def ring_checks(): + import fine_ring + + def execute(first, second, r, outer, f): + trace = fine_ring.Trace() + x = fine_ring.Tape(f + 8, trace) + y = fine_ring.Tape(f + 8, trace) + for left, right in zip(first, second, strict=True): + x.append(left) + y.append(right) + out = fine_ring.ring_products(x, y, r, outer, f) + out.home() + projections = [out.read() for _ in range(len(first))] + out.release() + require(trace.live == 0 and x.released and y.released, "ring banks still live") + return projections, vars(trace) + + seed = Random(7834) + tested = [] + for r, outer, f in ((4, (2,), 16), (8, (4, 8), 36), (16, (8,), 61)): + n = r * prod(outer) + endpoint = 1 << (f - 2) + a = [(seed.randint(-endpoint, endpoint), seed.randint(-endpoint, endpoint)) + for _ in range(n)] + b = [(seed.randint(-endpoint, endpoint), seed.randint(-endpoint, endpoint)) + for _ in range(n)] + a[r - 1] = (-endpoint, endpoint) + b[r - 1] = (endpoint, endpoint) + original, old = execute(a, b, r, outer, f) + with candidate() as calls: + fused, new = execute(a, b, r, outer, f) + require(original == fused == ring_expected(a, b, r, r << f), "negacyclic return changed") + require(calls == {"ring_products": prod(outer)}, "ring path did not execute") + movement = ("reads", "writes", "travel", "resets", "erased", "high_water") + require(all(old[k] == new[k] for k in movement), "ring tape behavior changed") + require(old["scalar_products"] - new["scalar_products"] == prod(outer), + "ring count changed outside the join") + tested.append({"r": r, "outer": outer, "f": f, "coefficients": n, + "word_products_old_new": [old["scalar_products"], new["scalar_products"]], + "payload_trace": {k: new[k] for k in (*movement, "live")}}) + return tested + + +def pre_carry_oracle(left, right, width, size): + mask = (1 << width) - 1 + x, y = int(left, 2), int(right, 2) + coeff = [0] * size + for i in range((len(left) + width - 1) // width): + for j in range((len(right) + width - 1) // width): + coeff[i + j] += ((x >> (i * width)) & mask) * ((y >> (j * width)) & mask) + return coeff + + +@contextmanager +def observed_sparse_drop(): + """Witness an actual individually rounded sparse sum without changing it.""" + import fine_ring + import sparse_tapes + + multiply_line = sparse_tapes.multiply_line + witness = {} + visited = 0 + + def compare(line, page, offsets, unit, owner): + nonlocal visited + visited += 1 + if not witness: + n = len(line.cells) + for i in range(n): + row = page.cells[i*len(offsets):(i + 1)*len(offsets)] + for component in (0, 1): + raw = [line.cells[(i + h) % n][component] * c + for h, (c, _) in zip(offsets, row, strict=True)] + actual = sum(fine_ring.tz(value, unit) for value in raw) + postponed = fine_ring.tz(sum(raw), unit) + if actual != postponed: + witness.update({"line_call": visited, "row": i, "component": component, + "scale_bits": unit.bit_length() - 1, + "nonzero_product_count": sum(value != 0 for value in raw), + "sum_of_drops_minus_drop_of_sum": actual - postponed, + "nonzero_signed_products_hex": [hex(x) for x in raw if x]}) + break + if witness: + break + return multiply_line(line, page, offsets, unit, owner) + + with patch.object(sparse_tapes, "multiply_line", compare): + yield witness + + +def full_checks(interior, regression_only=False): + import product + + fixtures = [ + (format(741503, "b"), format(466013, "b")), + ("0", "111101"), + ("0100010111001", "0111010010110010"), + ("1" * 144, "1" * 144), + ("1".zfill(1801), "11"), + ] + if regression_only: + fixtures = fixtures[:1] + elif interior: + fixtures.append((format(741503, "0145b"), format(466013, "0145b"))) + + catalogue_once = cache(product.catalogue) + evidence = [] + with patch.object(product, "catalogue", catalogue_once): + for a, b in fixtures: + with observed_sparse_drop() as witness: + original, old = product.multiply(a, b) + with candidate() as calls: + result, new = product.multiply(a, b) + require(original == result, "complete multiplier output changed") + require(result == format(int(a, 2) * int(b, 2), f"0{2 * max(len(a), len(b))}b"), + "complete product disagrees with the independent integer product") + if old["path"] == "elementary": + require(old == new and not calls, "the fallback entered the modified joins") + evidence.append({"input_bits": [len(a), len(b)], "path": old["path"], + "fused_parents": {}}) + continue + require(old["path"] == "gaussian", "the complete Gaussian route was not used") + require(bool(witness), "the concrete sparse grid control did not observe a drop change") + tr_old, tr_new = old.pop("trace"), new.pop("trace") + require(old == new, "complete normalization, recovery or public routing receipt changed") + require(new["coefficients"] == pre_carry_oracle(a, b, new["digit_bits"], prod(new["sources"])), + "the coefficients entering the carry scan changed") + require(tr_new["live"] == tr_old["live"] == 0, "tape still live after complete product") + require(tr_old["scalar_products"] - tr_new["scalar_products"] == sum(calls.values()), + "observed word savings differ from the localized joins") + require(calls["ring_products"] == tr_old["rings"], "synthetic ring attempt did not execute") + require(tr_new["fast_words"] == tr_old["fast_words"] == 0, + "finite control unexpectedly crossed the short-word cutoff") + movement = ("reads", "writes", "travel", "resets", "erased", "high_water", "live") + require(all(tr_old[k] == tr_new[k] for k in movement), "full record movements changed") + evidence.append({ + "input_bits": [len(a), len(b)], + "path": old["path"], + "sources": new["sources"], + "targets": new["targets"], + "fused_parents": dict(calls), + "word_products_old_new": [tr_old["scalar_products"], tr_new["scalar_products"]], + "fast_words_old_new": [tr_old["fast_words"], tr_new["fast_words"]], + "coefficients": len(new["coefficients"]), + "max_residual_squared_numerator": new["max_residual_squared_numerator"], + "radius_numerator": new["radius_numerator"], + "payload_trace": {k: tr_new[k] for k in movement}, + "reached_postponed_drop_failure": witness, + }) + return evidence + + +def wrapper_checks(): + """Use signed atom addresses to test the documented fitted body endpoint.""" + def add(a, b, modulus): + return tuple((x + y) % modulus for x, y in zip(a, b, strict=True)) + + def subtract(a, b, modulus): + return tuple((x - y) % modulus for x, y in zip(a, b, strict=True)) + + def root(h, d): + return d[::-1], h[::-1] + + def body(h, d, modulus): + x, y = root(h, subtract(d, h, modulus)) + z, w = root(x, add(x, y, modulus)) + return z, subtract(z, w, modulus) + + count = 0 + for modulus, n in ((3, 2), (3, 3), (2, 4)): + for h, d in combinations(combinations(range(modulus), repeat=n), repeat=2): + require(body(h, d, modulus) == (d, h), "two-root address identity failed") + count += 1 + n = 64 + empty = (0,) * n + basis = (1,) + empty[:-1] + modulus = 213 * (1 << 80) + 1 + first = root(empty, subtract(basis, empty, modulus)) + second = root(basis, subtract(basis, basis, modulus)) + require(add(*first, modulus) == add(*second, modulus), "missing equal-sum control") + require(first[0] != second[0], "the separate next input should differ") + require(body(empty, basis, modulus) != body(basis, basis, modulus), + "the two legal endpoint addresses must differ") + return {"abstract_address_checks": count, "production_width_collision": n, + "modulus_for_collision": modulus, "h_either_zero_or_first_basis": True, + "d_first_basis": True, "sum_in_both_cases": "e_63", "first_return_differs": True, + "physical_compact_root_executed": False} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--source", type=Path, default=HERE / "source") + mode = parser.add_mutually_exclusive_group() + mode.add_argument("--interior", action="store_true", help="also replay the costly 145-bit geometry") + mode.add_argument("--regression-only", action="store_true", help="replay just the full 20-bit product") + args = parser.parse_args() + result = {"source": bind_sources(args.source.resolve())} + if not args.regression_only: + result.update({ + "signed_arithmetic": raw_checks(), + "dispatch": word_dispatch_checks(), + "signed_ring_tapes": ring_checks(), + "charged_wrapper": wrapper_checks(), + }) + result["complete_finite_products"] = full_checks(args.interior, args.regression_only) + print(json.dumps(result, indent=2, sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/research/recursive-dot-carry/independent.py b/research/recursive-dot-carry/independent.py new file mode 100644 index 0000000000..c616f56b63 --- /dev/null +++ b/research/recursive-dot-carry/independent.py @@ -0,0 +1,310 @@ +"""Independent replay of the frozen recursive dot/carry proof and circuit DAGs.""" + +import argparse +import ast +from collections import Counter +from decimal import Decimal, localcontext +from hashlib import sha256 +from itertools import islice, product +import json +from pathlib import Path +from random import Random + + +FROZEN_SHA256 = { + "PROOF.md": "91a07dc16676855f4c8dee00d585aa4b76ecc9598d0bfa9505b2586f117c0f66", + "verify.py": "d9d79479677fd0bbabb5ea53922d5cd9c77ab63cb9705e10ae8364f640ef30c1", + "circuits.py": "6c42072338a467acbab3c177fbb9c1a0bd0db22bb550cc31a261bb43951a3ed8", + "RESULT.json": "0ef14058b848348703d7ae42e89811f881965a0f0bdcc72679754316e8ef6535", +} + + +def require(condition, detail): + if not condition: + raise ValueError(detail) + + +def residue(words, m, a, b): + x, u, y, v, c = words + modulus = 1 << m + d = max(0, m + 1 - a - b) + mean_x = ((x + u) // 2) % (modulus // 2) + mean_y = ((y + v) // 2) % (modulus // 2) + diff_x = (u - x) // (1 << a) + diff_y = (v - y) // (1 << b) + return (2 * mean_x * mean_y + ((diff_x * diff_y % (1 << d)) << (a + b - 1)) + c) % modulus + + +def direct(words, m): + x, u, y, v, c = words + return (x * y + u * v + c) % (1 << m) + + +def congruence_checks(): + # The determinant criterion would erroneously accept this smallest mixed minor. + pairs_mod_4 = tuple(product(range(4), repeat=2)) + require((2 * 2) % 4 == 0, "determinant control setup") + require( + all(tuple(s * t % 4 for s in left for t in right) != (2, 0, 0, 2) + for left, right in product(pairs_mod_4, repeat=2)), + "degenerate determinant control", + ) + + exact = 0 + for m in range(2, 6): + modulus = 1 << m + pairs = { + a: [(x, u) for x, u in product(range(modulus), repeat=2) if (u - x) % (1 << a) == 0] + for a in range(1, m + 1) + } + for a, b in product(pairs, repeat=2): + failed_without_residual = False + for (x, u), (y, v) in product(pairs[a], pairs[b]): + c = (3 * x - 7 * u + 11 * y - 13 * v) % modulus - modulus + words = (x, u, y, v, c) + want = direct(words, m) + require(residue(words, m, a, b) == want, (m, a, b, words)) + if ((x + u) * (y + v) // 2 + c) % modulus != want: + failed_without_residual = True + exact += 1 + require(failed_without_residual == (a + b <= m), (m, a, b, "no correction")) + + rng = Random(2941362) + signed = 0 + residual_witnesses = 0 + for m in (2, 3, 5, 8, 16, 63, 257, 1024): + modulus = 1 << m + choices = [(m, 1), (1, m), (m, m), (1, m - 1), (1, 1)] + choices += [(rng.randint(1, m), rng.randint(1, m)) for _ in range(101)] + for a, b in choices: + x, y, v, z, c = (rng.randrange(-2 * modulus, 2 * modulus) for _ in range(5)) + words = (x, x + (v << a), y, y + (z << b), c) + require(residue(words, m, a, b) == direct(words, m), (m, a, b, "signed lifts")) + signed += 1 + for a, b in product(range(1, min(m, 8) + 1), repeat=2): + d = m + 1 - a - b + if 1 <= d <= 8: + require(d <= m - a and d <= m - b, "inadmissible residual dimensions") + for swapped in (False, True): + outputs = set() + for k in range(1 << d): + v, z = (1, k) if swapped else (k, 1) + p, q = v << (a - 1), z << (b - 1) + words = (-p, p, -q, q, -29) + require(residue(words, m, a, b) == direct(words, m), "residual witness") + outputs.add(direct(words, m)) + require(len(outputs) == 1 << d, "narrow residual alias") + residual_witnesses += 1 + + low_width_alias = [direct((-k, k, -1, 1, 0), 5) for k in (0, 8)] + require(low_width_alias == [0, 16] and 0 % 8 == 8 % 8, "lost residual bit control") + return { + "exhaustive_case_count": exact, + "independent_signed_lift_cases": signed, + "residual_separation_families": residual_witnesses, + "zero_determinant_non_outer_product_mod_4": [[2, 0], [0, 2]], + "three_bit_alias_outputs_for_four_bit_residual": low_width_alias, + } + + +def odd_channel_checks(): + results = [] + for m in range(3, 7): + modulus = 1 << m + half = modulus // 2 + inner_mask = half // 2 - 1 + odds = tuple(product(range(1, modulus, 2), repeat=2)) + canonical = { + (x, u): (x & (half - 1), u ^ (x & half)) for x, u in odds + } + # One effective shift for each floor(c/2) mod 2^(m-1), with signed and odd lifts. + carries = tuple(range(-modulus + 1, 0, 2)) + (0,) + for carry in carries: + signatures = {} + for x, u in odds: + row = bytes(((x * y + u * v + carry) >> (m - 1)) & 1 for y, v in odds) + require(0 in row and 1 in row, (m, carry, x, u, "constant row")) + signature = canonical[x, u] + require(signatures.setdefault(row, signature) == signature, (m, carry, "wrong alias")) + row_count = len(signatures) + require(row_count == 1 << (2 * m - 3), (m, carry, row_count)) + require(row_count > (1 << (2 * m - 3)) - 1, "zero-code exclusion") + codes = set() + for x, u in odds: + code = ((x & half) ^ (u & half)) >> (m - 1) + code = code << (m - 2) | ((u >> 1) & inner_mask) + code = code << (m - 2) | ((x >> 1) & inner_mask) + unpacked_x = 1 | ((code & inner_mask) << 1) + unpacked_u = 1 | ((code >> (m - 2)) << 1) + require((unpacked_x, unpacked_u) == canonical[x, u], "channel decode") + codes.add(code) + require(codes == set(range(row_count)), "attaining constant-one channels") + results.append({ + "m": m, "row_classes": row_count, "minimum_total_width_per_side": row_count.bit_length(), + "distinct_carry_shifts": half, "checked_carry_lifts": len(carries), + }) + zero_code_outputs = [direct((1, 1, 1, v, 0), 3) >> 2 for v in (1, 3)] + reflection_outputs = [direct((x, x, 1, 1, 0), 3) >> 2 for x in (1, 3)] + require(zero_code_outputs == reflection_outputs == [0, 1], "odd-width negative controls") + return {"rows": results, "zero_code_and_reflection_control_outputs": [0, 1]} + + +def load_frozen_builder(directory): + for name, digest in FROZEN_SHA256.items(): + require(sha256((directory / name).read_bytes()).hexdigest() == digest, f"source pin {name}") + # Extract only the frozen DAG generator. Neither verifier nor evaluator is loaded. + tree = ast.parse((directory / "circuits.py").read_text(encoding="utf-8")) + circuit = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == "Circuit") + methods = {"__init__", "input", "gate", "add", "low_product"} + circuit.body = [node for node in circuit.body if isinstance(node, ast.FunctionDef) and node.name in methods] + build = next(node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == "build") + namespace = {} + exec(compile(ast.Module(body=[circuit, build], type_ignores=[]), "frozen circuit builder", "exec"), namespace) + return namespace["build"] + + +def compile_reversible(dag, outputs, width): + inputs = 5 * width + require(dag.inputs == inputs and len(outputs) == width, "input/output width") + instructions = [] + gates = Counter() + for target, (op, left, right) in enumerate(dag.gates, inputs + 1): + require(0 < left < right < target and op in ("and", "xor"), (target, op, left, right)) + gates[op] += 1 + if op == "xor": + instructions.extend(((target, left), (target, right))) + else: + instructions.append((target, left, right)) + allocated = inputs + len(dag.gates) + require(all(0 < source <= allocated for source in outputs), "invalid copy source") + copy = [(allocated + out, source) for out, source in enumerate(outputs, 1)] + word = instructions + copy + instructions[::-1] + types = Counter(map(len, word)) + invoice = { + "and": gates["and"], "xor": gates["xor"], "clean_scratch_bits": len(dag.gates), + "clean_cnot": types[2], "clean_toffoli": types[3], + } + return word, allocated, invoice + + +def planes(words, width): + packed = 0 + for index, word in enumerate(words): + packed |= word << (index * width) + columns = ((packed >> bit) for bit in range(width)) + mask = sum(1 << (index * width) for index in range(len(words))) + return [column & mask for column in columns] + + +def reversible_batch(cases, width, program, allocated, clean=True): + read_only = [0] + for field in zip(*cases, strict=True): + read_only.extend(planes(field, width)) + input_size = len(read_only) + seeds = [(37 * i ^ 0xA5) % (1 << width) for i in range(len(cases))] + initial = planes(seeds, width) + values = read_only + [0] * (allocated + 1 - input_size) + initial + for target, control, *other in program: + update = values[control] & values[other[0]] if other else values[control] + values[target] ^= update + expect = planes([direct(case, width) ^ seed for case, seed in zip(cases, seeds)], width) + require(values[:input_size] == read_only and values[-width:] == expect, ("reversible ports", width)) + scratch_is_zero = not any(values[input_size:-width]) + require(scratch_is_zero == clean, ("clean scratch", width, clean)) + + +def circuit_cases(m): + if m == 4: + for x, y, ux, vy, carry in product(range(16), range(16), range(4), range(4), range(16)): + yield x, x ^ (ux << 2), y, y ^ (vy << 2), carry + else: + rng = Random(54103) + for index in range(4096): + x, y = ((index >> bit) & 255 for bit in (0, 4)) if index < 256 else ( + rng.randrange(256), rng.randrange(256) + ) + u, v = x ^ (rng.randrange(16) << 4), y ^ (rng.randrange(16) << 4) + dot = x * y + u * v + for carry in (0, 255, -dot, 127 - dot, 128 - dot): + yield x, u, y, v, carry % 256 + + +def circuit_checks(directory): + builder = load_frozen_builder(directory) + expected = json.loads((directory / "RESULT.json").read_text(encoding="utf-8"))["circuits"] + results = [] + for row in expected: + width, a, b = (row[key] for key in ("m", "a", "b")) + programs = {} + result = {"m": width, "a": a, "b": b} + for fused, name in ((False, "two_products"), (True, "shared_carry")): + dag, outputs = builder(width, a, b, fused) + program, allocated, invoice = compile_reversible(dag, outputs, width) + require(invoice == row[name], (width, name, invoice, row[name])) + programs[name] = program, allocated + result[name] = invoice + cases = circuit_cases(width) + count = 0 + while batch := list(islice(cases, 128)): + for program, allocated in programs.values(): + reversible_batch(batch, width, program, allocated) + count += len(batch) + result["independent_cases"] = count + # Remove the uncompute suffix while keeping correct input/output ports. + case = [(1, 1, 1, 1, (1 << (width - 1)) - 2)] + for program, allocated in programs.values(): + reversible_batch(case, width, program[:(len(program) + width) // 2], allocated, clean=False) + results.append(result) + bad_no_toggle = (4 + 0) * (4 + 0) // 2 + require(bad_no_toggle % 16 == 8 and direct((0, 4, 0, 4, 0), 4) == 0, "missing toggle control") + require(direct((1, 1, 1, 1, 6), 4) == 8 and direct((1, 1, 1, 1, 0), 4) == 2, "carry control") + return results + + +def compare_price(path): + quoted = json.loads(path.read_text(encoding="utf-8")) + target = Decimal(quoted["target"]) + require(target == Decimal("0.003884928046155"), "enrolled target") + require(target - Decimal(quoted["comparator_upper"]) == Decimal("0.000005"), "target gain") + require(quoted["source_verified_head"] == "87fbf4f7b35b0f18ab12b5767775a9a424cf0b15", "comparator head") + crosscheck = {} + with localcontext() as context: + context.prec = 75 + for side, native_calls in (("rational", 48), ("binary", 36)): + invoice = quoted["sides"][side] + price = {grade: Decimal(grade) ** (1 - target) for grade in invoice["paid"] | invoice["targets"]} + margin = sum((invoice["targets"].get(k, 0) - invoice["paid"].get(k, 0)) * p for k, p in price.items()) + lower, upper = (Decimal(invoice["signed_margin"][key]) for key in ("lower", "upper")) + require(lower < margin < upper < 0 and invoice["native_calls"] == native_calls, (side, "price")) + crosscheck[side] = {"native_calls": native_calls, "unchanged_signed_margin": invoice["signed_margin"]} + return crosscheck + + +def main(): + here = Path(__file__).resolve().parent + primary = here + if not (primary / "PROOF.md").is_file(): + primary = here.parent.parent / "repo" / "research" / "recursive-dot-carry" + default_price = here / "reference-price.json" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--primary", type=Path, default=primary, help="directory of the four pinned primary files") + parser.add_argument( + "--comparator", type=Path, default=default_price if default_price.is_file() else None, + help="pinned price input, defaulting to reference-price.json beside the checker when present", + ) + args = parser.parse_args() + result = { + "status": "PASS_SCOPED_INDEPENDENT_REVIEW", + "frozen_sha256": FROZEN_SHA256, + "congruence": congruence_checks(), + "odd_channels": odd_channel_checks(), + "circuits": circuit_checks(args.primary), + "finite_circuit_signed_credit": "0", + } + if args.comparator: + result["comparator_check"] = compare_price(args.comparator) + print(json.dumps(result, indent=2, sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/research/recursive-dot-carry/reference-price.json b/research/recursive-dot-carry/reference-price.json new file mode 100644 index 0000000000..47ae40b9e1 --- /dev/null +++ b/research/recursive-dot-carry/reference-price.json @@ -0,0 +1,114 @@ +{ + "source_verified_head": "87fbf4f7b35b0f18ab12b5767775a9a424cf0b15", + "comparator_upper": "0.003879928046155", + "target": "0.003884928046155", + "gain": "0.000005", + "sides": { + "rational": { + "paid": { + "1": 184800, + "2": 37920, + "3": 23472, + "4": 11040, + "5": 15072, + "6": 1920, + "7": 144, + "8": 1296, + "16": 1248, + "24": 1248, + "32": 1248, + "40": 1248, + "48": 1248, + "56": 1248 + }, + "targets": { + "1": 960, + "2": 336, + "3": 480, + "4": 11616, + "5": 1536, + "7": 672, + "8": 1536, + "9": 26016, + "17": 1248, + "25": 1248, + "33": 1248, + "41": 1248, + "49": 1248, + "57": 1248, + "65": 1248, + "129": 624 + }, + "signed_margin": { + "lower": "-4.880391089954707282632121322599412665463258383", + "upper": "-4.880391089954707282632121322599412665463258123" + }, + "required_saving": { + "lower": "4.880391089954707282632121322599412665463258123", + "upper": "4.880391089954707282632121322599412665463258383" + }, + "raw_crossing": [ + "0.00388013644474", + "0.00388013644475" + ], + "native_calls": 48, + "native_word": "7660985e0b618cdbee13e4190a4c6d5f91fbdf01a8f7a5186fdde8b980c19b48", + "caller": "156fdf3a4a129b39225fd6ca51011de27974d7f104e8b04907c17ed5344bc858", + "layout": "f7de788c4a559282d35a9fce42f841a0e8de5a4015db871e718f9245569b0aa7", + "application_sha256": "1b2d87e93ae023f5ffd464546af53281b6cb4963dfd76ae4742e0a5540b752fa" + }, + "binary": { + "paid": { + "1": 49980, + "2": 46116, + "3": 1944, + "4": 1584, + "5": 612, + "6": 3672, + "7": 444, + "14": 444, + "21": 444, + "28": 444, + "35": 444, + "42": 444, + "49": 444, + "56": 444 + }, + "targets": { + "1": 288, + "2": 324, + "4": 1548, + "5": 288, + "6": 36, + "8": 14448, + "15": 444, + "22": 444, + "29": 444, + "36": 444, + "43": 444, + "50": 444, + "57": 444, + "64": 444, + "127": 222 + }, + "signed_margin": { + "lower": "-1.925615290709237255327353524062076005714818790", + "upper": "-1.925615290709237255327353524062076005714818658" + }, + "required_saving": { + "lower": "1.925615290709237255327353524062076005714818658", + "upper": "1.925615290709237255327353524062076005714818790" + }, + "raw_crossing": [ + "0.003879928046154", + "0.003879928046155" + ], + "native_calls": 36, + "native_word": "d3aa4426fa8fe7dc167270d01f2515184f2bff6a82744a14e941c5dd3afca27d", + "admitted": "0.0038799074072", + "caller": "757b3523798f840bdb02028b23708c3416627a99ea09e7a3c4bcdc5cd0c7ce4b", + "finite_receipt_sha256": "0cebc543d64ca53ac6c7141dfab40c658bf451fe89bb7744befb76c116ea45e6", + "independent_receipt_sha256": "5865e19155488b80ccb1faa1ba74c2ffbc5ac22e8f22f10c5f4496ae49fc1229" + } + } +} diff --git a/research/recursive-dot-carry/verify.py b/research/recursive-dot-carry/verify.py new file mode 100644 index 0000000000..f012c81b21 --- /dev/null +++ b/research/recursive-dot-carry/verify.py @@ -0,0 +1,98 @@ +"""Replay the exact residue construction, independent row oracle and finite circuit.""" + +from itertools import product +from pathlib import Path +import json +import random +import runpy + + +def require(condition, detail): + if not condition: + raise ValueError(detail) + + +def fused(left, right, a, b, carry, m): + mask = (1 << m) - 1 + x, u = left + y, v = right + left_mean = ((x + u) & mask) >> 1 + right_mean = ((y + v) & mask) >> 1 + base = 2 * left_mean * right_mean + width = max(0, m + 1 - a - b) + if width: + left_diff = (u >> a) - (x >> a) + right_diff = (v >> b) - (y >> b) + correction = left_diff * right_diff & ((1 << width) - 1) + base += correction << (a + b - 1) + return (base + carry) & mask + + +def valid_pairs(m, shared_bits): + size = 1 << m + return [(x, (x + offset) % size) + for x in range(size) for offset in range(0, size, 1 << shared_bits)] + + +def check_congruences(): + total = 0 + for m in range(2, 6): + size = 1 << m + for a, b in product(range(1, m + 1), repeat=2): + without_residual = True + for left, right in product(valid_pairs(m, a), valid_pairs(m, b)): + x, u = left + y, v = right + want = (x*y + u*v) % size + got = fused(left, right, a, b, 0, m) + require(got == want, (m, a, b, left, right, got, want)) + mean_only = 2 * ((x+u) // 2) * ((y+v) // 2) + if (mean_only - want) % size: + without_residual = False + total += 1 + require(without_residual == (a+b >= m+1), (m, a, b, 'threshold')) + rng = random.Random(891605) + for m in (6, 8, 16, 31, 64, 255, 1024): + for _ in range(120): + a, b = rng.randint(1, m), rng.randint(1, m) + x, y, c = [rng.randrange(-(1 << m), 1 << m) for _ in range(3)] + u = x + (rng.getrandbits(m-a) << a) + v = y + (rng.getrandbits(m-b) << b) + require(fused((x, u), (y, v), a, b, c, m) == (x*y + u*v + c) % (1 << m), + ('signed lifts', m, a, b, c)) + return {'exhaustive_congruent_inputs': total, 'signed_large_inputs': 840} + + +def literal_rows(m): + size = 1 << m + odds = list(product(range(1, size, 2), repeat=2)) + classes = {} + for x, u in odds: + row = bytes(((x*y+u*v) >> (m-1)) & 1 for y, v in odds) + require(0 in row and 1 in row, 'constant row') + classes.setdefault(row, set()).add((x, u)) + half = size >> 1 + for group in classes.values(): + x, u = next(iter(group)) + require(group == {(x, u), (x ^ half, u ^ half)}, ('row class', m, x, u)) + require(len(classes) == 1 << (2*m-3), 'row count') + return {'m': m, 'rows': len(odds), 'different': len(classes), + 'minimum_total_coordinates_per_side': len(classes).bit_length()} + + +def run(): + result = {'congruence': check_congruences(), + 'odd_dot_rows': [literal_rows(m) for m in range(3, 7)]} + result['circuits'] = runpy.run_path(str(Path(__file__).with_name('circuits.py')))['check']() + return result + + +if __name__ == '__main__': + result = run() + frozen = json.loads(Path(__file__).with_name('RESULT.json').read_text()) + require(result == frozen, 'replay differs from RESULT.json') + review = Path(__file__).with_name('independent.py') + if review.is_file(): + runpy.run_path(str(review), run_name='__main__') + print(json.dumps(result, sort_keys=True)) + print('PASS_RECURSIVE_DOT_CARRY') From ad132678053ebfb9682cc87be3df17e132b2efe8 Mon Sep 17 00:00:00 2001 From: Chris R Date: Fri, 20 Nov 2026 20:30:59 +1100 Subject: [PATCH 2/2] Add independent replay of the charged and Gaussian callers --- research/recursive-dot-carry/CALLER-REVIEW.md | 29 +++++++++++++++++++ research/recursive-dot-carry/CALLERS.md | 2 +- 2 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 research/recursive-dot-carry/CALLER-REVIEW.md diff --git a/research/recursive-dot-carry/CALLER-REVIEW.md b/research/recursive-dot-carry/CALLER-REVIEW.md new file mode 100644 index 0000000000..986073f229 --- /dev/null +++ b/research/recursive-dot-carry/CALLER-REVIEW.md @@ -0,0 +1,29 @@ +# Review of the #7834 and #7830 caller controls + +## The first payload twist in #7834 + +Let $T$ be the target volume, $r$ the fastest radix, $f$ the internal precision and $S=2^f$. At fastest coordinate $r/4$ or $3r/4$, the twist angle is $\pi/4$ or $3\pi/4$. The actual root generator uses the same square-root interval for both magnitudes and changes the cosine sign in the second case. Its output is $(u,v)$ with $|u|=|v|=\lfloor S/\sqrt2\rfloor$ and both operands have width $f$. This applies for admitted dyadic $r\ge4$. [Root enclosures and projection](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/fine-prime-gaussian-product/fine_ring.py#L139-L188) · [Twist construction](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/fine-prime-gaussian-product/fine_ring.py#L393-L430) + +The admitted payload lies inside the radius-$S/2$ disk after lifting to the internal grid. The preceding conjugate phase pass preserves this bound. Each phase root is projected inward componentwise, and each cached phase product drops each component toward zero, so a stored phase has norm at most $S$. Multiplication followed by the same truncation therefore preserves the payload bound. Conjugation for the opposite entry only changes signs. + +Write $v=\sigma u$, where $\sigma\in\{-1,1\}$. For a payload record $(x,y)$ the exact numerators are $u(x-\sigma y)$ and $u(y+\sigma x)$. Both mixtures have magnitude at most $\sqrt2\sqrt{x^2+y^2}\le S/\sqrt2$. Each of the original four calls and the replacement two calls therefore uses width $f$. The same signed normalizer sees the same two exact integers. There are two such records per fastest-axis row, so changing only this pass saves exactly $4T/r$ word-product dispatches per middle invocation. The dispatch threshold is 8,192 bits. At larger $f$, the affected calls select the source's wide child interface. This leaves the other transforms, routing, and cleanup charges in place. [Middle sequence](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/fine-prime-gaussian-product/fine_ring.py#L435-L489) · [Word dispatcher](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/fine-prime-gaussian-product/word_multiply.py#L55-L62) + +The independent checker pins and runs the source root, diagonal, and middle implementations. It tests 50 source projections, including internal precisions at and above the wide cutoff, and substitutes only at the two guaranteed positions in the first payload twist. Six complete middle runs over radices 4, 8 and 16 preserve their outputs and release the numeric tapes. In both directions, the pinned 128-bit grid at target shape $(8,8)$ uses 1,728 original dispatches and 1,696 after this substitution. I separately reproduced the joint-fusion worker's receipt byte for byte. Its broader guarded substitution reaches 1,664 on that geometry by accepting 32 records across the middle. These finite middle replays use short word dispatches. [Broader guarded replay](JOINT-REPLAY.json) + +An actual source-generated kernel record at coordinate $(2,1)$ in the same shape on the $f=16$ grid gives $(x,y)=(-25079,60547)$ against the twist $(46340,46340)$. All four original dispatches use 16-bit magnitudes. The mixture $x-y=-85626$ needs 17 bits. The payload half-disk guarantee therefore cannot be transferred to the kernel twist or to arbitrary diagonal passes. The wider test at $f=8200$ in the joint-fusion control checks the actual selector with an exact integer substitute for the wide child. It establishes preservation of the selector width and exact normalized integer at the named test record. [Independent checker](diagonal/independent_twist.py) · [Replay](diagonal/independent-twist.json) + +## Sign-adaptive three-product joins in #7834 + +The classical three-product identity also works for the source's full signed Kronecker words. Choose signs $s,t\in\{-1,1\}$ so that $a+sb$ and $c+td$ are differences of magnitudes on their respective sides. Both mixed operands fit the larger original width per side. For $P=(a+sb)(c+td)$, if $s=t$ then the imaginary cross term is $s(P-ac-bd)$. If $s=-t$ then the real cross term is $P-tad-sbc$. This preserves the full integer numerators through centered limb extraction, negacyclic folding and the signed drop. If the mixed product crosses the wide-child threshold, at least one product omitted by the selected matching crosses it too. The threshold control with four equal positive operands of magnitude $2^{8191}+1$ makes an unguarded additive mix cross that threshold and keeps the sign-adaptive mix below it. + +I replayed all four complete Gaussian product fixtures under optimized Python. Each uses 74,655 original and 62,284 substituted short-word dispatches, with 12,347 scalar joins and 24 ring joins changed. The pre-carry coefficients match a direct convolution oracle, the final binary outputs match ordinary multiplication, and numeric tapes are empty at return. All four exercise the same small Gaussian geometry. The high-width selector exercise covers 625 signed cases and substitutes an exact integer oracle for the wide child body. The replay demonstrates counts of calls, with separate sign, mixture, reconstruction, and tape work in any full cost comparison. + +Both substitutions earn zero P104 tariff credit. They affect the additive scalar and packed-ring rows in #7834. Its grouped butterfly and CRT recurrence retains its charged jobs. The proof and replay distinguish the sparse border, where separately dropped summands must remain separate. At divisor 4, pairs $(3,1)$ and $(4,0)$ share raw sum 4 and have sums of signed drops 0 and 1. The worker replay also observes a concrete source row where postponement changes the drop. Its two-root transpose control checks the documented address endpoint in a model. With $D=e_0$ and $H$ equal to $0$ or $e_0$, the first return's aligned sum is $C_nD$ in both cases, while its retained first lane $C_n(D-H)$ differs and is read by the second root. [#7834 fixed-tape invoice](https://github.com/CrocSwap/integer-mult-bounds/blob/4f0c67d5bb41d4af5501dcd40b3b388b35e0ff02/research/fine-prime-gaussian-product/PROOF.md#L63-L81) · [Complete regression replay](GAUSSIAN-REPLAY.json) + +## The pinned #7830 caller + +I replayed the signed-parent probe byte-for-byte and independently checked the equal-rank occurrence labels against the pinned BIT certificate. The two sampled rational and binary native pairs have separate protected readers. The alternate pulses share their aligned sum or XOR, so a decoder seeing only the sum and the same incoming carry cannot produce the distinct required outputs. Removing a paid entry and its matching productive target at the same grade contributes zero to their signed difference. + +The same-owner slab merge has a different interface and a positive split credit. Let $J=10^{480}$ and $R=4^{182}14^{134}21^{164}$. The source's low-first order really gives ranks $J$ and $R-J$, with $J0$ in the paid moment relative to that split. Even the unsplit raw BIT paid-to-productive moment at the target exceeds 1 at tensor power 480. Coarsening this fixed roster alone cannot clear the target. A new physical schedule would separately need its stock, matching and ordinary checks. [Mixed-rank construction](https://github.com/CrocSwap/integer-mult-bounds/blob/87fbf4f7b35b0f18ab12b5767775a9a424cf0b15/research/p104-mixed-rank-supplier/PROOF.md) · [Native price data](reference-price.json) -The source-bound coordinate and price checks are included in the [caller receipt](caller-evidence.json). The separate [twist verifier](diagonal/independent_twist.py) restricts the guard to the first payload twist; its [frozen output](diagonal/independent-twist.json) reports that narrower result. +The [independent caller review](CALLER-REVIEW.md) derives the twist count, tests its width guard and replays the charged controls. The [caller receipt](caller-evidence.json) records the source-bound coordinate and price checks. The separate [twist verifier](diagonal/independent_twist.py) restricts the guard to the first payload twist; its [frozen output](diagonal/independent-twist.json) reports that narrower result. The research starting point is canonical main `e54523517d0f03e58352e647c403a5af3e525a57`. The four-sibling promises, channel widths and gate savings have the scopes above. Earlier work on rectangular carry-state ranges, individual product bits, fixed-point Gaussian rounding and the mixed supplier supplies the comparison and the protected observations. [Rectangular convolution, #6252](https://github.com/CrocSwap/integer-mult-bounds/pull/6252) · [Single-product channels, #7838](https://github.com/CrocSwap/integer-mult-bounds/pull/7838) · [Selected result record](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/certificates/selected-result.json)