diff --git a/research/single-band-native-carriers/ACTIVATION-SPACE.md b/research/single-band-native-carriers/ACTIVATION-SPACE.md new file mode 100644 index 0000000000..52f71ba75c --- /dev/null +++ b/research/single-band-native-carriers/ACTIVATION-SPACE.md @@ -0,0 +1,47 @@ +# Historical tape space from the connected entrance + +Write $s=\lceil\log_2(p+2)\rceil$. Use the actual spectator H and byte-stripe CRT from the predecessor. Both have at least $2^k$ stripes, where $k=\lfloor s/2\rfloor-2$. Each public file remains present, with every arbitrary input, output, residue, coefficient, and hole. No additional stripe rounds are needed in this result. The following proof sharpens the absolute space coefficient at the new first entrances. [Stripes, grouped keys and previously charged resources](https://github.com/CrocSwap/integer-mult-bounds/blob/9585c1fa2ed5f2316ac09e04b357cb720badfcb8/research/triangular-native-supplier/FIRST-PEAK.md) · [Wide quotient and all-size control bill](https://github.com/CrocSwap/integer-mult-bounds/blob/9585c1fa2ed5f2316ac09e04b357cb720badfcb8/research/triangular-native-supplier/ACTIVATED-STORAGE.md) + +## Account for the actual band and the stack + +Let $v$ be the greater of the two strictifier powers. It is 128 on the compact profile. On the higher-rate profile the numerical power remains 128 and the binary power is 228. The raw ambient dimension $a$ is at most 153, and the raw target and paid counts $W_0,P_0$ are each less than $2^{20}$. The same raw-word structural budget $2^{64}$ covers a fixed basis program. The full powered-word census bounds structural visits, held ports, both sides of each binding, zero/retired owner and split by + +$$Q_v=2^{64}(v+1)[2(a+1)(W_0+P_0+2)]^v <2^{64+\lceil\log_2(v+1)\rceil+30v}.$$ + +The resulting binary logarithmic ceilings are 3912 and 6912. This includes every original tuple, even a target discarded by the new productive floor or a paid interval cut into several pieces. [Powered source census](https://github.com/CrocSwap/integer-mult-bounds/blob/3f7c3c1f2a9a0963736562037e01fe41aec46b8c/research/bounded-general-multiplier/PERIODIC.md#width-expanded-records-and-generator-clock) + +The higher-rate binary moment uses productive floor $15^v$ and paid cap $12^v$. Both numerical moments and the compact binary moment have at least this ratio. Thus $u/l\ge(5/4)^v>2^{5v/16}$ for the smallest target $u$ and largest paid rank $l$, by $5^{16}>2^5 4^{16}$. For $N=2^H$, $G\le16H/(5v)+1$. There are $W\le W_0^v$ productive ports and $P\le(aP_0)^v$ paid pieces, so $W+P<2^{29v}$. The number of candidate units before filtering is at most $\sum_{d=0}^G P^dW^{G-d}\le(P+W)^G64(j+1)+129$ for $j=\lfloor s/64\rfloor\ge32$. Consequently $k-D(s)\ge(1/2-\sigma-1/32)s-c-3$. The coefficient is positive, and this last lower bound already exceeds 1024 at $s=A+1$. It grows for every subsequent integer. The auxiliary *payload* historical extents total less than $pT/2^{1024}$ throughout. + +| Ordinary stages | $H_M$ | $s_0=A+1$ | $\sigma$ | $d_N(s_0)$ | $D(s_0)$ | $\lfloor s_0/2\rfloor-2-D(s_0)$ | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| 260000, 1600000 | 610000 | 2471429 | $496192/2478125$ | 25 | 950364 | 285348 | +| 25000000, 160000000, 1000000000, 6000000000, 36000000000, 224000000000 | 1600000 | 267186701154 | $5422628/123046875$ | 179693 | 11776557180 | 121816793395 | +| 175000000, 1120000000, 7000000000, 42000000000, 252000000000, 1568000000000 | 1600000 | 1870297303585 | $35662628/861328125$ | 1181637 | 77439959170 | 857708692620 | + +The expression with the uniform slope exceeds 172060 on the first compact $s$ and 113466985868 on the first higher-rate $s$. At the current-price entrance the integer lower bound is 799261674748. The six larger rank logarithms need at most 41 bits each, so the same local ceiling $q=32768$ holds. The Lean theorems `SquareGeometry.compactStripe` and `SquareGeometry.higherStripe` together with `SquareGeometry.priceMatchStripe` prove the integer-ceiling inequalities at every eligible $s$ with $64\,\operatorname{bitlength}(s+128)\le s$. The mapping from the literal file layouts and their shell/forest limits to these counts is the written argument above. + +## Private setup, movement counters and the complete bound + +Let $J$ be the number of bits and records in the installed finite compiler envelope. Put $K=2^{(s+1)^8}$ and $A_0=K^{8(s+130)}$. The code, tickets, owned field descriptors, actual coefficient setup, geometry lists, private numerators and modulus representatives, counters and every other control list use the predecessor's additive control bill. In this calculation use the smaller private bound $D_{\rm priv}=2^{2^{21}(s+1)}$ for every coefficient, table and intermediate. In particular no table costs a multiplier on an entire real stripe. Check + +$$64+8(\log_2 J+1)+64s+8(2^{21}(s+1)+1)<(s+1)^8$$ + +at each profile’s first $s_0$ with $\log_2 J=1024\max(H_M,H_1,\ldots,H_m)$. Each term divided by $(s+1)^8$ then decreases. During a native raw word the high-size trit matrices, per-request vectors and private raw scalar values fit the same bound, including one cell stream per actual instruction and all suspended program cursors. For the one-band lists, already emitted carrier sites and descriptor products have the program bound $J$; a mutable live ordinal or single complete coordinate list has size at most polynomial in $p$ and $J$. The old bounded-spool tag simulator still enumerates the actual, potentially nonzero quotient tags and runs the same motions as the opaque data. Running the new public finite word on that simulated tape preserves addresses too. Count its finite unmetered successful configurations. All write-only meters, high addresses and historical control storage fit $A_0^{16}$, as in the pinned proof. The ratio check $33^9<2\,32^9$ propagates $12[128(s+130)(s+1)^8+64]<2^{s-2}$ from $s_0$. Hence this control space is less than $T/2^{64}$. The same check bounds the grouped-key CRT prerequisite using the looser old width $128s^2$ throughout. `check_activation_space.receipt` verifies each initial comparison with the actual program-size exponent supplied by the caller. [Control derivation and nonzero tag/counter simulation](https://github.com/CrocSwap/integer-mult-bounds/blob/9585c1fa2ed5f2316ac09e04b357cb720badfcb8/research/triangular-native-supplier/ACTIVATED-STORAGE.md#reconstruct-nonzero-radix-tags-for-the-optional-movement-counters) + +The aggregate auxiliary backing is less than $pT/1024$. The two declared numerical files occupy at most $(4P+2p+116)T$, and canonical I/O at most $4n+32\le pT/6+32$. With $P<1.001p$ the **complete occupied storage is less than $6.2pT<297.6n$ bits** on every input at or above the connected entrance. The proof includes the first connected entry even if a smaller rank enters wide quotient mode, because it pays the full worst-case high, tags and all native levels on this entire range. The earliest entrance still requires $T=2^L$ genuinely independent records. These are absolute storage bounds, with no upper bound on attainable hardware or empirical time crossover implied. diff --git a/research/single-band-native-carriers/ACTUAL-SETUP.md b/research/single-band-native-carriers/ACTUAL-SETUP.md new file mode 100644 index 0000000000..61deda9516 --- /dev/null +++ b/research/single-band-native-carriers/ACTUAL-SETUP.md @@ -0,0 +1,25 @@ +# A lower bound on the predecessor's actual fixed setup + +The largest binary installer of [PR #7981](https://github.com/CrocSwap/integer-mult-bounds/pull/7981) builds a table with at least $2^{989379999989304}$ distinct exit records. Its specified expanded chronological stream contains at least $2^{3366293830151418}$ records. The second count is larger than the upper bound on **all** fixed setup, programs and scratch of each new installation. This comparison does not use the old degree-20,000 upper bound. [Predecessor receiver](https://github.com/CrocSwap/integer-mult-bounds/blob/9585c1fa2ed5f2316ac09e04b357cb720badfcb8/research/triangular-native-supplier/receiver.py) · [Required stream generation](https://github.com/CrocSwap/integer-mult-bounds/blob/3f7c3c1f2a9a0963736562037e01fe41aec46b8c/research/bounded-general-multiplier/MACHINE.md) · [New setup upper bound](BAND.md#installed-epoch-and-fixed-head-generation) + +The old planner keeps labelled paid occurrences separate. At rank $n$ it sets $u=\lfloor n/4\rfloor$ and makes a forest of height $G$, the largest integer with $A k^G\le u$. Here $A=134^{480}$ and $k$ is the least retained productive rank. The cutoff gives $k\ge16^{480}$. A real tuple with 320 rank-eight factors and 160 rank-64 factors attains equality. Every path of length $G+1$ in the paid alphabet has its own key in the exit table. At depth $G$ the all-paid branch always has a real unit because every paid rank is smaller than $k$. The emitted stream processes each such exit. It runs at least one round and one full copy group for the recursive request. Plans shared by rank can reuse their static census. The specified compiler still emits the chronological child instructions at each occurrence. [Exact forest, planner and recursive emitter](https://github.com/CrocSwap/integer-mult-bounds/blob/3f7c3c1f2a9a0963736562037e01fe41aec46b8c/research/bounded-general-multiplier/periodic.py) · [Emission across all smaller ranks](https://github.com/CrocSwap/integer-mult-bounds/blob/3f7c3c1f2a9a0963736562037e01fe41aec46b8c/research/bounded-general-multiplier/PERIODIC.md#width-expanded-records-and-generator-clock) + +There are 107,460 positive paid labels in the old raw word. Every ordered 480-tuple gives at least one nonempty paid block. There are 3,108 labels of rank at least 14. In any tuple made exclusively from those labels, its first block has rank exactly $11^{480}$. Its first factor selects the high cap and the product is at least $14^{480}$. Distinct tuples keep distinct labels even if their ranks agree. [Literal caller and labels](https://github.com/CrocSwap/integer-mult-bounds/blob/3f7c3c1f2a9a0963736562037e01fe41aec46b8c/research/bounded-general-multiplier/tagged_sources.py) · [Slab construction](https://github.com/CrocSwap/integer-mult-bounds/blob/3f7c3c1f2a9a0963736562037e01fe41aec46b8c/research/bounded-general-multiplier/powered.py) · [Production planner binding](https://github.com/CrocSwap/integer-mult-bounds/blob/46783fbbfc219a3faffbea76f60a2810b85ab75a/research/native-stock-activation/compiler_cut.py) + +For $n\ge2^H$ with $H\ge3394$, put $m(H)=1+\lfloor(H-2-3392)/1920\rfloor$. Rounding $n$ down to a multiple of four still leaves at least $2^H$. Since $A<2^{3392}$ and $k=2^{1920}$, there are at least $m(H)$ paid positions in every exit. The three integer power comparisons +$107460^{480}\ge2^{8022}$, $3108^{480}\ge2^{5568}$ and $11^{480}\ge2^{1660}$ suffice for the counts below. At the largest predecessor rank $H_0=236800000000000$ we have $m(H_0)=123333333332$. Thus just its root exit table has at least $2^{8022m(H_0)}$ entries. This first bound counts different keys in the actual dictionary and does not require chronological instruction expansion. + +For the expanded stream choose only the first blocks of the high tuples for six successive recursive descents. Put $H_{i+1}=1660m(H_i)$. At each visited call there are at least $2^{5568m(H_i)}$ distinct such exits. Each one's child rank is at least $2^{H_{i+1}}$, since the exit rank is the product of its block ranks. At the seventh forest count every exit. Paths issued by different ancestors occupy different positions in the expanded stream. Each final request emits at least one instruction. The resulting logarithmic lower bound is +$5568\sum_{i=0}^{5}m(H_i)+8022m(H_6)=3366293830151418$. A different interpreter could share a subprogram across invocations. This lower bound refers specifically to the expanded installer described above. + +| Installation | Upper exponent for all new fixed setup | Lower bound on old/new exponents from the expanded stream | +| --- | ---: | ---: | +| Compact | 1,638,400,002 | 2,054,622× | +| Higher rate | 229,376,000,000,003 | 14× | +| Current price match | 1,605,632,000,000,003 | 2× | + +The root table alone exceeds the whole compact upper bound by a factor greater than 603,869 in the exponents. The counts bound transitions as well as the stated table or stream size because each emitted record occupies at least one cell. They give lower-to-upper comparisons for these specific implementations. [Exact literal census, finite forest checks and integer inequalities](prior_setup.py) · [Three installation receipts](REQUIREMENTS.json) + +## Earlier execution than the predecessor permits + +The actual prior selector requires $\lfloor\log_2 e\rfloor\ge355760240964240$ for its sixth ordinary stage. Its outer requests have at most $p$ binary address bits. Conversion to ternary and previous-stage calls do not increase the width. At the first certified precision of each new installation, $p=2^A+2$ or $p=2^A+4$. All three satisfy $A+1<355760240964240$. The prior final stage cannot activate at any of those inputs. The new positive mixing operation reaches its own last ordinary stage and every earlier stage there. [Executed gate](https://github.com/CrocSwap/integer-mult-bounds/blob/9585c1fa2ed5f2316ac09e04b357cb720badfcb8/research/triangular-native-supplier/staged_carriers.py) · [Width bound](https://github.com/CrocSwap/integer-mult-bounds/blob/9585c1fa2ed5f2316ac09e04b357cb720badfcb8/research/triangular-native-supplier/STAGED-CARRIERS.md) · [New connected path](LINEAR-GEOMETRY.md) diff --git a/research/single-band-native-carriers/APPLICATION.md b/research/single-band-native-carriers/APPLICATION.md new file mode 100644 index 0000000000..07f01dadb8 --- /dev/null +++ b/research/single-band-native-carriers/APPLICATION.md @@ -0,0 +1,33 @@ +# From the funded carriers to an integer product + +For each installation let $N_i=2^{H_i}$ and $M=2^{H_M}$. The bit source price is $c_B$, and the charged binary loss is $d_B$ bits. The positive source price is $c_Z=2043/2^{19}$. Its full loss, including the caller's factor two, is 10 bits. `strict_moment.py` sums the ranks of the actual individual ports. Successive integer square roots enclose each dyadic power from both sides. For $t=1-c$, the retained credit after the productive floor and paid split has relative surplus at least $2/L$. The bound uses $P(t)/T(t)$ for the raw debit, $P(t+u)/(12^u T(t))$ for a split tail, and $k_0^w T(t-w)/T(t)$ for the discarded productive credit. At power $v$ the normalized debit is at most the first quantity to power $v$, twice the second to power $v$, and the third to power $v$, added together. This follows by summing actual disjoint blocks at rank above $12^v$ and counting the omitted tensors below $k_0^v$. Each omitted tensor uses an independent zero owner with a real return. [Strict moment receipt](strict_moment.py) · [Independent binary intervals](independent_binary_price.py) · [Physical word bindings](strong_binary.py) + +| Installation | $H_i$ | $H_M$ | Binary power, floor per factor, real column cutoff $L$ | $c_B$ | $d_B$ | +| --- | --- | ---: | --- | --- | ---: | +| Compact | 260000, 1600000 | 610000 | 128, 16, $2^{15}$ | $2039/2^{19}$ | 14 | +| Higher rate | 25000000, 160000000, 1000000000, 6000000000, 36000000000, 224000000000 | 1600000 | 228, 15, $2^{35}$ | $17108907955/2^{42}$ | 19 | +| Current price match | 175000000, 1120000000, 7000000000, 42000000000, 252000000000, 1568000000000 | 1600000 | 228, 15, $2^{35}$ | $17108907955/2^{42}$ | 19 | + +All three positive suppliers have 128 factors, a productive floor of $16^{128}$, and $L=2^{15}$. At every dyadic production rank the band proof gives a multiplier below $(9/4)(4A k_{\max}L)^c$ on the $N^{1-c}$ bill. In addition, the ordinary caller spends five bits and the positive caller spends one. Each actual binary source has maximum raw target 127 and ambient 134. The numerical values are 129 and 153. The exact integer logarithms in the receipt bound these products with $9/4<2^{5/4}$. Each production rank satisfies $N/(4A)\ge k_{\max}L$, so some real unit runs. Smaller stopped ranks issue each primitive on the same field. [Integer realization and rounding tariff](BAND.md) · [Exact profile calculations](calibration.py) + +## Ordinary service and native stock + +Let $e$ be the ternary width of each of the two physical address fields. Use $\rho=1/250$. Starting with $b_0=0$, the stage has $C_i=c_B-d_B/H_i$ and chooses a strict $b_i<\min(\eta,(249C_i+b_{i-1})/250)$. The compact and higher-rate profiles use $\eta=97/25000$ and $39/10000$, respectively. Each is smaller than $\rho$. The kernel checks the inequalities at all fourteen stage prices. Each full paid moment and its degree-one counterpart have the predecessor's geometric contraction, since the five-bit charge permits all nine physical rank-one children and the normalization allowance. At a growing entry the body costs $O_F(V[mc+c^{1-C_i}w^{1-b_{i-1}}])$, where $V$ is the complete local field volume, $c$ its number of coarse columns and $m$ the number of balanced components in an atom. Here $w=\max(E_{i-1}+1,\lceil e^\rho\rceil)$ after stage one. The component target is $\lceil e^\eta\rceil$. Thus $mc\le 2e^{1-\eta}$; for a growing $w$ the second term is at most a constant times $e^{1-[(1-\rho)C_i+\rho b_{i-1}]}$. For the fixed floor $w\le N_i$ its positive excess is a fixed carrier factor. Both terms fit $O_F(Ve^{1-b_i})$. Upper and lower body shears, older weights, covered matrix conversions, all previous calls, and complete head restoration have their original physical charge. Direct calls occur only at $c\le N_i^8$, so their additional factor fits once in the summed subcritical recurrence. [Actual ordinary receiver](ordinary_carrier.py) · [Rank-one and chart accounting](https://github.com/CrocSwap/integer-mult-bounds/blob/9585c1fa2ed5f2316ac09e04b357cb720badfcb8/research/triangular-native-supplier/BINARY.md) · [Changed exponent and stock inequalities](STRONG-BINARY.md) + +Write $a_i=\log_2 E_i$. The code takes $a_1=\lceil250(H_1+64)/249\rceil$. Later $a_i$ is the maximum of this stage's analogous cutoff and $H_i+a_{i-1}+64$. At the direct-to-quotient transition the stock includes every productive owner at every height. Beyond eight open heights it also includes every required low representative and its unrestricted high coordinates. The source proof of the reserve for $a_i$ uses $\eta<\rho$, $b_i<\eta$, the bound on the installed owner's width, and the quotient entry $u=\lceil(2H_i+64)/(1-\eta)\rceil$. All three installations satisfy those inequalities, including the fixed predecessor floor. The bound on the width of the new band owners fits the original ordinary and complex caps. The final direct call has enough full-width trits to enter each earlier stage. Missing widths run the preceding service. [Full reserve calculation](ACTIVATION-SPACE.md) · [Kernel-checked nested exchanges and reserve](lean/BandFlow.lean) · [Nested physical admission proof](https://github.com/CrocSwap/integer-mult-bounds/blob/9585c1fa2ed5f2316ac09e04b357cb720badfcb8/research/triangular-native-supplier/STAGED-CARRIERS.md) + +## Numerical and signed user boundary + +Set $g=10^{-14}$. The ordinary service covers $\kappa+4g$ and the complete padded positive service covers $\kappa+5g$. The final ordinary rates are 0.003879928035646, 0.003890115197377 and 0.003890115271496. The positive recursion takes a complete group of $\lfloor h/M\rfloor$ windows and pays its local suffix. It stops at $\max(M,h^g)$. The stopped cost has a finite carrier factor even where $h^g2\) and \(L\epsilon\ge2\). + +## Finite geometry and integral loans + +For target rank \(n\), set \(n'=4\lfloor n/4\rfloor\), \(m=n'/4\) and +\(U=m/A\). A stopped rank \(UU\). At each paid prefix \(p\) and productive suffix +\(a\) with \(|p|+|a|=G\) set + +\[ +x(p,a)=\prod_{j\in p}r_j\,\prod_{i\in a}k_i/r_{\max}^G . +\] + +Use the real raw program with \(c(x)=\lfloor x\rfloor-1\) integral columns +exactly where \(L\le x\le U\). Then \(Ac(x)\le m\) and \(c(x)\ge1\). +The first layer has every \(x>U\). The last has every \(x\le1\). +If \(U\ge L k_\min/r_\max\) then at least one layer has an active unit. +Follow occurrences with paid rank \(r_{\max}\) and future rank \(k_{\min}\). +Their only ratio per step is \(r_{\max}/k_{\min}\). At the first crossing +of \(U\) the result is greater than \(U r_{\max}/k_{\min}\ge L\). +For a narrower range the compiler directly tests for a nonempty band and +serves an empty band by elementary axes. All funded fixed ranks below use +the sufficient inequality. + +There is a unique edge from \((p,(i,a))\) at cut \(j\) to port \(i\) of +\((p j,a)\). If their virtual columns are \(y,x\), then +\(r_j y=k_i x\), with \(y\ge2x\). For two active endpoints, + +\[ +0\le r_j c(y)-k_i c(x)<2k_i . +\] + +Indeed \(z-2U\). Allocate a real external incidence of actual size +\(s'=k_i c(x)\) and virtual size \(s=k_i x=r_j y>U\). Then +\((1-2/L)s\le s'\le s\) and \(s'\le m\). If an active lender has no child +for a cut, its virtual \(e=r_j y=k_i x < k_{\max}L\). Fulfil the entire +actual request with \(r_jc(y)\le e\) elementary axes. +These cases include cuts incident to empty time layers. + +For any fixed chronological path, different active units have disjoint owner +pools. External slots are disjoint. At a paid cut one parent gives one job +to at most one child. A new private field has a fresh owner. This proves the +owner statement by induction. Open each group's native continuations in the +specified source order. At each paid cut obtain the exact jobs from all +current continuations, visit the next paid path, and restore all incoming +requests including their residual axes. Resume the raw words after the cut +returns. Empty layers with active descendants must still run those descendants. +A terminal child can perform its leftover leaves before returning. In the +iterator a job outside every consumer is disjoint from their owner pools at +this cut, so it can also complete after those consumers. +band_compiler.py computes the incidence plan. epoch_tape.py emits a complete epoch and replays its serialized stream at each outer round. +It never forms a job from an owner identity alone. Each subjob selects axes +from its typed parent. The underlying powered source remains responsible for +closing each raw adapter, including all of its temporary fields. + +Each terminal or residual axis calls the actual recursive leaf service. At a +fixed complex rank this is a whole bundle of consecutive physical windows. +It performs the saved group's operation on its complete owner. At a fixed +binary rank it consumes the actual line projector and full complement chart. +No subset is treated as a free move. The completed operations on two +disjoint parts commute in the enclosing job's basis. They need not commute +with a pending native adapter. For that reason all restoration is inside +that parent's suspension. + +## Normalized paid price + +Let \(S\) sum \(s^t\) over all external occurrence ports, and \(E\) sum +\(e^t\) over all terminal cuts before the replication of a round. Summing +all active node identities \(Tx^t-Px^t=(T-P)x^t\) gives exactly + +\[ +S=E+(T-P)\sum_{\mathrm{active}} x^t . +\] + +Equal virtual edge terms cancel with the same labeled edge. The actual +integral cardinalities can differ. Write \(D=(k_{\max}L)^C\). +Each terminal costs at most \(D e^t\) because \(e2^4\), the high-rate binary step gives \(vG<13H/4+v\). Hence the number of candidate units, including rejected ones, is bounded by +\[ +\sum_{d=0}^G P_\#^d W^{G-d} +\le(W+P_\#)^G4\), the lower step gives \(vG\le5H/2+v\) and the same binomial sum is below \(N^{75}\). Across all three installations the numerator and denominator of any virtual column have fewer than \(27H+2\) bits by \(A^G<2^{8vG}\). All later common bounds use \(N^{75}\) candidates, at most \(N^{76}\) external sources, \(R\le N\), \(h\le N^{77}\), \(B\le N^{79}\), and \(z\le30\). This construction has one fixed rank per program with no smaller-rank compiler group at a terminal. + +Use binary odometers to visit ordered labels, paths and owners. The installed epoch records one relative selector per external port, typed loan descriptors, native opens, paid issues, closes and complete finishes. The native subprogram, its factor words and the retained plan accompany the epoch. At round \(j\) the interpreter computes the absolute owner and its ordered axes from the recorded base, size and period. Native opcodes run in the held iterator. An issued job stays in its returned basis. A finish performs every residual elementary call. The file records each operand count and variable-length base-128 nonnegative operands. The following budget even counts explicit expanded selector, native, leaf and empty-prefix visits at all rounds. + +A powered-word unit needs fewer than \(2^{64}(v+1)2^{28v}1/512$, since $\log(1-x)\ge-2x$ for $0\le x\le1/2$. Thus $u_j>1/512$. For $t=k_j+1\ge21$, + +$$o_j\le R_j^t/t! \le (eR_j/t)^t < (9/t)^t<2^{-t}.$$ + +The first inequality follows by expanding the power and retaining only distinct-prime products. The factorial bound follows by integrating $\log x$ from 1 to $t$. Hence $\sum_j o_j/u_j<\sum_{j\ge0}512\,2^{-21-2j}<1/2$. Independence across bands gives a main term at least $2^{-9r-1}$ from the displayed lower polynomial. + +In its expansion each divisor of each of the $r+1$ product terms has coefficient of modulus one, since factorization into distinct band primes is unique. Each such divisor is at most + +$$ z^{\sum_{j\ge0}(21+2j)2^{-j}}=z^{46}.$$ + +An interval has a count of multiples of $D$ that differs from $H/D$ by less than one. The error on all the signed terms is at most $(r+1)z^{46}$. Prescribed primes above $z$ remove at most $H2^{-s}+2^s$ additional positions. For $512\cdot2^k\le s<1024\cdot2^k$, $r\le11+k\le16\cdot2^k\le s/32$. Thus $9r+20.$$ + +This proof bounds a deterministic first-coprime scan. The executed algorithm only needs integer square roots, exact gcd tests, and multiplication of its running prefix. It does not factor the operands or enumerate the bands or the inclusion–exclusion terms. + +## Apply the sieve to the actual shape + +The prefix of prior bases, including 2, has at most $p+2\le2^s$ distinct prime divisors since its binary length is at most $L+2\le p+2$. On axis $i$ take $m=4d$ for even $i$ or $16d$ for odd $i$. For $t=2^{\ell_i}$ require $(1-1/m)t\le x^2\le(1-1/(2m))t$. The difference of square roots is at least $2^{\ell_i/2}/(4m)$ by subtraction of the squares and division by their sum. Rounding both endpoints leaves at least $2^{\ell_i/2-s-6}-2$ consecutive integers because $d\le p\le2^s$. At $\ell_i\ge W$ this exceeds $2^{192s}$. The first odd base coprime to the previous bases therefore exists on every axis. The same endpoints and disjoint alternating bands give pairwise coprime true sides $x_i^2$ and $3T/4\le S=\prod_i x_i^2p$. The additive excess of the chosen minimum above this physical lower bound is at most 512 bits. The dyadic axis-count rounding can still double the actual width. [Executed precision and pack errors](https://github.com/CrocSwap/integer-mult-bounds/blob/9585c1fa2ed5f2316ac09e04b357cb720badfcb8/research/triangular-native-supplier/NUMERICAL-STORAGE.md) + +The two-root per-column defect still satisfies $2^{-P}(64t)^{400}<1/(2r_i)$ because even one active axis gives $P>32768(\ell+6)$. Group by the first real split of wire zero in its rational word and by physical width. The same number of possible tags gives at least one genuine positive pack of size + +$$ h\ge\min\{h_0,\lfloor d/[80000(\ell+2)^6]\rfloor\}\ge 2^{s-100}/s^7.$$ + +Indeed $\ell+2<2048s$, $80000<2^{17}$ and flooring a real number at least two costs a factor of at most two. This argument uses the genuine side, both root passes and the original sixteen-H lowering. The CRT also obtains a genuine complete switch. Its $G_0=64(\ell+s)\le128\ell$ and $r_{\max}=\lfloor L/(100G_0)\rfloor$ obey $L\ge10100G_0$, $r_{\max}\ge d/51200$, and $L/101\le H_0=r_{\max}G_0\le L/100$. There are at most $2^{46}\ell^3$ exceptional right-axis positions. Since $d/2>2^{46}\ell^3$ from the bounds above at 512 and the growth of $2^s/s^4$, an ordinary request with at least $p/2424$ trits occurs on the true CRT. [Mixing witness, actual CRT and whole-slot shuttles](https://github.com/CrocSwap/integer-mult-bounds/blob/46783fbbfc219a3faffbea76f60a2810b85ab75a/research/native-stock-activation/OUTER.md) + +Let $M=2^{H_M}$ be the installed positive carrier and $2^a$ a proved trit width for the full ordinary service. Let $s_0\ge512$ satisfy $s_0-100-7\lceil\log_2 s_0\rceil\ge H_M+a+2$. The helper `connected_exponent` returns $A=s_0-1$. The real function $s-7\log_2s$ increases on this tail. The integer lower bound $s-7\lceil\log_2s\rceil$ may drop by six at $2^k+1$. The helper also checks this next point. If it fails, advance to the first passing point of that next band, at most seven steps beyond $s_0$. Later postjump minima rise by $2^k-7>0$. Both the integer and real criteria now hold on the entire admitted tail. Since $2^s/s^7$ increases for $s\ge512$, every $p\ge2^A$ has $h\ge4M2^a$. Hence $h>M$ and $h^{10^{14}}>h$ at the root. The positive body executes on the real heavy pack. A powered external port repeating its rank-129 raw root has at least three source slots in the first head. Its periodic placement must move a whole slot of $f\ell_i$ bits, $f=\lfloor h/M\rfloor$. Thus its nested ordinary service receives at least $f\ell_i/2>2^a$ real trits. This port argument requires the sourced powered word and an externally assigned future with that target, including the periodic source width bounds; a new compiler must prove that its emitted plan retains this property. The ordinary dispatch at that width must also execute its full stated stages. These are explicit inputs to this geometry calculation. [Periodic gap and physical destination](https://github.com/CrocSwap/integer-mult-bounds/blob/46783fbbfc219a3faffbea76f60a2810b85ab75a/research/native-stock-activation/OUTER.md) + +For every native pack $\log_2 M\le s$. The sliced field keeps $L'=L-\lfloor s/2\rfloor\ge15L/16$. Its true windows occupy $h\ell_i\le d\ell/(1024s)M$ the root is active since $h^{10^{14}}>h$. No lower bound $h\ge M^{10^{14}}$ is needed for the algorithm or the price. The finite power of $M$ belongs to its recurring constant. For a fixed strict surplus $\epsilon>0$ any power $x^k e^{-\epsilon x}$ is at most $(k/(e\epsilon))^k$ for $x\ge0$, by differentiation. This gives a finite explicit absorption factor for log powers without moving the execution threshold. + +For the one-band compiler the source witness described above can be read directly at depth one. Put $A_c=153^{128}$, $u=\min_i r_i$ over powered target ranks and $l=\max_j r'_j$ over powered paid ranks. The forest height $v$ is the first integer with $A_c(u/l)^v>M/4$. Choose its depth-one paid path at $l$ and its all-minimum target future. Its virtual size is $x=(u/l)^{v-1}$. The upper test accepts $x$, and $x>Ml/(4A_c u)$. The profile inequality $M\ge4A_c\,\mathrm{floor}\,u/l$ ensures $x$ meets the lower test. Every port $r_i\ge u$ is external because $A_c x r_i>(M/4)l$. Select the target repeating the actual rank-129 rotated raw root. Its physical column extent is $c=\lfloor x\rfloor-1$ and $3\le c129^{128}\le cA_c\le M/4$. At iteration zero and replica zero its ordinal is less than the source slots per copy and hence below the actual productive width. Its first raw head spans $c129^{127}\ge3$ slots, so the inherited periodic gap theorem forces an actual whole-slot swap. This source is distinct from the predecessor's empty-path forest convention. + +The first input length satisfying the certified public inequality $p\ge2^A$ is $n_{\min}=2^{b-1}+1$ for $b=\lceil2^A/6\rceil$. The last length of this same first precision is $n_*=2^b$. Throughout that interval $p_*=6b=2^A+\delta$ with $\delta=2$ or $4$, and $s=A+1$. At the two endpoints respectively $L=b-A+4$ or $b-A+5$. Indeed $\lfloor\log_2 b\rfloor=A-3$ and $b/2^{A-3}\ge4/3>1+2^{1-b}$, so the extra one at the lower endpoint does not change the ceiling. Write $q=\lceil\log_2(6W)\rceil$. Since $6W$ is not a power of two, $2^{A-q}>6A$ proves $d=2^{A-q}$, $\ell=\lceil2^q/6\rceil$ at either end and for either parity of $A$. At the lower end $6L-6W2^{A-q}=(2^q-6W)2^{A-q}+\delta-6A+24>0$, and at the upper end $L<2W2^{A-q}$. Also the correction to $2^q/6$ in $L/d$ is negative with magnitude less than $1/6$, while its nonzero fractional part before correction is at least $1/3$. The compact profile has $\log_2 d=2471395$ and $\ell=1431655766$ at entry. The higher-rate profile has $\log_2 d=267186701103$ and $\ell=187649984473771$. Its wider ordinary component exponent $0.0039$ enters the ordinary service tariff and its sufficient trit width. Neither changes this outer square sieve or the genuine common mixing pack. The helpers evaluate these exact exponents without allocating $n_{\min}$ or $p_*$. This is the first length guaranteed by the sufficient public cut. Whether a smaller input activates every native stage depends on its actual emitted schedules. A measured crossover at a practical input requires separate execution evidence. + +At the third entrance $A=1870297303584$, the same controller gives $\log_2 d=1870297303531$, $\ell=1501199875790166$ and private clock exponent 1539145727545373217. The single old dense matrix at the same input has at least $2^{825293359523586849932749484}$ entries. The physical positive rank and the 128-digit window requirement are shared with the other higher-rate configuration. [Three controller receipts](REQUIREMENTS.json) diff --git a/research/single-band-native-carriers/NOTICE.md b/research/single-band-native-carriers/NOTICE.md new file mode 100644 index 0000000000..10167a0c8a --- /dev/null +++ b/research/single-band-native-carriers/NOTICE.md @@ -0,0 +1,9 @@ +# Attribution + +Ali Romman prepared the single-band compiler, its physical epoch and receivers, the three finite installations, the square sieve, the connected activation proof and the new verification with substantial OpenAI Codex assistance. Separate Codex research workers examined the binary word and prices, Gaussian word and phases, and outer geometry. These checks are part of the author submission. Independent scientific review remains open. The package uses Apache License 2.0. [License](LICENSE) · [Working Discussion](https://github.com/CrocSwap/integer-mult-bounds/discussions/8028) · [Earlier contribution index](https://github.com/CrocSwap/integer-mult-bounds/discussions/7794) + +- Ali Romman’s [PR #8027](https://github.com/CrocSwap/integer-mult-bounds/pull/8027) supplies the two literal circuits, the scalar journals and the 36-call and 48-call schedules. The finite source identifies Clear1nsight’s iterated-return programs and independent scalar audit, and preserves the earlier contributor notices. This work implements the changed graphs on the physical receivers and checks their actual port, phase, movement, grid and ownership obligations. [Literal source and history](https://github.com/CrocSwap/integer-mult-bounds/blob/fb9b6a7b0d27da1cf98430893a3016bf811e2aa4/research/p104-live-relative-gain/README.md) · [Retained source notice](inputs/complex-source/PARENT-NOTICE) +- [PR #8029](https://github.com/CrocSwap/integer-mult-bounds/pull/8029) supplies the comparison prices at a fixed 768-factor delayed cover. Its normalized moment and later fortieth moment use the same raw circuits. Its authors retain credit for those price calculations. This construction reprices its own 128- and 228-factor physical programs. [Normalized price](https://github.com/CrocSwap/integer-mult-bounds/blob/a9dbc75e68e8c645df425adc489234d22df67f8d/research/p104-paired-delayed-cover/normalized/PROOF.md) · [Later moment price](https://github.com/CrocSwap/integer-mult-bounds/blob/c3837013dd7e2c50f6c3065c8f99d52a33b617bb/research/p104-paired-delayed-cover/weighted/moment/PROOF.md) +- Ali Romman’s [PR #7981](https://github.com/CrocSwap/integer-mult-bounds/pull/7981) supplies the triangular row charts, two-bank receiver, complete numerical packs and storage proof. [PR #7914](https://github.com/CrocSwap/integer-mult-bounds/pull/7914) supplies the independent low and high data, stack backing and signed product path. [PR #7868](https://github.com/CrocSwap/integer-mult-bounds/pull/7868) supplies the periodic owner groups, stopped ordinary service and fixed-head program. The archive contains the original license and notices. [Physical baseline](inputs/triangular/NOTICE.md) · [Fixed-head and flow credit](https://github.com/CrocSwap/integer-mult-bounds/blob/3f7c3c1f2a9a0963736562037e01fe41aec46b8c/research/bounded-general-multiplier/FLOW-NOTICE.md) +- Clear1nsight supplied the mixed binary cut in [PR #7830](https://github.com/CrocSwap/integer-mult-bounds/pull/7830). [PR #7837](https://github.com/CrocSwap/integer-mult-bounds/pull/7837) supplies rational projectors and joint charts. [PR #7846](https://github.com/CrocSwap/integer-mult-bounds/pull/7846) supplies uniform composition and two-input recovery. [PR #7849](https://github.com/CrocSwap/integer-mult-bounds/pull/7849) supplies the rational Fourier construction, its scalar grid and its certified local bounds. Source notices identify Dugongue and Rohan Arun for earlier prices, Nick Petalas for pivoted fallback, and Jose Manuel, Chafik and Vlado for predecessor Fourier work. [Projector history](https://github.com/CrocSwap/integer-mult-bounds/blob/a7f99a5f5f919dd3ffb2987f90c1e7d6527feb1e/research/grade14-native-realization/NOTICE.md) · [Numerical history](https://github.com/CrocSwap/integer-mult-bounds/blob/3615fd982f2f4dc7172bef6f0dc9a4f77d5ab6dd/research/direct-circulant-fourier/NOTICE.md) +- The pinned repository supplies balanced CRT and compact sequential routing. Lean and mathlib supply the kernel and its libraries. The three modules in this package are new proofs. The immutable dependency manifests retain upstream file hashes and source commits. [Dependency pins](SOURCES.json) · [Mathlib revision](https://github.com/leanprover-community/mathlib4/tree/d13f23b723b8a846827a245b89c10fc7d3f11612) diff --git a/research/single-band-native-carriers/README.md b/research/single-band-native-carriers/README.md new file mode 100644 index 0000000000..5349b7f956 --- /dev/null +++ b/research/single-band-native-carriers/README.md @@ -0,0 +1,34 @@ +# Smaller carriers for general integer multiplication + +The compact construction preserves the complete saving `κ = 0.00387992803556` of [PR #7981](https://github.com/CrocSwap/integer-mult-bounds/pull/7981). It reduces the logarithm of the largest binary dimension from **236,800,000,000,000 to 1,600,000**. A second installation reaches κ = 0.00389011519729 with a largest binary rank exponent 1,057 times smaller than the physical predecessor. A third installation matches the current conditional price **κ = 0.00389011527141** of [PR #8029](https://github.com/CrocSwap/integer-mult-bounds/pull/8029). All three use the same physical compiler and signed tape entry. [Complete resource receipt](REQUIREMENTS.json) · [Signed binary entry](band_product.py) + +| Quantity | Physical predecessor #7981 | Compact | Higher rate | Current price match | +| --- | ---: | ---: | ---: | ---: | +| Complete κ | 0.00387992803556 | 0.00387992803556 | 0.00389011519729 | 0.00389011527141 | +| Ordinary stages | 6 | 2 | 6 | 6 | +| Largest binary rank, log₂ N | 236,800,000,000,000 | 1,600,000 | 224,000,000,000 | 1,568,000,000,000 | +| Positive numerical rank, log₂ M | 3,300,000,000 | 610,000 | 1,600,000 | 1,600,000 | +| Setup exponent for the largest stream, log₂ J | 4,736,000,000,000,000,000 | 1,638,400,000 | 229,376,000,000,000 | 1,605,632,000,000,000 | +| Connected sufficient threshold A in p ≥ 2^A | 355,763,540,965,264 | 2,471,428 | 267,186,701,153 | 1,870,297,303,584 | +| Largest padded axis at its own entrance, log₂ side | 13,521,606,402,434,446,949,298,167,524,011 | 1,431,655,766 | 187,649,984,473,771 | 1,501,199,875,790,166 | +| All per-input numerical setup at that entrance, log₂ upper bound | 132,715,849,533,509,598,534,716,307,019,923,456 | 1,468,548,787,717 | 192,427,450,469,892,962 | 1,539,145,727,545,373,217 | + +Let $n$ be the larger significant bit length and $p=6\lceil\log_2 n\rceil$. At each configuration the algorithm returns the exact signed product for arbitrary input tapes in $S+C n(1+\log n)^{1-\kappa}$ steps on the fixed-alphabet multitape model. For the finite initial lengths the same entry runs the signed scalar program. For **every** length at least $2^{\lceil2^A/6\rceil-1}+1$ it runs the full numerical word with a genuine call into the last binary stage and all its predecessor stages. Extra declared leading zeros cost their tape length. At these entrances the complete machine, including both inputs, output, field files, reserves, suspended owners and historical work space, fits below $6.2pT<297.6n$ bits for canonical inputs, with $T$ the actual padded tensor size. [Connected entrance and numerical setup](LINEAR-GEOMETRY.md) · [Simultaneous storage](ACTIVATION-SPACE.md) + +## Why the exponents fall + +- The literal 36-call and 48-call circuits of #8027 have extra price headroom. The binary implementation realizes the changed projectors on both physical banks. The numerical implementation reconstructs the rational circuit from its journals and generates all 2,971 required Clifford transports and 104 port pairs. Its 21 additional transports, 1,291 independent roles, divisions and absolute phases are checked on the changed graph. [Binary construction](STRONG-BINARY.md) · [Gaussian construction](STRONG-COMPLEX.md) +- A single band of native tensor calls replaces recursive compilation of unequal ranks. Each child borrows its exact prefix in the lender’s frame. The strict native surplus pays the remaining axes once. The installed tape encodes one chronological round for all subsequent rounds. It retains the actual owner, backing, loan, return and restoration at each issued operation. This removes the growing compiler loss at the finite rank. [Finite-flow proof and setup bill](BAND.md) · [Tape implementation](epoch_tape.py) +- A deterministic coprime-square search reduces the minimum axis width from $64s^2$ to $512s+1280$, where $s=\lceil\log_2(p+2)\rceil$. It selects more axes in the same padded tensor. At the compact entrance and **the same input**, one old root matrix alone needs $2^{1,501,199,875,790,166}$ entries. All new private generation fits in $2^{1,468,548,787,717}$ transitions, a factor above 1,022 **in the exponents**. This saving is independent of the smaller carrier ranks. [Uniform sieve and compiler proof](LINEAR-GEOMETRY.md) + +## Complete costs and evidence + +The smaller ordinary ranks reduce the component widths, the generated native streams and the length needed to expose a full recursive chain. These three effects share a cause. The shorter powered words, single-round representation and omission of lower-rank compiler batches also reduce setup at a fixed rank. The bound on generation, installed machinery and fixed setup scratch is $\sum_i N_i^{1024}+M^{1024}$. The previous rank-dependent clock used degree 20,000. The compact machine fits below $2^{1,638,400,002}$ fixed steps and cells. The higher-rate machine fits below $2^{229,376,000,000,003}$. The current-price machine fits below $2^{1,605,632,000,000,003}$. These are bounds for the specified generators. The old compiler’s root exit table alone had at least $2^{989379999989304}$ entries. Its specified expanded stream had at least $2^{3366293830151418}$ records. Against all new fixed setup this proves reductions greater than 2,054,622×, 14× and 2× in the exponents of actual required old work versus sufficient new work. [Old installer lower bounds and executed activation guard](ACTUAL-SETUP.md) · [Program, movement and recurring costs](APPLICATION.md) + +Feasible signed Fourier products, complete circuit traces, independent price calculations and kernel replay exercise different parts of the claim. The production input threshold still has a double exponential. No machine ran either production-dimensional multiplication. The least recurring constant and a crossover against a conventional multiplier are unknown. The two 228-factor configurations also change the cofinal bound on the logarithm of the chart reserve by a width factor $e^{1/50000}$ before the changed rank factors. [Verification and limitations](VERIFICATION.md) · [Predecessor attribution](NOTICE.md) · [Coordination](https://github.com/CrocSwap/integer-mult-bounds/discussions/8028) + +For the most demanding price, the 111-port source and the retained five-bit ordinary tariff force the largest rank exponent above 330,033,003,300, even when all other compiler losses are forgiven. At the installed 19-bit debit the necessary exponent is at least 1,455,682,013,917. The actual 1,568,000,000,000 is within 7.72% of this second floor. Both floors apply to the stated source and price method. [Global raw crossing and rank limits](STRONG-BINARY.md#what-prevents-a-thousandfold-cut-at-the-largest-price) + +## Open next questions + +Can a different ordinary caller pay less than five bits of finite rank loss at the same complete price? Can a numerical pack use fewer independent axes and still issue a real paid call into the last ordinary service? These two costs limit further reductions in the carrier rank and the outer entrance. [Exact obligations](TASK.json) diff --git a/research/single-band-native-carriers/REQUIREMENTS.json b/research/single-band-native-carriers/REQUIREMENTS.json new file mode 100644 index 0000000000..64a217df2f --- /dev/null +++ b/research/single-band-native-carriers/REQUIREMENTS.json @@ -0,0 +1,208 @@ +{ + "compact": { + "all_size_margin_lower_at_entrance": 172060, + "binary_entrance_logs": [ + 261109, + 1861173 + ], + "binary_rank_logs": [ + 260000, + 1600000 + ], + "complex_rank_log": 610000, + "component_exponent": "97/25000", + "full_binary_debit": 14, + "full_positive_debit": 10, + "initial_s": 2471429, + "kappa": "96998200889/25000000000000", + "linear_geometry": { + "actual_dense_root_entry_log2": 2863311532, + "first_extent_bits_minus_b": -2471424, + "largest_axis_width": 1431655766, + "last_extent_bits_minus_b": -2471423, + "log2_axis_count": 2471395, + "minimum_width": 1265372928, + "private_clock_log2_upper": 1468548787717, + "public_offset_above_2_to_A": 2 + }, + "log2_all_fixed_setup_upper": 1638400002, + "log2_dominant_J": 1638400000, + "log2_rank_part_of_recurring_envelope": 163840000000, + "log2_sufficient_public_precision": 2471428, + "native_depth_bound_at_entrance": 25, + "native_volume_log2_upper": 16384, + "ordinary_rate": "1939964017823/500000000000000", + "positive_context_cost_bitlength_upper": 56, + "prior_geometry_at_same_n": { + "actual_dense_root_entry_log2": 1501199875790166, + "first_extent_bits_minus_b": -2471424, + "largest_axis_width": 750599937895083, + "last_extent_bits_minus_b": -2471423, + "log2_axis_count": 2471376, + "minimum_width": 390909523330624, + "private_clock_log2_upper": 6404666813212262400, + "public_offset_above_2_to_A": 2 + }, + "rate_ticks_e18": [ + 3819896757624698, + 3879928035646000 + ], + "raw_structural_nodes_log2_upper": 3912, + "stripe_excess_log_at_entrance": 950364, + "stripe_margin_at_entrance": 285348, + "uniform_payload_slope": "496192/2478125" + }, + "high-rate": { + "all_size_margin_lower_at_entrance": 113466985868, + "binary_entrance_logs": [ + 25100466, + 185100530, + 1185100594, + 7185100658, + 43185100722, + 267185100786 + ], + "binary_rank_logs": [ + 25000000, + 160000000, + 1000000000, + 6000000000, + 36000000000, + 224000000000 + ], + "complex_rank_log": 1600000, + "component_exponent": "39/10000", + "full_binary_debit": 19, + "full_positive_debit": 10, + "initial_s": 267186701154, + "kappa": "389011519729/100000000000000", + "linear_geometry": { + "actual_dense_root_entry_log2": 375299968947542, + "first_extent_bits_minus_b": -267186701149, + "largest_axis_width": 187649984473771, + "last_extent_bits_minus_b": -267186701148, + "log2_axis_count": 267186701103, + "minimum_width": 136799590992128, + "private_clock_log2_upper": 192427450469892962, + "public_offset_above_2_to_A": 4 + }, + "log2_all_fixed_setup_upper": 229376000000003, + "log2_dominant_J": 229376000000000, + "log2_rank_part_of_recurring_envelope": 22937600000000000, + "log2_sufficient_public_precision": 267186701153, + "native_depth_bound_at_entrance": 179693, + "native_volume_log2_upper": 32768, + "ordinary_rate": "3890115197377/1000000000000000", + "positive_context_cost_bitlength_upper": 58, + "prior_geometry_at_same_n": { + "actual_dense_root_entry_log2": 12895208742556044530199212, + "first_extent_bits_minus_b": -267186701149, + "largest_axis_width": 6447604371278022265099606, + "last_extent_bits_minus_b": -267186701148, + "log2_axis_count": 267186701068, + "minimum_width": 4568878929507641915629824, + "private_clock_log2_upper": 74856512381613536270378598400, + "public_offset_above_2_to_A": 4 + }, + "rate_ticks_e18": [ + 3873797863410106, + 3889931739863747, + 3890095626369561, + 3890112051915585, + 3890114745951102, + 3890115197377000 + ], + "raw_structural_nodes_log2_upper": 6912, + "stripe_excess_log_at_entrance": 11776557180, + "stripe_margin_at_entrance": 121816793395, + "uniform_payload_slope": "5422628/123046875" + }, + "previous": { + "complex_rank_log": 3300000000, + "connected_precision_exponent": 355763540965264, + "geometry": { + "actual_dense_root_entry_log2": 27043212804868893898596335048022, + "first_extent_bits_minus_b": -355763540965260, + "largest_axis_width": 13521606402434446949298167524011, + "last_extent_bits_minus_b": -355763540965259, + "log2_axis_count": 355763540965158, + "minimum_width": 8100332613129202419707937294400, + "private_clock_log2_upper": 132715849533509598534716307019923456, + "public_offset_above_2_to_A": 2 + }, + "log2_dominant_J": 4736000000000000000, + "rank_logs": [ + 60000000000, + 400000000000, + 2500000000000, + 16000000000000, + 100000000000000, + 236800000000000 + ] + }, + "price-match": { + "all_size_margin_lower_at_entrance": 799261674748, + "binary_entrance_logs": [ + 175702876, + 1295702940, + 8295703004, + 50295703068, + 302295703132, + 1870295703196 + ], + "binary_rank_logs": [ + 175000000, + 1120000000, + 7000000000, + 42000000000, + 252000000000, + 1568000000000 + ], + "complex_rank_log": 1600000, + "component_exponent": "39/10000", + "full_binary_debit": 19, + "full_positive_debit": 10, + "initial_s": 1870297303585, + "kappa": "389011527141/100000000000000", + "linear_geometry": { + "actual_dense_root_entry_log2": 3002399751580332, + "first_extent_bits_minus_b": -1870297303580, + "largest_axis_width": 1501199875790166, + "last_extent_bits_minus_b": -1870297303579, + "log2_axis_count": 1870297303531, + "minimum_width": 957592219436800, + "private_clock_log2_upper": 1539145727545373217, + "public_offset_above_2_to_A": 2 + }, + "log2_all_fixed_setup_upper": 1605632000000003, + "log2_dominant_J": 1605632000000000, + "log2_rank_part_of_recurring_envelope": 160563200000000000, + "log2_sufficient_public_precision": 1870297303584, + "native_depth_bound_at_entrance": 1181637, + "native_volume_log2_upper": 32768, + "ordinary_rate": "486264408937/125000000000000", + "positive_context_cost_bitlength_upper": 58, + "prior_geometry_at_same_n": { + "actual_dense_root_entry_log2": 825293359523586849932749484, + "first_extent_bits_minus_b": -1870297303580, + "largest_axis_width": 412646679761793424966374742, + "last_extent_bits_minus_b": -1870297303579, + "log2_axis_count": 1870297303493, + "minimum_width": 223872768243028585846542400, + "private_clock_log2_upper": 3667931434897702648240559620096, + "public_offset_above_2_to_A": 2 + }, + "rate_ticks_e18": [ + 3874446686267249, + 3890035713726604, + 3890112262836441, + 3890114821890024, + 3890115207602428, + 3890115271496000 + ], + "raw_structural_nodes_log2_upper": 6912, + "stripe_excess_log_at_entrance": 77439959170, + "stripe_margin_at_entrance": 857708692620, + "uniform_payload_slope": "35662628/861328125" + } +} diff --git a/research/single-band-native-carriers/SOURCES.json b/research/single-band-native-carriers/SOURCES.json new file mode 100644 index 0000000000..94e74a7e02 --- /dev/null +++ b/research/single-band-native-carriers/SOURCES.json @@ -0,0 +1,75 @@ +{ + "schema_version": 1, + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "files": [ + { + "path": "AGENTS.md", + "git_blob": "ff81117fca368042f6092964d1f54eb4e6e08fb9", + "sha256": "fece32cdec9c1572ddce354a0b623459cb2c4ca162125d36d36262a92e3caa83", + "usage": "provenance" + }, + { + "path": "autoresearch.md", + "git_blob": "2fe84a7b30b1e26e60ce0ec4775894eb1831c5d6", + "sha256": "d16f0d3bb4d4b213d06c128db6d6460b0fe9ec1ac5a6c1ea1febf1db40e7b60d", + "usage": "provenance" + }, + { + "path": "CONTRIBUTING.md", + "git_blob": "5185786f2ec00f215019fb5777d70979429690a9", + "sha256": "fcd1a8d0e52342a23b8ffa9e905e85ccc539fb084145ef016dfc93cedfb3d924", + "usage": "provenance" + }, + { + "path": "certificates/selected-result.json", + "git_blob": "75d77b328ea02ded535e7f23aee5b1e55d0bb1a8", + "sha256": "154c3d30455d778fd3343b6b4851f0fa4665f0f7625b0adb3675e2bafbbf6bf1", + "usage": "provenance" + }, + { + "path": "docs/research/agent-task-catalog.json", + "git_blob": "3404fbdd5e7529a0674eef26114b5071e4586cec", + "sha256": "ead6cdc9d0af6d58e8a49744d8ec8c7c15e13d2ba93c276c434bcf9b51b93a81", + "usage": "provenance" + }, + { + "path": "research/unconditional-batched-crt/CRT.md", + "git_blob": "d98dd8e368431cac33d5fc1c8c336696663641d6", + "sha256": "02c3a1e38cbee25aefe2640cc72676da62ba10eb7519fbcb9adb9d48b74eff2b", + "usage": "provenance" + }, + { + "path": "research/delayed-cover-physical-batch-routing/PROOF.md", + "git_blob": "af919b5ba2257c07ea17180f9b8c9fd457556079", + "sha256": "1c3dcd294d327a16fa081b7ea27497941ac6480d352f53e55e8b9e87f45d1454", + "usage": "provenance" + }, + { + "path": "notes/compact-control-movement.tex", + "git_blob": "06b6a9ef24245ac7b724c53a204635415b402357", + "sha256": "b963c3d2f4e1b7059aa289bb4b4ac89b688920bcf42f5b20d7698cdef0132cc6", + "usage": "provenance" + } + ], + "mixed_price": "87fbf4f7b35b0f18ab12b5767775a9a424cf0b15", + "native": "a7f99a5f5f919dd3ffb2987f90c1e7d6527feb1e", + "uniform": "343f7b1817e26ad3f89d2ddad313b12741d53602", + "numerical_caller": "3615fd982f2f4dc7172bef6f0dc9a4f77d5ab6dd", + "self_borrowing_precedent": "f927ed7ffbb2b8870f109d59ddd94e1f87becb13", + "physical_predecessor": "46783fbbfc219a3faffbea76f60a2810b85ab75a", + "complete_periodic_predecessor": "3f7c3c1f2a9a0963736562037e01fe41aec46b8c", + "vendored_members": [ + "inputs/triangular.json", + "inputs/triangular/inputs/retained.json", + "inputs/review.json", + "inputs/complex-source.json" + ], + "immutable_input_archive_sha256": "77742c09b088f27e8742c3fad7b7148d3397e4d51b95312106f39a8970165903", + "mathlib": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "physical_cost_comparator": "9585c1fa2ed5f2316ac09e04b357cb720badfcb8", + "paired_literal_source": "fb9b6a7b0d27da1cf98430893a3016bf811e2aa4", + "normalized_price_comparator": "a9dbc75e68e8c645df425adc489234d22df67f8d", + "fortieth_moment_price_comparator": "c3837013dd7e2c50f6c3065c8f99d52a33b617bb", + "literal_binary_sha256": "74e93daf2b7acf794ffb51f92f03f51556f68126d41ee13a8969bddb4cbe6326", + "audit": "verify_sources.py" +} diff --git a/research/single-band-native-carriers/STRONG-BINARY.md b/research/single-band-native-carriers/STRONG-BINARY.md new file mode 100644 index 0000000000..530be21be9 --- /dev/null +++ b/research/single-band-native-carriers/STRONG-BINARY.md @@ -0,0 +1,196 @@ +# Physical binary word with 111 ports + +The general ordinary service uses the 111-port circuit of Ali Romman in +[PR #8027](https://github.com/CrocSwap/integer-mult-bounds/pull/8027). +Its literal 39,600-instruction graph is +[pinned here](https://github.com/aliromman/integer-mult-bounds/blob/fb9b6a7b0d27da1cf98430893a3016bf811e2aa4/research/p104-live-relative-gain/BINARY-CANDIDATE.json.gz). +The compressed SHA-256 is +`74e93daf2b7acf794ffb51f92f03f51556f68126d41ee13a8969bddb4cbe6326`. +The expanded SHA-256 is +`b096d6df2a0c4688296b13ab0cfd50fec1c7dec732819c624ddd7a745a144b69`. +The binary source module supplies this graph to the bank interpreter, +the image and kernel frame generators, and the ordered productive and +paid lists. It retains the 36-call outer binary word and the physical +bank operations of [PR #7914](https://github.com/CrocSwap/integer-mult-bounds/pull/7914). +Clear1nsight supplied the predecessor mixed-rank compiler. The 111-port +word extends the punctured E8 circuit. The +[source notice](https://github.com/aliromman/integer-mult-bounds/blob/fb9b6a7b0d27da1cf98430893a3016bf811e2aa4/research/p104-live-relative-gain/PARENT-NOTICE) +credits its predecessors. The new supplier binding, strict prices and +full exact chart check use substantial OpenAI Codex assistance. + +## Native action on arbitrary fields + +Work on one simultaneous ternary component. For a diagonal unit weight +matrix A, head h, tail t and a projector P, set d=t−A⁻¹h. Write D(P) for +the address permutation that takes (h,t) to (h+APd,t−Pd). +The new difference is (I−2P)d. It follows by substitution that +D(P)D(Q)=D(P+Q−2PQ) when P and Q commute. In particular, D(P) is its +own inverse, disjoint chart axes commute, and D(P)D(Q)=D(Q−P) when +PQ=QP=P. These equalities hold over every required cyclic ternary +ring. The common reduction lets them act on all component sizes at +once. Finite coordinate products with the identity on each column +and on all remaining positions preserve the identities. + +Let P_i be the projector onto the first dim(i) columns of the table +for frame i. The exact checker constructs all 636 projectors over the +rationals with denominators coprime to three. For every one of the +2,352 distinct MOVE and helper endpoint pairs it verifies both products +of the smaller and larger projectors equal the smaller projector. It +constructs a full invertible eigenbasis for their positive difference +at the stated rank. For each of 111 main pairs, the first input has a +rank-one head H, the second input has the zero projector, the first +output has the identity projector, and the final second projector is +I−H. The same checker verifies both the emitted chart word and its +inverse on the full basis. Its 44,825 forward factors have scale and +addition numerator and denominator magnitudes at most 20, including +their inverses. Each scale is a unit at three. These facts apply the +existing physical operations at every modulus and on every admitted +geometry. They also apply to Kronecker extension by the column identity. +The compiler preserves all spectators when it lifts a chart. + +At a register in frame i store D(P_i) applied to its normalized +field. INIT installs zero. MOVE uses the positive difference above. +ADD combines fields in a common chart. SWAP exchanges the two actual +register images and their current chart labels. CLEAR scrubs its +entire owned bank. Exact propagation of 630 independent binary basis +vectors through all instructions gives (x,y+x) on the 111 main pairs +and identity on all 408 separate helpers. It checks every chart label, +live register and allocation. All 3,433 private clears see a nonzero +symbolic form. Each of these fields goes through the paid bank scrub. +Specialized public zero helpers have a different lifetime. They remain +live through the source word and return zero before retirement. + +At one main port write B=I−H for this stage. Removing the input gauges +and installing the output gauges gives (D(B)x, D(I)x+D(B)y). +After its joint frame placement this has the form +S(x,Qx+y), where S is the stage body and Q is its disjoint head exchange. +The exact checker executes the full outer circuit over formal binary +sums of all 38 role inputs with monomials in the 19 commuting +involutions. A LOCAL uses that pair formula. QUERY adds Q times a +borrowed field and returns it for its charged retirement. Each IDLE_ONE +applies its listed stage product. ADD and SWAP act on the actual roles. +All 38 resulting expressions equal the one desired diagonal monomial +on the original role, with the required head and every named stage. +The 111 chart placements and inverses thus deliver every labelled field. +The 36 copies of all 408 helpers contribute separate productive ports. +Their omitted grades in the powered rule still receive full zero +fields and every original instruction. The 18,906 productive and +104,904 paid labels are generated from this same source. + +## Two strict powers + +Let T(t) and P(t) be the respective sums of true ranks to power t for +the 36-call word. For v equal to 128 or 228 run the full chronological +v-fold product. The productive cutoff is k^v, with k=16 at v=128 and +k=15 at v=228. Serve every paid +rank in lexicographic, disjoint blocks of size at most 12^v. +The full ambient is 134^v and the maximum productive rank is 127^v. +At a split the child receives the active coordinates in the current +complete physical chart. The outside change of basis remains live +until all blocks return. The executed primitive permutations commute +on these axes, including for an arbitrary dirty field, so all these +calls implement the one requested projector. The producer and graph +forms are independent of either operand. + +Put t=1−C and z=19/64. Use w=13/32 at v=128 and w=31/64 at v=228. +The high tail of a paid rank R>12^v costs at most 2R^(t+z)/12^(vz), +since z≥C. With K2. Let +P0=104904 be the number of true raw paid locations. Their rank sum +is S=285600. The number of paid blocks is at most P0^v+(S/12)^v, +by summing the actual block ceilings over all tuples. S<12P0, and +there are at most 18906^v productive tuples. Thus the total number of +port choices for a level is below 3P0^v<2^(18v). Since (5/4)^13>16, +the horizon satisfies vG≤13H/4+v. The syntactic enumeration has at +most (W+Pslots)^G<2^(18v) N^(117/2) units, including rejected ones. +All rational virtual column numerators and denominators have O(H) bits. +The outer charged tape generation still enumerates syntactic candidates, +rejected units, true banks and requested leaves. + +## High-rate component widths + +The current conditional comparator is +[PR #8029](https://github.com/CrocSwap/integer-mult-bounds/pull/8029), +at commit `a9dbc75e68e8c645df425adc489234d22df67f8d`. Its four-stage +ordinary rate is 0.003890115197377. Its complete claim is +0.00389011519729 with five stated premises. The high binary construction +funds that same ordinary rate in six cold stages. The stage logarithms +are 25,000,000, 160,000,000, 1,000,000,000, 6,000,000,000, +36,000,000,000 and 224,000,000,000. The last binary entry logarithm +is 267,185,100,786. The largest binary rank logarithm is +1,057 times smaller than in the earlier fully costed +[PR #7981](https://github.com/CrocSwap/integer-mult-bounds/pull/7981). +The complex supplier and outer geometry have their own entry conditions. + +For the high-rate profile use ρ=1/250, η=39/10000, R_i as in the +staged machine, w=max(R_i,ceil(e^ρ)), g=ceil(e^η). Since η<ρ, g≤w. +The balanced physical components attain widths u−1 or u, with +g/2≤u≤g. With c≤e/w coarse columns and m=ceil(w/g) components, +mc≤2e^(1−η). Also m≤2w^(1−b_prev) for b_prev≤η and w≤e. +Thus both the balanced scans and genuine full-width stopped return +retain the staged tariff at any b_i1/4 gives 1+(t−T)/4≤2^((1−η)(t−T)). +Multiplying this inequality by the paid row bill gives kP(t)$ before either change. Write $t=1-c$. + +There is a **global** ceiling on $c$ for this source. Divide $T(t)-P(t)$ by $8^t$. For ranks 1 through 7 the signed counts are −48972, −44892, −1980, −900, −1044, −2916 and −480. Each negative term increases with $t$ on this normalization. The 14,520 rank-eight terms give a constant. The remaining negative terms pair exactly with the next rank. For $r=14,21,28,35,42,49,56$ each pair contributes $444[((r+1)/8)^t-(r/8)^t]$. For $1\le a\le b$, $b^t-a^t$ increases for $t\ge0$: on adding $u\ge0$, $b^t(b^u-1)\ge a^t(a^u-1)$. Two positive terms remain, $444(64/8)^t$ and $222(127/8)^t$. These increase too. The independent checker recovers every signed count directly from the literal events and uses outward rational bounds to establish $P(1-c_0)>T(1-c_0)$ at $c_0=0.0038901152866$. Monotonicity excludes every $c\ge c_0$ up to one. [Exact source check](independent_binary_price.py) · [Kernel-checked real-power inequality and rank floors](lean/BandFlow.lean) + +Even if all compiler losses other than the present ordinary factor 32 vanish, its last $H=\log_2 N$ has covered rate at most $c-5/H$. The strict stage recurrence requires $b<(249(c-5/H)+b_{\rm prev})/250$ with $b_{\rm prev}\le b$, hence $b\kappa+4\cdot10^{-14}$. Together these require + +$$H>\frac{5}{c_0-\kappa-4\cdot10^{-14}}=\frac{10^{14}}{303},\qquad H\ge330033003301.$$ + +The thousandfold targets against the physical predecessor and the conditional delayed-cover competitor would be 236,800,000,000 and 299,610,000,000. Each is below this floor. At the actual installed $c_B=17108907955/2^{42}$, debit 19 and $b=0.003890115271496$, the same comparison requires $H\ge1455682013917$. The installed value $1568000000000$ is within **7.72%** of this necessary floor for the stated integer invoice. The first floor permits any tensor power, productive floor or paid cap with the stated raw necessity and five-bit tariff. The second fixes the actual price certificate. A cheaper ordinary contract, a source with a higher raw crossing, or a different price certificate can change these conclusions. diff --git a/research/single-band-native-carriers/STRONG-COMPLEX.md b/research/single-band-native-carriers/STRONG-COMPLEX.md new file mode 100644 index 0000000000..e9c08411e4 --- /dev/null +++ b/research/single-band-native-carriers/STRONG-COMPLEX.md @@ -0,0 +1,203 @@ +# Physical realization of the 5,674-transfer Gaussian word + +The positive supplier uses the actual rational graph and layout of +[PR #8027](https://github.com/CrocSwap/integer-mult-bounds/pull/8027). +An earlier revision of the conditional claim at \(\kappa=0.00389011519729\) prices +the same signed caller and words. The changed compiler binds all three +production configurations to those common physical operators. +[Comparable high-rate calculation](https://github.com/CrocSwap/integer-mult-bounds/pull/8029) +Their canonical SHA-256 digests are +\(\mathtt{38d2b3a2311a9ba5fee091cc7aa204c7ed95651aec95d75184b2391df090cbfb}\) +and +\(\mathtt{0ce3f9e383fc4bfdd22612b9e34fc9759d97204215937b82d23aec2cedd9b8ee}\). +Rebuild both objects from the literal circuit, the factor records and the +three source journals at install time. Check both digests. Construct +the 48 chronological callers from the pinned mixed templates and the new +source labels. The 1,103 frame definitions, all 104 main contacts and every +main entry and exit frame agree exactly with the physical predecessor. +The new program has 1,291 independently supplied roles, 5,674 move +instructions, 6,965 scheduled rows and 323,573 ordered donor terms per +graph call. Its 48 invocations supply 42,768 external helper owners in +addition to 9,840 main root owners. The compiled word retains every one +of those labels and issues every one of its 281,568 raw paid calls in order. +The frame-count and money bounds must use the resulting 52,608 productive +and 281,568 paid occurrences. +[Reconstructed source digests and application](https://github.com/CrocSwap/integer-mult-bounds/blob/fb9b6a7b0d27da1cf98430893a3016bf811e2aa4/research/p104-live-relative-gain/APPLICATION.json) +· [Source chronology](https://github.com/CrocSwap/integer-mult-bounds/blob/fb9b6a7b0d27da1cf98430893a3016bf811e2aa4/research/p104-live-relative-gain/verify_split_helpers.py) +· [Physical predecessor](https://github.com/CrocSwap/integer-mult-bounds/blob/46783fbbfc219a3faffbea76f60a2810b85ab75a/research/native-stock-activation/raw48.py) + +## Equality at every nonempty column count + +Let \(U_a\) be the absolute nine-axis Clifford for frame \(a\). In a raw +graph with \(f\ge1\) columns, a live row in frame \(a\) represents +\(U_a^{\otimes f}\) applied to a linear combination of decoded arbitrary +input fields. Row addition and each individual rational donor coefficient +preserve this invariant because the graph requires equal local frames. +A move from \(a\) to \(b\) must apply +\((U_bU_a^{-1})^{\otimes f}\), including its absolute phase. +For each ordered pair generate or read the two monomials \(L,R\) and +the positive rank \(r\). Verify \(r=|\dim b-\dim a|>0\) and +\(LC_rR=U_bU_a^{-1}\). Equality of all signed conjugated Pauli generators +fixes the operator up to scalar. Its exact Gaussian-dyadic image of +\(\lvert0\rangle\) fixes the scalar. The complete rank-\(rf\) operation and +tensor powers of the boundary monomials follow. A rank-zero main boundary +uses its checked monomial; the hosted duplicate uses the same checked frame. +The fields contain their full spectator ranges through every operation. +[Clifford recipe generator](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/shared-wire-split-composition/frozen/clifford_exact.py) +· [Independent exact Clifford interpreter](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/shared-wire-split-composition/frozen/native_verify.py) +· [All-column normalization and coverage](https://github.com/CrocSwap/integer-mult-bounds/blob/a7f99a5f5f919dd3ffb2987f90c1e7d6527feb1e/research/grade14-native-realization/PROOF.md) + +The installer generates all 2,971 distinct pairs and all 104 ports from +their actual signed frames. The predecessor already had 2,950 of the +required pairs. The 21 additional recipes also have an independent +1,464-byte audit file. The complete canonical atlas digest is +\(\mathtt{8a9ff9558bf5fa3854699937fe063f98c86467d5d32a4488bfc878d2be081e70}\). +The independent checker proves the equalities for every pair and every main +port, checks all 1,944,576 affine and phase basis images of the 3,798 +distinct monomials, and checks 95,420,416 Walsh contact-phase values. +A second replay runs the two actual physical chart sweeps and the positive +pair butterflies of each new recipe on a full 512-entry Gaussian field. +It checks every entry against direct independent frame circuits and checks +the return on all 10,752 entries. At higher column counts the constant +monomial phase is multiplied by \(f\), and each quadratic term is summed +over the actual columns. That prescription is present in the physical +chart implementation. It preserves both absolute phase and tensor dilation. + +For both directions of the scalar graph the exact signed-digit block +substitution checks every one of the \(1291^2=1666681\) matrix positions. +Its digit widths are 178 bits forward and 162 backward. The output is the +required hosted pair of shears and ordinary sum/difference at the main +ports, and identity on every retained independent helper in its directed +return frames. The raw receiver applies each helper's inverse entrance +right chart and inverse return left chart. These convert its chart transport +to the positive child on its ordered axes, and restore its complete external +placement. Main roles use the true port left/right normalizers and the +signed 17-axis contact corrections. The unchanged mixed root caller checks +its complete Laurent rows on all sixteen independent body symbols. At its +completed endpoints it delivers every signed root action, followed by the +prescribed head translation on a negative target. All 48 call bindings +regenerate 19,200 independent main inputs with no alias at a call. +The new ordered paid labels, ordered productive labels, chronology digest +and the rank-129 exposed physical root are compared against the actual +raw fields and schedules. +[All-column graph criterion](https://github.com/CrocSwap/integer-mult-bounds/blob/a7f99a5f5f919dd3ffb2987f90c1e7d6527feb1e/research/grade14-native-realization/graph_identity.py) +· [Signed Laurent-row evaluator](https://github.com/CrocSwap/integer-mult-bounds/blob/a7f99a5f5f919dd3ffb2987f90c1e7d6527feb1e/research/grade14-native-realization/retained/mixed_grid.py) + +## Exact executed scalar operations and common-root headroom + +The graph now enters on the odd scale \(143529619683167082194704875\). +This is the odd part of the independently replayed minimal product grid +\(154113755636630124932500335624192000\), of dyadic height 30. The signed +mixed caller retains its outer odd factor 2025. At each graph node store +the complete exact coefficient of every contributing input basis role on +this grid. For each donor with reduced coefficient \(a/b\), check that +\(b\) divides each stored coefficient *before* multiplication by \(a\). +Check the whole terminal transfer against the independent public rows. +This is the order of division and multiplication in the physical field's +scalar primitive. All 25,146,238 nonzero per-basis contributions passed, +including 17,231,591 nontrivial divisions. Their common divisor with the +grid is one. Clearing the odd part once at graph entrance and removing it +at graph return therefore works for every input after reserving the +30 dyadic positions. This coefficient proof applies in the current +Clifford frame. Each true matrix element can use the global Clifford +denominator already allocated on the full original selected coordinates. + +The physical scalar split checks all 60,206 distinct graph literals and +the inverse odd scale. Its largest divisor is 16,641,408, below \(2^{24}\). +The largest fixed operand including the odd factor has 87 bits. The +base-\(2^{23}\) multiply uses at most four magnitude limbs. All partial +Horner terms have one sign. The conservative sum of absolute donor +contributions therefore covers every partial row and scalar temporary +inside the source shift allowance. The positive path mass of the graph is + +\[ +\frac{205356183613728386434052488657699504746980105023} + {1621896683681232672237748224000}. +\] + +The checker generates it by the recurrence +\(w_u=\sum_v |q_{uv}| w_v,\ w_{\mathrm{input}}=1\) and takes the maximum +over all rows. Generate the signed caller's bound on every temporary and +its distinct native-ingress bound. Its dyadic requirement is the larger +of the all-caller maximum and the largest pre-native height plus 30. Its +scaled mass is the larger of the all-caller maximum times 2025 and the +pre-native mass times 2025, the graph odd scale and the graph path mass. +These exact calculations give **148 dyadic positions and 436 mass bits per +open raw context**. A leaf split or a completed child again acts as a +Clifford on the original selected factor. Thus with at most \(v(G+1)\) +causal raw contexts per band the fixed-root guard becomes +\(872\,v(G+1) limit * denominator: + continue + columns = x // denominator - 1 + ports = [] + for i, rank in enumerate(rule.targets): + if rule.ambient * x * rank > limit * denominator * previous_rank: + ports.append(("source", len(sources))) + sources.append((path, future, i, rank * columns)) + else: + parent_columns = x * rank // (previous_rank * denominator) - 1 + residue = previous_rank * parent_columns - rank * columns + if not 0 <= residue < 2 * rank: + raise ArithmeticError("The paying native unit cannot fund the input") + fringe += residue + ports.append(("parent", (i,) + future)) + consumer_target = rule.targets[future[0]] + for paid in rule.paid: + if x * paid < floor * denominator * consumer_target: + terminal += paid * columns + units.append(Unit(future, columns, tuple(ports))) + if units: + layers[path] = tuple(units) + if not sources: + return None + prefixes = {path[:d] for path in layers for d in range(len(path) + 1)} + return Band(layers, tuple(sources), frozenset(prefixes), height, terminal, fringe) + + +def make_planner(rule, floor): + @cache + def plan(n): + if n < 1: + raise ValueError("A positive rank is required") + active = n - n % 4 + band = forest(rule, active // 4, floor) + if band is None: + return Plan(n, n, None, (), (), 0, 0, 1, 1, n) + periods = tuple(period(active, root[-1]) for root in band.sources) + rounds = max(periods) + offsets, slots = [], 0 + for q in periods: + offsets.append(slots) + slots += rounds // q + width = power_ceiling(15 * slots) + copies = (width + slots - 1) // slots + leaves = (n - active) * width + rounds * copies * (band.terminal_axes + band.fringe_axes) + return Plan(n, active, band, periods, tuple(offsets), rounds, copies, slots, width, leaves) + + return plan diff --git a/research/single-band-native-carriers/band_positive.py b/research/single-band-native-carriers/band_positive.py new file mode 100644 index 0000000000..d2e6cf98c5 --- /dev/null +++ b/research/single-band-native-carriers/band_positive.py @@ -0,0 +1,86 @@ +"""Use the installed epoch inside the physical positive tensor receiver.""" + +from positive import Positive as PhysicalPositive, one_axis, power_le +from spool import scratch, snapshot, transfer + + +class Positive(PhysicalPositive): + @property + def owners(self): + from epoch_tape import Compiler + from calibration import COMPLEX_FLOOR + + if self._owners is not None: + return self._owners + self.rule = self.word.rule() + self.planner = Compiler(self.rule, COMPLEX_FLOOR) + self._owners = self.planner(self.carrier).width + if self._owners <= 1 or self._owners & (self._owners - 1): + raise ValueError("Use an admitted dyadic positive batch") + return self._owners + + def _run(self, field, low, selected, columns, root_width): + from epoch_tape import run + from periodic import Job + + k = columns.window + if selected <= self.carrier or power_le(selected, self.denominator, root_width): + for i in range(selected): + one_axis(field, low + i * k + columns.offset) + return + mult, extra = divmod(selected, self.carrier) + for i in range(selected - extra, selected): + one_axis(field, low + i * k + columns.offset) + rows = self.owners + remain = field.ambient_bits - (rows.bit_length() - 1) + if remain < max( + low + (selected - extra) * k, + columns.u + (mult - 1) * columns.digit, + columns.t + (mult - 1) * columns.digit, + ): + raise ValueError("No independent leading row stock at this positive call") + total = field.count * field.record + part = total // rows + with field.arena.child(remain) as frame: + # Stage inputs before the child opens its own head. + with snapshot(field.stream, total) as incoming: + fields = {} + for i in range(rows): + owned = frame.field() + transfer(incoming, owned.stream, part) + fields[i] = owned + raw = self.physical(fields, columns, low=low, bundle=mult, slots=self.carrier) + outer = self + + class Machine: + def native(self, ports, cols): + return outer.word.native(ports, cols, raw) + + def zero(self, exemplar): + job = raw.fresh(exemplar, len(exemplar.axes), ("periodic-zero",)) + return Job(job.owner, exemplar.axes) + + def retire_zero(self, job): + raw.retire(job) + + def leaf(self, job): + if len(job.axes) != 1: + raise ValueError("A positive leaf must contain one complete group") + outer._run( + fields[job.owner], low + job.axes[0] * mult * k, mult, columns, root_width + ) + + lanes = [Job(i, tuple(range(self.carrier))) for i in range(rows)] + run(self.rule, self.carrier, lanes, Machine(), planner=self.planner) + if len(fields) != rows: + raise ValueError("A complete positive call has outstanding private owners") + # Use the scratch head only after all paid subcalls have returned. + with scratch() as outgoing: + for i in range(rows): + returned = fields.pop(i) + returned.stream.seek(0) + transfer(returned.stream, outgoing, part) + returned.retire() + outgoing.seek(0) + field.stream.seek(0) + transfer(outgoing, field.stream, total) diff --git a/research/single-band-native-carriers/band_product.py b/research/single-band-native-carriers/band_product.py new file mode 100644 index 0000000000..4fba42dc54 --- /dev/null +++ b/research/single-band-native-carriers/band_product.py @@ -0,0 +1,129 @@ +"""Multiply signed binary tapes with the installed single-band native suppliers.""" + +from argparse import ArgumentParser +from functools import cache, partial +from io import BytesIO + +from upstream import HERE, install + +install() +from band_positive import Positive +from binary_io import magnitude_bits, magnitude_limbs +from calibration import COMPACT, PROFILES +from inputs.triangular.multiplier import Product as PackProduct, precision +from linear_geometry import parameters, square_sides +from ordinary_carrier import ordinary_swap +from positive_dispatch import h_pack +from product_path import scalar_product +from raw48 import ComplexRaw + + +@cache +def production_supplier(rank_log): + from strong_complex import artifacts, word + + _, _, _, source = install() + data = HERE / "inputs" + atlas = artifacts(source / "research/grade14-native-realization", data) + native = word(atlas.graph, atlas.layout) + + def physical(fields, columns, **kw): + return ComplexRaw(atlas, fields, columns, **kw) + + return Positive(native, physical, 1 << rank_log) + + +def prepare_native(profile=COMPACT): + """Generate the fixed native programs. The tape caller can also install each at first use.""" + from binary_receiver import source_planner + + binary = source_planner(profile.power, profile.floor) + streams = [binary.image(1 << log_rank) for log_rank in profile.rank_logs] + positive = production_supplier(profile.complex_log) + if positive.owners <= 1: + raise ArithmeticError("The numerical carrier needs independent rows") + streams.append(positive.planner.image(positive.carrier)) + return tuple(streams) + + +class Product(PackProduct): + def __init__(self, sides, b, P, exchange=None, *, engine=None, profile=COMPACT): + self.profile = profile + exchange = partial(ordinary_swap, profile=profile) if exchange is None else exchange + super().__init__(sides, b, P, exchange, engine=engine) + + def h(self, tape, start, end, bit): + h_pack( + self, + tape, + start, + end, + bit, + self.profile.complex_log, + partial(production_supplier, self.profile.complex_log), + ) + + +def multiply_tapes( + left, + left_bytes, + right, + right_bytes, + output, + *, + left_negative=False, + right_negative=False, + engine=None, + profile=COMPACT, +): + """Return the sign and length of the product. Restore both input heads.""" + if output is left or output is right: + raise ValueError("The product needs a separate output owner") + lengths = magnitude_bits(left, left_bytes), magnitude_bits(right, right_bytes) + negative = left_negative != right_negative + shape = parameters(max(lengths)) + if shape is None: + a, b = ( + sum(magnitude_limbs(src, size, max(1, size))) + for src, size in zip((left, right), lengths, strict=True) + ) + result = scalar_product(engine)(a, b) + raw = result.to_bytes(max(1, (result.bit_length() + 7) // 8), "little") + output.write(raw) + return bool(negative and all(lengths)), len(raw) + sides = tuple(square_sides(shape)) + machine = Product( + sides, + shape.public // 6, + precision(shape.public, shape.extent_bits, shape.count), + engine=engine, + profile=profile, + ) + sign, size, _ = machine._multiply_tapes(left, right, output, lengths, negative, False) + return sign, size + + +def multiply(left, right, *, profile=COMPACT): + raw = [abs(v).to_bytes((abs(v).bit_length() + 7) // 8, "little") for v in (left, right)] + out = BytesIO() + sign, _ = multiply_tapes( + BytesIO(raw[0]), + len(raw[0]), + BytesIO(raw[1]), + len(raw[1]), + out, + left_negative=left < 0, + right_negative=right < 0, + profile=profile, + ) + value = int.from_bytes(out.getvalue(), "little") + return -value if sign else value + + +if __name__ == "__main__": + args = ArgumentParser(description=__doc__) + args.add_argument("left", type=lambda x: int(x, 0)) + args.add_argument("right", type=lambda x: int(x, 0)) + args.add_argument("--profile", choices=PROFILES, default="compact") + call = args.parse_args() + print(multiply(call.left, call.right, profile=PROFILES[call.profile])) diff --git a/research/single-band-native-carriers/binary_receiver.py b/research/single-band-native-carriers/binary_receiver.py new file mode 100644 index 0000000000..d665292923 --- /dev/null +++ b/research/single-band-native-carriers/binary_receiver.py @@ -0,0 +1,115 @@ +"""Run the funded binary graph in the public bank and return every physical loan.""" + +from functools import cache + +from calibration import COMPACT +from compiler_cut import SourceRule +from epoch_tape import Compiler, run +from module_atoms import chart_width, total_width +from periodic import Job +from quotient_route import free_count, low_count +from raw_binary import job_frame +from receiver import OwnerBanks, Receiver as PhysicalReceiver +from streaming_routes import cold_swap_tape, erase, type_route +from strong_binary import StrongBinarySource, native_word + + +class NativeRule(SourceRule): + def __init__(self, power): + word = native_word(power) + self.word = word + self.ambient = word.ambient**word.power + + +@cache +def source_rule(power): + return NativeRule(power) + + +@cache +def source_planner(power, floor): + return Compiler(source_rule(power), floor) + + +class Receiver(PhysicalReceiver): + def __init__( + self, dimension, layout, previous=cold_swap_tape, *, direct=False, profile=COMPACT + ): + if dimension < 2: + raise ValueError("Use a native rank of at least two") + self.n, self.layout, self.previous = dimension, layout, previous + self.direct, self.profile = direct, profile + self.digits = chart_width(layout) + self.modulus = 3**self.digits + self.atom = 3 ** total_width(layout) + self.low = 1 if direct else low_count(dimension) + self.high = 1 if direct else 3 ** ((self.digits - 1) * free_count(dimension)) + self.rule = source_rule(profile.power) + self.planner = source_planner(profile.power, profile.floor) + self.owners = self.planner(dimension).width + self.stock = self.owners * self.low * self.high + self.arena = self.last_storage = None + self.small = None + + def weighted(self, source, target, **shape): + if not self.direct and shape["atoms"] <= self.n**8 and self.small is None: + self.small = Receiver( + self.n, self.layout, self.previous, direct=True, profile=self.profile + ) + super().weighted(source, target, **shape) + + def compiled(self, source, target, f, unused, older, gap, suffix, weight): + body = older * self.atom ** (2 * self.n * f) * gap * suffix + bank_width = self.low * self.high * body + with self.arena.frames("compiler", 3) as (backing, staged, result): + + def transition(src, dst, word): + self.transition(src, dst, word, f, unused, older, gap, suffix, weight) + + banks = OwnerBanks(backing, self.n, unused * bank_width, transition) + raw = StrongBinarySource(banks) + type_route(source, staged, unused, self.owners, bank_width) + staged.seek(0) + jobs = [] + for _ in range(self.owners): + owner = banks.zero() + banks.install(owner, staged) + jobs.append(Job(owner, tuple(range(self.n)))) + erase(staged) + core = self + + class Machine: + def leaf(self, job): + with core.arena.frames("issued-leaf", 1) as (out,): + banks.start(job.owner) + core.serve_line( + backing, + out, + job_frame(job, core.n), + f, + unused, + older, + gap, + suffix, + weight, + ) + out.seek(0) + banks.install(job.owner, out) + + def native(self, ports, columns): + return core.rule.word.native(ports, columns, raw) + + def zero(self, exemplar): + return Job(banks.zero(), exemplar.axes) + + def retire_zero(self, job): + banks.retire(job.owner, require_zero=True) + + run(self.rule, self.n, jobs, Machine(), planner=self.planner) + for job in jobs: + banks.read(job.owner, result) + banks.retire(job.owner) + if banks.live: + raise ArithmeticError("The periodic supplier retained a live owner") + result.seek(0) + type_route(result, target, unused, self.owners, bank_width, inverse=True) diff --git a/research/single-band-native-carriers/build_charts.py b/research/single-band-native-carriers/build_charts.py new file mode 100644 index 0000000000..65492d9f8d --- /dev/null +++ b/research/single-band-native-carriers/build_charts.py @@ -0,0 +1,42 @@ +"""Generate only the Clifford charts newly required by the changed native source.""" + +from functools import cache +from pathlib import Path +import argparse +import gzip +import json +import sys + +from strong_complex import digest, load_changed, required_pairs + + +def build(grade, engine, data): + sys.path.insert(0, str(engine)) + import clifford_exact + from raw48 import read_json + + graph, layout = load_changed(data) + old = read_json(grade / "complex-atlas.json.gz") + have = {(a, b) for a, b, _ in old["pairs"]} + needed = required_pairs(graph, layout) + + @cache + def chart(i): + return clifford_exact.canonical_frame(9, tuple(graph["frames"][i])) + + extra = [] + for a, b in sorted(needed - have): + rec = clifford_exact.lower_child(chart(a).adjoint().then(chart(b)))[0] + extra.append((a, b, rec)) + return extra + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + for key in ("grade", "engine", "data", "out"): + parser.add_argument(key, type=Path) + args = parser.parse_args() + result = build(args.grade, args.engine, args.data) + encoded = json.dumps(result, separators=(",", ":"), sort_keys=True).encode() + args.out.write_bytes(gzip.compress(encoded, mtime=0)) + print("additional Clifford pairs", len(result), digest(result)) diff --git a/research/single-band-native-carriers/calibration.py b/research/single-band-native-carriers/calibration.py new file mode 100644 index 0000000000..9992aee320 --- /dev/null +++ b/research/single-band-native-carriers/calibration.py @@ -0,0 +1,96 @@ +"""Set the physical ranks and check their complete price with rational arithmetic.""" + +from dataclasses import dataclass, replace +from fractions import Fraction + +from upstream import install + +install() +from staged_carriers import entrance_logs + +COMPLEX_POWER = 128 +COMPLEX_FLOOR = 1 << 15 +COMPLEX_C = Fraction(2043, 524288) +GAP = Fraction(1, 10**14) +SETUP_DEGREE = 1024 + + +@dataclass(frozen=True) +class Profile: + rank_logs: tuple + complex_log: int + power: int + floor: int + bit_c: Fraction + eta: Fraction + ordinary: Fraction + kappa: Fraction + + +COMPACT = Profile( + (260_000, 1_600_000), + 610_000, + 128, + 1 << 15, + Fraction(2039, 524288), + Fraction(97, 25_000), + Fraction("0.003879928035646"), + Fraction("0.00387992803556"), +) +HIGH_RATE = Profile( + (25_000_000, 160_000_000, 1_000_000_000, 6_000_000_000, 36_000_000_000, 224_000_000_000), + 1_600_000, + 228, + 1 << 35, + Fraction(17108907955, 2**42), + Fraction(39, 10_000), + Fraction("0.003890115197377"), + Fraction("0.00389011519729"), +) +PRICE_MATCH = replace( + HIGH_RATE, + rank_logs=tuple(7 * h for h in HIGH_RATE.rank_logs), + ordinary=Fraction("0.003890115271496"), + kappa=Fraction("0.00389011527141"), +) +PROFILES = {"compact": COMPACT, "high-rate": HIGH_RATE, "price-match": PRICE_MATCH} + + +def debit(ambient, largest_target, power, c, floor, outer_bits): + # The dyadic carrier needs no final axes. The paid replication factor is below 9/4. + assert 32 * floor * 4 < 9 * 15 * (floor - 2) + assert 9**4 < 2**5 * 4**4 + scale = 4 * (ambient * largest_target) ** power * floor + upper = Fraction(5, 4) + c * (scale - 1).bit_length() + outer_bits + return -(-upper.numerator // upper.denominator) + + +def prices(profile): + bit_loss = debit(134, 127, profile.power, profile.bit_c, profile.floor, 5) + numeric_loss = debit(153, 129, COMPLEX_POWER, COMPLEX_C, COMPLEX_FLOOR, 1) + result = [] + previous = Fraction(0) + for i, height in enumerate(profile.rank_logs): + covered = profile.bit_c - Fraction(bit_loss, height) + limit = min((249 * covered + previous) / 250, profile.eta) + rate = ( + profile.ordinary + if i == len(profile.rank_logs) - 1 + else Fraction(int(limit * 10**18) - 1, 10**18) + ) + if not previous < rate < limit: + raise ArithmeticError("An ordinary stage has insufficient strict price headroom") + result.append((height, covered, rate)) + previous = rate + if not ( + profile.kappa + 4 * GAP < profile.ordinary + and profile.kappa + 5 * GAP < COMPLEX_C - Fraction(numeric_loss, profile.complex_log) + ): + raise ArithmeticError("The numerical consumer cannot receive these prices") + return bit_loss, numeric_loss, result + + +def entrance(profile): + from linear_geometry import connected_exponent + + return connected_exponent(entrance_logs(profile.rank_logs)[-1], profile.complex_log) diff --git a/research/single-band-native-carriers/check_activation_space.py b/research/single-band-native-carriers/check_activation_space.py new file mode 100644 index 0000000000..5dfbd8e718 --- /dev/null +++ b/research/single-band-native-carriers/check_activation_space.py @@ -0,0 +1,62 @@ +"""Evaluate the all-size stripe bound and the exact entrance geometry of a native profile.""" + +from fractions import Fraction + +from linear_geometry import ceil_log2, connected_exponent, entrance_geometry + + +def receipt( + rank_logs, + complex_log, + final_width_log, + program_log, + raw_power, + raw_ports_log=20, + context_guard=872, + *, + complex_power=None, +): + exponent = connected_exponent(final_width_log, complex_log) + s = exponent + 1 + # Each raw rule has fewer than 2**raw_ports_log targets and paid occurrences separately. + # The ambient dimension is at most 153. Keep every bound on raw visits and live copies. + nodes_log = 64 + ceil_log2(raw_power + 1) + (raw_ports_log + 10) * raw_power + local_log = 4 * nodes_log + 8 * ceil_log2(1 + max(complex_log, *rank_logs)) + 512 + q = 1 << ceil_log2(local_log + 1) + numerical_power = raw_power if complex_power is None else complex_power + assert 0 < numerical_power <= raw_power + context_cost_bits = (context_guard * numerical_power * (complex_log + 1) ** 2).bit_length() + assert context_cost_bits <= complex_log + # Reserve 32 non-native outer levels at 1024 bits of local logarithmic slack per level. + ranks = (complex_log, *rank_logs) + quotients = [(s + h - 1) // h for h in ranks] + depth = 2 + quotients[0] + sum(3 + c for c in quotients[1:]) + payload_excess = (2 * depth + 4) * q + 64 * 1024 + 48 + 2 * (s + 128).bit_length() + slope = 2 * q * sum(Fraction(1, h) for h in ranks) + intercept = (10 + 8 * len(rank_logs)) * q + 64 * 1024 + 48 + per_step = Fraction(1, 2) - slope - Fraction(1, 32) + assert per_step > 0 and per_step * s - intercept - 3 > 1024 + assert s // 2 - 2 - payload_excess > 1024 + geometry = entrance_geometry(exponent) + legacy = entrance_geometry(exponent, quadratic=True) + # Linear sums divided by (s+1)^8 decrease on this tail. Every private and hardware + # counter has a separate allowance with no multiplicative factor on an actual field. + table_max = (1 << 21) * (s + 1) + assert 64 + 8 * (program_log + 1) + 64 * s + 8 * (table_max + 1) < (s + 1) ** 8 + assert 33**9 < 2 * 32**9 + assert (12 * (128 * (s + 130) * (s + 1) ** 8 + 64)).bit_length() <= s - 2 + assert (1200 * (64 * (128 * s**2 + s) + 2 * s + 128)).bit_length() <= s - 2 + return { + "log2_sufficient_public_precision": exponent, + "initial_s": s, + "raw_structural_nodes_log2_upper": nodes_log, + "native_volume_log2_upper": q, + "positive_context_cost_bitlength_upper": context_cost_bits, + "native_depth_bound_at_entrance": depth, + "stripe_excess_log_at_entrance": payload_excess, + "stripe_margin_at_entrance": s // 2 - 2 - payload_excess, + "uniform_payload_slope": str(slope), + "all_size_margin_lower_at_entrance": int(per_step * s - intercept - 3), + "linear_geometry": geometry, + "prior_geometry_at_same_n": legacy, + } diff --git a/research/single-band-native-carriers/check_band.py b/research/single-band-native-carriers/check_band.py new file mode 100644 index 0000000000..2a453d888f --- /dev/null +++ b/research/single-band-native-carriers/check_band.py @@ -0,0 +1,231 @@ +"""Compare the emitted single-band calls against independent finite oracles.""" + +from dataclasses import dataclass +from fractions import Fraction +from itertools import product +from math import prod +from random import Random + +from epoch_tape import Compiler as make_planner, run +from check_periodic import BitMachine +from check_powered import Toy +from periodic import Job, Rule +from powered import Port, PoweredWord + + +def census(rule, n, floor): + limit = (n - n % 4) // 4 + high = Fraction(limit, rule.ambient) + ratio = Fraction(min(rule.targets), max(rule.paid)) + g = 0 + while ratio**g <= high: + g += 1 + nodes = {} + for d in range(g + 1): + for p in product(range(len(rule.paid)), repeat=d): + for a in product(range(len(rule.targets)), repeat=g - d): + x = Fraction( + prod(rule.paid[j] for j in p) * prod(rule.targets[i] for i in a), + max(rule.paid) ** g, + ) + if floor <= x <= high: + nodes[p, a] = int(x) - 1 + roots = {} + costs = [0, 0] + for (p, a), c in nodes.items(): + for i, k in enumerate(rule.targets): + if (p[:-1], (i,) + a) not in nodes: + roots[p, a, i] = k * c + for j, r in enumerate(rule.paid): + child = (p + (j,), a[1:]) + if child in nodes: + costs[1] += r * c - rule.targets[a[0]] * nodes[child] + else: + costs[0] += r * c + if not roots: + return 1, n, costs + qs = [(1 << (((n - n % 4 + size - 1) // size) - 1).bit_length()) for size in roots.values()] + groups = sum(max(qs) // q for q in qs) + width = 1 << (15 * groups - 1).bit_length() + leaves = max(qs) * ((width + groups - 1) // groups) * sum(costs) + (n % 4) * width + return width, leaves, costs + + +@dataclass(frozen=True) +class ChartJob: + owner: int + axes: tuple + basis: int + + def select(self, indices): + return ChartJob(self.owner, tuple(self.axes[i] for i in indices), self.basis) + + +class Chart: + """Check each loan in its live chart before its native parent resumes.""" + + def __init__(self, rule, partitions, n): + self.rule, self.partitions, self.n = rule, partitions, n + self.data, self.chart = {}, {} + self.serial = self.leaves = self.freed = self.raw = self.noncommuting = 0 + assert tuple(map(sum, partitions)) == rule.targets + assert tuple(r for part in partitions for r in part) == rule.paid + + def zero(self, exemplar): + self.serial += 1 + owner = -self.serial + self.data[owner] = [0] * self.n + self.chart[owner] = 0 + return ChartJob(owner, exemplar.axes, 0) + + def retire_zero(self, job): + assert self.chart.pop(job.owner) == 0 + assert not any(self.data.pop(job.owner)) + self.freed += 1 + + def leaf(self, job): + assert job.basis == self.chart[job.owner] + (axis,) = job.axes + payload = self.data[job.owner] + payload[axis] = 4 * payload[axis] % 17 + self.leaves += 1 + + def native(self, ports, columns): + assert len({p.owner for p in ports}) == len(ports) + self.raw += 1 + for port, splits, target in zip(ports, self.partitions, self.rule.targets, strict=True): + assert port.basis == self.chart[port.owner] + assert len(port.axes) == target * columns and len(set(port.axes)) == len(port.axes) + payload = self.data[port.owner] + first, last = port.axes[0], port.axes[-1] + before = payload.copy() + payload[first] = (payload[first] + 3 * payload[last]) % 17 + self.chart[port.owner] += 1 + cursor = 0 + for step, split in enumerate(splits): + size = split * columns + axes = port.axes[cursor : cursor + size] + if step % 2: + # Change the full active chart between successive dependent cuts. + payload[first], payload[last] = payload[last], payload[first] + self.chart[port.owner] += 1 + if ((first in axes) != (last in axes)) and (payload[first] or payload[last]): + self.noncommuting += 1 + axes = tuple(last if i == first else first if i == last else i for i in axes) + expected = payload.copy() + for i in axes: + expected[i] = 4 * expected[i] % 17 + yield ChartJob(port.owner, axes, self.chart[port.owner]) + assert payload == expected + if step % 2: + payload[first], payload[last] = payload[last], payload[first] + self.chart[port.owner] -= 1 + cursor += size + payload[first] = (payload[first] - 3 * payload[last]) % 17 + self.chart[port.owner] -= 1 + expected = before + for i in port.axes: + expected[i] = 4 * expected[i] % 17 + assert payload == expected and port.basis == self.chart[port.owner] + + +def run_chart(rule, partitions, n, floor): + planner = make_planner(rule, floor) + plan = planner(n) + backend = Chart(rule, partitions, n) + rng = Random(812) + fields = [] + original = {} + for i in range(plan.width): + fields.append(ChartJob(i, tuple(rng.sample(range(n), n)), 0)) + original[i] = [rng.randrange(17) for _ in range(n)] + backend.data[i] = original[i].copy() + backend.chart[i] = 0 + run(rule, n, fields, backend, planner=planner) + assert backend.data == {i: [4 * x % 17 for x in data] for i, data in original.items()} + assert backend.leaves == plan.leaves and backend.serial == backend.freed + assert backend.noncommuting > 0 and not any(backend.chart.values()) + return plan.width, backend.raw, backend.noncommuting, backend.leaves + + +def weighted_swap(): + rule, partitions, n = Rule(5, (5,), (2, 2, 1)), ((2, 2, 1),), 323 + machine = BitMachine(rule, partitions) + planner = make_planner(rule, 4) + p = planner(n) + rng = Random(338833) + fields = [Job(i, tuple(rng.sample(range(n), n))) for i in range(p.width)] + for field in fields: + machine.data[field.owner] = machine.initial(field.owner, n) + machine.geometry[field.owner] = n + run(rule, n, fields, machine, planner=planner) + for i, state in machine.data.items(): + heads, tail, _, w, inv = machine.initial(i, n) + assert state[0] == [(tail[n - 1 - j] * w[j]) % 27 for j in range(n)] + assert state[1][::-1] == [(heads[j] * inv[j]) % 27 for j in range(n)] + assert machine.leaves == p.leaves and machine.zeros == machine.freed + return n, p.width, machine.frames, machine.leaves, machine.zeros + + +def powered(): + floor, cap = 3, 2 + word = PoweredWord( + 4, + (Port(("small",), 1), Port(("large",), 4)), + (Port(("a",), 1), Port(("b",), 3), Port(("c",), 1)), + 2, + floor, + cap, + cap, + ) + rule = word.rule() + n = 323 + planner = make_planner(rule, 4) + p = planner(n) + machine = Toy(n, word) + fields = [Job(~i, tuple((j + i) % n for j in range(n))) for i in range(p.width)] + original = {f.owner: [(j * 3 - f.owner + 1) % 17 for j in range(n)] for f in fields} + machine.data.update({i: x.copy() for i, x in original.items()}) + run(rule, n, fields, machine, planner=planner) + assert machine.data == {i: [4 * x % 17 for x in a] for i, a in original.items()} + assert machine.leaves == p.leaves and not machine.guard and machine.live_centres > 0 + return n, p.width, machine.raw_frames, machine.private, machine.live_centres, machine.leaves + + +if __name__ == "__main__": + + class StoppedRule: + ambient = 134**480 + + @property + def targets(self): + raise AssertionError("A stopped call tried to generate the native catalogue") + + paid = targets + + assert make_planner(StoppedRule(), 1 << 42)(2).leaves == 2 + rules = [ + Rule(5, (4, 5), (2, 2, 2, 2, 1)), + Rule(5, (5,), (2, 2, 1)), + Rule(3, (2, 3), (1, 1, 1, 1, 1)), + ] + cases = 0 + for rule in rules: + for floor in (2, 4, 8): + planner = make_planner(rule, floor) + for n in (1, 16, 24, 32, 48, 81, 129, 193, 256, 323): + p = planner(n) + w, leaves, ends = census(rule, n, floor) + assert (w, leaves) == (p.width, p.leaves) + if p.forest: + assert ends == [p.forest.terminal_axes, p.forest.fringe_axes] + cases += 1 + print("exact Fraction graph censuses", cases) + print( + "chart-dependent loan and ordered returns", *run_chart(rules[0], ((2, 2), (2, 2, 1)), 81, 4) + ) + print( + "simultaneous ordered returns and fringe", *run_chart(rules[2], ((1, 1), (1, 1, 1)), 48, 2) + ) + print("non-coordinate weighted swap including positive fringe", *weighted_swap()) + print("tagged powered raw source", *powered()) diff --git a/research/single-band-native-carriers/check_dense_band.py b/research/single-band-native-carriers/check_dense_band.py new file mode 100644 index 0000000000..eabff4f991 --- /dev/null +++ b/research/single-band-native-carriers/check_dense_band.py @@ -0,0 +1,33 @@ +"""Check every complex output against the independent exact spectral transform.""" + +from check_periodic import ComplexMachine, spectral_quarters +from periodic import Job, Rule +from epoch_tape import Compiler as make_planner, run + + +def dense(): + n = 16 + rule = Rule(2, (2,), (1, 1)) + machine = ComplexMachine(rule, ((1, 1),)) + planner = make_planner(rule, 2) + p = planner(n) + assert p.forest and p.forest.layers + lanes = [Job(i, tuple((k - i) % n for k in range(n))) for i in range(p.width)] + for lane in lanes: + machine.data[lane.owner] = machine.initial(lane.owner, n) + machine.geometry[lane.owner] = n + run(rule, n, lanes, machine, planner=planner) + for i in range(p.width): + real, imag, den = machine.data.pop(i) + initial_a, initial_b, _ = machine.initial(i, n) + expect_a, expect_b = spectral_quarters(initial_a, initial_b) + assert den[0] >= n + shift = den[0] - n + assert all(x << shift == y for x, y in zip(expect_a, real, strict=True)) + assert all(x << shift == y for x, y in zip(expect_b, imag, strict=True)) + assert machine.frames > 0 and machine.leaves == p.leaves + return n, p.width, machine.frames, p.width * (1 << n), machine.leaves + + +if __name__ == "__main__": + print("dense Gaussian outputs against two WHTs", *dense()) diff --git a/research/single-band-native-carriers/check_epoch_reentry.py b/research/single-band-native-carriers/check_epoch_reentry.py new file mode 100644 index 0000000000..fa1f66b441 --- /dev/null +++ b/research/single-band-native-carriers/check_epoch_reentry.py @@ -0,0 +1,81 @@ +"""Run a complete nested invocation on the same installed file before a parent resumes.""" + +from random import Random + +from upstream import install + +install() +from check_band import Chart, ChartJob +from epoch_tape import Compiler, run +from periodic import Rule + + +class Transfers: + def __init__(self, stream): + self.stream = stream + self.seeks = [] + self.bytes = 0 + + def seek(self, offset): + self.seeks.append((self.stream.tell(), offset)) + return self.stream.seek(offset) + + def read(self, size): + data = self.stream.read(size) + self.bytes += len(data) + return data + + def tell(self): + return self.stream.tell() + + +def trial(): + n = 323 + rule = Rule(5, (5,), (2, 2, 1)) + compiler_for_rank = Compiler(rule, 4) + plan = compiler_for_rank(n) + program = compiler_for_rank.image(n) + assert program is compiler_for_rank.image(n) + physical = Transfers(program.stream) + program.stream = physical + suspended = [] + + def exercise(nested): + rng = Random(19921 if nested else 19801) + machine = Chart(rule, ((2, 2, 1),), n) + original = {i: [rng.randrange(17) for _ in range(n)] for i in range(plan.width)} + fields = [ChartJob(i, tuple(rng.sample(range(n), n)), 0) for i in original] + machine.data = {i: a.copy() for i, a in original.items()} + machine.chart = dict.fromkeys(original, 0) + primitive = machine.leaf + + def leaf(job): + if not nested and not suspended: + suspended.append(physical.tell()) + assert 0 < suspended[0] < program.size + exercise(True) + assert physical.tell() == program.size + primitive(job) + + machine.leaf = leaf + run(rule, n, fields, machine, planner=compiler_for_rank) + assert machine.data == {i: [4 * x % 17 for x in z] for i, z in original.items()} + assert machine.leaves == plan.leaves and machine.serial == machine.freed + assert not any(machine.chart.values()) + + try: + exercise(False) + finally: + program.stream = physical.stream + assert (program.size, suspended[0]) in physical.seeks + assert physical.bytes == 2 * plan.rounds * program.size + moved = sum(abs(a - b) for a, b in physical.seeks) + assert moved <= program.size * 2 * plan.rounds * program.records + return n, plan.width, program.records, program.size, suspended[0], physical.bytes, moved + + +if __name__ == "__main__": + print( + "nested epoch rank, lanes, records, bytes, suspended offset, bytes read, seek distance", + *trial(), + ) diff --git a/research/single-band-native-carriers/check_linear_geometry.py b/research/single-band-native-carriers/check_linear_geometry.py new file mode 100644 index 0000000000..e8c636fc61 --- /dev/null +++ b/research/single-band-native-carriers/check_linear_geometry.py @@ -0,0 +1,195 @@ +"""Check the exact geometry, physical reservations and both dyadic controller boundaries.""" + +from fractions import Fraction +from itertools import combinations, islice, product +from math import comb, gcd, isqrt, prod + +from linear_geometry import ( + ceil_log2, + connected_exponent, + entrance_geometry, + minimum_window, + parameters, + public_shape, + square_sides, +) +from outer_schedule import Shape, parameters as predecessor_parameters, square_axes + + +def integer_guards(precision): + count = 0 + for s in (*range(512, 770), 1023, 1024, 1025, 8191, 8192, 8193, 12000): + # Include both ends of the public controller bucket, with actual multiples of six. + for p in (6 * (((1 << (s - 1)) + 4) // 6), 6 * (((1 << s) - 2) // 6)): + assert ceil_log2(p + 2) == s + for length in (p // 12, p // 6 + 3): + shape = public_shape(p, length) + width = (length + shape.count - 1) // shape.count + h0 = shape.count // (1024 * s) + p_work = precision(p, length, shape.count) + sp = ceil_log2(p_work + 2) + g = 4 * sp + 6 + rows = 448 * (4 * s + 1) + assert minimum_window(s) <= width <= 2 * minimum_window(s) + assert 50 * p_work < 51 * p and sp <= s + 1 + assert width - (length % shape.count != 0) >= 128 * g + assert p_work > 32768 * (width + 6) + assert minimum_window(s) // 2 - s - 6 >= 192 * s + 2 + amp = 4096 * h0 * (width + 6) + assert 8 * amp * s < 33 * length + if s >= 8192: + assert 1000 * p_work < 1001 * p + guaranteed = min(h0, shape.count // (80_000 * (width + 2) ** 6)) + assert guaranteed * s**7 >= 1 << (s - 100) + guard, rmax, crt = shape.crt_control() + assert 10100 * guard <= length and crt * 101 >= length >= 100 * crt + assert rmax * 51200 >= shape.count and shape.count // 2 > (1 << 46) * width**3 + body = h0 * width + required = body + rows + 3 * h0 * g + sp**2 + assert 4 * required < length and (length - s // 2 - body) // 2 >= required + clock_log = s + 1024 * (width + s + 67) + assert clock_log < (1 << 21) * (s + 1) < 1 << (s - 9) + count += 1 + return count + + +def band_checks(): + bands = ((2, 3, 5, 7), (11, 13, 17, 19), (23, 29, 31)) + orders = (2, 2, 0) + # Check the lower sieve as an integer identity for every possible divisibility pattern. + patterns = 0 + for counts in product(*(range(len(band) + 1) for band in bands)): + upper = [sum((-1) ** i * comb(m, i) for i in range(k + 1)) for m, k in zip(counts, orders)] + omitted = [comb(m, k + 1) for m, k in zip(counts, orders)] + lower = prod(upper) - sum( + x * prod(upper[:j] + upper[j + 1 :]) for j, x in enumerate(omitted) + ) + assert lower <= int(not any(counts)) <= prod(upper) + patterns += 1 + + # Expand a deliberately coarse case. Period averaging and arbitrary translated intervals + # must agree with the same signed divisor polynomial, including the interval-end errors. + def terms(band, ranks): + return {prod(t): (-1) ** k for k in ranks for t in combinations(band, k)} + + def tensor(parts): + return { + prod(v[0] for v in row): prod(v[1] for v in row) + for row in product(*(piece.items() for piece in parts)) + } + + upper = [terms(band, range(k + 1)) for band, k in zip(bands, orders)] + lower = tensor(upper) + for j, (band, k) in enumerate(zip(bands, orders)): + # k is even. Its next signed term has sign -1. + extra = tensor(upper[:j] + [terms(band, [k + 1])] + upper[j + 1 :]) + for divisor, weight in extra.items(): + lower[divisor] = lower.get(divisor, 0) + weight + expected = sum(Fraction(w, d) for d, w in lower.items()) + modulus = prod(prod(b) for b in bands) + for start in (0, 19, 131, 104729): + for size in (61, 334, 997): + count = sum(w * ((start + size) // d - start // d) for d, w in lower.items()) + survivors = sum(gcd(i, modulus) == 1 for i in range(start + 1, start + size + 1)) + assert count <= survivors and abs(count - size * expected) <= sum( + map(abs, lower.values()) + ) + return patterns + + +def positive_guards(): + from positive_dispatch import native_h + from spool import Field + + ranks_read = [] + + class AtFactory(Exception): + pass + + def factory(): + ranks_read.append(1) + raise AtFactory + + class Empty: + ambient_bits = 0 + + precision = 127 + required = 128 * (4 * (precision + 1).bit_length() + 6) + for h, window in ((4, required), (5, required - 1), (5, required), (9, required + 1)): + try: + native_h(Empty(), 0, h, window, 0, precision, None, 2, factory) + except AtFactory: + assert h > 4 and window >= required + except ValueError as err: + assert "windows do not fit" in str(err) and (h == 4 or window < required) + else: + raise AssertionError("The incomplete test field produced a numerical result") + assert len(ranks_read) == 2 + field = Field(4, 4) + data = [(i - 5, (5 * i) % 13 - 3) for i in range(16)] + field.write(data) + native_h(field, 0, 4, 1, 0, precision, None, 2, factory) + expected = [] + for j in range(16): + signs = [(-1) ** ((i & j).bit_count()) for i in range(16)] + expected.append( + tuple(sum(sign * value[c] for sign, value in zip(signs, data)) for c in range(2)) + ) + assert list(field.values()) == expected and len(ranks_read) == 2 + field.retire() + return 4 + + +def run(precision): + for n in (0, 1, 2, 5, 8, 741503, 1 << 8192, (1 << 16384) + 11): + assert parameters(n) == predecessor_parameters(n) + for width in (20, 21, 24, 28, 31, 38, 51, 66, 96): + shape = Shape(10000, 8 * width + 3, 8) + try: + before = tuple(square_axes(shape.axes())) + except ValueError: + try: + tuple(square_sides(shape)) + except ArithmeticError: + continue + raise AssertionError("The predecessor rejected a square that the new scan accepted") + ours = tuple(square_sides(shape)) + assert ours == before + assert all(gcd(r, prod(ours[:i])) == 1 for i, r in enumerate(ours)) + assert 4 * prod(ours) >= 3 * (1 << shape.extent_bits) + # Compute the first actual new prime-avoiding square choices at the production switch. + p = 6 * (((1 << 511) + 4) // 6) + b = p // 6 + # These are the exact controller arguments for the binary input length n = 2**b. + shape = public_shape(p, b + 2 - (b.bit_length() - 1)) + sides = tuple(islice(square_sides(shape), 4)) + assert all(gcd(r, prod(sides[:i])) == 1 and isqrt(r) ** 2 == r for i, r in enumerate(sides)) + for i, (r, width) in enumerate(zip(sides, shape.axes())): + m = (16 if i % 2 else 4) * shape.count + assert (m - 1) * (1 << width) <= m * r and 2 * m * r <= (2 * m - 1) * (1 << width) + for a in (512, 513, 517, 729, 1024, 4095, 4096): + p = 6 * (((1 << a) + 5) // 6) + b = p // 6 + for quadratic in (False, True): + actual = entrance_geometry(a, quadratic=quadratic) + assert p == (1 << a) + actual["public_offset_above_2_to_A"] + for correction in (1, 2): + length = b + correction - (b.bit_length() - 1) + cap = length // actual["minimum_width"] + d = 1 << (cap.bit_length() - 1) + assert actual["log2_axis_count"] == d.bit_length() - 1 + assert actual["largest_axis_width"] == (length + d - 1) // d + for top, carrier in ((1, 1), (800, 52), (6179, 471), (10**7, 2**21), (2**38, 3300000000)): + s = connected_exponent(top, carrier) + 1 + assert s - 100 - 7 * ceil_log2(s) >= top + carrier + 2 + for k in range(ceil_log2(s), ceil_log2(s) + 5): + after_jump = (1 << k) + 1 + assert after_jump - 100 - 7 * ceil_log2(after_jump) >= top + carrier + 2 + # The local inequality first holds at 1024, then fails at 1025 through 1030. + assert connected_exponent(800, 52) == 1030 + return { + "public_and_physical_guard_cases": integer_guards(precision), + "positive_dispatch_boundaries": positive_guards(), + "band_divisibility_patterns": band_checks(), + "actual_new_side_widths": [r.bit_length() for r in sides], + } diff --git a/research/single-band-native-carriers/check_product.py b/research/single-band-native-carriers/check_product.py new file mode 100644 index 0000000000..c1af1bd9cc --- /dev/null +++ b/research/single-band-native-carriers/check_product.py @@ -0,0 +1,140 @@ +"""Compare signed integer tapes and all recovered digits at the same Fourier geometry.""" + +from collections import Counter +from io import BytesIO +from time import perf_counter + +from band_product import PackProduct, Product, multiply +from ordinary_carrier import ordinary_swap, stage_body + + +def limbs(value, b): + v = abs(value) + return [(v >> q) % (1 << b) for q in range(0, v.bit_length(), b)] + + +def one(machine, a, b): + field_bits = machine.b + left, right = (abs(v).to_bytes((abs(v).bit_length() + 7) // 8, "little") for v in (a, b)) + inputs = [BytesIO(b"keep" + v + b"tail") for v in (left, right)] + for src in inputs: + src.seek(4) + target = BytesIO(b"head" + bytes(80) + b"guard") + target.seek(4) + before = machine.h_calls + start = perf_counter() + sign, size, coeff = machine.multiply_tapes( + inputs[0], + len(left), + inputs[1], + len(right), + target, + coefficients=True, + left_negative=a < 0, + right_negative=b < 0, + ) + seconds = perf_counter() - start + expected = [0] * machine.size + for i, x in enumerate(limbs(a, field_bits)): + for j, y in enumerate(limbs(b, field_bits)): + expected[i + j] += x * y + raw = abs(a * b).to_bytes(max(1, (abs(a * b).bit_length() + 7) // 8), "little") + assert list(coeff) == expected and sign == (a * b < 0) and size == len(raw) + assert target.getvalue() == b"head" + raw + bytes(80 - size) + b"guard" + assert all( + t.tell() == 4 and t.getvalue() == b"keep" + v + b"tail" + for t, v in zip(inputs, (left, right), strict=True) + ) + assert machine.h_calls > before + return { + "product": str(a * b), + "bits": [abs(a).bit_length(), abs(b).bit_length()], + "H_calls": machine.h_calls - before, + "coefficients_prefix": expected[:5], + "seconds": round(seconds, 4), + } + + +def stock_and_public(): + from dataclasses import replace + from calibration import COMPACT + + assert multiply(-741503, 466013) == -345550037539 + for x in (0, -1, 1, 37, -69, 2**16383 + 5): + assert multiply(x, -997) == x * -997 + # Exercise the production stage body with a feasible rank and all 81 by 81 addresses. + profile = replace(COMPACT, rank_logs=(1,)) + side = 3**4 + records = bytes((i * 97 + (i >> 4)) % 256 for i in range(side * side)) + result = BytesIO() + stage_body(BytesIO(records), result, 4, 1, 1, 1, 1, profile) + assert result.getvalue() == bytes( + records[j * side + i] for i in range(side) for j in range(side) + ) + + +def physical_product(): + from binary_receiver import Receiver + from module_atoms import balanced_widths + from ordinary import rectangle + from streaming_routes import work_tapes + from triangular_ordinary import root_body + + stock_and_public() + core = Receiver(2, balanced_widths(1), direct=True) + calls = Counter() + + def exchange(src, dst, bits, prefix, gap, suffix): + assert bits == 1 + calls["shuttles"] += 1 + calls["padded_bytes"] += prefix * 81 * gap * suffix + with work_tapes(2) as (opened, restored): + rectangle(src, opened, 2, 9, prefix, gap, suffix) + opened.seek(0) + root_body(opened, restored, 2, prefix, gap, suffix, core) + restored.seek(0) + rectangle(restored, dst, 2, 9, prefix, gap, suffix, restrict=True) + + machine = Product((3, 5), 8, 136, exchange) + row = one(machine, -741503, 466013) + assert calls["shuttles"] == 138 and row["H_calls"] == 157248 + return {**row, **calls, "rank": core.n, "stage_body_records": 81**2} + + +def matched(*, wide=False): + cases = [ + ((9,), 24, 224, [-((1 << 120) - 1), (1 << 119) + (1 << 96) + (1 << 49) + 1]), + ((3, 5), 8, 136, [-741503, 466013]), + ] + if wide: + cases.append(((9, 25), 8, 136, [-741503, 466013])) + for sides, b, P, values in cases: + for constructor in (PackProduct, Product): + counts = Counter() + + def charged(src, dst, bits, prefix, gap, suffix): + counts[bits] += 1 + ordinary_swap(src, dst, bits, prefix, gap, suffix) + + start = perf_counter() + machine = ( + constructor(sides, b, P, charged) + if constructor is Product + else constructor(sides, b, P) + ) + wall = perf_counter() - start + yield { + "path": constructor.__module__, + "true_sides": sides, + "padded_sites": machine.total, + "setup_seconds": round(wall, 4), + **one(machine, *values), + "physical_shuttles_by_width": dict(counts), + } + + +if __name__ == "__main__": + import json, sys + + for row in matched(wide="--wide" in sys.argv): + print(json.dumps(row), flush=True) diff --git a/research/single-band-native-carriers/check_strong_binary.py b/research/single-band-native-carriers/check_strong_binary.py new file mode 100644 index 0000000000..05f8801667 --- /dev/null +++ b/research/single-band-native-carriers/check_strong_binary.py @@ -0,0 +1,275 @@ +"""Check every binary chart, owner, grade, trace and powered price from the literal source.""" + +from collections import Counter +from fractions import Fraction +from functools import cache +from math import isqrt, lcm + +from factored_frames import inverse_word +from independent_binary_price import independent_prices +from strong_binary import caller, graph, native_word +from ternary_frames import frame_at_three, identity, projector, transpose +from vendor.cover import row_program + + +def run_registers(program, starts, ends, ports): + """Record exact data-form coefficients for all arbitrary public inputs at once.""" + count = len(starts) + frames = dict(enumerate(starts)) + values = {i: 1 << i for i in range(count)} + dirty = 0 + for op, dest, *args in program: + if op == "MOVE": + before, after = args + assert frames[dest] == before + frames[dest] = after + elif op == "ADD": + read, site = args + assert frames[dest] == frames[read] == site + values[dest] ^= values[read] + elif op == "SWAP": + (read,) = args + frames[dest], frames[read] = frames[read], frames[dest] + values[dest], values[read] = values[read], values[dest] + elif op == "INIT": + assert dest >= count and dest not in frames + frames[dest], values[dest] = args[0], 0 + elif op == "CLEAR": + assert dest >= count and frames.pop(dest) == args[0] + dirty += int(bool(values.pop(dest))) + else: + raise ValueError("Unknown graph instruction") + assert frames == dict(enumerate(ends)) + assert len(values) == count == 630 and ports == 111 + for i in range(count): + expected = 1 << i + if ports <= i < 2 * ports: + expected ^= 1 << (i - ports) + assert values[i] == expected + return dirty + + +def check_outer_word(root): + """Evaluate all 38 role images in the group ring of the commuting axis swaps.""" + + def shift(terms, mask): + return {(role, exponent ^ mask) for role, exponent in terms} + + def stage_mask(stages): + mask = 0 + for stage in stages: + mask ^= 1 << stage + return mask + + head = 1 + words = [{(i, 0)} for i in range(root["roles"])] + for op, *args in root["events"]: + if op == "LOCAL": + stage, x, y = args + body = stage_mask((stage,)) + first, second = words[x], words[y] + words[x] = shift(first, body) + words[y] = shift(first, body ^ head) ^ shift(second, body) + elif op == "IDLE_ONE": + x, stages = args + words[x] = shift(words[x], stage_mask(stages)) + elif op == "QUERY": + x, y = args + words[x] ^= shift(words[y], head) + elif op == "ADD": + x, y = args + words[x] ^= words[y] + elif op == "SWAP": + x, y = args + words[x], words[y] = words[y], words[x] + else: + raise ValueError("Unknown caller instruction") + for i, (answer, diag) in enumerate(zip(words, root["diagonal"], strict=True)): + assert diag["q"] == 1 + assert answer == {(i, head ^ stage_mask(diag["stages"]))} + + +def matrix_product(a, b): + cols = list(zip(*b, strict=True)) + return [[sum(x * y for x, y in zip(u, v, strict=True)) for v in cols] for u in a] + + +def integer_matrix(a): + den = lcm(*(v.denominator for row in a for v in row)) + assert den % 3 + return den, [[int(v * den) for v in row] for row in a] + + +def rational_word(frame): + word = row_program(frame, 3) + back = tuple(inverse_word(word)) + for program, base, goal in [ + (word, identity(len(frame)), frame), + (back, frame, identity(len(frame))), + ]: + rows = [list(row) for row in base] + for op, i, *args in program: + if op in ("scale", "add"): + q = Fraction(args[-1]) + assert q.denominator % 3 and max(abs(q.numerator), q.denominator) <= 20 + if op == "scale": + assert q.numerator % 3 + for row in rows: + if op == "scale": + row[i] *= q + elif op == "add": + row[i] += row[args[0]] * q + elif op == "swap": + j = args[0] + row[i], row[j] = row[j], row[i] + else: + raise ValueError("Unknown frame instruction") + assert rows == goal + return len(word) + + +def check_charts(data, ports): + frames, starts, ends = data["frames"], data["start"], data["final"] + ops = data["program"] + projectors, splits = [], [] + ident = identity(8) + for i in range(len(frames)): + spec = frames[str(i)] + p = projector(transpose(spec["B"] + spec["A"]), spec["dim"]) + projectors.append(p) + den, m = integer_matrix(p) + assert matrix_product(m, m) == [[den * x for x in row] for row in m] + splits.append((den, m)) + pairs = {tuple(row[2:]) for row in ops if row[0] == "MOVE"} + pairs.update(zip(starts[2 * ports :], ends[2 * ports :], strict=True)) + pairs = {tuple(sorted(pair, key=lambda j: frames[str(j)]["dim"])) for pair in pairs} + steps = 0 + for i, j in sorted(pairs): + di, pi = splits[i] + dj, pj = splits[j] + lifted = [[dj * x for x in row] for row in pi] + assert matrix_product(pi, pj) == matrix_product(pj, pi) == lifted + delta = [ + [y - x for x, y in zip(a, b, strict=True)] + for a, b in zip(projectors[i], projectors[j], strict=True) + ] + basis, rank = frame_at_three(delta) + assert rank == frames[str(j)]["dim"] - frames[str(i)]["dim"] + den, m = integer_matrix(delta) + assert matrix_product(m, basis) == [ + [den * v if col < rank else 0 for col, v in enumerate(row)] for row in basis + ] + steps += rational_word(basis) + for i in range(ports): + head, body = projectors[starts[i]], projectors[ends[ports + i]] + assert len(frames[str(starts[i])]["B"]) == 1 + assert projectors[ends[i]] == ident + assert all(x == 0 for row in projectors[starts[ports + i]] for x in row) + assert [ + [x + y for x, y in zip(a, b, strict=True)] for a, b in zip(head, body, strict=True) + ] == ident + basis = transpose(frames[str(starts[i])]["B"] + frames[str(ends[ports + i])]["B"]) + steps += rational_word(basis) + return len(projectors), len(pairs), steps + + +GRID = 1 << 128 + + +@cache +def power(rank, exponent): + """Enclose a nonnegative dyadic power with integer square roots and products.""" + n, q = exponent.as_integer_ratio() + assert n >= 0 and q & (q - 1) == 0 + a = b = rank * GRID + for _ in range(q.bit_length() - 1): + a, b = isqrt(a * GRID), isqrt(b * GRID) + 1 + lo = hi = GRID + while n: + if n & 1: + lo, hi = lo * a // GRID, (hi * b + GRID - 1) // GRID + n //= 2 + if n: + a, b = a * a // GRID, (b * b + GRID - 1) // GRID + return Fraction(lo, GRID), Fraction(hi, GRID) + + +def strict_surplus(word, saving, drop_tilt, caps, slack_bits, debit): + k, r = (Counter(port.rank for port in ports) for ports in (word.targets, word.paid)) + assert (len(word.targets), len(word.paid), word.ambient, word.low_cut, word.high_cut) == ( + 18906, + 104904, + 134, + 12, + 12, + ) + assert (word.power, word.floor) in ((128, 16), (228, 15)) + assert max(k) == 127 and max(r) == 56 + assert sum(rank * count for rank, count in r.items()) == 285_600 < 12 * len(word.paid) + assert 3 * len(word.paid) ** word.power < 2 ** (18 * word.power) + assert 5**13 > 16 * 4**13 + t, z, w = 1 - saving, Fraction(19, 64), drop_tilt + + def mass(counter, e, side): + return sum(count * power(rank, e)[side] for rank, count in counter.items()) + + base = mass(k, t, 0) + alpha = mass(r, t, 1) / base + gamma = mass(r, t + z, 1) / (power(word.high_cut, z)[0] * base) + lam = power(word.floor, w)[1] * mass(k, t - w, 1) / base + # These three upward rounded bounds keep the powered test small. + assert all(u < b for u, b in zip((alpha, gamma, lam), caps, strict=True)) + a, g, l = caps + assert a**word.power + 2 * g**word.power + l**word.power < 1 - Fraction(1, 2**slack_bits) + cutoff = 2 ** (slack_bits + 1) + assert Fraction(32 * 2 * 16 * cutoff, 15 * (cutoff - 2)) < 72 + assert 0 < saving < Fraction(39, 10_000) + base = 4 * (word.ambient * max(k)) ** word.power * cutoff + assert 72**10_000 * base**39 < 2 ** (debit * 10_000) + return caps + + +def main(): + data, root = graph(), caller() + assert sum(r[0] == "LOCAL" for r in root["events"]) == 36 + dirty = run_registers(data["program"], data["start"], data["final"], root["ports"]) + check_outer_word(root) + assert dirty == 3433 + frames, pairs, steps = check_charts(data, root["ports"]) + assert (frames, pairs, steps) == (636, 2352, 44825) + prices = [ + strict_surplus( + native_word(128), + Fraction(2039, 2**19), + Fraction(13, 32), + (Fraction(999998604, 10**9), Fraction(907282, 10**6), Fraction(926012, 10**6)), + 14, + 14, + ), + strict_surplus( + native_word(228), + Fraction(17108907955, 2**42), + Fraction(31, 64), + (Fraction(999999999997229, 10**15), Fraction(907282, 10**6), Fraction(900019, 10**6)), + 34, + 19, + ), + ] + print( + "PASS_STRONG_BINARY", + frames, + "frames", + pairs, + "deltas", + steps, + "frame gates", + dirty, + "dirty private clears", + "strict surplus > 2^-14 and 2^-34", + prices, + ) + print("PASS_INDEPENDENT_BINARY_SURPLUS_X_1E18", *independent_prices(data, root)) + + +if __name__ == "__main__": + main() diff --git a/research/single-band-native-carriers/check_strong_complex.py b/research/single-band-native-carriers/check_strong_complex.py new file mode 100644 index 0000000000..cc1232dabc --- /dev/null +++ b/research/single-band-native-carriers/check_strong_complex.py @@ -0,0 +1,252 @@ +"""Check the changed Gaussian raw word, all its charts, and the executed exact grid.""" + +from argparse import ArgumentParser +from collections import Counter +from fractions import Fraction +from hashlib import sha256 +from math import gcd, prod +from pathlib import Path +import json +import sys + +from strong_complex import ( + ADDITIONAL, + DYADIC, + GRID, + ODD, + artifacts, + digest, + load_changed, + packed, + required_pairs, + word, +) + + +def check(cond, why): + if not cond: + raise ValueError(why) + + +def atlas(grade, graph, layout, data): + from charts import native_catalogue + from check_complex import all_images + from contacts import contact_receipt + + prior = packed(grade / "complex-atlas.json.gz") + extra = packed(data / "new-charts.json.gz") + check(digest(extra) == ADDITIONAL, "supplemental Clifford factors") + need = required_pairs(graph, layout) + old = {(a, b): r for a, b, r in prior["pairs"]} + add = {(a, b): r for a, b, r in extra} + check( + need - old.keys() == add.keys() and len(add) == len(extra), "all supplementary directions" + ) + factors = old | add + catalogue = {"pairs": [[a, b, factors[a, b]] for a, b in sorted(need)], "ports": prior["ports"]} + checked = native_catalogue(graph, layout, catalogue) + contact = contact_receipt( + layout, json.loads((grade / "retained/data/CALLER-PHASE-BASES.json").read_bytes())["by_q"] + ) + return dict( + pairs=len(need), + new=len(extra), + ports=len(catalogue["ports"]), + atlas_sha256=digest(checked), + images=all_images(checked), + contact=contact, + ) + + +def literal_grid(graph, layout): + from spool import short_divisors + + size = len(graph["initial"]) + stocks = {~i: {i: GRID} for i in range(size)} + moves = {k for k, _, _ in graph["moves"]} + rows = {k: [(s, Fraction(q)) for s, q in row] for k, row in graph["forms"]} + masses = {~i: Fraction(1) for i in range(size)} + expected = [{i: GRID} for i in range(size)] + hosted = layout["hosted"] + for i, x in enumerate(layout["live"]): + y = x + 112 + if i in hosted["Dports"]: + expected[y][x] = GRID + else: + expected[x][y] = -GRID + expected[y] = {x: GRID // 2, y: GRID // 2} + for x, y in zip(hosted["X2"], hosted["Y2"], strict=True): + expected[x][y] = -GRID + peak = Fraction(1) + largest_limb = maximum_literal = products = nontrivial = 0 + common = GRID + literals = set() + for node in graph["schedule"]: + values, mass = {}, Fraction(0) + for src, coeff in rows[node]: + a, b = coeff.numerator, coeff.denominator + literals.add(coeff) + mass += abs(coeff) * masses[src] + for i, old in stocks[src].items(): + q, rem = divmod(old, b) + check(rem == 0, "inexact term before multiplication") + term = a * q + if common != 1: + common = gcd(common, term) + values[i] = values.get(i, 0) + term + products += len(stocks[src]) + nontrivial += (b != 1) * len(stocks[src]) + peak = max(peak, mass) + result = {i: v for i, v in values.items() if v} + if node in moves: + stocks[node] = result + masses[node] = mass + else: + check( + result == expected[node - graph["first_output"]], + "wrong whole inverse odd or endpoint", + ) + for coeff in literals | {Fraction(1, ODD), Fraction(ODD)}: + factors = short_divisors(coeff.denominator) + check( + prod(factors) == coeff.denominator and all(1 < v < 2**24 for v in factors), + "unrepresentable fixed coefficient denominator", + ) + maximum_literal = max( + maximum_literal, coeff.numerator.bit_length(), coeff.denominator.bit_length() + ) + largest_limb = max(largest_limb, *factors, 0) + check(common == 1 and (ODD << DYADIC) == GRID and ODD % 2 == 1, "minimal grid") + check((products, nontrivial) == (25146238, 17231591), "all signed basis products") + check( + peak + == Fraction( + 205356183613728386434052488657699504746980105023, 1621896683681232672237748224000 + ), + "source mass", + ) + return dict( + products=products, + nontrivial=nontrivial, + peak=str(peak), + odd=ODD, + literal_width_with_odd=maximum_literal, + distinct_literals=len(literals), + largest_divisor=largest_limb, + ) + + +def caller(grade, graph, layout, data, mass): + from mixed_grid import exact, envelope + from graph_identity import graph_identity + from raw48 import ComplexRaw + + a = artifacts(grade, data) + w = word(graph, layout) + heights, entrance = [], [] + masses, entrance_mass = [], [] + template = {} + for name, (events, diagonal) in a.words.items(): + receipt = exact(events, diagonal, 2025 << 9) + check(exact(events, diagonal, receipt["minimum_grid"]) == receipt, "signed complete caller") + e = envelope(events, len(diagonal)) + heights.append(e["height"]) + entrance.append(e["entrance_height"]) + masses.append(Fraction(e["mass"])) + entrance_mass.append(Fraction(e["entrance_mass"])) + template[name] = receipt + denominator = max(max(heights), max(entrance) + DYADIC) + scaled_mass = max(max(masses) * 2025, max(entrance_mass) * 2025 * ODD * mass) + mass_bits = (scaled_mass.numerator - 1) // scaled_mass.denominator + mass_bits = mass_bits.bit_length() + scheduled, source = [], [] + degrees = Counter() + for (kind, root), _ in a.roots.items(): + for i, (sign, terms) in enumerate(a.words[kind][1]): + tag = ("root", kind, root, a.offsets[kind, root] + i, sign) + source.append((tag, 1 + 8 * len(terms))) + source_events = sha256() + for clock, row in enumerate(a.instructions()): + source_events.update(json.dumps(row, separators=(",", ":")).encode()) + op = row[0] + degrees[op] += 1 + if op == "NATIVE": + call = row[1] + for i, (b, e) in enumerate(zip(graph["initial"], graph["final"], strict=True)): + if i not in a.main: + tag = "helper", clock, call, layout["source_labels"][i] + r = a.factors[b, e][0] + check( + r == len(graph["frames"][e]) - len(graph["frames"][b]) > 0, + "funded native helper", + ) + source.append((tag, r)) + scheduled.extend( + (("return", clock, call, k), a.factors[a.moves[k]][0]) + for k in graph["schedule"] + if k in a.moves + ) + elif op == "QUERY" or op.startswith("IDLE_"): + r = 1 if op == "QUERY" else 8 * len(row[2]) + (op == "IDLE_ODD") + scheduled.append(((op, clock, row[1]), r)) + check(source == [(x.tag, x.rank) for x in w.targets], "complete physical productive stream") + check(scheduled == [(x.tag, x.rank) for x in w.paid], "complete physical paid stream") + check( + source_events.hexdigest() + == json.loads((grade / "retained/grade14-audit.json").read_bytes())["signed"][ + "caller_sha256" + ], + "chronological native caller", + ) + check( + degrees["NATIVE"] == 48 + and len({x[0] for x in source}) == len(source) + and len({x[0] for x in scheduled}) == len(scheduled), + "independent owners and chronological tags", + ) + check( + ComplexRaw.axis_list(3, (0, 9, 17))[:3] == (0, 1, 2) + and (("root", "rotated", 191, 9825, 1), 129) in source, + "materialized exposed witness", + ) + return dict( + targets=len(source), + paid=len(scheduled), + target_hist=dict(sorted(Counter(r for _, r in source).items())), + paid_hist=dict(sorted(Counter(r for _, r in scheduled).items())), + stages=degrees, + graph=graph_identity(graph, layout), + binding=a.binding_receipt, + caller=template, + per_context_dyadic=denominator, + per_context_mass=mass_bits, + context_guard=2 * max(denominator, mass_bits), + caller_sha=source_events.hexdigest(), + ) + + +if __name__ == "__main__": + parser = ArgumentParser(description=__doc__) + for arg in ("grade", "engine", "native", "bounded", "data"): + parser.add_argument(arg, type=Path) + parser.add_argument("mode", choices=("atlas", "grid", "caller")) + args = parser.parse_args() + for path in ( + args.grade.resolve(), + args.grade.resolve() / "retained", + args.engine.resolve(), + args.native.resolve(), + args.bounded.resolve(), + ): + sys.path.append(str(path)) + g, l = load_changed(args.data) + proven_mass = Fraction( + 205356183613728386434052488657699504746980105023, 1621896683681232672237748224000 + ) + if args.mode == "atlas": + answer = atlas(args.grade, g, l, args.data) + elif args.mode == "grid": + answer = literal_grid(g, l) + else: + answer = caller(args.grade, g, l, args.data, proven_mass) + print(json.dumps(answer, sort_keys=True)) diff --git a/research/single-band-native-carriers/check_strong_physical.py b/research/single-band-native-carriers/check_strong_physical.py new file mode 100644 index 0000000000..754f4430b0 --- /dev/null +++ b/research/single-band-native-carriers/check_strong_physical.py @@ -0,0 +1,93 @@ +"""Run each new positive child on a dense numerical field with its actual charts.""" + +from argparse import ArgumentParser +from pathlib import Path +import sys + +from strong_complex import artifacts, packed + + +def direct(circuit, values, engine, quarter): + for gate in circuit: + op = gate[0] + if op == "P": + dest = engine.action(gate) + out = [None] * len(values) + for pos, new in enumerate(dest): + out[new] = values[pos] + values = out + elif op == "D": + values = [quarter(z, q) for z, q in zip(values, engine.action(gate), strict=True)] + elif op == "phase": + values = [quarter(z, gate[1]) for z in values] + elif op == "X": + values = [values[x ^ gate[1]] for x in range(len(values))] + elif op == "C": + _, v, sign = gate + out = [] + for x, (a, b) in enumerate(values): + c, d = values[x ^ v] + a, b = a + c + sign * (d - b), b + d + sign * (a - c) + if (a | b) & 1: + raise ArithmeticError("The direct Clifford oracle lost its grid") + out.append((a // 2, b // 2)) + values = out + else: + raise ValueError("Unknown independent frame gate") + return values + + +def run(grade, data): + from compact_columns import Columns + from positive import one_axis + from raw48 import ComplexRaw + from spool import Arena, cold_swap, quarter + import native_verify as independent + + art = artifacts(grade, data) + new = packed(data / "new-charts.json.gz") + frames = art.graph["frames"] + checked = 0 + for a, b, rec in new: + rank, right, left = art.factors[a, b] + if rank != rec["rank"]: + raise ValueError("The paid slot width differs") + amp = [((17 * j - 11 * a + b) << 18, (3 * j * j + 2 * a - b) << 18) for j in range(512)] + expected = direct( + independent.adjoint(independent.frame(tuple(frames[a]), 9)) + + independent.frame(tuple(frames[b]), 9), + amp, + independent, + quarter, + ) + pool = Arena(9, 16) + field = pool.field() + field.write(amp) + slots = Columns(1, 0, 1, 0, 0, 0, 0, cold_swap) + raw = ComplexRaw(art, {0: field}, slots, low=0, bundle=1, slots=9) + raw.chart(field, right, range(9), 1) + for axis in range(rank): + one_axis(field, axis) + raw.chart(field, left, range(9), 1) + if list(field.values()) != expected: + raise ValueError("Physical child differs from its independent true frame transport") + raw.chart(field, left, range(9), 1, inverse=True) + for axis in range(rank): + one_axis(field, axis) + slots.row(field, (axis,)) + raw.chart(field, right, range(9), 1, inverse=True) + if list(field.values()) != amp: + raise ValueError("The paid inverse did not restore the original field") + field.retire() + pool.close() + checked += 1 + return {"supplemental_dense_children": checked, "complex_values_per_direction": 512 * checked} + + +if __name__ == "__main__": + p = ArgumentParser(description=__doc__) + for key in ("grade", "engine", "native", "bounded", "data"): + p.add_argument(key, type=Path) + args = p.parse_args() + sys.path.extend(str(path.resolve()) for path in (args.engine, args.native, args.bounded)) + print(run(args.grade, args.data)) diff --git a/research/single-band-native-carriers/check_strong_raw_word.py b/research/single-band-native-carriers/check_strong_raw_word.py new file mode 100644 index 0000000000..32d3cc9d3b --- /dev/null +++ b/research/single-band-native-carriers/check_strong_raw_word.py @@ -0,0 +1,184 @@ +"""Run all 48 physical emitters on one exact spectator-constant input.""" + +from argparse import ArgumentParser +from fractions import Fraction +from pathlib import Path +import sys + +from strong_complex import artifacts, word + + +class Field: + def __init__(self, stock, data=None): + self.stock, self.data = stock, data + self.live = True + stock[0] += 1 + stock[1] = max(stock[0], stock[1]) + + def blank(self): + return Field(self.stock) + + def copy(self): + return Field(self.stock, None if self.data is None else self.data.copy()) + + def clear(self): + self.data = None + + def replace(self, other): + self.data = other.data + other.retire() + + def retire(self): + assert self.live + self.live = False + self.data = None + self.stock[0] -= 1 + + @staticmethod + def mul(x, c): + c = Fraction(c) + a, b = divmod(x, c.denominator) + if b: + raise ArithmeticError("The full native trace lost its exact grid") + return a * c.numerator + + def scale(self, real, imag=0): + if self.data is not None: + self.data = [ + (self.mul(a, real) - self.mul(b, imag), self.mul(b, real) + self.mul(a, imag)) + for a, b in self.data + ] + if not any(a or b for a, b in self.data): + self.data = None + + def scale_add(self, other, real=1, imag=0): + if other.data is not None: + value = other.copy() + value.scale(real, imag) + if value.data is not None: + if self.data is None: + self.data = value.data + else: + self.data = [ + (a + c, b + d) for (a, b), (c, d) in zip(self.data, value.data, strict=True) + ] + if not any(a or b for a, b in self.data): + self.data = None + value.retire() + + def phase(self, fn, suffix): + from spool import quarter + + if self.data is not None: + self.data = [quarter(v, fn(i)) for i, v in enumerate(self.data)] + + def swap(self, left, right, width, move): + if self.data is not None: + raise AssertionError("The selected witness requires a canonical external placement") + + +class Axes: + offset = suffix = 0 + window = 1 + swap = None + + @staticmethod + def row(field, targets, sources=None): + if field.data is None: + return + for i, j in zip(targets, sources or [None] * len(targets), strict=True): + if i >= 9 or (j is not None and j >= 9): + raise AssertionError("A live field left the nine-coordinate evaluation space") + field.data = [ + field.data[k ^ ((1 if j is None else (k >> j) & 1) << i)] for k in range(512) + ] + + +def positive(values, bit): + if not 0 <= bit < 9: + raise ValueError("The nonzero job changed a spectator") + out = [] + for j, (a, b) in enumerate(values): + c, d = values[j ^ (1 << bit)] + u, v = a - b + c + d, b + a + d - c + if (u | v) & 1: + raise ArithmeticError("The paid positive job lost its integer grid") + out.append((u // 2, v // 2)) + return out + + +def run(grade, data): + from periodic import Job + from raw48 import ComplexRaw + + class WordRaw(ComplexRaw): + def chart(self, field, tape, axes, cols, inverse=False): + if field.data is not None: + if any(j >= 9 for j in axes): + raise AssertionError("A nonzero crossed the pure helper/contact boundary") + super().chart(field, tape, axes, cols, inverse) + + a = artifacts(grade, data) + w = word(a.graph, a.layout) + reg = a.layout["source_labels"].index(1544) + assert reg not in a.main and reg == 1290 + clock, call = next((i, row[1]) for i, row in enumerate(a.instructions()) if row[0] == "NATIVE") + chosen = ("helper", clock, call, 1544) + jobs, fields, stock = [], {}, [0, 0] + ordinary_slots = {} + for (kind, root), visits in a.roots.items(): + for j, (sign, entries) in enumerate(a.words[kind][1]): + tag = ("root", kind, root, a.offsets[kind, root] + j, sign) + ordinary_slots[tag] = (0,) + tuple( + 9 + 8 * (visits[v][0] % 16) + k for v in entries for k in range(8) + ) + for i, port in enumerate(w.targets): + job = Job(i, ordinary_slots.get(port.tag, tuple(range(port.rank)))) + fields[i] = Field(stock) + jobs.append((port.tag, job)) + if port.tag == chosen: + owner, active = i, job.axes + initial = [((19 * j - 5) << 128, (3 * j * j + 11) << 128) for j in range(512)] + fields[owner].data = initial + raw = WordRaw(a, fields, Axes(), low=0, bundle=1, slots=153) + seen, nonzero, changed = 0, 0, 0 + iterator = raw.raw(jobs, 1) + for port in w.paid: + tag, job = next(iterator) + assert tag == port.tag and len(job.axes) == port.rank + field = raw.fields[job.owner] + if field.data is not None: + nonzero += 1 + changed += int(tag == ("return", clock, call, 95)) + for bit in job.axes: + field.data = positive(field.data, bit) + seen += 1 + assert next(iterator, None) is None + expected = initial + for bit in active: + expected = positive(expected, bit) + assert fields[owner].data == expected and all( + f.data is None for i, f in fields.items() if i != owner + ) + assert set(fields) == set(range(len(w.targets))) and stock[0] == len(fields) + assert nonzero and changed == 1 and a.moves[95] == (34, 127) + return dict( + complete_raw_callers=48, + external_roles=len(w.targets), + actual_paid=seen, + nonzero_paid=nonzero, + changed_paid=changed, + peak_test_fields=stock[1], + owner=owner, + helper_rank=len(active), + returned_records=512, + ) + + +if __name__ == "__main__": + p = ArgumentParser(description=__doc__) + for key in ("grade", "native", "bounded", "data"): + p.add_argument(key, type=Path) + args = p.parse_args() + sys.path.extend(str(path.resolve()) for path in (args.native, args.bounded)) + print(run(args.grade, args.data)) diff --git a/research/single-band-native-carriers/check_weighted_binary.py b/research/single-band-native-carriers/check_weighted_binary.py new file mode 100644 index 0000000000..5e500f3623 --- /dev/null +++ b/research/single-band-native-carriers/check_weighted_binary.py @@ -0,0 +1,179 @@ +"""Replay the full strong binary raw word on nonconstant weighted address data. + +The independent sparse endpoint oracle is from PR 7981. +""" + +from fractions import Fraction +from functools import cache +from random import Random + + +def weighted(): + from check_raw_delta import Sparse, right_columns + from strong_binary import StrongBinarySource, native_word + from direct_body import direct_actions, direct_factors + from factored_frames import Frame, inverse_word + from periodic import Job + from raw_binary import Axis, job_frame + from ternary_frames import residue + + source = native_word() + seeds = {0, 111, 114, len(source.targets) - 1} + for grade in (4, 8): + seeds.add( + next( + i + for i, port in enumerate(source.targets) + if port.tag[0] == "helper" and port.rank == grade + ) + ) + for modulus, columns in ((3, 1), (9, 2)): + n = source.ambient * columns + ident = tuple(bytes(int(x == y) for x in range(n)) for y in range(n)) + rng = Random(7914) + units = [x for x in range(modulus) if x % 3] + A = [rng.choice(units) for _ in range(n)] + Ai = [pow(a, -1, modulus) for a in A] + + @cache + def scaled_word(word): + out = [] + for op, tail, i, j, coeff in direct_actions(word, 1): + a = residue(coeff, modulus) + if not tail and op == "swap": + a = A[i] * Ai[j] % modulus + elif not tail and op == "add": + a = a * A[j] * Ai[i] % modulus + out.append((op, tail, i, j, a)) + return tuple(out) + + @cache + def factors(word, axis): + u, v = direct_factors(Frame(n, word, (axis,)), modulus) + return bytes(u), bytes(v) + + class DirectSparse(Sparse): + dimension = n + + def route(self, owner, word): + if not self.values[owner]: + return + self.active_routes += 1 + out = set() + for label, h, t in self.values[owner]: + pair = list(h), list(t) + for op, tail, i, j, a in scaled_word(word): + bank = pair[tail] + if op == "swap": + bank[i], bank[j] = ( + a * bank[j] % modulus, + pow(a, -1, modulus) * bank[i] % modulus, + ) + elif op == "scale": + bank[i] = a * bank[i] % modulus + else: + bank[j] = (bank[j] + a * bank[i]) % modulus + out.add((label, bytes(pair[0]), bytes(pair[1]))) + self.values[owner] = out + + def pay(self, job): + if not self.values[job.owner]: + return + self.active_paid += 1 + frame = job_frame(job, n) + out = set() + for label, h, t in self.values[job.owner]: + d = [(y - ai * x) % modulus for x, ai, y in zip(h, Ai, t, strict=True)] + change = [0] * n + for axis in frame.mask: + u, v = factors(frame.word, axis) + coeff = sum(x * y for x, y in zip(v, d, strict=True)) % modulus + if coeff: + change = [ + (x + coeff * y) % modulus for x, y in zip(change, u, strict=True) + ] + self.moved += any(change) + out.add( + ( + label, + bytes( + (x + a * v) % modulus for x, a, v in zip(h, A, change, strict=True) + ), + bytes((y - v) % modulus for y, v in zip(t, change, strict=True)), + ) + ) + self.values[job.owner] = out + + banks = DirectSparse(None, modulus) + entries, expected = [], {} + for i, port in enumerate(source.targets): + owner = banks.zero() + if i in seeds: + g = ( + ("add", 7, 113, Fraction(4, 5)), + ("swap", 0, 126), + ("scale", 4, Fraction(-2)), + ("add", 0, 32, 2), + ("add", 7, 0, i % 4 + 1), + ) + axes = tuple(Axis(g, j) for j in range(port.rank * columns)) + h, t = (bytes(rng.randrange(modulus) for _ in range(n)) for _ in range(2)) + banks.values[i].add((i, h, t)) + # Use full dense image and dual columns only in this endpoint check. + data = right_columns(ident, g, modulus) + inv = right_columns(ident, tuple(inverse_word(g)), modulus) + diff = [(y - ai * x) % modulus for x, ai, y in zip(h, Ai, t, strict=True)] + local = [ + sum(col[j] * x for col, x in zip(inv, diff, strict=True)) % modulus + for j in range(port.rank * columns) + ] + change = [ + sum(data[j][k] * entry for j, entry in enumerate(local)) % modulus + for k in range(n) + ] + expected[i] = { + ( + i, + bytes((x + a * v) % modulus for x, a, v in zip(h, A, change, strict=True)), + bytes((y - v) % modulus for y, v in zip(t, change, strict=True)), + ) + } + else: + axes = tuple(range(port.rank * columns)) + entries.append((port.tag, Job(owner, axes))) + count = 0 + for (tag, job), paid in zip( + StrongBinarySource(banks).raw(entries, columns), source.paid, strict=True + ): + assert tag == paid.tag and len(job.axes) == paid.rank * columns + banks.pay(job) + count += 1 + assert count == 104904 and len(banks.values) == len(entries) == 18906 + wrong = [k for k, v in banks.values.items() if v != expected.get(k, set())] + assert not wrong, wrong[:3] + print( + "modulus", + modulus, + "columns", + columns, + "raw paid", + count, + "outputs", + len(entries), + "seeds", + len(seeds), + "nonempty routes", + banks.active_routes, + "nonempty paid", + banks.active_paid, + "moved support", + banks.moved, + flush=True, + ) + + +if __name__ == "__main__": + from upstream import install + + install() + weighted() diff --git a/research/single-band-native-carriers/epoch_tape.py b/research/single-band-native-carriers/epoch_tape.py new file mode 100644 index 0000000000..2a54438538 --- /dev/null +++ b/research/single-band-native-carriers/epoch_tape.py @@ -0,0 +1,185 @@ +"""Install one chronological epoch and replay it on every actual owner group.""" + +from itertools import count +from tempfile import TemporaryFile + +from periodic import row_axes + +OPEN, ISSUE, CLOSE, FINISH = range(4) +EXTERNAL, LOAN = range(2) + + +def epoch(rule, plan): + """Emit frame and loan numbers. Keep placement relative to the current round.""" + band = plan.forest + ids = count() + + def layer(path, previous): + frames, consumed = [], {} + for unit in band.layers.get(path, ()): + group = [] + for copy in range(plan.copies): + frame = next(ids) + operation = [OPEN, frame, unit.columns] + for i, (kind, label) in enumerate(unit.ports): + size = rule.targets[i] * unit.columns + if kind == "parent": + operation.extend((LOAN, previous[label][copy], size)) + consumed[label] = size + else: + base = copy * plan.owners_per_copy + plan.offsets[label] + operation.extend((EXTERNAL, base, size, plan.periods[label])) + yield tuple(operation) + group.append(frame) + frames.append((unit, group)) + for j, paid in enumerate(rule.paid): + child = path + (j,) + requests = {} + for unit, group in frames: + loans = [] + for frame in group: + loan = next(ids) + yield (ISSUE, frame, loan, paid * unit.columns) + loans.append(loan) + requests[unit.future] = loans + if requests or child in band.prefixes: + yield layer(child, requests) + for _, group in frames: + for frame in group: + yield (CLOSE, frame) + for label, loans in previous.items(): + for loan in loans: + yield (FINISH, loan, consumed.get(label, 0)) + + stack = [layer((), {})] + while stack: + entry = next(stack[-1], None) + if entry is None: + stack.pop() + elif isinstance(entry, tuple): + yield entry + else: + stack.append(entry) + + +def put_nat(stream, value): + while value >= 128: + stream.write(bytes((128 | (value & 127),))) + value >>= 7 + stream.write(bytes((value,))) + + +def get_nat(stream): + value = shift = 0 + while True: + octet = stream.read(1) + if not octet: + raise EOFError("The installed instruction ended inside an integer") + b = octet[0] + value |= (b & 127) << shift + if b < 128: + return value + shift += 7 + + +class Image: + def __init__(self, rule, plan): + self.stream = TemporaryFile() + self.records = 0 + for row in epoch(rule, plan): + put_nat(self.stream, len(row)) + for value in row: + put_nat(self.stream, value) + self.records += 1 + self.size = self.stream.tell() + + def rows(self): + # A recursive invocation can use the same tape head while a loan is open. + offset = 0 + while offset < self.size: + self.stream.seek(offset) + row = tuple(get_nat(self.stream) for _ in range(get_nat(self.stream))) + offset = self.stream.tell() + yield row + + +class Compiler: + """Keep one generated plan and one installed stream per fixed carrier rank.""" + + def __init__(self, rule, floor): + from band_compiler import make_planner + + self.rule = rule + self.plan = make_planner(rule, floor) + self.images = {} + + def __call__(self, rank): + return self.plan(rank) + + def image(self, rank): + if rank not in self.images: + self.images[rank] = Image(self.rule, self.plan(rank)) + return self.images[rank] + + +def run(rule, n, fields, machine, *, planner): + plan = planner(n) + public = tuple(fields) + if ( + len(public) != plan.width + or len({job.owner for job in public}) != plan.width + or any(len(job.axes) != n for job in public) + ): + raise ValueError("The carrier needs independent full input fields") + + def finish(job, first): + for i in range(first, len(job.axes)): + machine.leaf(job.select((i,))) + + if plan.forest is None: + for job in public: + finish(job, 0) + return + code = planner.image(n) + fields = list(public) + for _ in range(plan.copies * plan.owners_per_copy - plan.width): + fields.append(machine.zero(public[0])) + frames, loans = {}, {} + end = object() + for iteration in range(plan.rounds): + for row in code.rows(): + op, key, *args = row + if op == OPEN: + columns, *descriptors = args + entries = iter(descriptors) + ports = [] + for kind in entries: + index, size = next(entries), next(entries) + if kind == LOAN: + job = loans[index].select(range(size)) + else: + q = next(entries) + job = fields[index + iteration // q].select( + row_axes(plan.active, size, q, iteration % q) + ) + ports.append(job) + frames[key] = iter(machine.native(tuple(ports), columns)) + elif op == ISSUE: + loan, size = args + job = next(frames[key]) + if len(job.axes) != size: + raise ValueError("A native cut issued the wrong rank") + loans[loan] = job + elif op == CLOSE: + if next(frames.pop(key), end) is not end: + raise ValueError("A native cut remained after the final return") + elif op == FINISH: + finish(loans.pop(key), args[0]) + else: + raise ValueError("The installed instruction is unknown") + if frames or loans: + raise ArithmeticError("The epoch left an open frame or loan") + for job in public: + finish(job, plan.active) + for job in reversed(fields[len(public) :]): + machine.retire_zero(job) diff --git a/research/single-band-native-carriers/independent_binary_price.py b/research/single-band-native-carriers/independent_binary_price.py new file mode 100644 index 0000000000..9cc55c5655 --- /dev/null +++ b/research/single-band-native-carriers/independent_binary_price.py @@ -0,0 +1,136 @@ +"""Reprice both binary words from the raw tapes using rational log and exp series.""" + +from collections import Counter +from fractions import Fraction +from functools import cache + + +GRID = 1 << 112 + + +def grid_bounds(lower, upper): + lo = lower * GRID + hi = upper * GRID + return Fraction(lo.__floor__(), GRID), Fraction(hi.__ceil__(), GRID) + + +@cache +def log_ratio(z): + """Enclose 2 atanh(z) by its positive series and a geometric tail.""" + assert 0 <= z <= Fraction(1, 3) + z2 = z * z + term = z + total = Fraction(0) + for j in range(45): + total += term / (2 * j + 1) + term *= z2 + return grid_bounds(2 * total, 2 * (total + term / (91 * (1 - z2)))) + + +@cache +def log_rank(rank): + """Reduce the argument to [1,2] before evaluation.""" + k = rank.bit_length() - 1 + radix = 1 << k + low, high = log_ratio(Fraction(rank - radix, rank + radix)) + log2low, log2high = log_ratio(Fraction(1, 3)) + return low + k * log2low, high + k * log2high + + +def small_exp(x): + """Use the first 32 terms and bound all later term ratios by x/33.""" + assert 0 <= x <= 1 + term = total = Fraction(1) + for j in range(1, 32): + term *= x / j + total += term + next_term = term * x / 32 + return grid_bounds(total, total + next_term / (1 - x / 33)) + + +@cache +def rank_price(rank, exponent): + low, high = log_rank(rank) + assert exponent >= 0 + a, _ = small_exp(low * exponent / 16) + _, b = small_exp(high * exponent / 16) + return grid_bounds(a**16, b**16) + + +def raw_moments(graph, caller): + ports = caller["ports"] + dims = {int(idx): frame["dim"] for idx, frame in graph["frames"].items()} + targets = Counter() + paid = Counter() + local = sum(row[0] == "LOCAL" for row in caller["events"]) + for row in caller["diagonal"]: + targets[1 + caller["body_rank"] * len(row["stages"])] += ports + for src, dst in zip(graph["start"][2 * ports :], graph["final"][2 * ports :], strict=True): + targets[abs(dims[dst] - dims[src])] += local + for row in graph["program"]: + if row[0] == "MOVE": + paid[abs(dims[row[3]] - dims[row[2]])] += local + for row in caller["events"]: + if row[0] == "QUERY": + paid[1] += ports + elif row[0] == "IDLE_ONE": + paid[len(row[2]) * caller["body_rank"]] += ports + assert targets.total() == 18_906 and paid.total() == 104_904 + return targets, paid + + +def mass(histogram, exponent, upper): + return sum(count * rank_price(rank, exponent)[upper] for rank, count in histogram.items()) + + +def independent_prices(graph, caller): + targets, paid = raw_moments(graph, caller) + profiles = ( + (128, 16, Fraction(2_039, 2**19), Fraction(13, 32), Fraction(1, 10_000)), + (228, 15, Fraction(17_108_907_955, 2**42), Fraction(31, 64), Fraction(1311, 10**13)), + ) + floors = [] + for v, keep, saving, w, required in profiles: + t, z = 1 - saving, Fraction(19, 64) + target = mass(targets, t, 0) + alpha = mass(paid, t, 1) / target + gamma = mass(paid, t + z, 1) / (rank_price(12, z)[0] * target) + lam = rank_price(keep, w)[1] * mass(targets, t - w, 1) / target + surplus = 1 - alpha**v - 2 * gamma**v - lam**v + assert surplus > required + if v == 228: + upper_target = mass(targets, t, 1) + lower_base = mass(paid, t, 0) / upper_target + old_drop = rank_price(16, w)[0] * mass(targets, t - w, 0) / upper_target + assert lower_base**v + old_drop**v > 1 + floors.append((surplus * 10**18).__floor__()) + crossing_limit(targets, paid) + return tuple(floors) + + +def crossing_limit(targets, paid): + """Bind the monotonicity proof to every signed coefficient of the literal word.""" + signed = { + r: targets[r] - paid[r] for r in targets.keys() | paid.keys() if targets[r] != paid[r] + } + expected = dict(enumerate((-48972, -44892, -1980, -900, -1044, -2916, -480), 1)) + expected.update({8: 14520, 64: 444, 127: 222}) + for low in range(14, 57, 7): + expected[low] = -444 + expected[low + 1] = 444 + assert signed == expected + upper = Fraction("0.0038901152866") + assert mass(paid, 1 - upper, 0) > mass(targets, 1 - upper, 1) + signed_rate_floor = Fraction("0.00389011527141") + Fraction(4, 10**14) + five_bit_floor = (5 / (upper - signed_rate_floor)).__floor__() + 1 + installed_floor = ( + 19 / (Fraction(17108907955, 2**42) - Fraction("0.003890115271496")) + ).__floor__() + 1 + assert (five_bit_floor, installed_floor) == (330033003301, 1455682013917) + print("PASS_BINARY_RANK_EXPONENT_FLOORS", five_bit_floor, installed_floor) + + +if __name__ == "__main__": + from strong_binary import caller, graph + + print("PASS_INDEPENDENT_BINARY_SURPLUS_X_1E18", *independent_prices(graph(), caller())) diff --git a/research/single-band-native-carriers/inputs/complex-source.json b/research/single-band-native-carriers/inputs/complex-source.json new file mode 100644 index 0000000000..6e1030bb2e --- /dev/null +++ b/research/single-band-native-carriers/inputs/complex-source.json @@ -0,0 +1,16 @@ +{ + "BANK-FACTORS.json.gz": "b009cd6bb13036879214cb6d43beb923578ef7fb4c83f36a1cc971ab4ea23543", + "BIDIRECTIONAL-QUOTIENT-RECEIPT.json": "459f519593242a3e8ecf42817f178fb214a6833e0df0e1ce727c5809035d02de", + "BIDIRECTIONAL-QUOTIENT.json.gz": "ed725d5c69a507352efc6a18f3e4f7e5c20592a655a7b80193034232feb43d6f", + "BIDIRECTIONAL.json.gz": "baf07c7085f588ce06201e2a6bf4f5f58632801202783ca195d3b8369ff74836", + "HELPER-SPLITS-RECEIPT.json": "712b783baf1463b738bd5c5ad3023bf42681d7d0105dd550ba3549c02674f711", + "HELPER-SPLITS.json": "f70ba89a9ed5839476bbe298d4cb8f4d9eeb703621d5f478c884861cdd91fb20", + "LAYOUT.json.gz": "84cd1d11ff454eecf3504e4b3f26adc371539b17553bfce1bcfda7a331811998", + "LICENSE": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4", + "PARENT-NOTICE": "b213998c8dae6d88e4a1f0fd17c81dd78c31ef35bc9460fa16ca692326f1a02b", + "WORD.json.gz": "731246c085638706bdb97e7e88618f8923e27ee4ce8eb4869f0847f8f4699f7c", + "replay.py": "9c847a1242e730acf1dfd3a83f4801470e3e2da6c3079f53ccb7ada620b37a7b", + "verify_bidirectional.py": "ef85db5c6f348b55e0db4d61517dde6a58b027737037e14b9fdea04f8b96e716", + "verify_component.py": "163b1ca3a35531da94ef454229f040592c754675f59dfb805d0a9aadb33b8d65", + "verify_split_helpers.py": "6a0b59657bd1902d19b9c0f8badef2caa13c8ba84e0311550d6391360bdf186b" +} diff --git a/research/single-band-native-carriers/inputs/complex-source/BANK-FACTORS.json.gz b/research/single-band-native-carriers/inputs/complex-source/BANK-FACTORS.json.gz new file mode 100644 index 0000000000..de611b5588 Binary files /dev/null and b/research/single-band-native-carriers/inputs/complex-source/BANK-FACTORS.json.gz differ diff --git a/research/single-band-native-carriers/inputs/complex-source/BIDIRECTIONAL-QUOTIENT-RECEIPT.json b/research/single-band-native-carriers/inputs/complex-source/BIDIRECTIONAL-QUOTIENT-RECEIPT.json new file mode 100644 index 0000000000..7606122e82 --- /dev/null +++ b/research/single-band-native-carriers/inputs/complex-source/BIDIRECTIONAL-QUOTIENT-RECEIPT.json @@ -0,0 +1,57 @@ +{ + "old_moves": 5680, + "moves": 5676, + "public": 1289, + "retired": 8, + "new_moves": 4, + "new_word": "9f055ab54604b1a56688138ef80c854a53f53d2fc3cab420b823ae58a92c10d3", + "forward_terms": 25106153, + "minimum_product_grid": "154113755636630124932500335624192000", + "literal_peak_bits": 57, + "adjoint_terms": 89136223, + "trial": "0.00391884648", + "trial_margin": [ + "-23.306408786869726116585221074", + "-23.306408786869726116585221073" + ], + "paid": { + "1": 183408, + "2": 38016, + "3": 23040, + "4": 10896, + "5": 15024, + "6": 2016, + "7": 432, + "8": 1344, + "16": 1248, + "24": 1248, + "32": 1248, + "40": 1248, + "48": 1248, + "56": 1248 + }, + "productive": { + "1": 960, + "2": 432, + "3": 432, + "4": 11568, + "5": 1584, + "7": 672, + "8": 1536, + "9": 25968, + "17": 1248, + "25": 1248, + "33": 1248, + "41": 1248, + "49": 1248, + "57": 1248, + "65": 1248, + "129": 624 + }, + "crossing_e14": [ + 389586937146, + 389586937147 + ], + "coefficient_edits": 126844, + "changed_rows": 771 +} diff --git a/research/single-band-native-carriers/inputs/complex-source/BIDIRECTIONAL-QUOTIENT.json.gz b/research/single-band-native-carriers/inputs/complex-source/BIDIRECTIONAL-QUOTIENT.json.gz new file mode 100644 index 0000000000..93b35fe944 Binary files /dev/null and b/research/single-band-native-carriers/inputs/complex-source/BIDIRECTIONAL-QUOTIENT.json.gz differ diff --git a/research/single-band-native-carriers/inputs/complex-source/BIDIRECTIONAL.json.gz b/research/single-band-native-carriers/inputs/complex-source/BIDIRECTIONAL.json.gz new file mode 100644 index 0000000000..3c91100fb0 Binary files /dev/null and b/research/single-band-native-carriers/inputs/complex-source/BIDIRECTIONAL.json.gz differ diff --git a/research/single-band-native-carriers/inputs/complex-source/HELPER-SPLITS-RECEIPT.json b/research/single-band-native-carriers/inputs/complex-source/HELPER-SPLITS-RECEIPT.json new file mode 100644 index 0000000000..f35d9f85be --- /dev/null +++ b/research/single-band-native-carriers/inputs/complex-source/HELPER-SPLITS-RECEIPT.json @@ -0,0 +1,54 @@ +{ + "splits": 2, + "moves": 5676, + "public": 1291, + "new_word": "a7a98bd3cd1044011ab62b103cb363d4ea6924f01340745e5a895ef650de953c", + "crossing_e14": [ + 389749436514, + 389749436515 + ], + "trial": "0.00391884648", + "trial_margin": [ + "-21.649081521690097244332831920", + "-21.649081521690097244332831919" + ], + "forward_terms": 25038131, + "adjoint_terms": 88780337, + "minimum_product_grid": "154113755636630124932500335624192000", + "literal_peak_bits": 57, + "paid": { + "1": 183408, + "2": 38016, + "3": 23040, + "4": 10896, + "5": 15024, + "6": 2016, + "7": 432, + "8": 1344, + "16": 1248, + "24": 1248, + "32": 1248, + "40": 1248, + "48": 1248, + "56": 1248 + }, + "productive": { + "1": 1008, + "2": 432, + "3": 480, + "4": 11568, + "5": 1584, + "6": 48, + "7": 672, + "8": 1584, + "9": 25872, + "17": 1248, + "25": 1248, + "33": 1248, + "41": 1248, + "49": 1248, + "57": 1248, + "65": 1248, + "129": 624 + } +} diff --git a/research/single-band-native-carriers/inputs/complex-source/HELPER-SPLITS.json b/research/single-band-native-carriers/inputs/complex-source/HELPER-SPLITS.json new file mode 100644 index 0000000000..a6225bf11b --- /dev/null +++ b/research/single-band-native-carriers/inputs/complex-source/HELPER-SPLITS.json @@ -0,0 +1,156 @@ +{ + "parent": "9f055ab54604b1a56688138ef80c854a53f53d2fc3cab420b823ae58a92c10d3", + "word": "a7a98bd3cd1044011ab62b103cb363d4ea6924f01340745e5a895ef650de953c", + "layout": "0ce3f9e383fc4bfdd22612b9e34fc9759d97204215937b82d23aec2cedd9b8ee", + "splits": [ + { + "role": 233, + "chart": 750, + "covector": [ + [3, "-1"], + [233, "1"], + [266, "2/3"], + [274, "-5/8"], + [299, "1"], + [308, "-10"], + [322, "2"], + [350, "3/2"], + [362, "-4"], + [364, "4"], + [402, "-1"], + [411, "1/3"], + [419, "2"], + [421, "5/4"], + [432, "4"], + [433, "2"], + [439, "-4"], + [440, "4"], + [441, "47/24"], + [450, "-1/12"], + [457, "-1"], + [459, "1/3"], + [462, "-2"], + [464, "3/2"], + [472, "-23/12"], + [482, "1"], + [488, "-2/3"], + [492, "1"], + [495, "-2/3"], + [501, "-1/2"], + [502, "3/4"], + [547, "3"], + [579, "1/3"], + [630, "-3"], + [645, "-3/4"], + [679, "1/2"], + [890, "1/2"], + [921, "1"], + [1025, "2"], + [1052, "2"], + [1064, "3"], + [1092, "-13/24"], + [1094, "2/3"], + [1115, "-17/4"], + [1118, "2/3"], + [1122, "-13/16"], + [1148, "-2"], + [1186, "-3/2"], + [1191, "21/2"], + [1224, "-2"], + [1227, "-2"], + [1236, "-2"] + ], + "direction": [ + [233, "-1/2"], + [894, "1/2"] + ], + "read": [ + [99004, "1"] + ], + "inject": [ + [105, "-1/2"], + [97761, "1"] + ] + }, + { + "role": 205, + "chart": 34, + "covector": [ + [205, "1"], + [234, "-1/4"], + [240, "2"], + [270, "1"], + [274, "7/24"], + [294, "4/3"], + [299, "1/6"], + [304, "-1/6"], + [308, "-1/3"], + [322, "-1/3"], + [328, "-2/3"], + [330, "-1/3"], + [335, "1/3"], + [350, "5/6"], + [358, "1/6"], + [375, "-4/3"], + [387, "-2/3"], + [394, "-1"], + [401, "4/3"], + [402, "-61/45"], + [410, "-1/6"], + [419, "-1"], + [421, "61/180"], + [432, "-2"], + [433, "2/3"], + [438, "1/3"], + [441, "-11/24"], + [450, "-43/12"], + [457, "2/3"], + [462, "-4/3"], + [464, "5/6"], + [472, "9/4"], + [478, "1/6"], + [482, "4/3"], + [485, "-1/6"], + [490, "1/3"], + [502, "-17/12"], + [503, "-1"], + [505, "4/3"], + [547, "5/3"], + [630, "-17/3"], + [634, "5/6"], + [645, "-5/12"], + [679, "-1/6"], + [890, "1/3"], + [913, "-4"], + [921, "1/3"], + [1003, "2/5"], + [1025, "-2/3"], + [1027, "-1"], + [1029, "-1/3"], + [1043, "11/3"], + [1049, "-4/3"], + [1052, "-4/3"], + [1064, "5/3"], + [1092, "1/24"], + [1115, "-11/12"], + [1122, "1/16"], + [1142, "-1"], + [1186, "1"], + [1191, "5/2"], + [1224, "2/3"], + [1227, "2/3"], + [1235, "-5/3"] + ], + "direction": [ + [205, "-1"] + ], + "read": [ + [89027, "1"] + ], + "inject": [ + [95, "-1"], + [94844, "1"] + ] + } + ] +} diff --git a/research/single-band-native-carriers/inputs/complex-source/LAYOUT.json.gz b/research/single-band-native-carriers/inputs/complex-source/LAYOUT.json.gz new file mode 100644 index 0000000000..3ee3637e63 Binary files /dev/null and b/research/single-band-native-carriers/inputs/complex-source/LAYOUT.json.gz differ diff --git a/research/single-band-native-carriers/inputs/complex-source/LICENSE b/research/single-band-native-carriers/inputs/complex-source/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/research/single-band-native-carriers/inputs/complex-source/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/research/single-band-native-carriers/inputs/complex-source/PARENT-NOTICE b/research/single-band-native-carriers/inputs/complex-source/PARENT-NOTICE new file mode 100644 index 0000000000..fe51894a1a --- /dev/null +++ b/research/single-band-native-carriers/inputs/complex-source/PARENT-NOTICE @@ -0,0 +1,31 @@ +Mixed paid cutoffs for the P104 ordinary BIT supplier + +Prepared for Clear1nsight with substantial OpenAI Codex assistance. The +new schedule, directed comparison, occurrence controls, and documentation +are offered under Apache-2.0. + +verify.py adapts the Apache-2.0 verifiers from Dugongue's PR #7831 +(2d1fb9c878ae1e292cb918de40fa8e4f7fa7f75e) and Rohan Arun's PR #7835 +(43007c979859fa84ccc3a3509ccacc9620d181fa). Rohan Arun submitted #7835 +through the original X request at +https://x.com/RohanArun/status/2123655584797143516. The source manifest +retains the published #7835 NOTICE. + +Retained predecessor NOTICE from the grade-14 package follows. + +Iterated returns on the P104 ordinary suppliers + +Clear1nsight prepared the successor construction, explicit witnesses and verification +with substantial OpenAI Codex assistance, including independent computational checks. +The new material is offered under Apache-2.0. + +The exact starting words and the rational and binary replay interfaces are from +Clear1nsight's PR #7781. The paid and productive scalar operations, the 48-call +complex schedule, the punctured binary supplier and the common outer application +come from Ali Romman's PR #7776. The two paid projections build on the local +quotient and terminal repair in #7774 and #7781. The binary paired caller and +finite compiler use work by DreamingOfClouds, Jerry Chen (CubeJerry), zxv and the +contributors cited in their retained sources. SYLforge, Rohan Arun, Cinna Davis, +Douglas Colkitt and other predecessors contributed the caller, physical and +analytic framework. The source-fetch helper is adapted from #7774. The immutable +source manifest identifies the public inputs and their notices. diff --git a/research/single-band-native-carriers/inputs/complex-source/WORD.json.gz b/research/single-band-native-carriers/inputs/complex-source/WORD.json.gz new file mode 100644 index 0000000000..31786df96c Binary files /dev/null and b/research/single-band-native-carriers/inputs/complex-source/WORD.json.gz differ diff --git a/research/single-band-native-carriers/inputs/complex-source/replay.py b/research/single-band-native-carriers/inputs/complex-source/replay.py new file mode 100644 index 0000000000..129817a60c --- /dev/null +++ b/research/single-band-native-carriers/inputs/complex-source/replay.py @@ -0,0 +1,267 @@ +"""Rebuild seven chart splits, one new helper and three removed transfers. Use Python 3.10 or later.""" +from argparse import ArgumentParser +from collections import Counter +from fractions import Fraction +from hashlib import sha256 +from math import gcd, lcm +from pathlib import Path +import gzip +import json +import sys + + +def encoded(value): + return json.dumps(value, sort_keys=True, separators=(",", ":")).encode() + + +def read(path): + raw = path.read_bytes() + return json.loads(gzip.decompress(raw) if raw[:2] == b"\x1f\x8b" else raw) + + +def require(condition, detail): + if not condition: + raise ValueError(detail) + + +def expected(layout, count, grid): + out = [{r: grid} for r in range(count)] + hosted = layout["hosted"] + for p, x in enumerate(layout["live"]): + y = x + 112 + if p in hosted["Dports"]: + out[y][x] = grid + else: + require(grid % 2 == 0, "odd main grid") + out[x][y] = -grid + out[y] = {x: grid // 2, y: grid // 2} + for x, y in zip(hosted["X2"], hosted["Y2"], strict=True): + out[x][y] = -grid + return out + + +def verify_integer_grid(net, graph, layout): + n = len(net.initial) + divisors = {~r: 1 for r in range(n)} + grid = 1 + peak_literal = 0 + for k in graph["schedule"]: + row_grid = 1 + for j, q in net.forms[k].items(): + peak_literal = max(peak_literal, q.numerator.bit_length(), q.denominator.bit_length()) + row_grid = lcm(row_grid, divisors[j] * q.denominator) + divisors[k] = row_grid + grid = lcm(grid, row_grid) + + ends = expected(layout, n, grid) + scalar = {~r: {r: grid} for r in range(n)} + checked = Counter() + common = grid + for k in graph["schedule"]: + row = {} + for j, q in net.forms[k].items(): + for c, value in scalar[j].items(): + term, remainder = divmod(q.numerator * value, q.denominator) + require(remainder == 0, f"inexact division at row {k}, donor {j}, column {c}") + common = gcd(common, term) + result = row.get(c, 0) + term + if result: + row[c] = result + else: + row.pop(c, None) + checked[q.denominator] += 1 + if k in net.moves: + scalar[k] = row + else: + require(row == ends[k-net.first_output], f"public output {k-net.first_output}") + return dict(path_grid=grid, minimum_product_grid=grid // common, literal_peak_bits=peak_literal, + products=sum(checked.values()), nontrivial_divisions=sum(checked.values())-checked[1], + by_denominator=dict(sorted(checked.items())), public_rows=n) + + +def add(row, donor, factor): + for index, value in donor.items(): + new = row.get(index, 0) + value * factor + if new: + row[index] = new + else: + row.pop(index, None) + + +def input_forms(net, labels): + needed = set(labels) + stack = list(needed) + while stack: + node = stack.pop() + for donor in net.forms[node]: + if donor >= 0 and donor not in needed: + needed.add(donor) + stack.append(donor) + signals = {} + for node in net.schedule(): + if node in needed: + row = {} + for donor, factor in net.forms[node].items(): + add(row, {donor: 1} if donor < 0 else signals[donor], factor) + signals[node] = row + return signals + + +def erase_return(net, event): + from network import Network + + move = event["move"] + calibration = event["calibration"] + pivot = event["pivot"] + receiver = event["receiver"] + sender = event["sender"] + initial = event["source"] + first = net.first_output + require(net.moves[move] == (sender, receiver), "erased move") + require(net.moves[calibration][1] == sender, "calibration receipt") + consumers = {k - first: row[move] for k, row in net.forms.items() if move in row} + require(consumers == {int(k): Fraction(v) for k, v in event["responses"].items()}, + "erased consumers") + require(all(net.initial[r] == initial and net.final[r] == receiver for r in consumers), + "helper endpoints") + form = input_forms(net, [calibration])[calibration] + require(all(net.initial[~i] == initial for i in form), "one calibration source") + pairing = sum(form.get(~r, 0) * value for r, value in consumers.items()) + require(pairing == 1, "calibration pairing") + lift = {i: -q / pairing for i, q in form.items() if i != ~pivot} + lift[~pivot] = 1 / pairing + rows = {} + for node, old in net.forms.items(): + if node == move: + continue + r = node - first + if r == pivot: + row = {calibration: 1} + else: + row = dict(old) + if r in consumers: + add(row, net.forms[first + pivot], -consumers[r] / consumers[pivot]) + require(move not in row, "erasure cancellation") + factor = sum(row.get(~r, 0) * q for r, q in consumers.items()) + row.pop(~pivot, None) + add(row, lift, factor) + rows[node] = row + moves = dict(net.moves) + del moves[move] + final = list(net.final) + final[pivot] = sender + return Network(first, list(net.initial), final, moves, rows) + + +def restrict_source(net, layout, event): + from network import Network + + first = net.first_output + pivot = event["pivot"] + last = len(net.initial) - 1 + require(last == 1289 and net.initial[pivot] == event["initial"] and net.final[pivot] == event["final"], + "old helper stock") + first_leg, second_leg = (entry["move"] for entry in event["receipts"]) + require(net.moves[first_leg] == (event["initial"], event["via"]) and + net.moves[second_leg] == (event["via"], event["final"]), "paid chain") + local = {entry["move"]: {i: Fraction(q) for i, q in entry["donors"]} + for entry in event["receipts"]} + values = input_forms(net, set(local) | {i for row in local.values() for i in row}) + relations = {} + for node, replacement in local.items(): + row = dict(values[node]) + for donor, amount in replacement.items(): + add(row, values[donor], -amount) + relations[node] = row + source = relations[first_leg] + require(source == {j: Fraction(event["proportion"]) * value for j, value in relations[second_leg].items()}, + "proportional source relations") + require(len(source) == event["support"] and all(net.initial[~j] == event["initial"] for j in source), + "one source chart") + divisor = source[~pivot] + require(divisor == Fraction(event["pivot_coefficient"]), "source pivot") + rewrites = dict(local) + rewrites[~pivot] = {j: -v / divisor for j, v in source.items() if j != ~pivot} + rows = {} + for node, row in net.forms.items(): + if node in local or node == first + pivot: + continue + out = {j: v for j, v in row.items() if j not in rewrites} + for donor in row.keys() & rewrites.keys(): + add(out, rewrites[donor], row[donor]) + if ~last in out: + out[~pivot] = out.pop(~last) + rows[first + pivot if node == first + last else node] = out + + def pack(sequence): + result = list(sequence[:-1]) + result[pivot] = sequence[last] + return result + + moves = {k: chart for k, chart in net.moves.items() if k not in local} + require(layout["public"] == last + 1 and layout["source_labels"][last] == 1542, + "public layout") + updated = dict(layout, public=last, source_labels=pack(layout["source_labels"])) + return Network(first, pack(net.initial), pack(net.final), moves, rows), updated + + +def replay(source, layout, journal, engines): + require(sha256(encoded(source)).hexdigest() == journal["source"], "source word pin") + require(sha256(encoded(layout)).hexdigest() == journal["layout"], "source layout pin") + for name, digest in journal["semantic_modules"].items(): + require(sha256((engines / name).read_bytes()).hexdigest() == digest, name) + sys.path[:0] = [str(engines), str(engines / "retained" / "vendor")] + from network import Network + from public_split import split + from birth_event import apply_split + + net = Network(source["first_output"], source["initial"], source["final"], + {k: (a, b) for k, a, b in source["moves"]}, + {k: {i: Fraction(v) for i, v in row} for k, row in source["forms"]}) + for e in journal["splits"]: + net = split(net, e) + net.schedule() + e = journal["subdivide"] + k, j, chart = e["move"], e["new"], e["through"] + a, b = net.moves[k] + require([a, b] == e["original"] and j not in net.moves, "carrier preimage") + moves = dict(net.moves) + forms = dict(net.forms) + moves[j], moves[k] = (a, chart), (chart, b) + forms[j], forms[k] = forms[k], {j: Fraction(1)} + net = apply_split(Network(net.first_output, net.initial, net.final, moves, forms), journal["birth"]) + layout = dict(layout, public=len(net.initial), + source_labels=[*layout["source_labels"], journal["birth_source_label"]]) + net = erase_return(net, journal["erasure"]) + net, layout = restrict_source(net, layout, journal["quotient"]) + require(sha256(encoded(layout)).hexdigest() == journal["child_layout_sha256"], "child layout pin") + graph = dict(first_output=net.first_output, initial=net.initial, final=net.final, frames=source["frames"], + moves=[[k, *pair] for k, pair in sorted(net.moves.items())], + forms=[[k, [[i, str(q)] for i, q in sorted(row.items())]] for k, row in sorted(net.forms.items())], + schedule=net.schedule()) + digest = sha256(encoded(graph)).hexdigest() + require(digest == journal["canonical_sha256"], "child word pin") + audit = verify_integer_grid(net, graph, layout) + return graph, dict(word_sha256=digest, **audit) + + +def main(): + parser = ArgumentParser(description=__doc__) + parser.add_argument("--source", required=True, type=Path) + parser.add_argument("--layout", required=True, type=Path) + parser.add_argument("--engines", required=True, type=Path) + parser.add_argument("--journal", type=Path, default=Path(__file__).with_name("EVENTS.json")) + parser.add_argument("--write-word", type=Path) + parser.add_argument("--write-audit", type=Path) + args = parser.parse_args() + require(sys.flags.optimize == 0, "the source engines use assertions") + graph, audit = replay(read(args.source), read(args.layout), read(args.journal), args.engines) + if args.write_word: + args.write_word.write_bytes(gzip.compress(encoded(graph), mtime=0)) + if args.write_audit: + args.write_audit.write_text(json.dumps(audit, sort_keys=True, indent=2)+"\n") + print(json.dumps(audit, sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/research/single-band-native-carriers/inputs/complex-source/verify_bidirectional.py b/research/single-band-native-carriers/inputs/complex-source/verify_bidirectional.py new file mode 100644 index 0000000000..dad4414718 --- /dev/null +++ b/research/single-band-native-carriers/inputs/complex-source/verify_bidirectional.py @@ -0,0 +1,152 @@ +"""Rebuild the rational circuit and replay its scalar map and caller tariff.""" +import argparse +from collections import Counter +from fractions import Fraction +from functools import cache +from graphlib import TopologicalSorter +from math import gcd, lcm +from pathlib import Path +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from verify_component import canonical, check, check_decrease, expected_columns, factor, inspect, margin, read + + +@cache +def rational(text): + return Fraction(text) + + +def reconstruct(parent, delta): + check(canonical(parent) == delta["parent"], "parent word") + moves = {k: (a, b) for k, a, b in parent["moves"]} + forms = {k: dict(row) for k, row in parent["forms"]} + for k in delta["removed"]: + del moves[k], forms[k] + for k, a, b in delta["moves"]: + check(k not in forms, "new transfer label") + moves[k], forms[k] = (a, b), {} + + differences = {} + literals = {} + for k, kind, entries in delta["differences"]: + check(k not in differences and k in forms, "changed coefficient row") + weights = {j: rational(s) for j, s in entries} + check(len(weights) == len(entries) and all(weights.values()), "distinct nonzero weights") + if kind == "add": + change = weights + literals[k] = change + else: + check(kind == "combine", "difference format") + change = {} + for j, weight in weights.items(): + for donor, value in literals[j].items(): + change[donor] = change.get(donor, 0) + weight * value + change = {j: v for j, v in change.items() if v} + differences[k] = len(change) + row = forms[k] + for j, v in change.items(): + coefficient = rational(row.get(j, "0")) + v + if coefficient: + row[j] = str(coefficient) + else: + del row[j] + deps = {k: tuple(j for j in sorted(row) if j >= 0) for k, row in sorted(forms.items())} + word = dict(parent, forms=[[k, sorted(row.items())] for k, row in sorted(forms.items())], + moves=[[k, a, b] for k, (a, b) in sorted(moves.items())], + schedule=list(TopologicalSorter(deps).static_order())) + check(canonical(word) == delta["word"], "reconstructed word") + return word, sum(differences.values()) + + +def forward(word, layout): + """Check all terminal rows. Find the smallest grid that contains every scalar product.""" + n, first = len(word["initial"]), word["first_output"] + columns, _ = expected_columns(layout, n) + want = [{} for _ in range(n)] + for i, column in enumerate(columns): + for j, fraction in column.items(): + want[j][i] = Fraction(*fraction) + rows = dict(word["forms"]) + stock = {~i: ({i: 1}, 1, 1) for i in range(n)} + uses = Counter(j for row in rows.values() for j, _ in row) + grid = literal_bits = 1 + products = 0 + for k in word["schedule"]: + terms = [] + divisor = 1 + for j, s in rows[k]: + num, den = factor(s) + literal_bits = max(literal_bits, num.bit_length(), den.bit_length()) + values, source_den, content = stock[j] + total_den = den * source_den + grid = lcm(grid, total_den // gcd(total_den, num * content)) + terms.append((values, num, total_den)) + divisor = lcm(divisor, total_den) + uses[j] -= 1 + if not uses[j]: + del stock[j] + result = {} + for values, num, den in terms: + products += len(values) + multiple = num * (divisor // den) + for i, v in values.items(): + result[i] = result.get(i, 0) + multiple * v + result = {i: v for i, v in result.items() if v} + if first <= k < first + n: + check(result.keys() == want[k-first].keys() and + all(v == divisor * want[k-first][i] for i, v in result.items()), f"terminal row {k-first}") + else: + content = gcd(*result.values()) + common = gcd(content, divisor) + stock[k] = ({i: v // common for i, v in result.items()}, divisor // common, content // common) + return products, grid, literal_bits + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--quotient", action="store_true", help="check the four-term quotient on the rebuilt parent") + args = parser.parse_args() + parent = read("WORD.json.gz") + check(canonical(parent) == read("RATIONAL-RECEIPT.json")["word"], "initial word") + prefix = "BIDIRECTIONAL" + if args.quotient: + parent, _ = reconstruct(parent, read("BIDIRECTIONAL.json.gz")) + check(canonical(parent) == read("BIDIRECTIONAL-RECEIPT.json")["new_word"], "intermediate word") + prefix = "BIDIRECTIONAL-QUOTIENT" + verify_step(parent, prefix) + + +def verify_step(parent, prefix, layout=None): + delta = read(prefix + ".json.gz") + receipt = read(prefix + "-RECEIPT.json") + word, edits = reconstruct(parent, delta) + check(delta["word"] == receipt["new_word"] and len(word["moves"]) == receipt["moves"], "word and charge count") + check(len(parent["moves"]) == receipt["old_moves"] and len(delta["removed"]) == receipt["retired"] + and len(delta["moves"]) == receipt["new_moves"], "changed transfers") + check(edits == receipt["coefficient_edits"] and len(delta["differences"]) == receipt["changed_rows"], + "coefficient count") + check_circuit(word, receipt, read("LAYOUT.json.gz") if layout is None else layout) + return word + + +def check_circuit(word, receipt, layout): + work, grid, bits = forward(word, layout) + check([work, grid, bits] == [receipt["forward_terms"], int(receipt["minimum_product_grid"]), + receipt["literal_peak_bits"]], "forward precision and work") + paid, targets, adjoint = inspect(word, layout, read("CALLER-CENSUS.json")) + check(adjoint == receipt["adjoint_terms"] and len(word["initial"]) == receipt["public"], "adjoint census") + for name, bins in (("paid", paid), ("productive", targets)): + check({str(k): v for k, v in bins.items()} == receipt[name], name) + lower, upper = [Fraction(v, 10**14) for v in receipt["crossing_e14"]] + check(margin(paid, targets, lower)[0] > 0 and margin(paid, targets, upper)[1] < 0, "crossing signs") + check_decrease(paid, targets) + lo, hi = margin(paid, targets, receipt["trial"]) + a, b = map(Fraction, receipt["trial_margin"]) + check(a <= lo <= hi <= b < 0, "trial margin") + print(f"PASS {len(word['moves'])} transfers, {work} forward products, {adjoint} adjoint terms, " + f"{len(word['initial'])} independent fields and both crossing signs") + + +if __name__ == "__main__": + main() diff --git a/research/single-band-native-carriers/inputs/complex-source/verify_component.py b/research/single-band-native-carriers/inputs/complex-source/verify_component.py new file mode 100644 index 0000000000..6f2aff9a04 --- /dev/null +++ b/research/single-band-native-carriers/inputs/complex-source/verify_component.py @@ -0,0 +1,189 @@ +"""Check the rational graph over every input and price its 48 calls.""" +from collections import Counter, defaultdict +from fractions import Fraction +from functools import cache +from hashlib import sha256 +from math import gcd, isqrt, lcm +from pathlib import Path +import gzip +import json + + +ROOT = Path(__file__).resolve().parent +SCALE = 1 << 192 + + +def check(condition, message): + if not condition: + raise ValueError(message) + + +def read(name): + raw = (ROOT / name).read_bytes() + return json.loads(gzip.decompress(raw) if name.endswith(".gz") else raw) + + +def canonical(value): + return sha256(json.dumps(value, sort_keys=True, separators=(",", ":")).encode()).hexdigest() + + +@cache +def factor(text): + value = Fraction(text) + return value.numerator, value.denominator + + +def frame_span(basis): + points = {0} + for vector in basis: + check(0 < vector < 512 and vector not in points, "invalid frame basis") + points.update([old ^ vector for old in points]) + return points + + +def expected_columns(layout, n): + expected = [{i: (1, 1)} for i in range(n)] + main = set() + hosted = layout["hosted"] + for port, x in enumerate(layout["live"]): + y = x + 112 + main.update((x, y)) + if port in hosted["Dports"]: + expected[x][y] = (1, 1) + else: + expected[x][y] = (1, 2) + expected[y] = {x: (-1, 1), y: (1, 2)} + for x, y in zip(hosted["X2"], hosted["Y2"], strict=True): + main.update((x, y)) + expected[y][x] = (-1, 1) + check(len(main) == 400, "main role count") + return expected, main + + +def inspect(word, layout, caller): + starts, ends = word["initial"], word["final"] + n = len(starts) + check(len(ends) == n == layout["public"] == len(layout["source_labels"]), "endpoint count") + check(word["frames"] == layout["frames"], "layout frames") + expected, main = expected_columns(layout, n) + rank = [len(f) for f in word["frames"]] + spans = list(map(frame_span, word["frames"])) + moves = {k: (a, b) for k, a, b in word["moves"]} + graph = dict(word["forms"]) + order = word["schedule"] + first = word["first_output"] + outputs = set(range(first, first + n)) + check(len(moves) == len(word["moves"]) and moves.keys().isdisjoint(outputs), "paid labels") + check(len(order) == len(graph) == len(word["forms"]), "row count") + check(set(order) == graph.keys() == moves.keys() | outputs, "schedule coverage") + + def grade(a, b): + check(spans[a] < spans[b] or spans[b] < spans[a], "strictly nested charts") + return abs(rank[b] - rank[a]) + + calls = caller["calls"] + paid = Counter({int(k): v for k, v in caller["fixed_caller_paid"].items()}) + targets = Counter({int(k): v for k, v in caller["fixed_root_targets"].items()}) + for i, (a, b) in enumerate(zip(starts, ends, strict=True)): + if i not in main: + targets[grade(a, b)] += calls + + bank = {~i: a for i, a in enumerate(starts)} + consumers = defaultdict(list) + for k in order: + a = moves[k][0] if k in moves else ends[k - first] + for donor, text in graph[k]: + check(bank[donor] == a, f"donor chart at {k}") + num, den = factor(text) + consumers[donor].append((k, num, den)) + if k in moves: + a, b = moves[k] + paid[grade(a, b)] += calls + bank[k] = b + + # Store a common positive denominator for every sparse adjoint row. + back = {first + i: ({i: 1}, 1) for i in range(n)} + terms = 0 + keys = [k for k in reversed(order) if k in moves] + [~i for i in range(n)] + for k in keys: + users = consumers[k] + common = lcm(*(den * back[j][1] for j, num, den in users)) + row = {} + for j, num, den in users: + values, divisor = back[j] + scale = num * (common // (den * divisor)) + for i, value in values.items(): + row[i] = row.get(i, 0) + scale * value + terms += len(values) + divisor = gcd(common, *row.values()) + back[k] = ({i: v // divisor for i, v in row.items() if v}, common // divisor) + for i, want in enumerate(expected): + row, divisor = back[~i] + check(row.keys() == want.keys(), f"column support at {i}") + check(all(v * want[j][1] == divisor * want[j][0] for j, v in row.items()), f"column {i}") + return paid, targets, terms + + +def price(rank, saving): + # Enclose rank**saving by successive integer square roots. Each bit + # selects the next positive root. The last root bounds the full tail. + lo = hi = rank * SCALE + product_lo = product_hi = SCALE + rem = Fraction(saving) + for _ in range(152): + lo = isqrt(lo * SCALE) + hi = 1 + isqrt(hi * SCALE - 1) + rem *= 2 + if rem >= 1: + rem -= 1 + product_lo = product_lo * lo // SCALE + product_hi = (product_hi * hi + SCALE - 1) // SCALE + if rem: + product_hi = (product_hi * hi + SCALE - 1) // SCALE + mass = rank * SCALE * SCALE + return mass // product_hi, (mass + product_lo - 1) // product_lo + + +def margin(paid, targets, saving): + lo = hi = 0 + for rank in targets.keys() | paid.keys(): + count = targets[rank] - paid[rank] + a, b = price(rank, saving) + lo += min(count * a, count * b) + hi += max(count * a, count * b) + return Fraction(lo, SCALE), Fraction(hi, SCALE) + + +def check_decrease(paid, targets): + # Bound the derivative divided by ln(2) from above on [0, 0.004]. + derivative = 0 + for rank in paid.keys() | targets.keys(): + count = targets[rank] - paid[rank] + if count > 0: + derivative -= count * (rank.bit_length() - 1) * price(rank, "0.004")[0] + else: + derivative -= count * (rank - 1).bit_length() * rank * SCALE + check(derivative < 0, "strict decrease on the comparison interval") + + +def main(): + word = read("WORD.json.gz") + layout = read("LAYOUT.json.gz") + receipt = read("RATIONAL-RECEIPT.json") + check(canonical(word) == receipt["word"] == read("EVENTS.json")["canonical_sha256"], "word pin") + check(canonical(layout) == read("EVENTS.json")["child_layout_sha256"], "layout pin") + paid, targets, terms = inspect(word, layout, read("CALLER-CENSUS.json")) + check(terms == receipt["adjoint_terms"] and len(word["initial"]) == receipt["public"], "adjoint census") + for name, bins in (("paid", paid), ("productive", targets)): + check({str(k): v for k, v in bins.items()} == receipt[name], name) + lower, upper = map(Fraction, receipt["crossing"]) + check(margin(paid, targets, lower)[0] > 0 and margin(paid, targets, upper)[1] < 0, "crossing signs") + check_decrease(paid, targets) + probe = margin(paid, targets, "0.00391884648") + left, right = map(Fraction, receipt["target_margin"]) + check(left <= probe[0] <= probe[1] <= right < 0, "target interval") + print(f"PASS {receipt['public']} columns, {terms} adjoint terms, both crossing signs and the target deficit") + + +if __name__ == "__main__": + main() diff --git a/research/single-band-native-carriers/inputs/complex-source/verify_split_helpers.py b/research/single-band-native-carriers/inputs/complex-source/verify_split_helpers.py new file mode 100644 index 0000000000..d596f75f1f --- /dev/null +++ b/research/single-band-native-carriers/inputs/complex-source/verify_split_helpers.py @@ -0,0 +1,95 @@ +"""Rebuild two helper splits and check the resulting rational program.""" +from fractions import Fraction +from graphlib import TopologicalSorter +from pathlib import Path +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from replay import add +from verify_bidirectional import canonical, check, check_circuit, read, reconstruct, verify_step + + +def split(word, event): + first = word["first_output"] + initial, final = word["initial"].copy(), word["final"].copy() + role, chart = event["role"], event["chart"] + fresh = len(initial) + check((initial[role], final[role]) == (3, 127), "old helper endpoints") + + def load_row(entries): + return {i: Fraction(q) for i, q in entries} + + rows = {k: load_row(entries) for k, entries in word["forms"]} + s, w = load_row(event["covector"]), load_row(event["direction"]) + pairing = sum(s.get(i, 0) * v for i, v in w.items()) + check(pairing and w.get(role), "nonzero helper pivots") + substitute = {~i: -v / pairing for i, v in s.items() if i != role} + substitute[~role] = 1 / pairing + + def change_source(row): + coefficient = sum(row.get(~i, 0) * v for i, v in w.items()) + row.pop(~role, None) + if coefficient: + add(row, substitute, coefficient) + + for row in rows.values(): + change_source(row) + observed = load_row(event["read"]) + change_source(observed) + difference = {~fresh: 1 / pairing} + add(difference, observed, -1 / pairing) + for k, coefficient in load_row(event["inject"]).items(): + add(rows[k], difference, coefficient) + + recovered = {} + for i, v in s.items(): + add(recovered, rows[first + i], v) + old_return = rows[first + role] + for i, v in w.items(): + if i != role: + add(rows[first + i], old_return, -v / w[role]) + rows[first + role] = observed + rows[first + fresh] = recovered + initial.append(chart) + final.append(final[role]) + final[role] = chart + deps = {k: tuple(j for j in sorted(row) if j >= 0) for k, row in sorted(rows.items())} + return dict(word, initial=initial, final=final, schedule=list(TopologicalSorter(deps).static_order()), + forms=[[k, [[j, str(q)] for j, q in sorted(row.items())]] for k, row in sorted(rows.items())]) + + +def rebuild(check_parents=False): + parent = read("WORD.json.gz") + for name in ("BIDIRECTIONAL", "BIDIRECTIONAL-QUOTIENT"): + if check_parents: + parent = verify_step(parent, name) + else: + parent, _ = reconstruct(parent, read(name + ".json.gz")) + journal, receipt = read("HELPER-SPLITS.json"), read("HELPER-SPLITS-RECEIPT.json") + check(canonical(parent) == journal["parent"] == read("BIDIRECTIONAL-QUOTIENT-RECEIPT.json")["new_word"], + "split parent") + events = journal["splits"] + check(len(events) == receipt["splits"], "split count") + word = parent + for event in events: + word = split(word, event) + check(canonical(word) == journal["word"] == receipt["new_word"], "split word") + check(word["moves"] == parent["moves"] and len(word["moves"]) == receipt["moves"], "shared paid transfers") + layout = read("LAYOUT.json.gz") + labels = layout["source_labels"] + first_label = max(labels) + 1 + layout = dict(layout, public=len(word["initial"]), + source_labels=[*labels, *range(first_label, first_label + len(events))]) + check(canonical(layout) == journal["layout"], "new public labels") + return word, layout + + +def main(): + word, layout = rebuild(check_parents=True) + receipt = read("HELPER-SPLITS-RECEIPT.json") + check_circuit(word, receipt, layout) + verify_step(word, "BANK-FACTORS", layout) + + +if __name__ == "__main__": + main() diff --git a/research/single-band-native-carriers/inputs/new-charts.json.gz b/research/single-band-native-carriers/inputs/new-charts.json.gz new file mode 100644 index 0000000000..04d818a87c Binary files /dev/null and b/research/single-band-native-carriers/inputs/new-charts.json.gz differ diff --git a/research/single-band-native-carriers/inputs/review.json b/research/single-band-native-carriers/inputs/review.json new file mode 100644 index 0000000000..be3441d8eb --- /dev/null +++ b/research/single-band-native-carriers/inputs/review.json @@ -0,0 +1,32 @@ +{ + "check_complex.py": { + "commit": "a7f99a5f5f919dd3ffb2987f90c1e7d6527feb1e", + "path": "research/grade14-native-realization/check_complex.py", + "sha256": "ce8dc94ccc9fc780b991aad35aceba03b95335f9fd5b77235deb9e1a7f52e9f8" + }, + "check_periodic.py": { + "commit": "3f7c3c1f2a9a0963736562037e01fe41aec46b8c", + "path": "research/bounded-general-multiplier/check_periodic.py", + "sha256": "c1a5c81b5a4121498886758dd021ffdaa237c9fdc6e71e0d315a80947edc70d5" + }, + "check_powered.py": { + "commit": "3f7c3c1f2a9a0963736562037e01fe41aec46b8c", + "path": "research/bounded-general-multiplier/check_powered.py", + "sha256": "fc81d8d652b4290f473874114f72d4c7c8213ee4f26f5be8968894e01f786c35" + }, + "clifford_exact.py": { + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/shared-wire-split-composition/frozen/clifford_exact.py", + "sha256": "2982ead07721e83358dc67c6f49c2b4c16a236a6bebdfd72f58221be1f5d0962" + }, + "graph_identity.py": { + "commit": "a7f99a5f5f919dd3ffb2987f90c1e7d6527feb1e", + "path": "research/grade14-native-realization/graph_identity.py", + "sha256": "90440581667a00a8e0a8e02a8a5a196a88dc0edb48eb8e89c22603e615524681" + }, + "native_verify.py": { + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/shared-wire-split-composition/frozen/native_verify.py", + "sha256": "3049471905b47b385c88378a1a3be7a18b8858aadd035b8a6da2f4a03b470f38" + } +} diff --git a/research/single-band-native-carriers/inputs/review/check_complex.py b/research/single-band-native-carriers/inputs/review/check_complex.py new file mode 100644 index 0000000000..e1c0793e65 --- /dev/null +++ b/research/single-band-native-carriers/inputs/review/check_complex.py @@ -0,0 +1,185 @@ +"""Verify the complete complex supplier in its positive-child normalization.""" + +from collections import Counter +from functools import reduce +from hashlib import sha256 +from operator import xor +from pathlib import Path +import json +import sys + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE), str(HERE / "retained")] +from charts import action, encode, monomial_records, native_catalogue, packed, require +from contacts import contact_receipt +from graph_identity import graph_identity +from closed_caller import placement, templates +from mixed_caller import instructions, layout_bindings +from mixed_grid import exact + +DATA = HERE / "retained/data" + + +def all_images(atlas): + all_bits = (1 << 512) - 1 + digits = [sum(1 << x for x in range(512) if x >> i & 1) for i in range(9)] + factors = [m for _, _, r in atlas["pairs"] for m in (r["left"], r["right"])] + factors.extend(m for _, a, b in atlas["ports"] for m in (a, b)) + unique = {encode(m): m for m in factors} + maximum = 0 + for m in unique.values(): + ops = monomial_records(m) + maximum = max( + maximum, + sum( + row[2] if row[0] == "S" else row[1] if row[0] == "I" else 1 + for row in ops + ), + ) + wires = digits.copy() + lo = hi = 0 + for op, *a in ops: + i = a[0] + if op == "ROW": + wires[i] ^= wires[a[1]] + elif op == "NOT": + wires[i] ^= all_bits + elif op == "CZ": + hi ^= wires[i] & wires[a[1]] + else: + term, times = (wires[i], a[1]) if op == "S" else (all_bits, i) + for _ in range(times): + hi ^= lo & term + lo ^= term + want = [ + reduce(xor, (v for j, v in enumerate(digits) if row >> j & 1), 0) + ^ (all_bits if m["offset"] >> i & 1 else 0) + for i, row in enumerate(m["matrix_rows"]) + ] + require(wires == want, "all 512 affine addresses") + even = all_bits if m["phase"] & 2 else 0 + odd = all_bits if m["phase"] & 1 else 0 + for j, b in enumerate(digits): + c = m["linear_Z4"][j] + if c & 1: + even ^= odd & b + odd ^= b + if c & 2: + even ^= b + for k in range(j + 1, 9): + if m["quadratic_rows"][j] >> k & 1: + even ^= b & digits[k] + require((lo, hi) == (odd, even), "all 512 absolute phases") + require(maximum <= 171, "monomial tariff") + rec = next(r["right"] for a, b, r in atlas["pairs"] if (a, b) == (0, 249)) + require( + rec["phase"] == 1 and action(monomial_records(rec), (0,) * 9 + (3,), 2)[1] == 2, + "two-column absolute phase", + ) + return dict( + factor_occurrences=len(factors), + distinct_factors=len(unique), + basis_images=512 * len(unique), + maximum_factor_records=maximum, + ) + + +def completed_caller(graph, layout): + source = packed(DATA / "CALLER.json.gz") + words, roots = templates(source), placement(source) + bound, offsets, owners = layout_bindings(words, roots, layout, 48) + targets = Counter() + paid = Counter() + for events, diagonal in words.values(): + certificate = exact(events, diagonal, 2025 << 9) + require( + exact(events, diagonal, certificate["minimum_grid"]) == certificate, + "exact signed native caller", + ) + for root, visits in roots.items(): + colors = [t % 16 for t, _ in visits] + require(sorted(colors) == list(range(16)), "complete fresh bodies") + for sign, entries in words[root[0]][1]: + require( + sign in (-1, 1) and len(set(entries)) == len(entries), + "whole root output", + ) + targets[1 + 8 * len(entries)] += 1 + digest = sha256() + calls = normalizers = events_count = 0 + for row in instructions(words, roots, bound, offsets): + digest.update(json.dumps(row, separators=(",", ":")).encode()) + events_count += 1 + op = row[0] + if op == "QUERY": + paid[1] += 1 + elif op.startswith("IDLE_"): + paid[8 * len(row[2]) + int(op == "IDLE_ODD")] += 1 + elif op == "NATIVE": + calls += 1 + elif op == "LAMBDA": + normalizers += 1 + mains = ( + set(layout["live"]) + | {i + 112 for i in layout["live"]} + | set(layout["hosted"]["X2"]) + | set(layout["hosted"]["Y2"]) + ) + dims = list(map(len, graph["frames"])) + for _, a, b in graph["moves"]: + paid[abs(dims[a] - dims[b])] += calls + for i, (a, b) in enumerate(zip(graph["initial"], graph["final"], strict=True)): + if i not in mains: + targets[dims[b] - dims[a]] += calls + price = json.loads((HERE / "retained/grade14-audit.json").read_bytes()) + require( + digest.hexdigest() == price["signed"]["caller_sha256"], + "chronological source digest", + ) + require( + dict(paid) == {int(k): v for k, v in price["signed"]["paid"].items()} + and dict(targets) + == {int(k): v for k, v in price["signed"]["productive"].items()}, + "complete signed price", + ) + return dict( + events=events_count, + calls=calls, + normalizers=normalizers, + main_bindings=owners["native_main_bindings"], + targets=sum(targets.values()), + paid=sum(paid.values()), + ) + + +def run(): + graph, layout = [packed(DATA / f) for f in ("complex.json.gz", "layout.json.gz")] + receipt = json.loads((HERE / "retained/grade14-result.json").read_bytes()) + require( + sha256(encode(graph)).hexdigest() == receipt["rational_word"], + "priced rational word", + ) + atlas = native_catalogue(graph, layout, packed(HERE / "complex-atlas.json.gz")) + result = dict( + relative_pairs=len(atlas["pairs"]), + ports=len(atlas["ports"]), + atlas_sha256=sha256(encode(atlas)).hexdigest(), + factors=all_images(atlas), + graph=graph_identity(graph, layout), + caller=completed_caller(graph, layout), + phases=contact_receipt( + layout, json.loads((DATA / "CALLER-PHASE-BASES.json").read_bytes())["by_q"] + ), + ) + return result + + +if __name__ == "__main__": + result = run() + if "--emit" not in sys.argv: + require( + result == json.loads((HERE / "RESULT.json").read_bytes())["complex"], + "frozen complex evidence", + ) + print(json.dumps(result, sort_keys=True)) + print("PASS_GRADE14_ALL_COLUMN_COMPLEX") diff --git a/research/single-band-native-carriers/inputs/review/check_periodic.py b/research/single-band-native-carriers/inputs/review/check_periodic.py new file mode 100644 index 0000000000..f18ce6df23 --- /dev/null +++ b/research/single-band-native-carriers/inputs/review/check_periodic.py @@ -0,0 +1,210 @@ +"""Check literal row addresses, complete complex phase, weighted BIT and ownership.""" + +from collections import Counter +from random import Random +from pathlib import Path +import sys +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from periodic import Job, Rule, make_planner, period, row_axes, run + + +class Machine: + def __init__(self, rule, partition): + self.rule = rule + self.partition = partition + assert tuple(sum(splits) for splits in partition) == rule.targets + assert tuple(r for splits in partition for r in splits) == rule.paid + self.next_owner = -1 + self.data = {} + self.geometry = {} + self.frames = self.issued = self.leaves = self.zeros = self.freed = 0 + + def native(self, ports, columns): + assert len({p.owner for p in ports}) == len(ports) + self.frames += 1 + for p, splits, target in zip(ports, self.partition, self.rule.targets, strict=True): + assert len(p.axes) == target * columns and len(set(p.axes)) == len(p.axes) + cursor = 0 + for split in splits: + width = split * columns + self.issued += 1 + yield Job(p.owner, p.axes[cursor:cursor + width]) + cursor += width + assert cursor == len(p.axes) + + def zero(self, exemplar): + n = self.geometry[exemplar.owner] + owner = self.next_owner + self.next_owner -= 1 + self.zeros += 1 + self.data[owner] = self.initial(owner, n) + self.geometry[owner] = n + return Job(owner, exemplar.axes) + + def retire_zero(self, job): + state = self.data.pop(job.owner) + self.geometry.pop(job.owner) + assert job.owner < 0 and self.is_zero(state) + self.freed += 1 + + +def sweep(machine, n, *, axes=None): + rule = machine.rule + planner = make_planner(rule) + p = planner(n) + fields = [Job(i, tuple(axes[i]) if axes is not None else tuple(range(n))) + for i in range(p.width)] + for field in fields: + machine.data[field.owner] = machine.initial(field.owner, n) + machine.geometry[field.owner] = n + run(rule, n, fields, machine, planner=planner) + assert machine.leaves == p.leaves and machine.zeros == machine.freed + assert set(machine.data) == set(range(p.width)) + return p + + +def check_subsets(): + count = fives = 0 + for active in range(4, 257, 4): + for rank in range(1, active // 4 + 1): + k = period(active, rank) + rows = [tuple(row_axes(active, rank, k, j)) for j in range(k)] + assert all(len(row) == len(set(row)) == rank for row in rows) + hits = Counter(i for row in rows for i in row) + assert set(hits) == set(range(active)) + assert all(hits[i] in (1, 5) for i in range(active)) + assert sum(hits[i] == 5 for i in hits) == (k * rank - active) // 4 + count += 1 + fives += int(5 in hits.values()) + return count, fives + + +def walsh(values): + a = values.copy() + width = 1 + while width < len(a): + for i in range(0, len(a), width * 2): + for j in range(i, i + width): + x, y = a[j], a[j + width] + a[j], a[j + width] = x + y, x - y + width *= 2 + return a + + +def spectral_quarters(reals, imags): + """Use the exact spectral action i^popcount and two unnormalized WHTs.""" + real = walsh(reals) + imag = walsh(imags) + for j in range(len(real)): + phase = j.bit_count() % 4 + a, b = real[j], imag[j] + real[j], imag[j] = ((a, b), (-b, a), (-a, -b), (b, -a))[phase] + return walsh(real), walsh(imag) + + +class ComplexMachine(Machine): + def initial(self, owner, n): + size = 1 << n + if owner < 0: + return [0] * size, [0] * size, [0] + random = Random(94051991 + owner) + return ([random.randrange(-7, 8) for _ in range(size)], + [random.randrange(-7, 8) for _ in range(size)], [0]) + + def is_zero(self, state): + return not any(state[0]) and not any(state[1]) + + def leaf(self, job): + self.leaves += 1 + reals, imags, den = self.data[job.owner] + width = 1 << job.axes[0] + den[0] += 1 + for block in range(0, len(reals), 2 * width): + for j in range(block, block + width): + k = j + width + a, b, c, d = reals[j], imags[j], reals[k], imags[k] + reals[j] = a - b + c + d + imags[j] = a + b + d - c + reals[k] = a + b + c - d + imags[k] = b - a + c + d + + +def check_complex(): + m = ComplexMachine(Rule(3, (2, 3), (1, 1, 1, 1, 1)), ((1, 1), (1, 1, 1))) + n = 12 + p = sweep(m, n) + mistake_count = 0 + for owner, (real, imag, den) in m.data.items(): + a, b, _ = m.initial(owner, n) + expected_a, expected_b = spectral_quarters(a, b) + assert den[0] >= n + scale = 1 << (den[0] - n) + assert [z * scale for z in expected_a] == real + assert [z * scale for z in expected_b] == imag + # Missing all i factors leaves at least one wrong dense output on every lane. + if [z << den[0] for z in a] != real: + mistake_count += 1 + assert mistake_count == p.width + return n, p.width, p.copies * p.owners_per_copy, m.frames, m.leaves + + +class BitMachine(Machine): + """Use a non-coordinate projector chart, an exterior weight and reversed tail.""" + + def initial(self, owner, n): + random = Random(7957 + owner) + # The chart is fixed at the full-field boundary. U = I + a e_0 e_last^T. + a = 1 + (abs(owner) % 21) + weights = [random.choice((1, 2, 4, 5, 7, 8, 10, 11, 13)) for _ in range(n)] + inverse = [pow(w, -1, 27) for w in weights] + heads = [0] * n if owner < 0 else [random.randrange(27) for _ in range(n)] + physical = [0] * n if owner < 0 else [random.randrange(27) for _ in range(n)] + return heads, physical, a, weights, inverse + + def is_zero(self, state): + return not any(state[0]) and not any(state[1]) + + def leaf(self, job): + self.leaves += 1 + heads, physical, a, weights, inverse = self.data[job.owner] + j = job.axes[0] + n = len(heads) + + def difference(i): + return physical[n - 1 - i] - inverse[i] * heads[i] + + # Column Ue_j times row e_j^T U^-1. Pull the physical weight outside D. + d = difference(j) + if j == 0: + d -= a * difference(n - 1) + + def transfer(i, value): + heads[i] = (heads[i] + weights[i] * value) % 27 + physical[n - 1 - i] = (physical[n - 1 - i] - value) % 27 + + transfer(j, d) + if j == n - 1: + transfer(0, a * d) + + +def check_bit(n, rule, partitions): + m = BitMachine(rule, partitions) + p = make_planner(rule)(n) + rng = Random(338833) + orders = [rng.sample(range(n), n) for _ in range(p.width)] + sweep(m, n, axes=orders) + for owner, state in m.data.items(): + before_h, before_t, _, w, inv = m.initial(owner, n) + assert state[0] == [(before_t[n - 1 - i] * w[i]) % 27 for i in range(n)] + assert state[1][::-1] == [(before_h[i] * inv[i]) % 27 for i in range(n)] + return n, p.width, p.copies * p.owners_per_copy, m.frames, m.leaves, m.zeros + + +if __name__ == "__main__": + print("row tapes, degree-five examples", *check_subsets()) + print("exact Gaussian arrays", *check_complex()) + r = Rule(4, (3, 4), (1, 2, 2, 2)) + print("non-coordinate weighted BIT", *check_bit(51, r, ((1, 2), (2, 2)))) + deep = Rule(3, (3,), (1, 2)) + print("nested exit weighted BIT", *check_bit(325, deep, ((1, 2),))) diff --git a/research/single-band-native-carriers/inputs/review/check_powered.py b/research/single-band-native-carriers/inputs/review/check_powered.py new file mode 100644 index 0000000000..2f1c1192cd --- /dev/null +++ b/research/single-band-native-carriers/inputs/review/check_powered.py @@ -0,0 +1,130 @@ +"""Check actual raw labels and replay the full tensor, strictifier and periodic flow.""" + +from collections import Counter +from itertools import islice +from pathlib import Path +import sys +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from periodic import Job, make_planner, run +from powered import Port, PoweredWord +from tagged_sources import read_words + + +def first_index(ports, rank): + return next(i for i, port in enumerate(ports) if port.rank == rank) + + +def actual_sources(): + bit, comp = read_words() + assert (len(bit.targets), len(bit.paid)) == (20706, 107460) + assert (len(comp.targets), len(comp.paid)) == (52512, 283152) + for word, expected in ((bit, 46116), (comp, 37920)): + assert Counter(x.rank for x in word.paid)[2] == expected + assert len({p.tag for p in word.targets}) == len(word.targets) + assert len({p.tag for p in word.paid}) == len(word.paid) + assert all(1 <= t.rank <= word.ambient for t in (*word.targets, *word.paid)) + repeat = (first_index(word.paid, 2),) * word.power + unit, = word.blocks(repeat) + assert unit.first == 0 and unit.rank == 2 ** word.power + assert unit.tags == (word.paid[repeat[0]].tag,) * word.power + # The first real occurrence controls the BIT slab, even with the same multiset. + j4, j14, j21 = (first_index(bit.paid, r) for r in (4, 14, 21)) + inside = (j4,) * 181 + (j14,) * 133 + (j21,) * 164 + p, q = tuple(bit.blocks((j4, j14) + inside)), tuple(bit.blocks((j14, j4) + inside)) + assert [a.rank for a in p] == [10 ** 480, q[0].rank - 10 ** 480] + assert len(q) == 1 and p[1].first == p[0].rank + ids = tuple(first_index(bit.targets, r) for r in (4, 64)) + assert bit.target((ids[0],) * 240 + (ids[1],) * 240).rank == bit.floor ** bit.power + c17 = first_index(comp.targets, 17) + assert comp.target((c17,) * comp.power).rank == comp.floor ** comp.power + # Do not enumerate the remaining blocks of this high-grade actual coefficient. + j = first_index(comp.paid, 56) + first, second = islice(comp.blocks((j,) * comp.power), 2) + assert (first.first, first.rank, second.first, second.rank) == (0, 10**264, 10**264, 10**264) + for name, word in (("BIT", bit), ("complex", comp)): + print(name, len(word.targets), len(word.paid), word.targets[0].tag, word.paid[0].tag) + print("paired BIT slabs", len(p), len(q), "real floor ranks", 16, 17) + + +class Toy: + def __init__(self, world, word): + self.world = world + self.word = word + self.data = {} + self.serial = 0 + self.guard = {} + self.private = self.live_centres = self.raw_frames = self.leaves = 0 + + def fresh(self, exemplar, rank, tag): + assert exemplar.owner in self.data and rank <= self.world + key = self.serial + self.serial += 1 + self.private += 1 + self.data[key] = [0] * self.world + self.guard[key] = tag + return Job(key, tuple(range(rank))) + + def zero(self, exemplar): + job = self.fresh(exemplar, len(exemplar.axes), ("replica-padding",)) + return Job(job.owner, exemplar.axes) + + def retire(self, job): + assert job.owner in self.guard and not any(self.data.pop(job.owner)) + del self.guard[job.owner] + + retire_zero = retire + + def raw(self, ports, columns): + ((t0, small), (t1, large)) = ports + assert (t0, t1) == tuple(t.tag for t in self.word.targets) + assert len(small.axes) == columns and len(large.axes) == 4 * columns + assert small.owner != large.owner + self.raw_frames += 1 + # The original positive owner is now parked in a fresh full centre. + private = self.fresh(large, len(large.axes), ("raw-centre",)) + self.data[private.owner], self.data[large.owner] = self.data[large.owner], self.data[private.owner] + self.live_centres += int(any(self.data[private.owner])) + actual = Job(private.owner, large.axes) + yield self.word.paid[0].tag, small + yield self.word.paid[1].tag, actual.select(range(3 * columns)) + yield self.word.paid[2].tag, actual.select(range(3 * columns, 4 * columns)) + self.data[private.owner], self.data[large.owner] = self.data[large.owner], self.data[private.owner] + self.retire(private) + + def native(self, fields, columns): + return self.word.native(fields, columns, self) + + def leaf(self, job): + self.leaves += 1 + (i,) = job.axes + # 4 is an exact fourth root in Z/17. This oracle uses the typed ordinals. + self.data[job.owner][i] = 4 * self.data[job.owner][i] % 17 + + +def nested_compilation(): + targets = (Port(("one-axis",), 1), Port(("four-axis",), 4)) + paid = (Port(("first",), 1), Port(("middle",), 3), Port(("last",), 1)) + for floor, cap in ((3, 2), (2, 1)): + word = PoweredWord(4, targets, paid, 2, floor, cap, cap) + rule = word.rule() + n = 67 + planner = make_planner(rule) + p = planner(n) + backend = Toy(n, word) + fields = [Job(~i, tuple((j + i) % n for j in range(n))) for i in range(p.width)] + original = {field.owner: [(j * 11 - field.owner * 3 + 1) % 17 for j in range(n)] + for field in fields} + backend.data.update({owner: state.copy() for owner, state in original.items()}) + run(rule, n, fields, backend, planner=planner) + assert backend.leaves == p.leaves and not backend.guard and backend.live_centres > 0 + assert backend.data == {o: [4 * z % 17 for z in state] for o, state in original.items()} + assert (sum(1 for _, k in word.target_paths() if not k) > 0 + and any(len(b.tags) == 2 and b.first > 0 for b in word.paid_paths())) + print("strict powered tape", floor, cap, p.width, backend.raw_frames, + backend.private, backend.live_centres, backend.leaves) + + +if __name__ == "__main__": + actual_sources() + nested_compilation() diff --git a/research/single-band-native-carriers/inputs/review/clifford_exact.py b/research/single-band-native-carriers/inputs/review/clifford_exact.py new file mode 100644 index 0000000000..166841a037 --- /dev/null +++ b/research/single-band-native-carriers/inputs/review/clifford_exact.py @@ -0,0 +1,149 @@ +"""Small exact Gaussian-dyadic Clifford compiler, independent of gx internals. +Paulis use i^p X^x Z^z. State vectors use integer Gaussian numerators / 2^d. +The tableau is supplemented by a literal circuit, so global phases are kept. +""" +from dataclasses import dataclass + +def parity(x):return x.bit_count()&1 +def rank(rows): + p={} + for x in rows: + while x: + b=x.bit_length()-1 + if b not in p:p[b]=x;break + x^=p[b] + return len(p) +def transpose(rows,n):return tuple(sum(((rows[j]>>i)&1)<>j&1);a[j],a[k]=a[k],a[j] + for i in range(n): + if i!=j and a[i]>>j&1:a[i]^=a[j] + assert [r&((1<>n for r in a) +def basis_extend(cols,n): + out=[] + for x in list(cols)+[1<len(out):out.append(x) + assert len(out)==n + return tuple(out) +def nullspace(rows,n): + a=list(rows);p=[];k=0 + for j in range(n): + t=next((i for i in range(k,len(a)) if a[i]>>j&1),None) + if t is None:continue + a[t],a[k]=a[k],a[t] + for i in range(len(a)): + if i!=k and a[i]>>j&1:a[i]^=a[k] + p.append(j);k+=1 + return tuple((1<>j)&1)<>i&1:out=pmul(out,T[i]) + for i in range(n): + if z>>i&1:out=pmul(out,T[n+i]) + return out +def compose(A,B):return tuple(apply(A,p) for p in B) +def inverse(T): + n=len(T)//2;cols=[x|(z<>n;u,v,p=apply(T,(x,z,0));assert (u,v)==identity(n)[j][:2];out.append((x,z,(-p)%4)) + return tuple(out) +def qvalue(Q,alpha,x,n): + return (sum(alpha[i] for i in range(n) if x>>i&1)+2*sum(parity((Q[i]>>(i+1))&(x>>(i+1))) for i in range(n) if x>>i&1))%4 +def mul_i(a,p): + x,y=a;p%=4 + return [(x,y),(-y,x),(-x,-y),(y,-x)][p] +@dataclass +class Op: + n:int + tab:tuple + circuit:list + def then(self,b): + assert self.n==b.n + return Op(self.n,compose(b.tab,self.tab),self.circuit+b.circuit) + def adjoint(self): + circ=[] + for e in reversed(self.circuit): + if e[0]=='P':circ.append(('P',inv(e[1],self.n))) + elif e[0]=='D':circ.append(('D',e[1],tuple((-x)%4 for x in e[2]))) + elif e[0]=='C':circ.append(('C',e[1],-e[2])) + elif e[0]=='phase':circ.append(('phase',(-e[1])%4)) + else:circ.append(e) + return Op(self.n,inverse(self.tab),circ) + def zero_state(self,basis=0): + N=1<>i)&1 for i in range(n)) + assert all(alpha[i]%2==(Q[i]>>i)&1 for i in range(n)) + return Op(n,tuple([(1<>i&1 else 0,1<>i&1 else 0) for i in range(n)]),[('C',q,sgn)]) +def xgate(n,b):return Op(n,tuple([(1<>i)&1)) for i in range(n)]),[('X',b)]) +def fourier(n,axes=None): + out=ident(n) + for i in range(n) if axes is None else axes:out=out.then(cgate(n,1<len(selected):picks.append(j);selected.append(x) + assert len(picks)==r and all(x>>r==0 for x in Bcols) + Br=transpose(selected,r);Bi=inv(Br,r);Dr=transpose([Dcols[j]&((1<> j) & 1) << i for i, row in enumerate(matrix)) for j in range(len(matrix))) + + +def inverse(matrix): + n = len(matrix) + rows = [row | (1 << (n+i)) for i, row in enumerate(matrix)] + for j in range(n): + pivot = next((i for i in range(j, n) if rows[i] >> j & 1), None) + require(pivot is not None, 'singular binary chart') + rows[j], rows[pivot] = rows[pivot], rows[j] + for i in range(n): + if i != j and rows[i] >> j & 1: + rows[i] ^= rows[j] + require([row & ((1 << n)-1) for row in rows] == [1 << i for i in range(n)], 'binary inverse') + return tuple(row >> n for row in rows) + + +def extend(vectors, n): + columns, pivots = [], {} + for value in tuple(vectors) + tuple(1 << i for i in range(n)): + reduced = value + while reduced: + j = reduced.bit_length()-1 + if j not in pivots: + pivots[j] = reduced + columns.append(value) + break + reduced ^= pivots[j] + require(len(columns) == n, 'frame basis extension') + return tuple(columns) + + +def adjoint(circuit): + out = [] + for gate in reversed(circuit): + if gate[0] == 'P': + out.append(('P', inverse(gate[1]))) + elif gate[0] == 'D': + out.append(('D', gate[1], tuple(-a % 4 for a in gate[2]))) + elif gate[0] == 'C': + out.append(('C', gate[1], -gate[2])) + elif gate[0] == 'phase': + out.append(('phase', -gate[1] % 4)) + else: + require(gate[0] == 'X', 'adjoint gate type') + out.append(gate) + return tuple(out) + + +def fourier(rank): + return tuple(('C', 1 << i, 1) for i in range(rank)) + + +def frame(vectors, n): + rank = len(vectors) + if rank == 0: + return () + if rank == n: + return fourier(n) + matrix = transpose(extend(vectors, n)) + columns = transpose(inverse(matrix)) + quadratic = tuple((1 << i) ^ sum(parity(a & b) << j for j, b in enumerate(columns)) for i, a in enumerate(columns)) + diagonal = tuple((row >> i) & 1 for i, row in enumerate(quadratic)) + chart = (('P', matrix), ('D', quadratic, diagonal)) + return adjoint(chart) + fourier(rank) + chart + + +def monomial(record): + matrix = tuple(record['matrix_rows']) + quadratic = tuple(record['quadratic_rows']) + linear = tuple(record['linear_Z4']) + require(transpose(quadratic) == quadratic, 'quadratic symmetry') + require(len(matrix) == len(quadratic) == len(linear) == 9, 'monomial dimension') + require(all(a % 2 == (quadratic[i] >> i) & 1 for i, a in enumerate(linear)), 'diagonal parity') + inverse(matrix) + return (('D', quadratic, linear), ('P', matrix), ('X', record['offset']), ('phase', record['phase'])) + + +def recipe(record): + rank = record['rank'] + require(isinstance(rank, int) and 0 <= rank <= 9, 'child rank') + if rank == 0: + require(record['right'] is None, 'rank zero right factor') + return monomial(record['left']) + return monomial(record['right']) + fourier(rank) + monomial(record['left']) + + +def tableau(circuit, n=9): + rows = [(1 << i, 0, 0) for i in range(n)] + [(0, 1 << i, 0) for i in range(n)] + for gate in circuit: + tag = gate[0] + out = [] + inverse_transpose = transpose(inverse(gate[1])) if tag == 'P' else None + for x, z, phase in rows: + if tag == 'P': + x, z = mul(gate[1], x), mul(inverse_transpose, z) + elif tag == 'X': + phase += 2 * parity(z & gate[1]) + elif tag == 'C': + if parity(z & gate[1]): + x ^= gate[1] + phase += 3 * gate[2] + elif tag == 'D': + quadratic, linear = gate[1:] + phase += sum(linear[i] for i in range(n) if x >> i & 1) + phase += 2 * sum(parity((quadratic[i] >> (i+1)) & (x >> (i+1))) for i in range(n) if x >> i & 1) + z ^= mul(quadratic, x) + else: + require(tag == 'phase', 'tableau gate type') + out.append((x, z, phase % 4)) + rows = out + return tuple(rows) + + +@lru_cache(maxsize=512) +def action(gate): + if gate[0] == 'P': + return tuple(mul(gate[1], x) for x in range(512)) + require(gate[0] == 'D', 'state action type') + quadratic, linear = gate[1:] + return tuple((sum(linear[i] for i in range(9) if x >> i & 1) + + 2 * sum(parity((quadratic[i] >> (i+1)) & (x >> (i+1))) for i in range(9) if x >> i & 1)) % 4 for x in range(512)) + + +def rotate(pair, power): + a, b = pair + return ((a, b), (-b, a), (-a, -b), (b, -a))[power % 4] + + +def state(circuit, basis=0): + value, denominator = {basis: (1, 0)}, 0 + for gate in circuit: + tag = gate[0] + result = {} + if tag == "C": + direction, sign = gate[1:] + for address, (a, b) in value.items(): + for target, pair in ((address, (a - sign*b, b + sign*a)), + (address ^ direction, (a + sign*b, b - sign*a))): + old = result.get(target, (0, 0)) + result[target] = (old[0] + pair[0], old[1] + pair[1]) + denominator += 1 + else: + for address, pair in value.items(): + if tag == "P": + target = mul(gate[1], address) + elif tag == "X": + target = address ^ gate[1] + else: + target = address + if tag == "D": + pair = rotate(pair, action(gate)[address]) + else: + require(tag == "phase", "Unknown Gaussian state gate") + pair = rotate(pair, gate[1]) + require(target not in result, "A monomial address map is not injective") + result[target] = pair + value = {address: pair for address, pair in result.items() if pair != (0, 0)} + while denominator and all((a | b) % 2 == 0 for a, b in value.values()): + denominator -= 1 + value = {address: (a//2, b//2) for address, (a, b) in value.items()} + return value, denominator + + +def equal(actual, expected, label): + require(tableau(actual) == tableau(expected), label + ": signed Pauli action") + require(state(actual) == state(expected), label + ": exact global phase") + + +def verify(data, certificate): + word = data["word"] + original, clean = data["programs"], data["clean_programs"] + source_recipes = data["recipes"] + residuals = data["residuals"]["recipes"] + native_tags = {"climb", "adapter", "residual_adapter"} + for orientation in ("forward", "backward"): + native = [event for event in clean[orientation] if event[0] in native_tags] + require(native == [event for event in original[orientation] if event[0] in native_tags], + "A retained native event changed") + require(len(native) == 5056, "The retained native event count changed") + frames = [frame(tuple(vectors), 9) for vectors in word["frames"]] + used = {(event[3], event[4]) for program in clean.values() + for event in program if event[0] == "climb"} + children = {(record["old"], record["new"]): record for record in source_recipes["children"]} + require(len(children) == len(source_recipes["children"]) and used <= set(children), + "The retained child recipe coverage is incomplete") + for old, new in sorted(used): + record = children[old, new] + require(record["rank"] == len(word["frames"][new]) - len(word["frames"][old]), + "A retained child has the wrong rank") + equal(recipe(record), adjoint(frames[old]) + frames[new], "Retained child") + endpoints = {(record["role"], record["port"]): record + for record in source_recipes["endpoint_adapters"]} + require(len(endpoints) == len(source_recipes["endpoint_adapters"]) + and set(endpoints) == {(role, p) for role in ("source", "target") for p in range(112)}, + "The endpoint adapter coverage is incomplete") + for (role, port), record in endpoints.items(): + direction = word["ports"][port] + conventional = (("C", direction, 1),) if role == "source" else ( + ("C", direction, -1),) + fourier(9) + index = word["start"][port] if role == "source" else word["final"][112 + port] + require(record["frame"] == index and record["rank"] == 0, "An endpoint frame changed") + equal(recipe(record), adjoint(conventional) + frames[index], "Endpoint adapter") + used_residuals = set() + for program in clean.values(): + for event in program: + if event[0] != "residual_adapter": + continue + _, position, register, entry, *tail = event + terminal = tail[0] if tail else 1 + key = str(entry) if terminal == 1 else str(entry) + ":" + str(terminal) + require(key in residuals and position in ("pre", "post"), "A residual binding changed") + require(entry == word["start"][register] and terminal == word["final"][register], + "A residual endpoint changed") + used_residuals.add(key) + for key in sorted(used_residuals): + record = residuals[key] + equal(recipe(record), adjoint(frames[record["frame"]]) + frames[record.get("terminal", 1)], + "Residual adapter") + records = certificate["input_recipes"] + ports = certificate["compensation_ports"] + require([record["port"] for record in records] == ports and len(records) == 8, + "The eight input recipes changed") + columns = 0 + for item in records: + port, label = item["port"], item["label"] + require(label == word["ports"][port] and item["canonical_start_frame_id"] == word["start"][port], + "An input recipe has the wrong supplier label") + record = item["recipe"] + require(record["rank"] == 1, "An input copy has the wrong child rank") + for side in ("left", "right"): + factor = record[side] + require(factor["quadratic_rows"] == [0] * 9 and factor["linear_Z4"] == [0] * 9 + and factor["offset"] == factor["phase"] == 0, + "An input factor is not an address permutation") + actual, expected = recipe(record), (("C", label, 1),) + equal(actual, expected, "Positive inherited input line") + for basis in range(512): + require(state(actual, basis) == state(expected, basis), "A complete input Gaussian column differs") + columns += 1 + negative = monomial(record["right"]) + (("C", 1, -1),) + monomial(record["left"]) + require(tableau(negative) != tableau(expected) or state(negative) != state(expected), + "An inverse input child was not detected") + phased = actual + (("phase", 1),) + require(tableau(phased) == tableau(actual) and state(phased) != state(expected), + "An input phase-only error was not detected") + return {"status": "PASS_EXACT_INPUT_NATIVE_FRAMES", "retained_native_events_per_orientation": 5056, + "retained_child_recipes": len(used), "endpoint_adapter_recipes": len(endpoints), + "residual_adapter_recipes": len(used_residuals), "new_input_recipes": len(records), + "new_exact_gaussian_columns": columns, "inverse_input_child_controls": len(records), + "phase_only_controls": len(records), "address_permutation_factors": 2 * len(records), + "method": "Independent signed Pauli and exact Gaussian interpretation; no compiler import", + "scope": "Positive inherited input frames before every retained adapter. No recursive hosting claim."} diff --git a/research/single-band-native-carriers/inputs/triangular.json b/research/single-band-native-carriers/inputs/triangular.json new file mode 100644 index 0000000000..349cba11da --- /dev/null +++ b/research/single-band-native-carriers/inputs/triangular.json @@ -0,0 +1,19 @@ +{ + "commit": "9585c1fa2ed5f2316ac09e04b357cb720badfcb8", + "directory": "research/triangular-native-supplier", + "sha256": { + "LICENSE": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4", + "NOTICE.md": "7ec57034ab47631a47e35ab9cd86a563a6a4bb2ce7397d545861f898281c696c", + "direct_body.py": "f4ca3082b95f958b50f84a3c138667add0051d6a796e7f63afe95d41cf24e7af", + "inputs/retained.json": "4d0dd81eb156c97403d752a3dc654d85a93b0284aed8cfa5eed840259f6abd88", + "inputs/retained.tar.gz": "77742c09b088f27e8742c3fad7b7148d3397e4d51b95312106f39a8970165903", + "limb_scale.py": "ed7c27348c2bc8259683b617c45bb0ee6aacb781c0ad04168c59035b7b5cf8ff", + "multiplier.py": "e805fb05caaa76d4c65dc3a55b99c6332a1c3772516547cf24e8027ade718cf4", + "quotient_route.py": "3243f45d6097a80bc8b077d8682426e4555f6c4a3097bd0a12ffd4f1f5c45ba8", + "receiver.py": "09d2e9508e3e34934a6f2132c6e864f6b4ba68fa96aaadbec0a1902aa7762642", + "retained.py": "970e71bb0fcab41a03ccc5068ddc5e0df5c00953098f542fdc1a3e0e2048ffda", + "same_order_body.py": "56a15ce431daf25794741cb5157e136ce509ed646b32aaea34348088396e459d", + "staged_carriers.py": "6c925ae4b39dc9999ac5891d1a27dcbb38e129a36e1473b2b418f27a806b6fc4", + "triangular_ordinary.py": "1f69f21881229566e0b251a2edd8a3c9ac6409eeebdb68ee046f27e74dd8af71" + } +} diff --git a/research/single-band-native-carriers/inputs/triangular/LICENSE b/research/single-band-native-carriers/inputs/triangular/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/research/single-band-native-carriers/inputs/triangular/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/research/single-band-native-carriers/inputs/triangular/NOTICE.md b/research/single-band-native-carriers/inputs/triangular/NOTICE.md new file mode 100644 index 0000000000..9323d93ce1 --- /dev/null +++ b/research/single-band-native-carriers/inputs/triangular/NOTICE.md @@ -0,0 +1,8 @@ +# Attribution and source history + +Ali Romman prepared the same-order native supplier, the triangular quotient router, its staged use, the completed Fourier pack schedule, the product integration and its verification, with substantial OpenAI Codex assistance. The new work includes the reduced working grid, the measurements on matched payloads, and the new Lean arguments. This package uses Apache License 2.0. [License](LICENSE) · [Working discussion](https://github.com/CrocSwap/integer-mult-bounds/discussions/7940) · [Earlier contribution index](https://github.com/CrocSwap/integer-mult-bounds/discussions/7794) + +- Ali Romman's [PR #7914](https://github.com/CrocSwap/integer-mult-bounds/pull/7914) supplies the balanced product-module representation, independent rows, stripe and stack backing, outer geometry, productive mixing source and signed product caller. [PR #7868](https://github.com/CrocSwap/integer-mult-bounds/pull/7868) supplies the 480/264 price, chronological periodic compiler, fixed heads and fully generated program. These results retain their original credit. [Stock and activation notice](https://github.com/CrocSwap/integer-mult-bounds/blob/46783fbbfc219a3faffbea76f60a2810b85ab75a/research/native-stock-activation/NOTICE.md) · [Complete multiplier notice](https://github.com/CrocSwap/integer-mult-bounds/blob/3f7c3c1f2a9a0963736562037e01fe41aec46b8c/research/bounded-general-multiplier/NOTICE.md) +- Clear1nsight supplied the mixed binary cut in [PR #7830](https://github.com/CrocSwap/integer-mult-bounds/pull/7830). Its source credits Dugongue and Rohan Arun for predecessor prices and Ali Romman for the complex schedule. The rational binary projectors and joint charts come from [PR #7837](https://github.com/CrocSwap/integer-mult-bounds/pull/7837). Nick Petalas supplied the pivoted fallback. [PR #7846](https://github.com/CrocSwap/integer-mult-bounds/pull/7846) supplies uniform composition and the two-input recovery chain. [Mixed-cut notice](https://github.com/CrocSwap/integer-mult-bounds/blob/87fbf4f7b35b0f18ab12b5767775a9a424cf0b15/research/p104-mixed-rank-supplier/NOTICE) · [Grade-14 notice](https://github.com/CrocSwap/integer-mult-bounds/blob/a7f99a5f5f919dd3ffb2987f90c1e7d6527feb1e/research/grade14-native-realization/NOTICE.md) · [Uniform composition notice](https://github.com/CrocSwap/integer-mult-bounds/blob/343f7b1817e26ad3f89d2ddad313b12741d53602/research/mixed-rank-uniform-composition/NOTICE.md) +- Ali Romman's [PR #7849](https://github.com/CrocSwap/integer-mult-bounds/pull/7849) supplies the certified direct-circulant Fourier synthesis, its grid arithmetic, and the local conditioned interval bounds. It credits Jose Manuel for the rational Fourier compiler, Chafik and Vlado for earlier constructions, Bluestein's identity and Karatsuba–Ofman multiplication. The retained CRT, tagged owner and compact routing proofs carry their original author notices. [Fourier notice](https://github.com/CrocSwap/integer-mult-bounds/blob/3615fd982f2f4dc7172bef6f0dc9a4f77d5ab6dd/research/direct-circulant-fourier/NOTICE.md) · [Balanced CRT](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/unconditional-batched-crt/CRT.md) · [Full credit history](https://github.com/CrocSwap/integer-mult-bounds/blob/3f7c3c1f2a9a0963736562037e01fe41aec46b8c/research/bounded-general-multiplier/FLOW-NOTICE.md) +- The Lean and mathlib authors supply the kernel, the libraries and their proofs. The eleven retained modules are byte-exact original files. The portable archive retains the predecessor's source notices and its own full dependency archive. [Formal source bindings](lean/retained/sources.json) · [Runtime source bindings](inputs/retained.json) · [Mathlib revision](https://github.com/leanprover-community/mathlib4/tree/d13f23b723b8a846827a245b89c10fc7d3f11612) diff --git a/research/single-band-native-carriers/inputs/triangular/direct_body.py b/research/single-band-native-carriers/inputs/triangular/direct_body.py new file mode 100644 index 0000000000..e8d742d9ef --- /dev/null +++ b/research/single-band-native-carriers/inputs/triangular/direct_body.py @@ -0,0 +1,167 @@ +"""Move a native matcher on the two actual bodies when the column count is bounded.""" + +from fractions import Fraction +from functools import partial +from math import prod + +from factored_frames import apply_row, inverse_word +from growing_binary import pipe +from module_atoms import component_widths, lower_tape, pair_shape, total_width, weighted_pair +from same_order_body import same_order_line +from streaming_routes import copy_bytes, erase, integer_scale, negate_field, work_tapes +from ternary_frames import residue +from ternary_leaf import select_pivot + + +def scale_atom(source, target, layout, prefix, suffix, factor): + """Apply a fixed native unit to every cyclic component of the selected atom.""" + width = total_width(layout) + numerator, denominator = factor.numerator, factor.denominator + if max(abs(numerator), denominator) > 20: + raise ValueError("Scaling exceeds the proved raw factor alphabet") + volume = prefix * 3**width * suffix + with work_tapes(22) as (current, other, *buckets): + copy_bytes(source, current, volume) + + def step(operation, *args): + nonlocal current, other + current.seek(0) + operation(current, other, *args) + erase(current) + current, other = other, current + + before = 0 + for size in component_widths(layout): + side = 3**size + extent = prefix * 3**before, side, suffix * 3 ** (width - before - size) + if abs(numerator) > 1: + step(integer_scale, buckets, *extent, abs(numerator), False) + if numerator < 0: + step(negate_field, buckets[0], *extent) + if denominator > 1: + step(integer_scale, buckets, *extent, denominator, True) + before += size + current.seek(0) + copy_bytes(current, target, volume) + + +def direct_actions(word, f): + """Convert each right matrix to its inverse action on the two body columns.""" + for gate, i, *args in word: + for tail in (False, True): + for column in range(f): + src = i * f + column + if gate == "scale": + yield gate, tail, src, None, 1 / Fraction(args[0]) + elif gate == "swap": + left, right = sorted((src, args[0] * f + column)) + yield gate, tail, left, right, 1 + elif gate == "add": + yield gate, tail, src, args[0] * f + column, -args[1] + else: + raise ValueError("The native body matcher has an unknown operation") + + +def direct_route(core, source, target, word, f, unused, older, gap, suffix, weight): + """For a right word S, move head addresses by A S⁻¹ A⁻¹ and tails by S⁻¹.""" + n, atom, modulus = core.n, core.atom, core.modulus + width = total_width(core.layout) + dims = [unused, older] + [atom] * (n * f) + [gap] + [atom] * (n * f) + + def runs(left, scalar, numerator, denominator): + visible = prod(dims[2:left]) + for _ in range(unused): + for old in range(older): + if numerator is None: + value = scalar + else: + value = ( + scalar * weight(old, numerator) * pow(weight(old, denominator), -1, modulus) + ) + yield visible, value % modulus + + def schedule(): + for gate, tail, a, b, factor in direct_actions(word, f): + start = 3 + n * f if tail else 2 + x = start + a + if gate == "scale": + yield partial( + scale_atom, + layout=core.layout, + prefix=prod(dims[:x]), + suffix=suffix * prod(dims[x + 1 :]), + factor=factor, + ) + continue + y = start + b + left, right = sorted((x, y)) + p, g, s = pair_shape(dims, left, right, suffix) + + def exchange(src, dst, p=p, g=g, s=s): + core.previous(src, dst, width, p, g, s) + + if gate == "swap": + if tail: + yield exchange + else: + coeffs = partial(runs, left, 1, a, b) + yield partial( + weighted_pair, + layout=core.layout, + prefix=p, + gap=g, + suffix_bytes=s, + weight=None, + previous_swap=core.previous, + runs=coeffs, + ) + continue + if x > y: + yield exchange + value = residue(factor, modulus) + coeffs = partial(runs, left, value, None if tail else b, None if tail else a) + yield partial( + lower_tape, layout=core.layout, prefix=p, gap=g, suffix_bytes=s, runs=coeffs + ) + if x > y: + yield exchange + + with core.storage() as arena: + pipe(arena, "matcher", source, target, prod(dims) * suffix, schedule()) + + +def direct_factors(frame, modulus): + """Return F e and eᵗ F⁻¹ at the one selected coordinate.""" + if len(frame.mask) != 1: + raise ValueError("A terminal leaf must have rank one") + unit = [int(i == frame.mask[0]) for i in range(frame.size)] + + def transpose_word(): + for op, i, *args in reversed(frame.word): + if op == "add": + yield op, args[0], i, args[1] + else: + yield (op, i, *args) + + return apply_row(transpose_word(), unit, modulus), apply_row( + inverse_word(frame.word), unit, modulus + ) + + +def direct_line(core, source, target, frame, f, unused, older, gap, suffix, weight): + """Act on one compiled line in its actual basis, with the chart fixed to identity.""" + u, v = direct_factors(frame, core.modulus) + same_order_line( + core, + source, + target, + pivot=select_pivot(u, v), + factors=lambda high: (u, v), + f=f, + unused=unused, + heights=1, + older=older, + gap=gap, + suffix=suffix, + weight=weight, + ) diff --git a/research/single-band-native-carriers/inputs/triangular/inputs/retained.json b/research/single-band-native-carriers/inputs/triangular/inputs/retained.json new file mode 100644 index 0000000000..43a35ae8c0 --- /dev/null +++ b/research/single-band-native-carriers/inputs/triangular/inputs/retained.json @@ -0,0 +1,141 @@ +{ + "archive_sha256": "77742c09b088f27e8742c3fad7b7148d3397e4d51b95312106f39a8970165903", + "commit": "46783fbbfc219a3faffbea76f60a2810b85ab75a", + "members": { + "LICENSE": { + "git_blob": "261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64", + "path": "research/native-stock-activation/LICENSE", + "sha256": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4" + }, + "NOTICE.md": { + "git_blob": "c7691ccfa20b33641bcba35a2ce0033830564f1c", + "path": "research/native-stock-activation/NOTICE.md", + "sha256": "340f5a46188a47be6e83622bd5b0574c8d0c8e9b259778e5dc5e8d6d5674521a" + }, + "binary_io.py": { + "git_blob": "9c3bb0d6f7cca9a2c76bd548abc18d2c45bbf772", + "path": "research/native-stock-activation/binary_io.py", + "sha256": "1b26c96526c90c3eb22996d454cfe769784695865e080c07d561b51acb261fe6" + }, + "bound.py": { + "git_blob": "66328e3fd615038d11894e7e7b7c799bdbe0e41d", + "path": "research/native-stock-activation/bound.py", + "sha256": "91beba512f8cada7cb3bfe0a74861b92c0a8dbcb8bb66b1e8aabc3f23d827932" + }, + "check_module_atoms.py": { + "git_blob": "21470502bdeaff5dc92cf49a86e666fbb546e6bf", + "path": "research/native-stock-activation/check_module_atoms.py", + "sha256": "0573cde1e09f4a551038151f63dffa645065c762abc9b67831b63188f3fcba20" + }, + "check_raw_delta.py": { + "git_blob": "c5a6fd9dbec04be1cc7cb4120783a8bbecc8314a", + "path": "research/native-stock-activation/check_raw_delta.py", + "sha256": "643cc4f75b1ab6a504be1d730e0579658ae3af91486b3e54a056c4b4606b8f7f" + }, + "compact_columns.py": { + "git_blob": "eea0bd3668334fb869669acff3a04a4a3372d400", + "path": "research/native-stock-activation/compact_columns.py", + "sha256": "2a9cdf04bbb22fe8e3cc065dd9159916cc13d83a8700477b595faf834be76f50" + }, + "compact_crt.py": { + "git_blob": "32456ec2767d9abab757f2df03c5c1574da89fc2", + "path": "research/native-stock-activation/compact_crt.py", + "sha256": "ef13a093564cdc3fff88a9b57543b878d6e0f77afc4cd6d58eab3bbc96418e61" + }, + "compiler_cut.py": { + "git_blob": "c4c4ef3f5ec8a7dc4a8853110adf445117c77d0c", + "path": "research/native-stock-activation/compiler_cut.py", + "sha256": "eaa29ae4b759e46a9a73939d951697e49eaffae00ec62ef545e1f060b28180b8" + }, + "complex_stage.py": { + "git_blob": "c20499d98cde25bf403c68af94c39f4964672b8e", + "path": "research/native-stock-activation/complex_stage.py", + "sha256": "8d72d9b90cc12720b40b7ba5877a41e6c3eb4510d640753d049b9488216f5efe" + }, + "crt_tree.py": { + "git_blob": "b4b18499e6a62a16f9ee3cdc2d211b7d87581aff", + "path": "research/native-stock-activation/crt_tree.py", + "sha256": "f221f1bfed419b2a1101268b2ef290c1fd590c45411dda805b609be16bbe7187" + }, + "growing_binary.py": { + "git_blob": "a004121c0914deb8f91766479a2a049937c07fb6", + "path": "research/native-stock-activation/growing_binary.py", + "sha256": "16aaeba6e55f2a99cdf1dae88ca7e0eae1673721181480c6be63e4048f197b6f" + }, + "inputs/origins.json": { + "git_blob": "2819bed06729fed3c199dbbbbe282f0e928dd815", + "path": "research/native-stock-activation/inputs/origins.json", + "sha256": "cc1ebbe8a95c24886017a5b1d36a8f3b39f771a66c556c8ae6a2ef3757c7c593" + }, + "inputs/runtime.tar.gz": { + "git_blob": "3c8efaac2e55d880a2aa146d972bc808fde2af2c", + "path": "research/native-stock-activation/inputs/runtime.tar.gz", + "sha256": "305d410c1868be970d30cf0700e5e036001bf60fa8ba59510ef763ff957dd983" + }, + "module_atoms.py": { + "git_blob": "6f2495e197c0e6a145a84df8b4a40f81fb8b1fa6", + "path": "research/native-stock-activation/module_atoms.py", + "sha256": "1f3e60a5baae12a679ae64ad8fc7e5456f2040862fb938a99541fdd0b2018ac0" + }, + "ordinary.py": { + "git_blob": "a24d49ec18f76c6a454c79c4d7cb008b0b35f49b", + "path": "research/native-stock-activation/ordinary.py", + "sha256": "257008fc0804dfbbe21eefeb4eb25ff7cb4527111bd2fa26dbcd51a4d201cbf6" + }, + "outer_schedule.py": { + "git_blob": "8c7cac8f6b2365efb36e5759e0cba4fad72f1513", + "path": "research/native-stock-activation/outer_schedule.py", + "sha256": "b95ae48b925d423178e9ab51b29115ce1be8f73f6c01947d621df9f00bbac3a8" + }, + "positive.py": { + "git_blob": "9969e8935213c483017186e7d06e6c82ef897c29", + "path": "research/native-stock-activation/positive.py", + "sha256": "a1b5d1725c6230667646d3e50551d566e2faac39bc39a02c703c3da065f4db5c" + }, + "product_path.py": { + "git_blob": "e40de201e3ed8a32d8523bf9be97500a86d2d098", + "path": "research/native-stock-activation/product_path.py", + "sha256": "2b9cb90c648dac0cc7e6f0b2e64027b7e41680342b8dd7d8eabe9a82bebb2c77" + }, + "raw48.py": { + "git_blob": "bce9cf35ca58db910ead37256a502618ba90a63d", + "path": "research/native-stock-activation/raw48.py", + "sha256": "86c30fd4a906830bb6f4b54cdc0be083bd2649bebf68da7383efd7beee223700" + }, + "raw_binary.py": { + "git_blob": "46932a83c41284bb178f17d0250ab6754e01a55b", + "path": "research/native-stock-activation/raw_binary.py", + "sha256": "9629a92d7383640ccbe9cb5b86972bee7901e63162d691b4fba8056624501ae2" + }, + "short_product.c": { + "git_blob": "d475f1095afec6033d9f44719edbfd6af0ade028", + "path": "research/native-stock-activation/short_product.c", + "sha256": "bef9315b1ddb3a08a153c807af93867ae5d3d3f0f79f30808a36ce25cfcf6f80" + }, + "source_inputs.py": { + "git_blob": "ee206a3b37e12e216a92ec3a72a2b3cd23e9fa0b", + "path": "research/native-stock-activation/source_inputs.py", + "sha256": "21a760fe9a4eef7e47fbe59d4e94709690a4a53c2c233726c3e11eee401cf071" + }, + "spool.py": { + "git_blob": "bb5365fe301e9827dad5ecc012f05f1f3a481c52", + "path": "research/native-stock-activation/spool.py", + "sha256": "b24796e8d220eed9107ecf4e7b1bb28bd3c75f1e3596774bb47a9c6af9a0814d" + }, + "stack_tapes.py": { + "git_blob": "5ec0cde47538a61ebbed269307dac80731faaaa8", + "path": "research/native-stock-activation/stack_tapes.py", + "sha256": "5a0edfc1f670caecaf057a706bf7caef7c74bd1e51d1cd9ccc4951ba9daf7cfe" + }, + "stripe_route.py": { + "git_blob": "77b4b65cb03250c9cfdfdc3a5eb39e259c8f3ef4", + "path": "research/native-stock-activation/stripe_route.py", + "sha256": "f8eff0923ae6a4dd851adec72699165a361ef20cb2032853ea8f3594faaf7acd" + }, + "striped_tensor.py": { + "git_blob": "17ad1b0c76a4ca2bbfd831a7f03c4dd52919d534", + "path": "research/native-stock-activation/striped_tensor.py", + "sha256": "d84b2ff66f33b57c8c18da7838a535ef64c86af2546c9770c5ae67c4f60db38b" + } + } +} diff --git a/research/single-band-native-carriers/inputs/triangular/inputs/retained.tar.gz b/research/single-band-native-carriers/inputs/triangular/inputs/retained.tar.gz new file mode 100644 index 0000000000..c1a75d8f55 Binary files /dev/null and b/research/single-band-native-carriers/inputs/triangular/inputs/retained.tar.gz differ diff --git a/research/single-band-native-carriers/inputs/triangular/limb_scale.py b/research/single-band-native-carriers/inputs/triangular/limb_scale.py new file mode 100644 index 0000000000..2c7243ddb8 --- /dev/null +++ b/research/single-band-native-carriers/inputs/triangular/limb_scale.py @@ -0,0 +1,97 @@ +"""Move arbitrary payloads under multiplication by any unit of a ternary digit field.""" + +from streaming_routes import copy_bytes, erase, negate_field, shift_field, work_tapes + + +def unit_scale(source, target, digits, prefixes, piece, unit, previous_swap): + """Route x to unit*x modulo 3**digits without another full independent digit.""" + + def odd_step(src, dst, branch_prefix, side, branch_piece, factor): + # Convert a high field and a trailing trit into three whole high fields. + with work_tapes(7) as tapes: + ins, outs, scratch = tapes[:3], tapes[3:6], tapes[6] + for _ in range(branch_prefix): + for _ in range(side): + for tape in ins: + copy_bytes(src, tape, branch_piece) + for t, tape in enumerate(ins): + tape.seek(0) + shift_field( + tape, + outs[factor * t % 3], + scratch, + 1, + side, + 1, + branch_piece, + None, + (factor * t // 3) % side, + ) + erase(tape) + for tape in outs: + tape.seek(0) + for _ in range(side): + for tape in outs: + copy_bytes(tape, dst, branch_piece) + for tape in outs: + erase(tape) + + def carry_step(src, dst, branch_prefix, base, branch_piece, factor, inv): + with work_tapes(1) as (temporary,): + for _ in range(branch_prefix): + for low_after in range(base): + old_low = low_after * inv % base + carry = (factor * old_low // base) % base + shift_field(src, dst, temporary, 1, base, 1, branch_piece, None, carry) + + def schedule(v, a, front, tail): + finishes = [] + while v: + a %= 3**v + if a == 1: + break + if v == 1: + yield negate_field, (temporary, front, 3, tail) + break + if v % 2: + v -= 1 + finishes.append((odd_step, (front, 3**v, tail, a))) + tail *= 3 + continue + v //= 2 + base = 3**v + inv = pow(a, -1, base) + swap = previous_swap, (v, front, 1, tail) + + # Scale the two limbs by reciprocal units before the one smaller call. + if inv != 1: + for upper, coefficient in ( + (False, -inv), + (True, a - 1), + (False, 1), + (True, inv - 1), + ): + coefficient %= base + if coefficient: + if upper: + yield swap + yield shift_field, (temporary, front, base, 1, tail, coefficient, 0) + if upper: + yield swap + finishes.extend((swap, (carry_step, (front, base, tail, a, inv)), swap)) + a *= a + tail *= base + yield from reversed(finishes) + + if digits < 0 or unit % 3 == 0 or prefixes < 0 or piece < 1: + raise ValueError("A unit and a complete ternary field are required") + size = prefixes * 3**digits * piece + with work_tapes(3) as (current, other, temporary): + copy_bytes(source, current, size) + for action, args in schedule(digits, unit, prefixes, piece): + current.seek(0) + action(current, other, *args) + erase(current) + current, other = other, current + current.seek(0) + copy_bytes(current, target, size) diff --git a/research/single-band-native-carriers/inputs/triangular/multiplier.py b/research/single-band-native-carriers/inputs/triangular/multiplier.py new file mode 100644 index 0000000000..512cc8cba4 --- /dev/null +++ b/research/single-band-native-carriers/inputs/triangular/multiplier.py @@ -0,0 +1,129 @@ +"""Multiply signed binary tapes through completed normalized Fourier packs.""" + +from io import BytesIO + +from retained import install + +install() + +from binary_io import magnitude_bits +from outer_schedule import parameters, square_axes +from product_path import Product as RetainedProduct +from product_path import multiply_tapes as stopped_or_retained +from product_path import number, put, tensor_diagonal +from triangular_ordinary import ordinary_swap + + +def precision(public, extent, count): + """Fund intervals within one normalized pack and the sum of all its endpoint errors.""" + maximum = (extent + count - 1) // count + active = max(1, count // (1024 * (public + 1).bit_length())) + amplification = 4096 * active * (maximum + 6) + stages = 20000 * (count + 1) * (maximum + 2) ** 6 + 2 * count + return ( + public + + 3 + + 8 * amplification + + 4 * (stages * (count + 1)).bit_length() + + (count + 1).bit_length() + + 64 + ) + + +class Product(RetainedProduct): + def __init__(self, sides, b, P, exchange=ordinary_swap, *, engine=None): + super().__init__(sides, b, P, exchange, engine=engine) + + def transform(self, tape, opposite=False): + def conjugate(): + tape.seek(0) + for _ in range(self.total): + tape.seek(self.wide, 1) + value = number(tape, self.wide) + tape.seek(-self.wide, 1) + put(tape, (-value,), self.wide) + + if opposite: + conjugate() + for start, end, layers in self.packs: + + def diagonal(active): + tables = self.idles.copy() + tables[start:end] = active + tensor_diagonal(tape, self.wide, self.grid, tables) + + diagonal(self.entrance[start:end]) + for _ in range(2): + for layer in layers: + bit = layer[0][0] + if any(row[0] != bit for row in layer): + raise ArithmeticError("The pack contains different physical significances") + diagonal([row[1] for row in layer]) + if bit is not None: + self.h(tape, start, end, bit) + diagonal(self.exit[start:end]) + if opposite: + conjugate() + + +def multiply_tapes( + left, + left_bytes, + right, + right_bytes, + output, + *, + left_negative=False, + right_negative=False, + engine=None, +): + """Return the sign and byte count. Preserve both signed-magnitude input intervals.""" + if output is left or output is right: + raise ValueError("The product needs a separate output owner") + lengths = magnitude_bits(left, left_bytes), magnitude_bits(right, right_bytes) + shape = parameters(max(lengths)) + if shape is None: + return stopped_or_retained( + left, + left_bytes, + right, + right_bytes, + output, + left_negative=left_negative, + right_negative=right_negative, + engine=engine, + ) + sides = tuple(square_axes(shape.axes())) + P = precision(shape.public, shape.extent_bits, shape.count) + machine = Product(sides, shape.public // 6, P, engine=engine) + sign, size, _ = machine._multiply_tapes( + left, right, output, lengths, left_negative != right_negative, False + ) + return sign, size + + +def multiply(left, right, *, engine=None): + raw = [abs(x).to_bytes((abs(x).bit_length() + 7) // 8, "little") for x in (left, right)] + out = BytesIO() + sign, _ = multiply_tapes( + BytesIO(raw[0]), + len(raw[0]), + BytesIO(raw[1]), + len(raw[1]), + out, + left_negative=left < 0, + right_negative=right < 0, + engine=engine, + ) + value = int.from_bytes(out.getvalue(), "little") + return -value if sign else value + + +if __name__ == "__main__": + from argparse import ArgumentParser + + parser = ArgumentParser(description=__doc__) + parser.add_argument("left", type=lambda x: int(x, 0)) + parser.add_argument("right", type=lambda x: int(x, 0)) + args = parser.parse_args() + print(multiply(args.left, args.right)) diff --git a/research/single-band-native-carriers/inputs/triangular/quotient_route.py b/research/single-band-native-carriers/inputs/triangular/quotient_route.py new file mode 100644 index 0000000000..fc8502647a --- /dev/null +++ b/research/single-band-native-carriers/inputs/triangular/quotient_route.py @@ -0,0 +1,340 @@ +"""Move full arbitrary records on lower-unitriangular chart classes.""" + +from math import prod + +from limb_scale import unit_scale +from streaming_routes import copy_bytes, erase, read_exact, shift_field, work_tapes +from ternary_frames import residue + + +def digits_in_order(radix, width): + """Emit each tuple once. Keep a single counter with the stated width.""" + row = [0] * width + while True: + yield tuple(row) + pos = width - 1 + while pos >= 0 and row[pos] == radix - 1: + row[pos] = 0 + pos -= 1 + if pos < 0: + return + row[pos] += 1 + + +def low_count(n): + return prod(3**d - 1 for d in range(1, n + 1)) + + +def free_count(n): + return n * (n + 1) // 2 + + +def low_rows(n): + """Emit the canonical representatives in row-major lexicographic order.""" + limits = tuple(3**width for width in range(n, 0, -1)) + ordinals = [1] * n + while True: + free = list(range(n)) + rows = [] + for ordinal in ordinals: + row = [0] * n + for column in reversed(free): + ordinal, row[column] = divmod(ordinal, 3) + pivot = next(column for column in free if row[column]) + free.remove(pivot) + rows.append(tuple(row)) + yield tuple(rows) + for index in reversed(range(n)): + ordinals[index] += 1 + if ordinals[index] < limits[index]: + break + ordinals[index] = 1 + else: + return + + +def positions(low): + free = tuple(range(len(low))) + result = [] + for row in low: + result.append(free) + pivot = next(c for c in free if row[c] % 3) + free = tuple(c for c in free if c != pivot) + return tuple(result) + + +def canonical_lows(n): + for rows in low_rows(n): + yield tuple(x for row in rows for x in row) + + +def representative(low, high_index, n, digits): + """Decode a true flat low and the lexicographic index of its free high digits.""" + side = 3 ** (digits - 1) + number = high_index + free = [0] * free_count(n) + for j in reversed(range(len(free))): + number, free[j] = divmod(number, side) + if number or high_index < 0: + raise ValueError("The high coordinate lies outside the complete chart") + rows = tuple(tuple(low[i : i + n]) for i in range(0, n * n, n)) + return lift_rows(rows, positions(rows), free) + + +def lift_rows(low, free, digits): + """Read the high digits of a canonical row prefix.""" + values = iter(digits) + result = [] + for row, columns in zip(low, free, strict=True): + lifted = list(row) + for c in columns: + lifted[c] += 3 * next(values) + result.append(tuple(lifted)) + return tuple(result) + + +def right_matrix(n, word, modulus): + rows = [[int(i == j) for j in range(n)] for i in range(n)] + for op, i, *args in word: + if op == "swap": + j = args[0] + for row in rows: + row[i], row[j] = row[j], row[i] + elif op == "scale": + k = residue(args[0], modulus) + for row in rows: + row[i] = row[i] * k % modulus + elif op == "add": + j, k = args + k = residue(k, modulus) + for row in rows: + row[i] = (row[i] + k * row[j]) % modulus + else: + raise ValueError("Unknown matrix factor") + return tuple(tuple(row) for row in rows) + + +def multiply_row(row, matrix, modulus): + return [ + sum(a * x for a, x in zip(row, col, strict=True)) % modulus + for col in zip(*matrix, strict=True) + ] + + +def reduce_row(row, previous, pivots, modulus): + out, multipliers = list(row), [] + for basis, p in zip(previous, pivots, strict=True): + scalar = out[p] * pow(basis[p], -1, modulus) % modulus + multipliers.append(scalar) + out = [(x - scalar * a) % modulus for x, a in zip(out, basis, strict=True)] + return out, tuple(multipliers) + + +def canonical_right(rows, matrix, modulus): + """Return y,L with rows*matrix=L*y and L lower unitriangular.""" + canon, lower, pivots = [], [], [] + for i, row in enumerate(rows): + out, coeffs = reduce_row(multiply_row(row, matrix, modulus), canon, pivots, modulus) + pivots.append(next(j for j, x in enumerate(out) if x % 3)) + canon.append(tuple(out)) + lower.append(coeffs + (1,) + (0,) * (len(rows) - i - 1)) + return tuple(canon), tuple(lower) + + +def row_action(low, before, after, output, pivots, previous, matrix, modulus): + """Return the affine map on this row's free high digits.""" + columns = [] + for c in before: + v, _ = reduce_row(matrix[c], previous, pivots, modulus) + columns.append(tuple(v[k] for k in after)) + a = tuple(zip(*columns, strict=True)) + base = multiply_row([low[k] for k in before], columns, modulus) + shift = tuple(((x - output[c]) % modulus) // 3 for x, c in zip(base, after, strict=True)) + return a, shift + + +def elementary_factors(matrix, side): + """Use row reduction to factor the invertible matrix over the local ring.""" + a = [[x % side for x in row] for row in matrix] + inverses = [] + for j in range(len(a)): + p = next(i for i in range(j, len(a)) if a[i][j] % 3) + if p != j: + a[p], a[j] = a[j], a[p] + inverses.append(("swap", p, j)) + unit = a[j][j] + if unit != 1: + inv = pow(unit, -1, side) + a[j] = [x * inv % side for x in a[j]] + inverses.append(("scale", j, unit)) + for i in range(len(a)): + if i == j or not a[i][j]: + continue + k = a[i][j] + a[i] = [(x - k * y) % side for x, y in zip(a[i], a[j], strict=True)] + inverses.append(("add", i, j, k)) + return reversed(inverses) + + +def affine_packet(source, target, digits, fields, piece, matrix, shift, previous_swap): + """Move each free high digit in one exposed-prefix packet.""" + side = 3**digits + with work_tapes(3) as (a, b, temporary): + copy_bytes(source, a, side**fields * piece) + + def step(action, *args): + nonlocal a, b + a.seek(0) + action(a, b, *args) + erase(a) + a, b = b, a + + def exchange(i, j): + left, right = sorted((i, j)) + step( + previous_swap, + digits, + side**left, + side ** (right - left - 1), + side ** (fields - right - 1) * piece, + ) + + def add(dst, src, k): + k %= side + if not k: + return + if src > dst: + exchange(src, dst) + left, right = sorted((src, dst)) + step( + shift_field, + temporary, + side**left, + side, + side ** (right - left - 1), + side ** (fields - right - 1) * piece, + k, + 0, + ) + if src > dst: + exchange(src, dst) + + for kind, i, *args in elementary_factors(matrix, side): + if kind == "add": + add(i, *args) + elif kind == "swap": + exchange(i, args[0]) + else: + step( + unit_scale, + digits, + side**i, + side ** (fields - i - 1) * piece, + args[0], + previous_swap, + ) + for i, k in enumerate(shift): + if k: + step( + shift_field, + temporary, + side**i, + side, + 1, + side ** (fields - i - 1) * piece, + None, + k, + ) + a.seek(0) + copy_bytes(a, target, side**fields * piece) + + +def high_packet(source, target, low, result_low, matrix, digits, piece, previous_swap, transform): + n = len(low) + q, side, modulus = free_count(n), 3 ** (digits - 1), 3**digits + before, after = positions(low), positions(result_low) + pivots = [next(j for j in free if row[j]) for free, row in zip(after, result_low, strict=True)] + volume = side**q * piece + with work_tapes(2) as (a, b): + if transform is None: + copy_bytes(source, a, volume) + else: + for high in digits_in_order(side, q): + g = lift_rows(low, before, high) + _, lower = canonical_right(g, matrix, modulus) + transform(source, a, lower, piece) + used = 0 + if side > 1: + for i in range(n): + a.seek(0) + for prefix in digits_in_order(side, used): + previous = lift_rows(result_low[:i], after[:i], prefix) + linear, shift = row_action( + low[i], + before[i], + after[i], + result_low[i], + pivots[:i], + previous, + matrix, + modulus, + ) + affine_packet(a, b, digits - 1, q - used, piece, linear, shift, previous_swap) + erase(a) + a, b = b, a + used += len(before[i]) + a.seek(0) + copy_bytes(a, target, volume) + + +def sort_packets(data, tags, target, slots, block, tag_width, tapes): + """Use stable ternary passes. Each tag describes one complete high packet.""" + other, other_tags, *buckets = tapes + for j in reversed(range(tag_width)): + data.seek(0) + tags.seek(0) + for _ in range(slots): + tag = read_exact(tags, tag_width) + bucket = tag[j] + buckets[2 * bucket].write(tag) + copy_bytes(data, buckets[2 * bucket + 1], block) + erase(data) + erase(tags) + for k in range(3): + for tape, dest in ((buckets[2 * k], other_tags), (buckets[2 * k + 1], other)): + length = tape.tell() + tape.seek(0) + copy_bytes(tape, dest, length) + erase(tape) + data, other = other, data + tags, other_tags = other_tags, tags + data.seek(0) + copy_bytes(data, target, slots * block) + erase(data) + erase(tags) + + +def quotient_right_route( + source, target, n, digits, groups, suffix_bytes, word, *, previous_swap=None, transform=None +): + """Move each complete [low][high][body] bank in its own group.""" + if n < 1 or digits < 1 or groups < 0 or suffix_bytes <= 0: + raise ValueError("The full chart and each suffix must have positive size") + if digits > 1 and previous_swap is None: + raise ValueError("The high router requires the preceding ordinary interchange") + word = tuple(word) + slots, q = low_count(n), free_count(n) + block = 3 ** ((digits - 1) * q) * suffix_bytes + if not word: + copy_bytes(source, target, groups * slots * block) + return + matrix = right_matrix(n, word, 3**digits) + with work_tapes(10) as (data, tags, *others): + for _ in range(groups): + for low in low_rows(n): + image, _ = canonical_right(low, matrix, 3) + tags.write(bytes(x for row in image for x in row)) + high_packet( + source, data, low, image, matrix, digits, suffix_bytes, previous_swap, transform + ) + sort_packets(data, tags, target, slots, block, n * n, others) diff --git a/research/single-band-native-carriers/inputs/triangular/receiver.py b/research/single-band-native-carriers/inputs/triangular/receiver.py new file mode 100644 index 0000000000..37646beb73 --- /dev/null +++ b/research/single-band-native-carriers/inputs/triangular/receiver.py @@ -0,0 +1,269 @@ +"""Run the actual binary supplier on canonical charts or directly on the body.""" + +from contextlib import contextmanager +from functools import partial +from math import prod + +from compiler_cut import source_planner, source_rule +from direct_body import direct_line, direct_route +from growing_binary import pipe +from module_atoms import chart_width, lower_tape, pair_shape, total_width +from periodic import Job, run +from raw_binary import Banks, BinarySource, job_frame +from stack_tapes import Arena +from streaming_routes import cold_swap_tape, erase, type_route, work_tapes +from ternary_leaf import select_pivot + +from quotient_route import ( + canonical_lows, + free_count, + low_count, + quotient_right_route, + representative, +) +from same_order_body import SameOrderBody, same_order_line + + +class OwnerBanks(Banks): + """Use the original owner and XOR instructions with the new full-field transition.""" + + def __init__(self, tape, dimension, volume, route): + self.tape = tape + self.dimension = dimension + self.volume = volume + self.transition = route + self.capacity = 0 + self.vacant = [] + self.live = set() + + def route(self, owner, word): + with work_tapes(1) as (out,): + self.start(owner) + self.transition(self.tape, out, word) + out.seek(0) + self.install(owner, out) + + +class Receiver(SameOrderBody): + def __init__(self, dimension, layout, previous=cold_swap_tape, *, direct=False): + if dimension < 2: + raise ValueError("Use a native rank of at least two") + self.n, self.layout, self.previous = dimension, layout, previous + self.direct = direct + self.digits = chart_width(layout) + self.modulus = 3**self.digits + self.atom = 3 ** total_width(layout) + self.low = 1 if direct else low_count(dimension) + self.high = 1 if direct else 3 ** ((self.digits - 1) * free_count(dimension)) + self.rule = source_rule() + self.planner = source_planner() + self.owners = self.planner(dimension).width + self.stock = self.owners * self.low * self.high + self.arena = self.last_storage = None + self.small = None + + def weighted(self, source, target, **shape): + if not self.direct and shape["atoms"] <= self.n**8: + if self.small is None: + self.small = Receiver(self.n, self.layout, self.previous, direct=True) + self.small.arena = self.arena + try: + self.small.weighted(source, target, **shape) + finally: + self.small.arena = None + return + super().weighted(source, target, **shape) + + @contextmanager + def storage(self): + top = self.arena is None + if top: + self.arena = Arena() + try: + yield self.arena + finally: + if top: + self.last_storage = self.arena.counts() + self.arena.close() + self.arena = None + + def compensate(self, source, target, lower, f, older, gap, suffix, weight): + """Solve L times the returned tail equals the old tail. Normalize heads by A.""" + n = self.n + dims = [older] + [self.atom] * (n * f) + [gap] + [self.atom] * (n * f) + volume = prod(dims) * suffix + + def shear(i, k, j, head, entry): + offset = 1 if head else n * f + 2 + src = offset + k * f + j + dst = offset + i * f + j + front = prod(dims[1:src]) + + def coefficients(): + for old in range(older): + value = -entry + if head: + value *= weight(old, i * f + j) * pow( + weight(old, k * f + j), -1, self.modulus + ) + yield front, value % self.modulus + + p, g, s = pair_shape(dims, src, dst, suffix) + return partial( + lower_tape, layout=self.layout, prefix=p, gap=g, suffix_bytes=s, runs=coefficients + ) + + def schedule(): + for i, row in enumerate(lower): + for k in range(i): + if row[k]: + for j in range(f): + for head in (True, False): + yield shear(i, k, j, head, row[k]) + + pipe(self.arena, "triangular-body", source, target, volume, schedule()) + + def transition(self, source, target, word, f, unused, older, gap, suffix, weight): + if self.direct: + direct_route(self, source, target, word, f, unused, older, gap, suffix, weight) + return + body = older * self.atom ** (2 * self.n * f) * gap * suffix + + def compensate(src, dst, lower, size): + self.compensate(src, dst, lower, f, older, gap, suffix, weight) + + quotient_right_route( + source, + target, + self.n, + self.digits, + unused, + body, + word, + previous_swap=self.previous, + transform=compensate, + ) + + def serve_line(self, source, target, frame, f, unused, older, gap, suffix, weight): + """Evaluate the requested projector in each live chart at its actual paid position.""" + if self.direct: + if not frame.word: + (axis,) = frame.mask + head = self.atom ** (axis * f) + mid = self.atom ** ((self.n - 1) * f) * gap + tail = self.atom ** ((self.n - axis - 1) * f) * suffix + + def child_weight(row, j): + return weight(row // head, axis * f + j) + + self.weighted( + source, + target, + atoms=f, + available=unused, + older=older * head, + gap=mid, + suffix=tail, + weight=child_weight, + ) + return + direct_line(self, source, target, frame, f, unused, older, gap, suffix, weight) + return + body = older * self.atom ** (2 * self.n * f) * gap * suffix + packet = self.high * body + length = unused * packet + with self.arena.frames("chart-line", 2) as (split, completed): + type_route(source, split, unused, self.low, packet) + pending, answers = self.arena.pending, self.arena.answers + before, after = pending.top, answers.top + pending.push_reverse(split, self.low * length) + erase(split) + for low in canonical_lows(self.n): + low_rows = tuple(low[i : i + self.n] for i in range(0, self.n**2, self.n)) + pivot = select_pivot(*frame.covered_line(low_rows, 1)) + + def factors(high): + return frame.covered_line( + representative(low, high, self.n, self.digits), self.digits + ) + + with self.arena.frames("chart-packet", 2) as (argument, reply): + pending.pop_forward(argument, length) + argument.seek(0) + same_order_line( + self, + argument, + reply, + pivot=pivot, + factors=factors, + f=f, + unused=unused, + heights=self.high, + older=older, + gap=gap, + suffix=suffix, + weight=weight, + ) + reply.seek(0) + answers.append(reply, length) + if pending.top != before: + raise ArithmeticError("The issued line left an unfinished chart") + answers.take_answers(after, completed) + completed.seek(0) + type_route(completed, target, unused, self.low, packet, inverse=True) + + def compiled(self, source, target, f, unused, older, gap, suffix, weight): + body = older * self.atom ** (2 * self.n * f) * gap * suffix + bank_width = self.low * self.high * body + with self.arena.frames("compiler", 3) as (backing, staged, result): + + def transition(src, dst, word): + self.transition(src, dst, word, f, unused, older, gap, suffix, weight) + + banks = OwnerBanks(backing, self.n, unused * bank_width, transition) + raw = BinarySource(banks) + type_route(source, staged, unused, self.owners, bank_width) + staged.seek(0) + jobs = [] + for _ in range(self.owners): + owner = banks.zero() + banks.install(owner, staged) + jobs.append(Job(owner, tuple(range(self.n)))) + erase(staged) + core = self + + class Machine: + def leaf(self, job): + with core.arena.frames("issued-leaf", 1) as (out,): + banks.start(job.owner) + core.serve_line( + backing, + out, + job_frame(job, core.n), + f, + unused, + older, + gap, + suffix, + weight, + ) + out.seek(0) + banks.install(job.owner, out) + + def native(self, ports, columns): + return core.rule.word.native(ports, columns, raw) + + def zero(self, exemplar): + return Job(banks.zero(), exemplar.axes) + + def retire_zero(self, job): + banks.retire(job.owner, require_zero=True) + + run(self.rule, self.n, jobs, Machine(), planner=self.planner) + for job in jobs: + banks.read(job.owner, result) + banks.retire(job.owner) + if banks.live: + raise ArithmeticError("The periodic supplier retained a live owner") + result.seek(0) + type_route(result, target, unused, self.owners, bank_width, inverse=True) diff --git a/research/single-band-native-carriers/inputs/triangular/retained.py b/research/single-band-native-carriers/inputs/triangular/retained.py new file mode 100644 index 0000000000..47d4944542 --- /dev/null +++ b/research/single-band-native-carriers/inputs/triangular/retained.py @@ -0,0 +1,44 @@ +"""Open the pinned predecessor and its own checked source bundle.""" + +from functools import cache +from hashlib import sha256 +from io import BytesIO +import json +from pathlib import Path +import sys +import tarfile +from tempfile import TemporaryDirectory + + +@cache +def install(): + inputs = Path(__file__).resolve().parent / "inputs" + manifest = json.loads((inputs / "retained.json").read_text()) + archive = (inputs / "retained.tar.gz").read_bytes() + if sha256(archive).hexdigest() != manifest["archive_sha256"]: + raise ValueError("The predecessor archive failed its hash check") + work = TemporaryDirectory(prefix="triangular-multiplier-") + root = Path(work.name) + with tarfile.open(fileobj=BytesIO(archive), mode="r:gz") as packet: + objects = {} + for item in packet: + if not item.isfile() or item.name in objects: + raise ValueError("Unexpected source archive member") + content = packet.extractfile(item).read() + if sha256(content).hexdigest() != item.name: + raise ValueError("A source member failed its hash check") + objects[item.name] = content + if set(objects) != {v["sha256"] for v in manifest["members"].values()}: + raise ValueError("The predecessor source list differs") + for name, member in manifest["members"].items(): + relative = Path(name) + if relative.is_absolute() or ".." in relative.parts: + raise ValueError("The predecessor member path is invalid") + path = root / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(objects[member["sha256"]]) + sys.path.insert(0, str(root)) + from source_inputs import activate + + prior, sources = activate() + return work, root, prior, sources diff --git a/research/single-band-native-carriers/inputs/triangular/same_order_body.py b/research/single-band-native-carriers/inputs/triangular/same_order_body.py new file mode 100644 index 0000000000..0b7afa194a --- /dev/null +++ b/research/single-band-native-carriers/inputs/triangular/same_order_body.py @@ -0,0 +1,190 @@ +"""Execute weighted equal-order atom exchanges on arbitrary complete tape records.""" + +from functools import lru_cache, partial +from math import prod + +from growing_binary import one_weight, pipe +from module_atoms import lower_tape, pair_shape, weighted_pair +from ternary_leaf import lower_coefficient + + +def switch(position, left, right): + if position == left: + return right + if position == right: + return left + return position + + +def pivot_exchanges(n, pivot): + """Return opposite-bank pairs. Move the pivot to the first head and last tail.""" + last = n - 1 + if n == 1: + return () + if pivot == 0: + return ((0, 0), (0, last), (0, 0)) + if pivot == last: + return ((0, last), (last, last), (0, last)) + return ((0, pivot), (pivot, last), (0, last), (pivot, pivot)) + + +def leaf_slots(n, pivot, undo): + """Return the ordered source, destination, sweep and original coordinate.""" + last = n - 1 + sweeps = range(3, -1, -1) if undo else range(4) + order = range(n - 1, -1, -1) if undo else range(n) + for sweep in sweeps: + for i in order: + if i != pivot: + head = switch(i, 0, pivot) + tail = n + switch(i, pivot, last) + source, target = ((0, head), (tail, 2 * n - 1), (0, tail), (head, 2 * n - 1))[sweep] + yield source, target, sweep, i + + +def chart_factors(u, v, pivot, modulus): + unit = u[pivot] + reciprocal = pow(unit, -1, modulus) + b = tuple(x * reciprocal % modulus for x in u) + c = tuple(x * unit % modulus for x in v) + return b, c, pow(c[pivot], -1, modulus) + + +def same_order_line( + core, source, target, *, pivot, factors, f, unused, heights, older, gap, suffix, weight +): + """The fixed low chart supplies one pivot. Each high ordinal supplies its two vectors.""" + n, atom, modulus = core.n, core.atom, core.modulus + rows = heights * older + dims = [unused, rows] + [atom] * (n * f) + [gap] + [atom] * (n * f) + pairs = pivot_exchanges(n, pivot) + + @lru_cache(maxsize=1) + def lifted(high): + u, v = factors(high) + return chart_factors(u, v, pivot, modulus) + + def physical(block, j): + return (2 if block < n else 3) + block * f + j + + def child(left, right, central): + start = left * f + end = (n + right) * f + front = atom**start + middle = gap * atom ** (end - start - f) + last = suffix * atom ** (2 * n * f - end - f) + if central: + + def child_weight(row, j): + high, old = divmod(row // front, older) + _, c, _ = lifted(high) + return weight(old, pivot * f + j) * c[pivot] % modulus + else: + child_weight = one_weight + return partial( + core.weighted, + atoms=f, + available=unused, + older=rows * front, + gap=middle, + suffix=last, + weight=child_weight, + ) + + def shear(src, dst, sweep, i, j, undo): + x, y = physical(src, j), physical(dst, j) + visible = prod(dims[2:x]) + + def coefficients(): + for _ in range(unused): + for high in range(heights): + b, c, inv = lifted(high) + for old in range(older): + a = lower_coefficient( + sweep, + i, + b, + c, + weight(old, pivot * f + j), + weight(old, i * f + j), + inv, + modulus, + ) + yield visible, -a if undo else a + + p, g, s = pair_shape(dims, x, y, suffix) + return partial( + lower_tape, layout=core.layout, prefix=p, gap=g, suffix_bytes=s, runs=coefficients + ) + + def schedule(): + for left, right in pairs: + yield child(left, right, False) + for undo in (False, True): + if undo: + yield child(0, n - 1, True) + for src, dst, sweep, i in leaf_slots(n, pivot, undo): + for j in range(f): + yield shear(src, dst, sweep, i, j, undo) + for left, right in reversed(pairs): + yield child(left, right, False) + + with core.storage() as arena: + pipe(arena, "exposed-leaf", source, target, prod(dims) * suffix, schedule()) + + +class SameOrderBody: + """Both banks have the same order at every recursive boundary.""" + + def weighted(self, source, target, *, atoms, available, older, gap, suffix, weight=one_weight): + f, remainder = divmod(atoms, self.n) + unused = 0 + if f: + unused, rem = divmod(available, self.stock) + if rem or not unused: + raise ValueError("The active call lacks a complete independent fresh stock") + dims = [available * older] + [self.atom] * atoms + [gap] + [self.atom] * atoms + + def stopped(j): + axis = self.n * f + j + shape = pair_shape(dims, 1 + axis, 2 + atoms + axis, suffix) + visible = self.atom**axis + + def coefficients(): + for _ in range(available): + for old in range(older): + yield visible, weight(old, axis) + + return partial( + weighted_pair, + layout=self.layout, + prefix=shape[0], + gap=shape[1], + suffix_bytes=shape[2], + weight=None, + previous_swap=self.previous, + runs=coefficients, + ) + + def schedule(): + for j in range(remainder): + yield stopped(j) + if f: + extra = self.atom**remainder + yield partial( + self.compiled, + f=f, + unused=unused, + older=older, + gap=gap * extra, + suffix=suffix * extra, + weight=weight, + ) + + with self.storage() as arena: + pipe(arena, "weighted", source, target, prod(dims) * suffix, schedule()) + + def body_ordinary(self, source, target, atoms, available, older, gap, suffix): + self.weighted( + source, target, atoms=atoms, available=available, older=older, gap=gap, suffix=suffix + ) diff --git a/research/single-band-native-carriers/inputs/triangular/staged_carriers.py b/research/single-band-native-carriers/inputs/triangular/staged_carriers.py new file mode 100644 index 0000000000..4dd73b0d36 --- /dev/null +++ b/research/single-band-native-carriers/inputs/triangular/staged_carriers.py @@ -0,0 +1,141 @@ +"""Choose six funded binary ranks and balance the chart width against tape motion.""" + +from fractions import Fraction + + +RANK_LOGS = ( + 60_000_000_000, + 400_000_000_000, + 2_500_000_000_000, + 16_000_000_000_000, + 100_000_000_000_000, + 236_800_000_000_000, +) +SOURCE = Fraction(3_879_928_046_148, 10**15) +ORDINARY = Fraction(3_879_928_035_646, 10**15) +KAPPA = Fraction(387_992_803_556, 10**14) +ETA = Fraction(97, 25_000) +COMPLEX_LOG = 3_300_000_000 + + +def ceiling_ratio(numerator, denominator): + return (numerator + denominator - 1) // denominator + + +def quotient_entry_log(rank_log): + """Return a sufficient width logarithm for all quotient rows and high lifts.""" + return ceiling_ratio((2 * rank_log + 64) * 25_000, 24_903) + + +def entrance_logs(rank_logs=RANK_LOGS): + """Return the entry widths that admit a genuine native body at each stage.""" + cuts = [] + for rank_log in rank_logs: + minimum = ceiling_ratio(250 * (rank_log + 64), 249) + floor = rank_log + cuts[-1] + 64 if cuts else 0 + cuts.append(max(minimum, floor)) + return tuple(cuts) + + +def admitted_stage(digits, maximum=6, rank_logs=RANK_LOGS): + if digits < 1 or not 0 <= maximum <= len(rank_logs): + raise ValueError("Use a positive trit width and a supported stage") + available = digits.bit_length() - 1 + cuts = entrance_logs(rank_logs) + return next( + (i for i in range(maximum, 0, -1) if available >= cuts[i - 1]), + 0, + ) + + +def stage_layout(digits, predecessor_width, ceil_root): + """Return the two balanced component sizes and their multiplicities. + + The predecessor width is its complete entry value, or zero at the cold stage. + ceil_root is the exact integer ceiling function used by the native package. + """ + if digits < 1 or predecessor_width < 0: + raise ValueError("Use a positive field and a nonnegative previous width") + width = max(predecessor_width + 1, ceil_root(digits, 250)) + target = ceil_root(digits**97, 25_000) + count = ceiling_ratio(width, target) + short, longer = divmod(width, count) + return longer, short + 1, count - longer, short + + +def prices(rank_logs=RANK_LOGS): + """Bound the native paid moment by comparing exact integers and rationals.""" + previous = Fraction(0) + out = [] + grid = 10**18 + for index, height in enumerate(rank_logs): + # 32 (1+H/8192)^71 < 2^debit. A positive static gap funds every rank. + top = 32 * (8192 + height) ** 71 + debit = (top - 1).bit_length() - 13 * 71 + assert top < 1 << (debit + 13 * 71) + covered = SOURCE - Fraction(debit, height) + bound = (249 * covered + previous) / 250 + at_grid = (bound * grid).__floor__() - 1 + rate = ORDINARY if index == len(rank_logs) - 1 else Fraction(at_grid, grid) + assert previous < rate < min(bound, ETA) + out.append((height, debit, covered, rate)) + previous = rate + return tuple(out) + + +def strong_precision_log(rank_logs=RANK_LOGS): + return entrance_logs(rank_logs)[-1] + COMPLEX_LOG + 1_024 + + +def receipt(): + cuts = entrance_logs() + s = strong_precision_log() + 1 + for i, (h, cut) in enumerate(zip(RANK_LOGS, cuts)): + qcut = quotient_entry_log(h) + assert (1 - ETA) * qcut >= 2 * h + 64 and qcut < 3 * h < 8 * h + assert 249 * cut >= 250 * (h + 64) + if i: + assert cuts[i - 1] + 2 < h + assert cut >= h + cuts[i - 1] + 64 + # Throughout the first complete connected product, every selected + # width e is below 2^top. The next stage can only send max(E_i+1, + # ceil(e_parent^(1/250))) down to this stage. + top = cuts[i + 1] if i + 1 < len(cuts) else s + if i + 1 < len(cuts): + parent_top = cuts[i + 2] if i + 2 < len(cuts) else s + assert parent_top + 250 < 250 * top and cuts[i] + 1 < top + floor_log = cuts[i - 1] if i else 0 + assert top - floor_log <= 8 * h + log_s = (s - 1).bit_length() + assert s - 100 - 16 * (log_s + 1) - COMPLEX_LOG - 2 >= cuts[-1] + old_h = 240_000_000_000_000 + ledger_floor = 234_000_000_000_000 + assert 32 * (8192 + ledger_floor) ** 71 > 1 << (923 + 2471) + assert Fraction(249 * 2471, 250 * ledger_floor) > SOURCE - ORDINARY + old_six_log = 2_881_869_654_258_596 + direct_binary_row_log = 1050 * sum(RANK_LOGS) + 448 * (3 * COMPLEX_LOG + s + 1) + assert direct_binary_row_log < 2**59 + return { + "ordinary_rate": str(ORDINARY), + "complete_kappa": str(KAPPA), + "stage_price_debits": [row[1] for row in prices()], + "rank_log2": list(RANK_LOGS), + "last_rank_log2_strict_lower_for_same_envelope_and_ordinary_price": ledger_floor, + "stage_rates_in_units_of_1e_minus_18": [int(row[3] * 10**18) for row in prices()], + "log2_trit_entries": list(cuts), + "log2_public_precision_sufficient_connected": strong_precision_log(), + "old_log2_public_precision_sufficient_connected": 16 * old_h, + "old_necessary_public_log_floor_for_its_sixth_explicit_gate": old_six_log - 1, + "first_connected_log2_simultaneous_rows_upper": direct_binary_row_log, + "first_connected_log2_log3_simultaneous_rows_strict_upper": 59, + "old_single_low_log2_log3_lower_floor": 2 * old_h - 1, + "old_one_low_vs_all_new_log3_count_log2_ratio_lower_floor": 2 * old_h - 60, + "fixed_native_log2_J_old": 20_000 * old_h, + "fixed_native_log2_J_new": 20_000 * RANK_LOGS[-1], + } + + +if __name__ == "__main__": + import json + + print(json.dumps(receipt(), indent=2)) diff --git a/research/single-band-native-carriers/inputs/triangular/triangular_ordinary.py b/research/single-band-native-carriers/inputs/triangular/triangular_ordinary.py new file mode 100644 index 0000000000..f9f44f1852 --- /dev/null +++ b/research/single-band-native-carriers/inputs/triangular/triangular_ordinary.py @@ -0,0 +1,87 @@ +"""Exchange two complete binary fields through the six native stages.""" + +from functools import partial + +from module_atoms import ceil_root, total_width +from ordinary import least_power, rectangle +from receiver import Receiver +from staged_carriers import RANK_LOGS, admitted_stage, entrance_logs, stage_layout +from streaming_routes import cold_swap_tape, copy_bytes, work_tapes, write_zeros + + +def root_body(source, target, e, prefix, gap, suffix, core): + width = total_width(core.layout) + atoms = (e + width - 1) // width + height = least_power(core.n, atoms) + # The rightmost fresh charts are used first. Every level still needs independent owners. + chart_levels = max(0, height - 8) + rows = core.owners ** (2 + height) * (core.low * core.high) ** chart_levels + k = least_power(3, rows) + if 2 * k >= e: + raise ArithmeticError("The admitted native stock exceeds half its operand") + c, r = divmod(e - k, width) + if c < core.n: + raise ArithmeticError("The admitted ordinary call did not reach its native supplier") + extent = 3**k + padded = ((extent + rows - 1) // rows) * rows + piece = 3 ** (2 * e - k) * gap * suffix + with work_tapes(5) as (expanded, body, genuine, high, trailing): + for _ in range(prefix): + copy_bytes(source, expanded, extent * piece) + write_zeros(expanded, (padded - extent) * piece) + expanded.seek(0) + core.body_ordinary( + expanded, body, c, prefix * padded, 1, 3**r * gap * extent, 3**r * suffix + ) + body.seek(0) + for _ in range(prefix): + copy_bytes(body, genuine, extent * piece) + copy_bytes(body, None, (padded - extent) * piece) + current = genuine + if k: + current.seek(0) + cold_swap_tape(current, high, k, prefix, 3 ** (e - k) * gap, 3 ** (e - k) * suffix) + current = high + if r: + current.seek(0) + cold_swap_tape(current, trailing, r, prefix * 3 ** (e - r), gap * 3 ** (e - r), suffix) + current = trailing + current.seek(0) + copy_bytes(current, target, prefix * extent * piece) + + +def ternary(source, target, e, prefix, gap, suffix, *, maximum, rank_logs=RANK_LOGS): + stage = admitted_stage(e, maximum, rank_logs) + if not stage: + cold_swap_tape(source, target, e, prefix, gap, suffix) + return + rank = 1 << rank_logs[stage - 1] + previous_width = 0 if stage == 1 else 1 << entrance_logs(rank_logs)[stage - 2] + layout = stage_layout(e, previous_width, ceil_root) + width = total_width(layout) + direct = (e + width - 1) // width <= rank**8 + previous = partial(ternary, maximum=stage - 1, rank_logs=rank_logs) + core = Receiver(rank, layout, previous, direct=direct) + root_body(source, target, e, prefix, gap, suffix, core) + + +def ordinary_swap(source, target, bits, prefix, gap, suffix): + if bits < 0 or min(prefix, gap, suffix) < 1: + raise ValueError("Use positive rectangular fields and a nonnegative width") + if not bits: + copy_bytes(source, target, prefix * gap * suffix) + return + extent = 1 << bits + e = least_power(3, extent) + if not admitted_stage(e): + from compact_crt import binary_swap + + binary_swap(source, target, bits, prefix, gap, suffix) + return + padded = 3**e + with work_tapes(2) as (opened, completed): + rectangle(source, opened, extent, padded, prefix, gap, suffix) + opened.seek(0) + ternary(opened, completed, e, prefix, gap, suffix, maximum=6) + completed.seek(0) + rectangle(completed, target, extent, padded, prefix, gap, suffix, restrict=True) diff --git a/research/single-band-native-carriers/lean/.gitignore b/research/single-band-native-carriers/lean/.gitignore new file mode 100644 index 0000000000..01f8cdb637 --- /dev/null +++ b/research/single-band-native-carriers/lean/.gitignore @@ -0,0 +1 @@ +.lake/ diff --git a/research/single-band-native-carriers/lean/BandFlow.lean b/research/single-band-native-carriers/lean/BandFlow.lean new file mode 100644 index 0000000000..71e109b0ab --- /dev/null +++ b/research/single-band-native-carriers/lean/BandFlow.lean @@ -0,0 +1,333 @@ +import Mathlib.Analysis.SpecialFunctions.Pow.Real +import Mathlib.Algebra.Order.BigOperators.Ring.Finset +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Positivity +import Mathlib.Tactic.Ring +import Mathlib.Tactic.Abel + +/-! Integral column counts and the single charge for every edge of a finite band. -/ + +namespace BandFlow + +open scoped BigOperators + +/-- The generator puts this many complete columns at virtual width `x`. -/ +noncomputable def columns (x : ℝ) : ℕ := ⌊x⌋₊ - 1 + +theorem column_window {x : ℝ} (hx : 2 ≤ x) : + x - 2 < (columns x : ℝ) ∧ (columns x : ℝ) ≤ x - 1 := by + have hf : 1 ≤ ⌊x⌋₊ := Nat.le_floor (by simpa using (show (1 : ℝ) ≤ x by linarith)) + have h1 := Nat.floor_le (show 0 ≤ x by linarith) + have h2 := Nat.lt_floor_add_one x + simp only [columns, Nat.cast_sub hf, Nat.cast_one] + constructor <;> linarith + +/-- An internal port takes the first child axes. Its complement is a valid + nonnegative integral rank and costs fewer than two target blocks. -/ +theorem interface_fringe {x y : ℝ} {r k : ℕ} (hx : 2 ≤ x) (hy : 2 ≤ y) + (hr : 0 < r) (hk : 2*r ≤ k) (hmatch : (r : ℝ)*y = (k : ℝ)*x) : + k * columns x ≤ r * columns y ∧ + r * columns y - k * columns x < 2*k := by + obtain ⟨hx₁, hx₂⟩ := column_window hx + obtain ⟨hy₁, hy₂⟩ := column_window hy + have hrr : (0 : ℝ) < r := by exact_mod_cast hr + have hkk : (2 : ℝ)*r ≤ k := by exact_mod_cast hk + have hkp : (0 : ℝ) < k := by linarith + have he : (k : ℝ) * (columns x : ℝ) ≤ (r : ℝ) * (columns y : ℝ) := by + nlinarith [mul_le_mul_of_nonneg_left hx₂ hkp.le, + mul_le_mul_of_nonneg_left hy₁.le hrr.le] + have he' : k * columns x ≤ r * columns y := by exact_mod_cast he + refine ⟨he', ?_⟩ + have hs : (r : ℝ)*(columns y : ℝ) - (k : ℝ)*(columns x : ℝ) < 2*(k : ℝ) := by + nlinarith [mul_le_mul_of_nonneg_left hy₂ hrr.le, + mul_lt_mul_of_pos_left hx₁ hkp] + exact_mod_cast (show ((r * columns y - k * columns x : ℕ) : ℝ) < (2 : ℝ)*k by + simpa only [Nat.cast_sub he', Nat.cast_mul] using hs) + +/-- The true number of source axes pays a fixed fraction of the virtual size. -/ +theorem source_columns {x L : ℝ} (hL : 2 ≤ L) (hx : L ≤ x) : + (1 - 2/L)*x ≤ (columns x : ℝ) := by + have hL' : 0 < L := by linarith + have h := (column_window (hL.trans hx)).1.le + have hdiv : (2/L)*L = (2 : ℝ) := div_mul_cancel₀ _ hL'.ne' + have hz : 0 ≤ 2/L := by positivity + nlinarith [mul_le_mul_of_nonneg_left hx hz] + +private theorem powers_recombine {x C : ℝ} (hx : 0 < x) : + x^C * x^(1-C) = x := by + rw [← Real.rpow_add hx, add_sub_cancel, Real.rpow_one] + +/-- The same factor that pays terminal calls also pays complete rank-one + residuals at internal ports. -/ +theorem port_allowance {C A L k x : ℝ} (hC : 0 ≤ C) (ht : C ≤ 1) + (hL : 0 < L) (hk : 0 < k) (hkA : k ≤ A) (hx : L ≤ x) : + L*k ≤ (A*L)^C * (k*x)^(1-C) := by + have hs := Real.rpow_le_rpow (mul_pos hk hL).le (mul_le_mul_of_nonneg_right hkA hL.le) hC + have hp := Real.rpow_le_rpow (mul_pos hk hL).le (mul_le_mul_of_nonneg_left hx hk.le) + (show 0 ≤ 1-C by linarith) + calc + L*k = (k*L)^C*(k*L)^(1-C) := by rw [powers_recombine (mul_pos hk hL), mul_comm] + _ ≤ _ := mul_le_mul hs hp (Real.rpow_nonneg (mul_pos hk hL).le _) + (Real.rpow_nonneg (mul_nonneg (hk.le.trans hkA) hL.le) _) + +theorem terminal_allowance {C A L a : ℝ} (hC : 0 ≤ C) + (ha : 0 < a) (hstop : a ≤ A*L) : + a ≤ (A*L)^C * a^(1-C) := by + calc + a = a^C * a^(1-C) := (powers_recombine ha).symm + _ ≤ _ := mul_le_mul_of_nonneg_right (Real.rpow_le_rpow ha.le hstop hC) + (Real.rpow_nonneg ha.le _) + +/-- Use one strict native moment for all inputs at a live node. -/ +theorem local_charge {I J : Type*} [Fintype I] [Fintype J] + (k : I → ℝ) (r : J → ℝ) (lost : I → ℝ) {C A L x ε : ℝ} + (hC : 0 ≤ C) (ht : C ≤ 1) (hL : 0 < L) (hx : L ≤ x) + (hε : 0 ≤ ε) (hfund : 2 ≤ ε*L) + (hk : ∀ i, 0 < k i ∧ k i ≤ A) (hr : ∀ j, 0 ≤ r j) + (hfringe : ∀ i, lost i ≤ 2*k i) + (hnative : ∑ j, (r j)^(1-C) ≤ (1-ε) * ∑ i, (k i)^(1-C)) : + (∑ i, lost i) + (A*L)^C * ∑ j, (r j*x)^(1-C) ≤ + (A*L)^C * ∑ i, (k i*x)^(1-C) := by + have hx' : 0 < x := hL.trans_le hx + have hn : ∑ j, (r j*x)^(1-C) ≤ (1-ε) * ∑ i, (k i*x)^(1-C) := by + simpa only [Real.mul_rpow (hr _) hx'.le, Real.mul_rpow (hk _).1.le hx'.le, + Finset.sum_mul, mul_assoc] using + mul_le_mul_of_nonneg_right hnative (Real.rpow_nonneg hx'.le (1-C)) + have hloc : ∀ i, lost i ≤ ε*((A*L)^C*(k i*x)^(1-C)) := by + intro i + have h := port_allowance hC ht hL (hk i).1 (hk i).2 hx + calc + lost i ≤ 2*k i := hfringe i + _ ≤ ε*(L*k i) := by simpa only [mul_assoc] using + mul_le_mul_of_nonneg_right hfund (hk i).1.le + _ ≤ _ := mul_le_mul_of_nonneg_left h hε + have hsum := Finset.sum_le_sum (s := Finset.univ) (fun i _ => hloc i) + simp only [← Finset.mul_sum] at hsum + by_cases hI : Nonempty I + · have hA : 0 ≤ A := ((hk (Classical.choice hI)).1.le).trans (hk _).2 + have hm := Real.rpow_nonneg (mul_nonneg hA hL.le) C + nlinarith [mul_le_mul_of_nonneg_left hn hm] + · have : IsEmpty I := not_nonempty_iff.mp hI + simp only [Fintype.sum_empty, mul_zero] at hn hsum ⊢ + have hq : 0 ≤ ∑ j, (r j*x)^(1-C) := Finset.sum_nonneg fun j _ => + Real.rpow_nonneg (mul_nonneg (hr j) hx'.le) _ + have hz := le_antisymm hn hq + rw [hz] + simp + +/-- Sum the weights whose endpoint is a given node. `none` is the boundary. -/ +noncomputable def atEnd {V E : Type*} [Fintype E] [DecidableEq V] + (endpoint : E → Option V) (weight : E → ℝ) (v : Option V) : ℝ := + ∑ e, if endpoint e = v then weight e else 0 + +private theorem partition {V E : Type*} [Fintype V] [Fintype E] [DecidableEq V] + (endpoint : E → Option V) (weight : E → ℝ) : + (∑ v : V, atEnd endpoint weight (some v)) + atEnd endpoint weight none = ∑ e, weight e := by + classical + unfold atEnd + rw [Finset.sum_comm, ← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro e _ + cases he : endpoint e with + | none => simp + | some v => simp + +/-- Directed edges use the same virtual rank at their two ends. Each edge + is counted once at each end even when the forest has holes. -/ +theorem finite_flow {V E : Type*} [Fintype V] [Fintype E] [DecidableEq V] + (src dst : E → Option V) (weight : E → ℝ) + (fringe : V → ℝ) {M stop : ℝ} (hM : 0 ≤ M) + (node : ∀ v, fringe v + M * atEnd src weight (some v) ≤ + M * atEnd dst weight (some v)) + (terminal : stop ≤ M * atEnd dst weight none) : + (∑ v, fringe v) + stop ≤ M * atEnd src weight none := by + have h := Finset.sum_le_sum (s := Finset.univ) (fun v _ => node v) + simp only [Finset.sum_add_distrib, ← Finset.mul_sum] at h + have hi := partition dst weight + have ho := partition src weight + linarith [mul_le_mul_of_nonneg_left (le_of_eq (hi.trans ho.symm)) hM] + +/-- Price one source at its actual period. The factor `scale` accounts for the + reduction from virtual columns to complete physical columns. -/ +theorem period_price {u v s X q scale C : ℝ} (hu : 0 < u) (hv : 0 < v) + (hX : 0 < X) (hq : 0 ≤ q) (hscale : 0 ≤ scale) (hC : 0 ≤ C) + (hentry : u ≤ X*v) (hphysical : scale*v ≤ s) (hperiod : q*s ≤ 2*u) : + scale*q*v^(1-C) ≤ 2*X^C*u^(1-C) := by + have hvp := Real.rpow_nonneg hv.le (1-C) + have hXp := Real.rpow_nonneg hX.le C + have hs := Real.rpow_le_rpow hu.le hentry hC + rw [Real.mul_rpow hX.le hv.le] at hs + have hcomb : u^C * v^(1-C) ≤ X^C * v := by + calc + _ ≤ (X^C*v^C)*v^(1-C) := mul_le_mul_of_nonneg_right hs hvp + _ = _ := by rw [mul_assoc, powers_recombine hv] + have hreal : q*(scale*v) ≤ 2*u := + (mul_le_mul_of_nonneg_left hphysical hq).trans hperiod + have hm : u^C*(scale*q*v^(1-C)) ≤ u^C*(2*X^C*u^(1-C)) := by + calc + _ = (scale*q)*(u^C*v^(1-C)) := by ring + _ ≤ (scale*q)*(X^C*v) := mul_le_mul_of_nonneg_left hcomb (mul_nonneg hscale hq) + _ = X^C*(q*(scale*v)) := by ring + _ ≤ X^C*(2*u) := mul_le_mul_of_nonneg_left hreal hXp + _ = _ := by conv_lhs => rw [← powers_recombine (C := C) hu] + ring + exact (mul_le_mul_iff_right₀ (Real.rpow_pos_of_pos hu C)).mp hm + +/-- Divide only by returned independent owners. The common lane multiplicity + includes the calls on zero fields and the completed period at each source. -/ +theorem normalized_flow {V E : Type*} [Fintype V] [Fintype E] [DecidableEq V] + (src dst : E → Option V) (weight shares : E → ℝ) (fringe : V → ℝ) + {M Q stop lanes B pad : ℝ} (hM : 0 ≤ M) (hQ : 0 ≤ Q) + (hlanes : 0 ≤ lanes) (hB : 0 < B) + (node : ∀ v, fringe v + M * atEnd src weight (some v) ≤ + M * atEnd dst weight (some v)) + (terminal : stop ≤ M * atEnd dst weight none) + (source : ∀ e, src e = none → weight e ≤ Q*shares e) + (owners : lanes*atEnd src shares none ≤ pad*B) : + (lanes*((∑ v, fringe v) + stop))/B ≤ pad*M*Q := by + have hs : atEnd src weight none ≤ Q*atEnd src shares none := by + simp only [atEnd, Finset.mul_sum] + apply Finset.sum_le_sum + intro e _ + by_cases he : src e = none + · simpa [he] using source e he + · simp [he] + have hp := (finite_flow src dst weight fringe hM node terminal).trans + (mul_le_mul_of_nonneg_left hs hM) + rw [div_le_iff₀ hB] + calc + _ ≤ lanes*(M*(Q*atEnd src shares none)) := mul_le_mul_of_nonneg_left hp hlanes + _ = (M*Q)*(lanes*atEnd src shares none) := by ring + _ ≤ (M*Q)*(pad*B) := mul_le_mul_of_nonneg_left owners (mul_nonneg hM hQ) + _ = _ := by ring + + +/- The row-reserve argument below generalizes PR 7981 to a variable atom exponent. -/ +private theorem depth_growth {eta z : ℝ} (hη : eta ≤ 1/2) (hz : 0 ≤ z) : + 1+z/4 ≤ (2:ℝ)^((1-eta)*z) := by + have h := Real.one_sub_inv_le_log_of_pos (by norm_num : (0:ℝ)<2) + have hl : (1:ℝ)/2 ≤ Real.log 2 := by linarith + have he := Real.add_one_le_exp (Real.log 2*((1-eta)*z)) + rw [Real.rpow_def_of_pos (by norm_num : (0:ℝ)<2)] + have hη' : (1:ℝ)/2 ≤ 1-eta := by linarith + have hprod := mul_le_mul hl hη' (by norm_num : (0:ℝ) ≤ 1/2) + (le_trans (by norm_num) hl) + nlinarith [mul_le_mul_of_nonneg_right hprod hz] + +/-- Charge one stage's complete row reserve, also when the caller is suspended. -/ +theorem stage_reserve {eta h cut t n k : ℝ} (heta : 0 ≤ eta) (hη : eta ≤ 1/2) + (hh : 1 ≤ h) (hc : cut ≤ 3*h) (entered : cut ≤ t) (hn : 1 ≤ n) + (nonnegative : 0 ≤ t) + (first : (2:ℝ)^64 * n^2 ≤ (2:ℝ)^((1-eta)*cut)) + (bill : k ≤ 1+6*(3+t/h)*n^2*(2:ℝ)^(eta*t)) : + k < (2:ℝ)^t/64 := by + have hd' := depth_growth hη (sub_nonneg.mpr entered) + set D := (2:ℝ)^((1-eta)*(t-cut)) + have hd : 1 ≤ D := (by linarith : (1:ℝ) ≤ 1+(t-cut)/4).trans hd' + have hcut : cut/h ≤ 3 := (div_le_iff₀ (by linarith : 0 < h)).mpr hc + have hrem : (t-cut)/h ≤ t-cut := + div_le_self (sub_nonneg.mpr entered) hh + have hsum : 3+t/h ≤ 6*D := by + rw [show t/h = cut/h+(t-cut)/h by ring] + dsimp [D] at * + linarith + have hp : 1 ≤ (2:ℝ)^(eta*t) := + Real.one_le_rpow (by norm_num) (mul_nonneg heta nonnegative) + have prod : 1 ≤ n^2 * D * (2:ℝ)^(eta*t) := + one_le_mul_of_one_le_of_one_le + (one_le_mul_of_one_le_of_one_le (one_le_pow₀ hn) hd) hp + have iden : (2:ℝ)^((1-eta)*cut) * (D * 2^(eta*t)) = 2^t := by + dsimp [D] + rw [← Real.rpow_add (by norm_num : (0:ℝ)<2), + ← Real.rpow_add (by norm_num : (0:ℝ)<2)] + congr 1 + ring + have room := mul_le_mul_of_nonneg_right first + (mul_nonneg (le_trans (by norm_num) hd) (le_trans (by norm_num) hp)) + rw [iden] at room + have tariff := mul_le_mul_of_nonneg_right hsum + (mul_nonneg (sq_nonneg n) (le_trans (by norm_num) hp)) + norm_num at room + nlinarith + +/-- The producer's projector exchanges act on arbitrary additive address + groups. The two operated coordinates can each be a whole product module. -/ +def exchange {M : Type*} [AddCommGroup M] (p : M →+ M) (a : M × M) : M × M := + (a.1 + p (a.2-a.1), a.2 - p (a.2-a.1)) + +def weighted {M : Type*} [AddCommGroup M] (A : M ≃+ M) (p : M →+ M) + (a : M × M) : M × M := + let b := exchange p (A.symm a.1, a.2) + (A b.1, b.2) + +theorem nested_exchange {M : Type*} [AddCommGroup M] (p q : M →+ M) + (nested : ∀ z, p (q z) = p z) (a : M × M) : + exchange p (exchange q a) = exchange (q-p) a := by + obtain ⟨x, y⟩ := a + apply Prod.ext + · simp [exchange, map_sub, nested] + abel + · simp [exchange, map_sub, nested] + abel + +theorem weighted_nested {M : Type*} [AddCommGroup M] (A : M ≃+ M) (p q : M →+ M) + (nested : ∀ z, p (q z) = p z) (a : M × M) : + weighted A p (weighted A q a) = weighted A (q-p) a := by + obtain ⟨x, y⟩ := a + unfold weighted + simp only [AddEquiv.symm_apply_apply, Prod.mk.eta, nested_exchange p q nested] + + +#print axioms weighted_nested +#print axioms stage_reserve +#print axioms interface_fringe +#print axioms source_columns +#print axioms port_allowance +#print axioms terminal_allowance +#print axioms local_charge +#print axioms finite_flow +#print axioms period_price +#print axioms normalized_flow + +/-- A high positive rank can pay an adjacent negative rank at every larger moment. -/ +theorem paired_high_monotone {a b s t : ℝ} (ha : 1 ≤ a) (hab : a ≤ b) + (hs : 0 ≤ s) (hst : s ≤ t) : b ^ s - a ^ s ≤ b ^ t - a ^ t := by + have hst' : 0 ≤ t - s := by linarith + have a0 : 0 < a := by linarith + have b0 : 0 < b := by linarith + have m₁ := Real.rpow_le_rpow a0.le hab hs + have m₂ := sub_le_sub_right (Real.rpow_le_rpow a0.le hab hst') 1 + have prod := mul_le_mul m₁ m₂ (sub_nonneg.mpr (Real.one_le_rpow ha hst')) + (Real.rpow_nonneg b0.le s) + have eq : s + (t - s) = t := by ring + have ea := Real.rpow_add a0 s (t-s) + have eb := Real.rpow_add b0 s (t-s) + rw [eq] at ea eb + linarith only [prod, ea, eb] + +/-- With the stated raw crossing even the five-bit-only invoice needs this rank. -/ +theorem outer_five_bit_floor {H : ℕ} {b c : ℝ} + (raw : c ≤ 38901152866 / (10:ℝ)^13) (rate : 389011527145 / (10:ℝ)^14 ≤ b) + (bill : 5 < (c-b)*H) : 330033003301 ≤ H := by + by_contra! h + have hz : (H : ℝ) ≤ 330033003300 := by exact_mod_cast (show H ≤ 330033003300 by omega) + have step := mul_le_mul_of_nonneg_right (sub_le_sub raw rate) (Nat.cast_nonneg (α := ℝ) H) + norm_num at step + linarith only [hz, step, bill] + +/-- The actual integral invoice at the installed ordinary rate has a stronger floor. -/ +theorem installed_nineteen_bit_floor {H : ℕ} + (bill : 19 < (17108907955/(2:ℝ)^42 - 3890115271496/(10:ℝ)^15)*H) : + 1455682013917 ≤ H := by + by_contra! h + have hz : (H : ℝ) ≤ 1455682013916 := + by exact_mod_cast (show H ≤ 1455682013916 by omega) + norm_num at bill + linarith only [hz, bill] + +#print axioms paired_high_monotone +#print axioms outer_five_bit_floor +#print axioms installed_nineteen_bit_floor + +end BandFlow diff --git a/research/single-band-native-carriers/lean/Profiles.lean b/research/single-band-native-carriers/lean/Profiles.lean new file mode 100644 index 0000000000..2423069aa7 --- /dev/null +++ b/research/single-band-native-carriers/lean/Profiles.lean @@ -0,0 +1,55 @@ +import Mathlib.Tactic.NormNum + +/-! Exact funding and activation at the installed ranks. -/ +namespace Profiles + +def funded (raw eta : ℚ) (debit : ℕ) (previous : ℚ) : List (ℕ × ℕ) → Bool + | [] => true + | (height, ticks) :: rest => + let b : ℚ := ticks / (10 : ℚ)^18 + let c := raw - (debit : ℚ) / height + decide (0 < height ∧ previous < b ∧ b < eta ∧ b < (249*c+previous)/250) && + funded raw eta debit b rest + +def compact : List (ℕ × ℕ) := + [(260000,3819896757624698),(1600000,3879928035646000)] + +def highRate : List (ℕ × ℕ) := + [(25000000,3873797863410106),(160000000,3889931739863747), + (1000000000,3890095626369561),(6000000000,3890112051915585), + (36000000000,3890114745951102),(224000000000,3890115197377000)] + +def priceMatch : List (ℕ × ℕ) := + [(175000000,3874446686267249),(1120000000,3890035713726604), + (7000000000,3890112262836441),(42000000000,3890114821890024), + (252000000000,3890115207602428),(1568000000000,3890115271496000)] + +theorem ordinaryFunding : + funded (2039/524288) (97/25000) 14 0 compact = true ∧ + funded (17108907955/4398046511104) (39/10000) 19 0 highRate = true ∧ + funded (17108907955/4398046511104) (39/10000) 19 0 priceMatch = true := by + norm_num [funded, compact, highRate, priceMatch] + +def positive (m : ℕ) (k b : ℚ) : Prop := + k + 4/(10:ℚ)^14 < b ∧ k + 5/(10:ℚ)^14 < 2043/524288 - 10/(m:ℚ) + +theorem allConsumers : + positive 610000 (387992803556/(10:ℚ)^14) (3879928035646/(10:ℚ)^15) ∧ + positive 1600000 (389011519729/(10:ℚ)^14) (3890115197377/(10:ℚ)^15) ∧ + positive 1600000 (389011527141/(10:ℚ)^14) (3890115271496/(10:ℚ)^15) := by + norm_num [positive] + +def entranceCuts (old : ℕ) : List (ℕ × ℕ) → ℕ + | [] => old + | (h,_) :: rest => entranceCuts + (max ((250*(h+64)+248)/249) (if old=0 then 0 else h+old+64)) rest + +theorem trueWidthCuts : + entranceCuts 0 compact = 1861173 ∧ entranceCuts 0 highRate = 267185100786 ∧ + entranceCuts 0 priceMatch = 1870295703196 := by decide + +#print axioms ordinaryFunding +#print axioms allConsumers +#print axioms trueWidthCuts + +end Profiles diff --git a/research/single-band-native-carriers/lean/SquareSieve.lean b/research/single-band-native-carriers/lean/SquareSieve.lean new file mode 100644 index 0000000000..183d1e6705 --- /dev/null +++ b/research/single-band-native-carriers/lean/SquareSieve.lean @@ -0,0 +1,159 @@ +import Mathlib.Data.Nat.Choose.Sum +import Mathlib.Algebra.Order.Floor.Div +import Mathlib.Tactic + +/-! Pointwise truncation of the coprime indicator in disjoint prime bands. -/ + +namespace SquareSieve + +open Finset + +/-- `hits` counts the primes of one band that divide the current integer. -/ +structure Band where + hits : ℕ + halfOrder : ℕ + +def Band.upper (b : Band) : ℤ := + ∑ i ∈ range (2 * b.halfOrder + 1), (-1 : ℤ) ^ i * (b.hits.choose i : ℤ) + +def Band.good (b : Band) : ℤ := if b.hits = 0 then 1 else 0 + +def Band.omitted (b : Band) : ℤ := b.hits.choose (2 * b.halfOrder + 1) + +theorem oneBand (b : Band) : + 0 ≤ b.good ∧ b.good ≤ b.upper ∧ b.upper - b.good ≤ b.omitted := by + rcases b with ⟨m, k⟩ + cases m with + | zero => simp [Band.good, Band.upper, Band.omitted, sum_range_succ'] + | succ m => + simp only [Band.good, Band.upper, Band.omitted, Nat.succ_ne_zero, ite_false, + Int.alternating_sum_range_choose_eq_choose, Nat.choose_succ_succ', Nat.cast_add] + simp [pow_mul] + +def allUpper : List Band → ℤ + | [] => 1 + | b :: bs => b.upper * allUpper bs + +def allGood : List Band → ℤ + | [] => 1 + | b :: bs => b.good * allGood bs + +/-- Each summand uses the first omitted degree in one band and the upper sum in all other bands. -/ +def correction : List Band → ℤ + | [] => 0 + | b :: bs => b.omitted * allUpper bs + b.upper * correction bs + +theorem joint (bs : List Band) : + 0 ≤ allGood bs ∧ allGood bs ≤ allUpper bs ∧ allUpper bs - allGood bs ≤ correction bs := by + induction bs with + | nil => norm_num [allGood, allUpper, correction] + | cons b bs ih => + rcases ih with ⟨good, leUpper, leCorr⟩ + rcases oneBand b with ⟨bg, bu, bo⟩ + have upper := le_trans good leUpper + have bUpper := le_trans bg bu + refine ⟨mul_nonneg bg good, mul_le_mul bu leUpper good bUpper, ?_⟩ + calc + allUpper (b :: bs) - allGood (b :: bs) = + (b.upper - b.good) * allUpper bs + b.good * (allUpper bs - allGood bs) := by + simp only [allUpper, allGood] + ring + _ ≤ b.omitted * allUpper bs + b.upper * (allUpper bs - allGood bs) := + add_le_add (mul_le_mul_of_nonneg_right bo upper) + (mul_le_mul_of_nonneg_right bu (sub_nonneg.mpr leUpper)) + _ ≤ correction (b :: bs) := + add_le_add le_rfl (mul_le_mul_of_nonneg_left leCorr bUpper) + +theorem lowerIndicator (bs : List Band) : allUpper bs - correction bs ≤ allGood bs := + by linarith only [(joint bs).2.2] + +#print axioms lowerIndicator + +end SquareSieve + +namespace SquareGeometry + +theorem postjumpRise (k : ℕ) (h : 7 ≤ 2 ^ k) : + 2 ^ k + 1 - 7 * (k + 1) ≤ 2 ^ (k + 1) + 1 - 7 * (k + 2) := by + rw [pow_succ] + omega + +#print axioms postjumpRise + +def compactNativeDepth (s : ℕ) : ℕ := + 8 + (s + 609999) / 610000 + (s + 259999) / 260000 + (s + 1599999) / 1600000 + +/-- A complete stack at every compact input, including all suspended native levels. -/ +theorem compactStripe {s handleBits : ℕ} (hs : 2471429 ≤ s) + (handles : 64 * handleBits ≤ s) : + 1024 + ((2 * compactNativeDepth s + 4) * 16384 + 65584 + 2 * handleBits) < s / 2 - 2 := by + unfold compactNativeDepth + omega + +#print axioms compactStripe + +def higherNativeDepth (s : ℕ) : ℕ := + 20 + (s + 1599999) / 1600000 + (s + 24999999) / 25000000 + + (s + 159999999) / 160000000 + (s + 999999999) / 1000000000 + + (s + 5999999999) / 6000000000 + (s + 35999999999) / 36000000000 + + (s + 223999999999) / 224000000000 + +private theorem upperCeil (s d : ℕ) : ((s + d - 1) / d) * d ≤ s + d := + le_trans (Nat.div_mul_le_self _ _) (by omega) + +private theorem highMargins {s bits pos a b c d e f : ℕ} (hs : 267186701154 ≤ s) + (head : 64 * bits ≤ s) (p : pos * 1600000 ≤ s+1600000) + (ha : a * 25000000 ≤ s+25000000) (hb : b * 160000000 ≤ s+160000000) + (hc : c * 1000000000 ≤ s+1000000000) (hd : d * 6000000000 ≤ s+6000000000) + (he : e * 36000000000 ≤ s+36000000000) (hf : f * 224000000000 ≤ s+224000000000) : + 2 * (1027 + (2 * (20+pos+a+b+c+d+e+f) + 4) * 32768 + 65584 + 2 * bits) < s := by + linarith only [hs, head, p, ha, hb, hc, hd, he, hf] + +/-- The separate high-rate stack includes all six ordinary services. -/ +theorem higherStripe {s handleBits : ℕ} (hs : 267186701154 ≤ s) + (handles : 64 * handleBits ≤ s) : + 1024 + ((2 * higherNativeDepth s + 4) * 32768 + 65584 + 2 * handleBits) < s / 2 - 2 := by + have h := highMargins hs handles (upperCeil s 1600000) (upperCeil s 25000000) + (upperCeil s 160000000) (upperCeil s 1000000000) (upperCeil s 6000000000) + (upperCeil s 36000000000) (upperCeil s 224000000000) + have eq (x : ℕ) : s + (x+1) - 1 = s + x := by omega + simp only [eq] at h + change 2 * (1027 + (2 * higherNativeDepth s + 4) * 32768 + 65584 + 2 * handleBits) < s at h + generalize higherNativeDepth s = k at h ⊢ + omega + +#print axioms higherStripe + +private theorem fewerLevels (s d e : ℕ) (hd : 0 < d) (de : d ≤ e) : + (s + (e - 1)) / e ≤ (s + (d - 1)) / d := by + have he : 0 < e := by omega + rw [← Nat.add_sub_assoc he, ← Nat.add_sub_assoc hd, + ← Nat.ceilDiv_eq_add_pred_div, ← Nat.ceilDiv_eq_add_pred_div] + apply (ceilDiv_le_iff_le_mul he).2 + exact le_trans ((ceilDiv_le_iff_le_mul hd).1 le_rfl) (Nat.mul_le_mul_right _ de) + +def priceMatchDepth (s : ℕ) : ℕ := + 20 + (s + 1599999) / 1600000 + (s + 174999999) / 175000000 + + (s + 1119999999) / 1120000000 + (s + 6999999999) / 7000000000 + + (s + 41999999999) / 42000000000 + (s + 251999999999) / 252000000000 + + (s + 1567999999999) / 1568000000000 + +/-- Higher ranks reduce the depth at every public width. -/ +theorem priceMatchStripe {s bits : ℕ} (hs : 1870297303585 ≤ s) (handles : 64 * bits ≤ s) : + 1024 + ((2 * priceMatchDepth s + 4) * 32768 + 65584 + 2 * bits) < s / 2 - 2 := by + apply lt_of_le_of_lt _ (higherStripe (s := s) (by omega) handles) + have depth : priceMatchDepth s ≤ higherNativeDepth s := by + unfold priceMatchDepth higherNativeDepth + have h₁ := fewerLevels s 25000000 175000000 (by decide) (by decide) + have h₂ := fewerLevels s 160000000 1120000000 (by decide) (by decide) + have h₃ := fewerLevels s 1000000000 7000000000 (by decide) (by decide) + have h₄ := fewerLevels s 6000000000 42000000000 (by decide) (by decide) + have h₅ := fewerLevels s 36000000000 252000000000 (by decide) (by decide) + have h₆ := fewerLevels s 224000000000 1568000000000 (by decide) (by decide) + exact Nat.add_le_add (Nat.add_le_add (Nat.add_le_add (Nat.add_le_add + (Nat.add_le_add (Nat.add_le_add (Nat.le_refl _) h₁) h₂) h₃) h₄) h₅) h₆ + omega + +#print axioms priceMatchStripe + +end SquareGeometry diff --git a/research/single-band-native-carriers/lean/lake-manifest.json b/research/single-band-native-carriers/lean/lake-manifest.json new file mode 100644 index 0000000000..f27574d9f7 --- /dev/null +++ b/research/single-band-native-carriers/lean/lake-manifest.json @@ -0,0 +1,117 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + } + ], + "name": "SingleBandCarriers", + "lakeDir": ".lake", + "fixedToolchain": true +} diff --git a/research/single-band-native-carriers/lean/lakefile.toml b/research/single-band-native-carriers/lean/lakefile.toml new file mode 100644 index 0000000000..cac451e8fb --- /dev/null +++ b/research/single-band-native-carriers/lean/lakefile.toml @@ -0,0 +1,12 @@ +name = "SingleBandCarriers" +version = "1.0.0" +defaultTargets = ["Construction"] + +[[require]] +name = "mathlib" +git = "https://github.com/leanprover-community/mathlib4.git" +rev = "d13f23b723b8a846827a245b89c10fc7d3f11612" + +[[lean_lib]] +name = "Construction" +roots = ["BandFlow", "SquareSieve", "Profiles"] diff --git a/research/single-band-native-carriers/lean/lean-toolchain b/research/single-band-native-carriers/lean/lean-toolchain new file mode 100644 index 0000000000..ba8ebf2dba --- /dev/null +++ b/research/single-band-native-carriers/lean/lean-toolchain @@ -0,0 +1 @@ +leanprover/lean4:v4.34.1 diff --git a/research/single-band-native-carriers/linear_geometry.py b/research/single-band-native-carriers/linear_geometry.py new file mode 100644 index 0000000000..f042bfa42f --- /dev/null +++ b/research/single-band-native-carriers/linear_geometry.py @@ -0,0 +1,80 @@ +"""Choose coprime square sides with complete binary windows for the numerical supplier.""" + +from math import gcd, isqrt + +from outer_schedule import Shape, ceil_log2 + + +def minimum_window(s): + """Keep the finite selector. On the proved tail expose 128 complete digit positions.""" + return 64 * s * s if s < 512 else 128 * (4 * (s + 1) + 6) + + +def public_shape(public, extent): + s = ceil_log2(public + 2) + capacity = extent // minimum_window(s) + return Shape(public, extent, 1 << (capacity.bit_length() - 1)) if capacity else None + + +def parameters(input_bits): + if input_bits < 2: + return None + b = ceil_log2(input_bits) + return public_shape(6 * b, ceil_log2((4 * input_bits + b - 1) // b)) + + +def square_sides(shape): + """Emit each actual side. The running product includes 2 and all previous bases.""" + modulus = 2 + for index, width in enumerate(shape.axes()): + denominator = (16 if index % 2 else 4) * shape.count + side = 1 << width + low_square = side - side // denominator + high_square = side - (side + 2 * denominator - 1) // (2 * denominator) + first = max(3, (1 + isqrt(low_square - 1)) | 1) + for base in range(first, isqrt(high_square) + 1, 2): + if gcd(base, modulus) == 1: + modulus *= base + yield base * base + break + else: + raise ArithmeticError("The square interval has no admissible odd base") + + +def connected_exponent(ordinary_width_log, complex_rank_log): + """Return A with p >= 2**A sufficient for a real complex-to-ordinary invocation.""" + if min(ordinary_width_log, complex_rank_log) < 1: + raise ValueError("Both native logarithms must be positive") + target = ordinary_width_log + complex_rank_log + 102 + s = max(512, target) + while s < target + 7 * ceil_log2(s): + s = target + 7 * ceil_log2(s) + dyadic_log = ceil_log2(s) + after_jump = target + 7 * (dyadic_log + 1) + if (1 << dyadic_log) + 1 < after_jump: + s = after_jump + return s - 1 + + +def entrance_geometry(exponent, *, quadratic=False): + """Compute the exact largest side throughout the first certified public precision.""" + if exponent < 511: + raise ValueError("Use a controller exponent of at least 511") + s = exponent + 1 + minimum = 64 * s**2 if quadratic else minimum_window(s) + q = ceil_log2(6 * minimum) + if exponent - q < (6 * exponent).bit_length(): + raise ArithmeticError("The controller correction exceeds the dyadic gap") + largest = ((1 << q) + 5) // 6 + # The older compiler used a uniform bound in s. The linear picker pays the actual width. + private = (1 << 20) * (s + 1) ** 2 if quadratic else 1024 * (largest + s + 67) + s + return { + "public_offset_above_2_to_A": (-pow(2, exponent, 6)) % 6, + "first_extent_bits_minus_b": 4 - exponent, + "last_extent_bits_minus_b": 5 - exponent, + "minimum_width": minimum, + "log2_axis_count": exponent - q, + "largest_axis_width": largest, + "private_clock_log2_upper": private, + "actual_dense_root_entry_log2": 2 * largest, + } diff --git a/research/single-band-native-carriers/ordinary_carrier.py b/research/single-band-native-carriers/ordinary_carrier.py new file mode 100644 index 0000000000..15382c98cb --- /dev/null +++ b/research/single-band-native-carriers/ordinary_carrier.py @@ -0,0 +1,64 @@ +"""Route both signed-product shuttles through the two installed binary carriers.""" + +from functools import partial + +from upstream import install + +install() +from binary_receiver import Receiver +from calibration import COMPACT +from module_atoms import ceil_root +from ordinary import least_power, rectangle +from staged_carriers import admitted_stage, entrance_logs +from streaming_routes import cold_swap_tape, copy_bytes, work_tapes, erase +from triangular_ordinary import root_body + + +def ternary(source, target, digits, prefix, gap, suffix, *, maximum, profile): + stage = admitted_stage(digits, maximum, profile.rank_logs) + if not stage: + cold_swap_tape(source, target, digits, prefix, gap, suffix) + return + stage_body(source, target, digits, prefix, gap, suffix, stage, profile) + + +def stage_body(source, target, digits, prefix, gap, suffix, stage, profile): + """Run the selected stage on the two full ternary fields.""" + rank_logs = profile.rank_logs + rank = 1 << rank_logs[stage - 1] + previous_width = (1 << entrance_logs(rank_logs)[stage - 2]) if stage > 1 else 0 + width = max(previous_width + 1, ceil_root(digits, 250)) + eta = profile.eta + component_width = ceil_root(digits**eta.numerator, eta.denominator) + count = (width + component_width - 1) // component_width + short, longer = divmod(width, count) + layout = (longer, short + 1, count - longer, short) + previous = partial(ternary, maximum=stage - 1, profile=profile) + direct = (digits + width - 1) // width <= rank**8 + backend = Receiver(rank, layout, previous, direct=direct, profile=profile) + root_body(source, target, digits, prefix, gap, suffix, backend) + + +def ordinary_swap(source, target, bits, prefix, gap, suffix, *, profile=COMPACT): + rank_logs = profile.rank_logs + if bits < 0 or min(prefix, gap, suffix) < 1: + raise ValueError("Use a nonnegative width and positive field dimensions") + if not bits: + copy_bytes(source, target, prefix * gap * suffix) + return + extent = 1 << bits + digits = least_power(3, extent) + stages = len(rank_logs) + if not admitted_stage(digits, stages, rank_logs): + from compact_crt import binary_swap + + binary_swap(source, target, bits, prefix, gap, suffix) + return + padded = 3**digits + with work_tapes(2) as (opened, completed): + rectangle(source, opened, extent, padded, prefix, gap, suffix) + opened.seek(0) + ternary(opened, completed, digits, prefix, gap, suffix, maximum=stages, profile=profile) + erase(opened) + completed.seek(0) + rectangle(completed, target, extent, padded, prefix, gap, suffix, restrict=True) diff --git a/research/single-band-native-carriers/positive_dispatch.py b/research/single-band-native-carriers/positive_dispatch.py new file mode 100644 index 0000000000..6846c690e0 --- /dev/null +++ b/research/single-band-native-carriers/positive_dispatch.py @@ -0,0 +1,58 @@ +"""Bind the striped numerical tensor to its installed dyadic carrier.""" + +from compact_columns import Columns +from complex_stage import place_and_apply +from positive import Positive +from product_path import Product as RetainedProduct +from spool import Field, transfer +from striped_tensor import hadamard_tape + + +def native_h(field, low, h, window, offset, precision, swap, rank_log, make_supplier): + digits = (precision + 1).bit_length() + digit = 4 * digits + 6 + # At equality the positive operation already consists only of primitive leaves. + if (h - 1).bit_length() <= rank_log or window < 128 * digit: + columns = Columns(window, offset, digit, 0, 0, 0, 0, swap) + Positive(None, None, h).hadamard(field, low, h, columns) + return + supplier = make_supplier() + carrier = supplier.carrier + if carrier.bit_length() - 1 != rank_log or carrier & (carrier - 1): + raise ArithmeticError("The installed numerical carrier differs from the public rank") + layers = 2 + (h.bit_length() + rank_log - 1) // rank_log + rows = (supplier.owners.bit_length() - 1) * layers + place_and_apply(field, low, h, window, offset, rows, digit, digits**2, swap, supplier) + + +def h_pack(machine, tape, start, end, bit, rank_log, make_supplier): + """Apply the installed numerical word to each spectator stripe, then restore it.""" + if machine.total <= 4096: + # Every stripe here takes the source's local integer H kernel. + return RetainedProduct.h(machine, tape, start, end, bit) + positions = tuple(machine.starts[i] + bit for i in range(start, end)) + + def apply(source, target, width, selected, record): + if end - start != len(selected): + raise ArithmeticError("The spectator stripe lost a selected window") + field = Field(width, machine.wide) + extent = (1 << width) * record + transfer(source, field.stream, extent) + native_h( + field, + selected[0] - bit, + len(selected), + machine.widths[start], + bit, + machine.P, + machine.exchange, + rank_log, + make_supplier, + ) + field.stream.seek(0) + transfer(field.stream, target, extent) + field.retire() + + tape.seek(0) + hadamard_tape(tape, machine.widths, positions, machine.p, 2 * machine.wide, apply) + machine.h_calls += 1 diff --git a/research/single-band-native-carriers/prior_setup.py b/research/single-band-native-carriers/prior_setup.py new file mode 100644 index 0000000000..282d755de1 --- /dev/null +++ b/research/single-band-native-carriers/prior_setup.py @@ -0,0 +1,73 @@ +"""Count records that the preceding fixed compiler must generate.""" + +from collections import Counter + + +def compare(profiles): + from compiler_cut import source_rule + from periodic import Rule, forest, make_planner + from staged_carriers import RANK_LOGS, entrance_logs + + word = source_rule().word + targets = Counter(port.rank for port in word.targets) + paid = Counter(port.rank for port in word.paid) + v = word.power + assert (word.ambient, v, word.floor, word.high_cut) == (134, 480, 16, 11) + assert targets[8] and targets[64] and 8**320 * 64**160 == word.floor**v + assert min(paid) > 0 + high = sum(count for rank, count in paid.items() if rank >= 14) + assert sum(paid.values()) == 107460 and high == 3108 + + ambient_log = (word.ambient**v - 1).bit_length() + floor_log = (word.floor**v).bit_length() - 1 + block_log = (word.high_cut**v).bit_length() - 1 + high_log = (high**v).bit_length() - 1 + all_log = (sum(paid.values())**v).bit_length() - 1 + assert (ambient_log, floor_log, block_log, high_log, all_log) == (3392, 1920, 1660, 5568, 8022) + + # Count the exits of the actual predecessor on finite words with repeated ranks. + rule = Rule(8, (4, 5), (2, 2, 3)) + for limit in (8, 31, 32, 127, 128, 512): + plan = forest(rule, limit) + depth = plan.height + 1 + assert len(plan.exits) == 3**depth + assert sum(rank == 2**depth for rank in plan.exits.values()) == 2**depth + + planner = make_planner(rule) + for rank in (8192, 32768): + outer = planner(rank) + places = outer.forest.height + 1 + child = planner(2**places) + assert child.forest is not None + assert outer.leaves >= 2**places * len(child.forest.exits) + + H = RANK_LOGS[-1] + assert H == 236800000000000 + restricted_total = 0 + levels = [] + for _ in range(7): + places = (H - 2 - ambient_log) // floor_log + 1 + assert places > 0 + levels.append((H, places, restricted_total + places * all_log)) + restricted_total += places * high_log + H = places * block_log + + top_table = levels[0][-1] + expanded_stream = levels[-1][-1] + assert (top_table, expanded_stream) == (989379999989304, 3366293830151418) + old_gate = entrance_logs()[-1] + assert old_gate == 355760240964240 + ratios = {} + for name in ("compact", "high-rate", "price-match"): + current = profiles[name] + setup = current["log2_all_fixed_setup_upper"] + assert current["log2_sufficient_public_precision"] + 1 < old_gate + ratios[name] = expanded_stream // setup + assert ratios == {"compact": 2054622, "high-rate": 14, "price-match": 2} + return { + "top_exit_table_log2_lower": top_table, + "expanded_stream_log2_lower": expanded_stream, + "lower_to_upper_exponent_ratio_floor": ratios, + "old_final_gate_log2": old_gate, + "levels": levels, + } diff --git a/research/single-band-native-carriers/resources.py b/research/single-band-native-carriers/resources.py new file mode 100644 index 0000000000..36cf93f347 --- /dev/null +++ b/research/single-band-native-carriers/resources.py @@ -0,0 +1,77 @@ +"""Compute the complete entrance and the costs for each fully priced installation.""" + +from fractions import Fraction + +from calibration import COMPLEX_POWER, PROFILES, SETUP_DEGREE, prices +from check_activation_space import receipt +from linear_geometry import entrance_geometry +from staged_carriers import entrance_logs + + +def requirements(profile): + bit_loss, complex_loss, rates = prices(profile) + ranks = profile.rank_logs + cuts = entrance_logs(ranks) + hmax = max(*ranks, profile.complex_log) + # All per-stage programs persist. J includes each generator and its scratch. + jlog = hmax * SETUP_DEGREE + total_log = jlog + (len(ranks) + 1).bit_length() + stock = receipt( + ranks, profile.complex_log, cuts[-1], total_log, profile.power, complex_power=COMPLEX_POWER + ) + s = stock["initial_s"] + # Each small rank really reaches a body and a positive stopped call into its predecessor. + for i, h in enumerate(ranks): + assert 512 * profile.power <= h + assert ( + h + >= 2 + + (134**profile.power).bit_length() + + (127**profile.power).bit_length() + + profile.floor.bit_length() + ) + assert not i or cuts[i - 1] < h + assert cuts[i] >= (250 * (h + 64) + 248) // 249 + assert 512 * COMPLEX_POWER <= profile.complex_log + assert prices(profile)[2][-1][-1] == profile.ordinary + assert 872 * COMPLEX_POWER * (profile.complex_log + 1) ** 2 < ( + 1 << min(1024, profile.complex_log) + ) + assert s - 100 - 7 * (s - 1).bit_length() >= cuts[-1] + profile.complex_log + 2 + assert Fraction(1, 250) > profile.eta > profile.ordinary > profile.kappa + return { + "kappa": str(profile.kappa), + "binary_rank_logs": ranks, + "complex_rank_log": profile.complex_log, + "binary_entrance_logs": cuts, + "full_binary_debit": bit_loss, + "full_positive_debit": complex_loss, + "ordinary_rate": str(profile.ordinary), + "component_exponent": str(profile.eta), + "rate_ticks_e18": [int(rate * 10**18) for _, _, rate in rates], + "log2_dominant_J": jlog, + "log2_all_fixed_setup_upper": total_log, + "log2_rank_part_of_recurring_envelope": 100 * jlog, + **stock, + } + + +def all_profiles(): + old = 355_763_540_965_264 + return { + "previous": { + "rank_logs": ( + 60_000_000_000, + 400_000_000_000, + 2_500_000_000_000, + 16_000_000_000_000, + 100_000_000_000_000, + 236_800_000_000_000, + ), + "complex_rank_log": 3_300_000_000, + "log2_dominant_J": 4_736_000_000_000_000_000, + "connected_precision_exponent": old, + "geometry": entrance_geometry(old, quadratic=True), + }, + **{name: requirements(profile) for name, profile in PROFILES.items()}, + } diff --git a/research/single-band-native-carriers/strict_moment.py b/research/single-band-native-carriers/strict_moment.py new file mode 100644 index 0000000000..f95dff0192 --- /dev/null +++ b/research/single-band-native-carriers/strict_moment.py @@ -0,0 +1,72 @@ +"""Bound the two powered moments from all the actual labelled port ranks.""" + +from collections import Counter +from fractions import Fraction +from math import isqrt + +from calibration import COMPLEX_C, COMPLEX_POWER + +UNIT = 1 << 112 + + +def ceiling(a, b): + return -(-a // b) + + +def power_interval(rank, exponent): + """Return outward integer bounds in units of 2^-112 for a dyadic power.""" + k, d = exponent.numerator, exponent.denominator + if rank <= 0 or k < 0 or d & (d - 1): + raise ValueError("Use positive ranks and nonnegative dyadic powers") + whole, residue = divmod(k, d) + low = high = rank**whole * UNIT + lo_root = hi_root = rank * UNIT + while d > 1: + d //= 2 + lo_root = isqrt(lo_root * UNIT) + hi_root = 1 + isqrt(hi_root * UNIT - 1) + if residue & d: + low = low * lo_root // UNIT + high = ceiling(high * hi_root, UNIT) + return low, high + + +def moment(hist, exponent, upper): + return sum(count * power_interval(rank, exponent)[upper] for rank, count in hist.items()) + + +def certify(word, c, tilt, drop, power, slack_bits, cutoff): + if (word.power, word.floor, word.low_cut, word.high_cut) != (power, cutoff, 12, 12): + raise ValueError("The evaluated strictifier differs from the installed one") + targets = Counter(p.rank for p in word.targets) + paid = Counter(p.rank for p in word.paid) + t = 1 - c + lower = moment(targets, t, False) + alpha = Fraction(moment(paid, t, True), lower) + gamma = Fraction(moment(paid, t + tilt, True) * UNIT, lower * power_interval(12, tilt)[0]) + loss = Fraction(moment(targets, t - drop, True) * power_interval(cutoff, drop)[1], lower * UNIT) + deficit = 1 - alpha**power - 2 * gamma**power - loss**power + if not (tilt >= c and deficit > Fraction(1, 1 << slack_bits)): + raise ArithmeticError("The strict local surplus cannot pay all physical fringe axes") + return { + "raw_productive": sum(targets.values()), + "raw_paid": sum(paid.values()), + "productive": dict(sorted(targets.items())), + "paid": dict(sorted(paid.items())), + "surplus_lower_units_1e12": int(10**12 * deficit), + } + + +def both(binary, positive, profile): + return ( + certify( + binary, + profile.bit_c, + Fraction(19, 64), + Fraction(31 if profile.power == 228 else 26, 64), + profile.power, + profile.floor.bit_length() - 2, + 15 if profile.power == 228 else 16, + ), + certify(positive, COMPLEX_C, Fraction(19, 64), Fraction(23, 64), COMPLEX_POWER, 14, 16), + ) diff --git a/research/single-band-native-carriers/strong-bit.json.gz b/research/single-band-native-carriers/strong-bit.json.gz new file mode 100644 index 0000000000..16f8cafb1c Binary files /dev/null and b/research/single-band-native-carriers/strong-bit.json.gz differ diff --git a/research/single-band-native-carriers/strong_binary.py b/research/single-band-native-carriers/strong_binary.py new file mode 100644 index 0000000000..913e4faaa3 --- /dev/null +++ b/research/single-band-native-carriers/strong_binary.py @@ -0,0 +1,125 @@ +"""Run the 111-port binary source on the retained physical bank machine. + +The catalogue initialization and the outer 36-call interpreter use the +construction of PR 7914. The inner MOVE, ADD, SWAP, INIT and CLEAR interpreter +and the complete chart constructors come from that package. +""" + +from functools import cache +from hashlib import sha256 +from pathlib import Path + +from factored_frames import inverse_word +from powered import PoweredWord +from raw_binary import BinarySource, Catalogue, job_frame, placed_job +from tagged_sources import BIT_CALLER, BIT_PIN, binary_ports, packed, pinned + + +SOURCE_SHA256 = "74e93daf2b7acf794ffb51f92f03f51556f68126d41ee13a8969bddb4cbe6326" + + +@cache +def graph(): + data = Path(__file__).with_name("strong-bit.json.gz").read_bytes() + if sha256(data).hexdigest() != SOURCE_SHA256: + raise ValueError("The 111-port binary source differs") + return packed(data) + + +@cache +def caller(): + return packed(pinned(BIT_CALLER, BIT_PIN)) + + +@cache +def native_word(power=128): + if power not in (128, 228): + raise ValueError("Select a certified binary power") + raw = binary_ports(graph(), caller()) + floor = 16 if power == 128 else 15 + return PoweredWord(raw.ambient, raw.targets, raw.paid, power, floor, 12, 12) + + +class ActiveCatalogue(Catalogue): + def __init__(self, dimension, columns): + self.dimension = dimension + self.columns = columns + self.graph = graph() + self.root = caller() + self.ports = self.root["ports"] + self.body = self.root["body_rank"] + self.ambient = 1 + self.body + self.body * self.root["stages"] + if self.ambient * columns > dimension or columns < 1: + raise ValueError("The complete source ambient and its columns must fit the frame") + + for name in ( + "raw_projector", + "difference", + "joint", + "target", + "head", + "idle", + "port_stage", + ): + setattr(self, name, cache(getattr(self, name))) + + +@cache +def active_catalogue(dimension, columns): + return ActiveCatalogue(dimension, columns) + + +class StrongBinarySource(BinarySource): + """Use the same literal graph for the paid jobs, true charts and owner program.""" + + def raw(self, inputs, columns): + c = active_catalogue(self.banks.dimension, columns) + active, restores = {}, [] + for tag, job in inputs: + target = c.target(tag) + source = job_frame(job, self.banks.dimension) + matcher = source.matcher_to(target) + self.banks.route(job.owner, matcher) + active[tag] = job.owner + restores.append((job.owner, matcher)) + for clock, row in enumerate(c.root["events"]): + op, *args = row + if op == "LOCAL": + stage, x, y = args + pairs = [(active["root", x, p], active["root", y, p]) for p in range(c.ports)] + for p, pair in enumerate(pairs): + matcher = c.port_stage(p, stage) + for owner in pair: + self.banks.route(owner, matcher) + owners = ( + [a for a, b in pairs] + + [b for a, b in pairs] + + [active["helper", clock, i] for i in range(2 * c.ports, c.graph["public"])] + ) + yield from self.inner(clock, owners, c) + for p, pair in enumerate(pairs): + back = tuple(inverse_word(c.port_stage(p, stage))) + for owner in pair: + self.banks.route(owner, back) + elif op == "IDLE_ONE": + x, stages = args + frame = c.idle(tuple(stages)) + for p in range(c.ports): + yield (op, clock, p), placed_job(active["root", x, p], frame) + else: + x, y = args + for p in range(c.ports): + left, right = active["root", x, p], active["root", y, p] + if op == "ADD": + self.banks.xor(left, right) + elif op == "SWAP": + self.banks.swap(left, right) + elif op == "QUERY": + borrowed = self.banks.clone(right) + yield (op, clock, p), placed_job(borrowed, c.head(p)) + self.banks.xor(left, borrowed) + self.banks.retire(borrowed) + else: + raise ValueError("Unknown binary root opcode") + for owner, matcher in reversed(restores): + self.banks.route(owner, tuple(inverse_word(matcher))) diff --git a/research/single-band-native-carriers/strong_complex.py b/research/single-band-native-carriers/strong_complex.py new file mode 100644 index 0000000000..3d5fa9f9b2 --- /dev/null +++ b/research/single-band-native-carriers/strong_complex.py @@ -0,0 +1,118 @@ +"""Bind the 48-call physical receiver to the 5,674-transfer source.""" + +from functools import cache +from fractions import Fraction +from types import SimpleNamespace +from hashlib import sha256 +from pathlib import Path +import gzip +import json + +WORD = "38d2b3a2311a9ba5fee091cc7aa204c7ed95651aec95d75184b2391df090cbfb" +LAYOUT = "0ce3f9e383fc4bfdd22612b9e34fc9759d97204215937b82d23aec2cedd9b8ee" +ADDITIONAL = "6ff19e063214b1698165d9da1fcd6182d9b837ac2d6e61aa71658b629aabbc95" +GRID = 154113755636630124932500335624192000 +DYADIC = 30 +ODD = GRID >> DYADIC + + +def digest(value): + raw = json.dumps(value, separators=(",", ":"), sort_keys=True).encode() + return sha256(raw).hexdigest() + + +def packed(path): + return json.loads(gzip.decompress(path.read_bytes())) + + +@cache +def load_changed(data): + """Reconstruct the 1,291-role program from the literal graph and its three journals.""" + import sys + + data = Path(data) + source = data / "complex-source" + for name, pin in json.loads((data / "complex-source.json").read_bytes()).items(): + if sha256((source / name).read_bytes()).hexdigest() != pin: + raise ValueError(f"The circuit source differs at {name}") + sys.path.insert(0, str(source)) + from verify_split_helpers import read, rebuild, reconstruct + + parent, layout = rebuild() + graph, _ = reconstruct(parent, read("BANK-FACTORS.json.gz")) + if digest(graph) != WORD or digest(layout) != LAYOUT: + raise ValueError("The reconstructed Gaussian graph or its owner layout differs") + return graph, layout + + +def required_pairs(graph, layout): + main = ( + set(layout["live"]) + | {x + 112 for x in layout["live"]} + | set(layout["hosted"]["X2"]) + | set(layout["hosted"]["Y2"]) + ) + helpers = { + (a, b) + for i, (a, b) in enumerate(zip(graph["initial"], graph["final"], strict=True)) + if i not in main + } + return helpers | {(a, b) for _, a, b in graph["moves"]} + + +def word(graph, layout): + from powered import PoweredWord + from tagged_sources import PINS, complex_ports, pinned + import tagged_sources + + local = { + key: pinned(key, PINS[key]) + for key in ("mixed_caller.py", "closed_caller.py", "data/CONJUGATE-CALLER.json.gz") + } + key = "data/CALLER.json.gz" + caller = tagged_sources.packed(pinned(key, PINS[key])) + raw = complex_ports(graph, layout, caller, local) + return PoweredWord(153, raw.targets, raw.paid, 128, 16, 12, 12) + + +@cache +def artifacts(grade, data): + """Construct every paid Clifford factor and true port from its signed frame.""" + from charts import native_catalogue + from closed_caller import placement, templates + from mixed_caller import instructions, layout_bindings + from raw48 import contact, monomial, read_json + + graph, layout = load_changed(data) + catalogue = native_catalogue(graph, layout) + if digest(catalogue) != "8a9ff9558bf5fa3854699937fe063f98c86467d5d32a4488bfc878d2be081e70": + raise ValueError("The generated all-column Clifford catalogue differs") + tables = Path(grade) / "retained/data" + bases = read_json(tables / "CALLER-PHASE-BASES.json")["by_q"] + contacts = [contact(q, tuple(bases[str(q)])) for q in layout["ports"]] + caller = read_json(tables / "CALLER.json.gz") + words, roots = templates(caller), placement(caller) + binds, offsets, census = layout_bindings(words, roots, layout, 48) + hosted = layout["hosted"] + pairs = dict(zip(hosted["Dports"], zip(hosted["X2"], hosted["Y2"], strict=True), strict=True)) + regs = [(x, x + 112) + pairs.get(i, ()) for i, x in enumerate(layout["live"])] + return SimpleNamespace( + graph=graph, + layout=layout, + contacts=contacts, + words=words, + roots=roots, + offsets=offsets, + instructions=lambda: instructions(words, roots, binds, offsets), + binding_receipt=census, + factors={ + (a, b): (r["rank"], monomial(r["right"]), monomial(r["left"])) + for a, b, r in catalogue["pairs"] + }, + port=[(monomial(left), monomial(right)) for _, left, right in catalogue["ports"]], + regs=regs, + main={n for row in regs for n in row}, + odd=ODD, + moves={i: (a, b) for i, a, b in graph["moves"]}, + forms={i: tuple((j, Fraction(c)) for j, c in row) for i, row in graph["forms"]}, + ) diff --git a/research/single-band-native-carriers/upstream.py b/research/single-band-native-carriers/upstream.py new file mode 100644 index 0000000000..f68872df22 --- /dev/null +++ b/research/single-band-native-carriers/upstream.py @@ -0,0 +1,30 @@ +"""Load the immutable numerical and routing operations for this construction.""" + +from functools import cache +from hashlib import sha256 +import json +from pathlib import Path +import sys + +HERE = Path(__file__).resolve().parent + + +@cache +def install(): + inputs = HERE / "inputs" + folder = inputs / "triangular" + record = json.loads((inputs / "triangular.json").read_bytes()) + for name, digest in record["sha256"].items(): + if sha256((folder / name).read_bytes()).hexdigest() != digest: + raise ValueError(f"The retained source differs at {name}") + sys.path.insert(0, str(folder)) + from retained import install as open_triangular + + result = open_triangular() + review = inputs / "review" + for name, pin in json.loads((inputs / "review.json").read_bytes()).items(): + if sha256((review / name).read_bytes()).hexdigest() != pin["sha256"]: + raise ValueError(f"The source for the Clifford generator or review differs at {name}") + grade = result[-1] / "research/grade14-native-realization" + sys.path.extend(map(str, (review, grade, grade / "retained"))) + return result diff --git a/research/single-band-native-carriers/verify.py b/research/single-band-native-carriers/verify.py new file mode 100644 index 0000000000..c0b5cbeba1 --- /dev/null +++ b/research/single-band-native-carriers/verify.py @@ -0,0 +1,110 @@ +"""Run one self-contained research check with the stated source versions.""" + +from argparse import ArgumentParser +from fractions import Fraction +import json +from pathlib import Path +import runpy +import sys + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from upstream import install + +_, native, bounded, source = install() +data = HERE / "inputs" +grade = source / "research/grade14-native-realization" + + +def main(): + parser = ArgumentParser(description=__doc__) + parser.add_argument( + "mode", + choices=( + "price", + "band", + "binary", + "grid", + "atlas", + "physical", + "product", + "dense", + "resources", + "wide-product", + ), + ) + mode = parser.parse_args().mode + if mode == "price": + from calibration import PROFILES + from strict_moment import both + from strong_binary import native_word + from strong_complex import word, load_changed + from resources import all_profiles + from prior_setup import compare + from check_linear_geometry import run + from inputs.triangular.multiplier import precision + + positive = word(*load_changed(data)) + for name, profile in PROFILES.items(): + result = both(native_word(profile.power), positive, profile) + print(name, *(r["surplus_lower_units_1e12"] for r in result)) + receipt = json.loads(json.dumps(all_profiles())) + assert receipt == json.loads((HERE / "REQUIREMENTS.json").read_bytes()) + print(json.dumps(receipt, sort_keys=True)) + print(run(precision)) + print(compare(receipt)) + elif mode == "band": + runpy.run_path(str(HERE / "check_band.py"), run_name="__main__") + from check_epoch_reentry import trial + + print(trial()) + elif mode == "dense": + from check_dense_band import dense + + print(dense()) + elif mode == "binary": + from check_strong_binary import main as binary + from check_weighted_binary import weighted + + binary() + weighted() + elif mode == "grid": + from check_strong_complex import literal_grid + from strong_complex import load_changed + + result = literal_grid(*load_changed(data)) + print(json.dumps(result, sort_keys=True)) + elif mode == "atlas": + from check_strong_complex import atlas, caller + from strong_complex import load_changed + + g, l = load_changed(data) + mass = Fraction( + 205356183613728386434052488657699504746980105023, 1621896683681232672237748224000 + ) + print(json.dumps(atlas(grade, g, l, data), sort_keys=True)) + print(json.dumps(caller(grade, g, l, data, mass), sort_keys=True)) + elif mode == "physical": + from check_strong_physical import run + from check_strong_raw_word import run as raw + + print(run(grade, data), raw(grade, data)) + elif mode == "product": + from check_product import physical_product + + print(json.dumps(physical_product()), flush=True) + elif mode == "wide-product": + from check_product import matched + + for row in matched(wide=True): + print(json.dumps(row), flush=True) + else: + from resources import all_profiles + + print(json.dumps(all_profiles(), indent=2, sort_keys=True)) + return + print("PASS_NATIVE_SCALE", mode, flush=True) + + +if __name__ == "__main__": + main() diff --git a/research/single-band-native-carriers/verify_formal.py b/research/single-band-native-carriers/verify_formal.py new file mode 100644 index 0000000000..0f35787441 --- /dev/null +++ b/research/single-band-native-carriers/verify_formal.py @@ -0,0 +1,50 @@ +"""Build the project, inspect its declared axioms, and replay each kernel object.""" + +from pathlib import Path +import re +import subprocess + +ROOT = Path(__file__).resolve().parent / "lean" + + +def replay(): + expected = set() + for file in ROOT.glob("*.lean"): + source = re.sub(r"/-.*?-/|--[^\n]*", "", file.read_text(), flags=re.S) + if re.search(r"\b(sorry|admit|axiom|unsafe|native_decide)\b", source): + raise ValueError(f"The proof contains an unchecked declaration in {file.name}") + expected.update( + (file.name, n.split(".")[-1]) + for n in re.findall(r"^#print axioms ([\w.]+)", source, re.M) + ) + build = subprocess.run( + ["lake", "--wfail", "build"], cwd=ROOT, capture_output=True, text=True + ) + report = build.stdout + build.stderr + print(report, end="") + build.check_returncode() + if "Build completed successfully" not in report or "sorryAx" in report: + raise ValueError("The formal build or axiom audit failed") + rows = re.findall( + r"info: ([\w.]+\.lean):\d+:\d+: '([^']+)' (?:depends on axioms: \[([^\]]+)\]|does not depend on any axioms)", + report, + ) + assert {(file, name.split(".")[-1]) for file, name, _ in rows} == expected + axioms = {a for _, _, items in rows for a in items.split(", ") if a} + assert axioms == {"propext", "Classical.choice", "Quot.sound"} + for name in sorted({Path(f).stem for f, _ in expected}): + run = subprocess.run( + ["lake", "env", "leanchecker", "-v", name], + cwd=ROOT, + check=True, + capture_output=True, + text=True, + ) + if "replaying " + name not in run.stdout + run.stderr: + raise ValueError("Missing kernel replay of " + name) + print(run.stdout + run.stderr, end="") + print("PASS_NATIVE_SCALE_KERNEL", len(expected), "axiom reports", sorted(axioms)) + + +if __name__ == "__main__": + replay() diff --git a/research/single-band-native-carriers/verify_sources.py b/research/single-band-native-carriers/verify_sources.py new file mode 100644 index 0000000000..a3ef7f7788 --- /dev/null +++ b/research/single-band-native-carriers/verify_sources.py @@ -0,0 +1,60 @@ +"""Compare runtime sources and independent reviewers with their original Git objects.""" + +from hashlib import sha256 +import json +from pathlib import Path +import subprocess +import sys + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from upstream import install + + +def verify(repo): + _, installed, _, source = install() + pins = [] + tri = json.loads((HERE / "inputs/triangular.json").read_bytes()) + for file, digest in tri["sha256"].items(): + pins.append( + ( + HERE / "inputs/triangular" / file, + digest, + tri["commit"], + tri["directory"] + "/" + file, + ) + ) + middle = json.loads((HERE / "inputs/triangular/inputs/retained.json").read_bytes()) + for file, item in middle["members"].items(): + pins.append((installed / file, item["sha256"], middle["commit"], item["path"])) + oldest = json.loads((installed / "inputs/origins.json").read_bytes()) + for file, item in oldest["members"].items(): + pins.append((source / file, item["sha256"], item["commit"], file)) + for file, item in json.loads((HERE / "inputs/review.json").read_bytes()).items(): + pins.append((HERE / "inputs/review" / file, item["sha256"], item["commit"], item["path"])) + pins.append( + ( + HERE / "strong-bit.json.gz", + "74e93daf2b7acf794ffb51f92f03f51556f68126d41ee13a8969bddb4cbe6326", + "fb9b6a7b0d27da1cf98430893a3016bf811e2aa4", + "research/p104-live-relative-gain/BINARY-CANDIDATE.json.gz", + ) + ) + for name, digest in json.loads((HERE / "inputs/complex-source.json").read_bytes()).items(): + pins.append( + ( + HERE / "inputs/complex-source" / name, + digest, + "fb9b6a7b0d27da1cf98430893a3016bf811e2aa4", + "research/p104-live-relative-gain/" + name, + ) + ) + for file, digest, revision, name in pins: + data = subprocess.check_output(["git", "-C", str(repo), "show", revision + ":" + name]) + if sha256(data).hexdigest() != digest or data != file.read_bytes(): + raise ValueError(f"The source differs at {revision}:{name}") + print("PASS_NATIVE_SCALE_SOURCE_BINDINGS", len(pins)) + + +if __name__ == "__main__": + verify(Path(sys.argv[1]))