diff --git a/research/clifford-sparse-row/COST.md b/research/clifford-sparse-row/COST.md new file mode 100644 index 0000000000..bef91d3168 --- /dev/null +++ b/research/clifford-sparse-row/COST.md @@ -0,0 +1,65 @@ +# Cost of one width-13 Bell observation + +This is the cost of the coset-sum reader in Section 2 of [PR #7799](https://github.com/apoursh/integer-mult-bounds/blob/7f08a74037788311cc6b7da27297b25f1b188e45/research/clifford-bell-fibres/PROOF.md). Its input in this model is an arbitrary dense matrix `Y` of normalized width-13 observations in computational coordinates. Each row and column has thirteen four-bit indices. A coordinate probe returns one exact complex entry. Transporters, Bell labels and phases are fixed in advance. The four-qubit Clifford image is a restricted subspace of this domain. + +## One block and one trace + +For an ordered input tuple write its six Weyl labels as `(x_j,z_j)`. Use primes for the output tuple. The Bell vector for one label has amplitude `(-1)^(z·r)/4` on the ordered pair `(r xor x,r)` for each nibble `r`. For six nibbles `r`, let `R(r,a)` concatenate the six pairs `(r_j xor x'_j,r_j)` followed by the singleton row `a`. Define `C(s,b)` the same way using the input shifts. Before the singleton Weyl corrections the block is + +```text +B[a,b] = 4 sum_(r,s) (-1)^(sum_j z'_j·r_j + z_j·s_j) Y[R(r,a), C(s,b)]. +``` + +There are twelve independent nibbles. The scalar is `4^13 / 4^12 = 4` from undoing the column normalization and applying twelve normalized Bell vectors. The corrections permute and sign the sixteen singleton row and column indices. The transport phase rotates the result by a known Gaussian unit. + +For the identity Clifford coefficient, the subsequent scalar is the trace of the corrected block divided by 16. If `w,w'` are the input/output label sums and `x(w),x(w')` their X parts, the original singleton entries required by the diagonal satisfy `b = a xor x(w') xor x(w)`. Each of these sixteen entries has a known sign. Thus the coefficient of every retained coordinate in this scalar is a Gaussian unit times `1/4`. + +| Requested output from one block | Distinct input entries | Binary signed complex combines | +|---|---:|---:| +| One singleton entry | 2⁴⁸ | 2⁴⁸ − 1 | +| All 256 singleton entries | 2⁵⁶ | 2⁵⁶ − 256 | +| One normalized identity trace | 2⁵² | 2⁵² − 1 | + +Each count is attained by visiting the indicated coordinates and reducing their signed values. Copies, fixed signs, Gaussian-unit rotations and powers-of-two scalings are separate from binary combines. The coordinates are distinct because the second nibble of every pair recovers its free index. Different singleton addresses give disjoint sets. On zero input, perturbing an unread required entry would change at least one answer. Hence even an adaptive exact reader must probe every listed entry in the worst case. In a linear circuit with binary addition/subtraction and unary scaling, every required input has a path to an output. A binary gate can merge at most two connected components, and every component remaining on those paths contains an output. The circuit needs at least the number of required inputs minus the number of outputs in binary gates. + +## The complete compiled identity row + +The compiler fixes one realization of each block on arbitrary observations. Combining its 4,265 weighted traces gives a sharper bill for this specific output. Group terms by the twelve four-bit X shifts of their Bell labels, six on the output followed by six on the input. These shifts are read directly from a raw coordinate by XORing its adjacent pairs. Thus different groups read disjoint coordinates. In all 22 groups the singleton X corrections agree on both sides and the trace uses a common singleton nibble `a=b`. The emitted transport phase is one on this identity row. + +Within a group the free coordinates are the 52 bits of `v=(r_1,...,r_6,s_1,...,s_6,a)`. A term with signed integer block numerator `n` contributes the raw weight + +```text +(n/4096) (-1)^(frequency · v). +``` + +The first twelve frequency nibbles are the Z parts of the output and input labels in that order. The last nibble is `z(w') xor z(w)` from the trace. In fact `W_w^-1 W_(w')` is exactly this diagonal Z when the X parts agree. The denominator is the block denominator 1,024 multiplied by the four in the single-trace formula above. + +For each group, binary elimination expresses its frequencies in a basis of rank `r ≤ 10`. Evaluate their weighted Walsh sum at every assignment of the `r` independent parity bits. Every assignment occurs exactly `2^(52-r)` times among the raw coordinates. Exhausting **10,530** assignments across the 22 groups therefore covers the full sum, including cancellations. This produces the following multiplicities in the normalized identity row. + +| Raw weight | Multiplicity | +|---|---:| +| +1/32 | 10,133,099,161,583,616 | +| −1/32 | 10,133,099,161,583,616 | +| +1/8 | 492,581,209,243,648 | +| −1/8 | 492,581,209,243,648 | +| Zero inside the 22 groups | 77,827,831,060,496,384 | + +Every coordinate outside the groups is zero as well. Hence the input-query cost on arbitrary dense observations is exactly **151 × 2⁴⁷ = 21,251,360,741,654,528**. On zero input a single unseen nonzero-weight coordinate could change the answer. Conversely, the compiler solves the parity equations at each nonzero assignment. Its streaming iterator visits every point of the resulting affine set by flipping one free bit at a time in reflected Gray order. Distinct groups and distinct assignments have disjoint supports. This supplies the matching schedule and a separate indexed lookup without storing or traversing the full support. The program verifies boundary addresses and the equality of the squared weights to `2^45`. + +With arbitrary unary scales and signs, the exact binary-combine count is the number of probes minus one. The connected-component argument above gives the lower bound. Summing the two signed magnitude classes and combining the subtotals attains it. If all real and imaginary input numerators have magnitude at most H on grid `2^-p`, one can use grid `2^(-p-5)` throughout the accumulator. The absolute numerator bound per component is `(144+4·7)2^47 H = 43·2^49 H`. On arbitrary signed data it can be attained by matching the row signs. + +For the row-major record tape below, the extremal active addresses are hexadecimal `00000000000210000000000021` and `fffffffffffdefffffffffffde`. To certify them, map one affine cell's origin and free binary directions to their 104-bit addresses. Echelon reduction of the directions, followed by clearing or setting attainable leading bits in descending order, gives the exact minimum and maximum in that cell. Taking extrema over all active cells proves the two addresses. Starting and returning at record zero costs exactly twice the maximum in input-head movement. An ordered scan attains the movement bound, while the Gray iterator attains the query count. An ordered scan can also restrict its arithmetic probes by the coefficient lookup. None of these counts pays for producing the dense tape or moving its arithmetic workspace. + +## Precision, movement and cleanup + +For input real and imaginary numerators in `[-H,H]` on a common grid `2^-p`, unscaled entry accumulators need magnitude at most `2^48 H`. Multiplying the result by four can shift the shared exponent, or increase the bound to `2^50 H` on the original grid. A direct trace accumulator needs magnitude at most `2^52 H` on its numerator and can return it on grid `2^(-p-2)`. For a bound `M`, a signed register of `1 + ceil(log2(M+1))` bits suffices. No rounding is required. + +On a row-major dense tape with one fixed-size record per entry, start the read-only head at record zero and require its return. The minimum required address `m` for the full block has nibbles `(0,x'_1,...,0,x'_6,0,0,x_1,...,0,x_6,0)`, with each zero/shift pair ordered as in the formula. For the trace replace the final zero by `x(w') xor x(w)`. Complementing every nibble preserves all pair constraints and the trace constraint, so the maximum required address is `M = 2^104 - 1 - m`. Every exact algorithm on this tape makes at least `2M` input-head moves on zero input. One ordered forward scan to `M` followed by the return attains this count. The scan can generate the selected addresses in order by enumerating the first nibble of each pair and deriving the second by XOR. It reads values into the arithmetic only at selected addresses. Traversed intermediate records still count toward movement. + +The forward pass needs up to 256 complex sums for the block or one for the trace, plus fixed-width address and loop counters. With write-once final output and all mutable storage charged, a one-pass block reader also has a working-state lower bound. At the cut where the highest row bit first becomes one, exactly half of each singleton sum's terms have occurred. Varying the prefix on its disjoint supports gives `(2^48 H+1)^512` distinct vectors of partial real and imaginary sums. The common zero suffix preserves all these distinctions at output. This requires at least `ceil(512 log2(2^48 H+1))` live bits at the cut for integer `H >= 1`. + +The head count is in record units and excludes arithmetic-workspace movement. An ordinary reader can emit the scaled sums and clear its accumulators. A reversible implementation may copy the result to clean output and undo the accumulations on the return sweep, which adds a second probe of each selected entry. Bit-serial arithmetic, physical preparation of the observations and a complete multiplier invoice require additional accounting. + +Different transported blocks can reuse input coordinates. The single-block lower bounds do not add across the decoder. They also do not apply directly to a compact word or a promised Clifford expansion. For example, the repository already computes phase-sensitive contractions from compact affine supports. Connecting such a producer to the decoder requires an explicit input contract. [Compact contractions](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/clifford-exact-contractions/README.md) + +Prepared by apoursh with substantial OpenAI Codex assistance. Apache-2.0. diff --git a/research/clifford-sparse-row/PROOF.md b/research/clifford-sparse-row/PROOF.md new file mode 100644 index 0000000000..43150df18c --- /dev/null +++ b/research/clifford-sparse-row/PROOF.md @@ -0,0 +1,181 @@ +# A sparse reconstruction formula at Clifford width 13 + +Fix one Gaussian-dyadic unitary representative `U` of each four-qubit +Clifford scalar coset. For normalized columns `(vec(U)/4)^(tensor 13)` +write `c_U` for the input mixture coefficients. The width-13 proof +recovers the matrix `M_S = sum_(U over S) c_U U` for each symplectic +action `S`, then returns `Tr(U* M_S)/16`. Here we compile its group +algebra identity into **4,265 signed reads for one complete matrix +M_S**, shared by its 256 coefficient outputs. +[Width-13 source, sections 1–4](https://github.com/apoursh/integer-mult-bounds/blob/7f08a74037788311cc6b7da27297b25f1b188e45/research/clifford-bell-fibres/PROOF.md) + +## Measurement coordinates + +Use `V=F₂⁸` with Z in the low four bits and X in the high four bits, +and write `G=Sp(V)`. The seed of six unphased Weyl labels is +`T=(0,Z1,Z2,Z3,Z4,X4)`. Its affine Bell orbit is `G/C`, where `C` +is the order-eight group of controlled-Z shear products on the +first three qubits. In this orbit, the ordered input/output tuple pair +`(g_in T, g_out T)` selects the set `g_out C g_in⁻¹` of symplectic +actions. All tuple images here use the **affine Bell action**. + +Given a normalized observation vector, multiply by `4^13`, view it as an +operator on thirteen registers, and take the matrix block between these +six-pair Bell input and output tuples. The other register gives a 16-by-16 +block. With `w_in,w_out` the respective XORs of the six Weyl labels, +multiply by `W_(w_out)` on the left and `W_(w_in)⁻¹` on the right. +Apply the transport phase `j_in / j_out` from section 2 of the cited +proof. Explicitly, if `U W_t Uᵀ = θ_U(t) W_(L_S t)` and +`U W_v U* = γ_U(v) W_(Sv)`, then for a transporter g of the seed use +`j_g = (product_(t in T) θ_U(t)) / γ_U(XOR(T))` for any Clifford lift +of g. The phase is constant on each transporter coset. Thus the corrected +block returns the **sum** of the M matrices over the selected set. +The averaging factor 1/8 is accounted for below. On an arbitrary +off-image observation the same instructions define a linear block read. + +## Compress the two character sums + +Let `A=Sym₄(F₂)` be the abelian group of 1,024 shears fixing the +Z-Lagrangian pointwise. We use additive notation for its masks, and +write `e_J=|J|⁻¹ sum_(j in J) j` and +`e_Q=|A|⁻¹ sum_(a in A) χ_Q(a) a`. +The source proof assigns each character Q an isotropic three-plane W +and a factor d, with `d e_Q e_(C_W) e_Q = e_Q`. Here +`C_W=g C g⁻¹` for a transporter taking the first three Z directions +to a basis of W. Its generators from two independent basis vectors +u,v send y to `y + v + u`. + +Group characters by the actual plane W. For a fixed W let +`H=A∩C_W`, `N=N_A(C_W)` (its normalizer within A), and +`h=|H|, k=[A:N], m=[A:H]`. Every character assigned to W is trivial +on H. In the double sum with factors a,b replace a by `x+b`. The +product of character signs is `χ_Q(x)`, and the group term becomes +`x e_(b C_W b⁻¹)`. Conjugation depends only on `b mod N`. +Translation depends only on `x mod H` because b commutes with H. +Consequently + +```text +d e_Q e_(C_W) e_Q + = d/(m k) sum_(x in A/H, b in A/N) χ_Q(x) x e_(b C_W b⁻¹). +``` + +For a raw eight-element coset **sum**, let +`F_W(x) = sum_(Q assigned to W) χ_Q(x)`. The resulting coefficient is +`d F_W(x)/(8 m k)`. + +- **All-Z W.** Here `C_W <= A`, so h=8, k=1, m=128 and d=1. + The coefficient of the read is `F_W(x)/1024`. +- **Mixed W.** Write `W=P + span(ℓ)`, with P a two-plane in the + Z-Lagrangian and ℓ its chosen nonzero pure-X covector annihilating P. + The source proof gives `H=Λ²P` of order two and d=4. For p in P + the basis change `T_p=I+pℓᵀ` gives a complement to H in C_W. + A shear B normalizes C_W exactly if + `T_p B T_pᵀ + B` lies in H for all p in P. With `v=Bℓ` this difference is + `pvᵀ + vpᵀ + (ℓᵀv)ppᵀ`. If v lies in P it belongs to Λ²P. + Conversely a nonzero p forces `ℓᵀv=0` by the zero diagonal of H. + The remaining alternating matrix belongs to Λ²P for every p only + if v lies in P (take p nonzero and examine its image when v is + outside P). The linear map B↦Bℓ is onto the four-dimensional + Z-Lagrangian: in a basis adapted to ℓ it is the last column of a + symmetric matrix, which can be chosen freely. Hence k=4, m=512, + and the coefficient of each read is `F_W(x)/4096`. + +The compiler uses the source verifier's lexicographic plane selection. +For each plane it chooses a single binary basis by scanning its points +in ascending order. Replacing one basis of the same plane by another +does not change C_W. It evaluates F_W by a length-1,024 signed Walsh +transform and drops zeros. For a surviving pair x,b the transporters are + +```text +input_map = b g +output_map = S (x+b) g +``` + +where S is the desired output fibre. The term therefore measures +`S x b C_W b⁻¹`. Division by 1,024 suffices for the emitted integers, +since every nonzero mixed F_W used here is divisible by four. +This denominator is attained by the fixed compiled row. The program +does not claim a minimum denominator or a sparsity lower bound for all +possible decoders. + +Two blocks with the same affine tuple input and output would select +the same subset of G. The verifier expands every emitted coset as +eight actual binary matrices and checks that all subsets are distinct. +The available coefficients sum over each of their group elements to +exactly the single chosen indicator. This supplies an independent direct +certificate for the resulting list, without relying on Fourier +orthogonality inside its final test. Choosing one Bell pair of tuples +to represent an equal coset sum is valid on the mixture image. On general +noise the chosen block coordinates define this particular decoder, whose +norm is computed below. + +## Counts and Euclidean bounds + +For the identity fibre the seven all-Z planes contribute 17 reads and +the fifteen mixed planes contribute 4,248. The 34,120 group terms +encounter 8,304 distinct group elements. The signed numerator sums are +1,024 at the identity and zero at each other one. All other target fibres +use the same list with its outputs left-translated by S. + +For raw-sum coefficients `a_t = numerator_t/1024` the certificate gives + +```text +sum_t |a_t| = 25/2, sum_t |a_t|² = 1/8. +``` + +For a fixed U over S, the final trace against `U*/16` has Euclidean row +norm 1/4 on a matrix in the Frobenius norm. The left/right Weyl and scalar +phase corrections are isometries, and the normalized observation supplies +the factor `4^13`. The Bell basis change is unitary. Since distinct reads +occupy distinct ordered input/output blocks, they are orthogonal as +functionals. This gives the exact squared norm of a scalar output row +of the compiled decoder, `(4^13/4)² / 8 = 2^45`. + +For a simultaneous norm bound group terms by their actual input Bell +tuple i, and put `m_i = sum_(t with input i) |a_t|`. There are 67 such +inputs. Their absolute numerator masses are as follows. + +| Absolute numerator mass | Number of input tuples | +| ---: | ---: | +| 128 | 29 | +| 192 | 10 | +| 224 | 8 | +| 240 | 8 | +| 288 | 12 | + +A fixed term of seed output o sends the normalized matrix coordinates +`Y_(j,i)` to one matrix at each S by reading `Y_(So,i)` and applying +unitary entrywise-block corrections. As S ranges over G, every j in the +orbit occurs |C|=8 times, by orbit-stabilizer. Thus, before restoring +normalization, this map has operator norm at most √8 on Frobenius direct +sums. For fixed i the weighted sum of terms has norm at most `√8 m_i`. +Across different i the input domains are orthogonal. Cauchy–Schwarz +bounds their combined norm by `sqrt(8 sum_i m_i²)`. Within each output +fibre, taking all 256 traces against the orthogonal representative +matrices jointly multiplies the Frobenius norm by 1/4. Therefore the +full normalized decoder satisfies + +```text +||B_13||₂ <= 4^12 sqrt(8 sum_i m_i²) = 4^12 sqrt(1319/64) < 2^27. +``` + +At f>13 apply the width-13 map on the first factors and the identity +on the remaining ones. In each output component next contract the +remaining factors against its own unit-norm target row. The latter +direct-sum operation has norm at most one, so the bound persists. +These estimates concern a specific finite linear operator. Its block +count assumes access to the indicated Bell-coordinate projections. +Acquisition from physical storage and the complete multiplier cost +require their own accounting. + +The width-13 result and its coset readout are due to apoursh, building +on Ali Romman's Clifford/Bell work and the character and Pauli lineage +of Nick Petalas and alephnan. Fourier compression and Walsh transforms +are classical. Prepared by **apoursh** with substantial OpenAI Codex and +separate agent assistance. Apache-2.0. + +## Transport phases in the executable read list + +The program fixes a lift for each binary transvection with nonzero axis `p`. Write `q(p)=x_p·z_p mod 2`, `P=i^q(p) W_p` and `U=(1+i)(I+iP)/2`. For ordinary conjugation, a commuting label is fixed with phase one. An anticommuting label has image `t+p` and phase `i^(1+q(p)) (-1)^(z_p·x_t)`, from the product `iP W_t`. To obtain the Bell action multiply the conjugated Weyl on the right by `U U^T`. This is `−W_p` if `q(p)=0` and `iI` otherwise. Tracking the six Bell phases and subtracting the ordinary phase for the XOR of the labels gives the transport exponent modulo four. The opposite signs of the input and output exponents in the read list undo the block phase. + +The executable reduces a symplectic matrix to the identity one column at a time. For current and desired labels `u,v`, already fixed columns span `F`. The vector `u+v` pairs to zero with `F`. If `=1`, the transvection along `u+v` sends `u` to `v`. For distinct orthogonal labels choose an intermediate `h` pairing to one with both and having the same pairings as `u` with `F`. These linear constraints are consistent. Neither `u` nor `v` belongs to `F`; if `u+v` is in `F` the two requested values sum to zero, matching `=0`. Nondegeneracy realizes the resulting functional. The two transvections along `u+h,h+v` fix `F` and put that column in position. Reversing the reduction realizes the specified transporter. The self-check also reconstructs the affine label offsets by quadratic parity. The literal matrix tests cover both types of transvection and off-identity target phases. diff --git a/research/clifford-sparse-row/README.md b/research/clifford-sparse-row/README.md new file mode 100644 index 0000000000..26f7540b8b --- /dev/null +++ b/research/clifford-sparse-row/README.md @@ -0,0 +1,38 @@ +# What the width-13 Clifford decoder reads + +The width-13 construction in #7799 specifies an exact Gaussian-dyadic left inverse for the full four-qubit Clifford alphabet. This package compiles it into **4,265 signed Bell-block reads for one symplectic fibre**. Those blocks are shared by all 256 Pauli coefficients of that fibre. It also prices the identity coefficient when the input is supplied as ordinary dense tensor coordinates. [Construction](PROOF.md) · [Input costs](COST.md) · [Width-13 precursor](https://github.com/apoursh/integer-mult-bounds/blob/7f08a74037788311cc6b7da27297b25f1b188e45/research/clifford-bell-fibres/PROOF.md) + +| Input access and requested output | Cost for this implementation | +|---|---:| +| Transported 16 × 16 Bell blocks to recover one fibre | 4,265 block reads | +| Ordinary dense coordinates for one complete Bell block | 2⁵⁶ scalar reads | +| Ordinary dense coordinates for the identity trace of one block | 2⁵² scalar reads | +| Ordinary dense coordinates for the combined identity coefficient | **151 × 2⁴⁷ = 21,251,360,741,654,528 scalar reads** | + +The last number counts every nonzero coordinate once. The 4,265 traces share 22 patterns of addresses. Within each pattern their signs are Walsh characters on at most ten independent parity bits. Combining their weights before reading gives four distinct nonzero raw weight values, ±1/32 and ±1/8. On arbitrary dense input every one of those coordinates can change the answer. A streaming schedule attains the count. This lower bound applies to the particular emitted row. A producer that supplies compressed Clifford operators or already-transformed blocks has a different access cost. No change to the selected multiplication exponent κ follows. [Raw weights, precision and tape movement](COST.md#the-complete-compiled-identity-row) · [Compact operator interface](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/clifford-exact-contractions/README.md) + +The signed group certificate expands the reads into 34,120 terms on 8,304 distinct group elements. Their weights cancel at every element except the requested one. This proves exact recovery on the entire Clifford-mixture image. Choosing one representative per coset also defines a specific extension to arbitrary observations: its normalized coefficient rows have squared Euclidean norm **2⁴⁵**, and its full operator norm is at most **4¹²√(1319/64) < 2²⁷**. [Certificate and norm derivation](PROOF.md#counts-and-euclidean-bounds) + +## Run the compiler + +Use CPython 3.12 and the standard library. These examples run from the repository root. + +```sh +python3.12 -B scripts/research_package.py --package research/clifford-sparse-row +python3.12 -B research/clifford-sparse-row/bell_reads.py --emit +python3.12 -B research/clifford-sparse-row/raw_row.py --probe-index 0 +python3.12 -B research/clifford-sparse-row/raw_row.py --entry 513 139777 +``` + +The second command emits the 4,265 weights, six input and six output Bell labels, and Gaussian phase corrections as JSON lines. In Python, `bell_reads.iter_reads(target)` accepts any symplectic target as the binary images of the eight standard basis vectors, with four low Z bits and four high X bits. Use the Weyl corrections in the proof with each emitted block. The raw row commands refer to the identity representative and return the signed numerator over 4,096. An address is a 52-bit row and a 52-bit column. The first probe in this schedule is entry (513, 139777) with weight −1/32. The Python iterator `raw_row.iter_probes()` streams only nonzero coordinates. The indexed command accesses a single scheduled coordinate directly. + +The registered checks cover finite group cancellation, every Walsh cell, all 4,265 transport pairs, independent literal Bell contractions and Pauli phases, and recovery from a coherent 64-operator mixture for two target fibres. All use exact arithmetic. The raw support is counted by the sizes of disjoint affine sets. The large dense tensor and a full physical multiplier are not materialized. [Replay manifest](VERIFY.json) · [Source pins](SOURCES.json) + +## Credit and coordination + +Prepared by **apoursh** with substantial OpenAI Codex and separate agent assistance under Apache-2.0. The group identity, plane choice and Bell phase correction follow #7799. Ali Romman, Nick Petalas and alephnan supplied earlier Clifford, spectral and Pauli work. Walsh transforms, normalizer quotients and binary linear algebra are classical. This package follows the implementation-cost handoff on upstream main `e54523517d0f03e58352e647c403a5af3e525a57`. [Public claim](https://github.com/CrocSwap/integer-mult-bounds/discussions/1166#discussioncomment-19753796) · [Scope and overlap record](TASK.json) + +## Open next questions + +1. Can a compact producer evaluate one of the active Walsh cells at its actual precision and storage layout? Include the cost of acquiring its inputs, moving scratch and restoring the caller. +2. Can changing which tuple represents an equal coset sum shrink the raw support further? Preserve the group identity and recompile all affected sign cancellations before comparing costs. diff --git a/research/clifford-sparse-row/SOURCES.json b/research/clifford-sparse-row/SOURCES.json new file mode 100644 index 0000000000..c66fbcab98 --- /dev/null +++ b/research/clifford-sparse-row/SOURCES.json @@ -0,0 +1,38 @@ +{ + "schema_version": 1, + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "files": [ + { + "path": "certificates/selected-result.json", + "usage": "provenance", + "git_blob": "75d77b328ea02ded535e7f23aee5b1e55d0bb1a8", + "sha256": "154c3d30455d778fd3343b6b4851f0fa4665f0f7625b0adb3675e2bafbbf6bf1" + }, + { + "path": "docs/research/agent-task-catalog.json", + "usage": "provenance", + "git_blob": "3404fbdd5e7529a0674eef26114b5071e4586cec", + "sha256": "ead6cdc9d0af6d58e8a49744d8ec8c7c15e13d2ba93c276c434bcf9b51b93a81" + } + ], + "cited_research": [ + { + "pr": 7799, + "author": "apoursh", + "head": "7f08a74037788311cc6b7da27297b25f1b188e45", + "url": "https://github.com/apoursh/integer-mult-bounds/tree/7f08a74037788311cc6b7da27297b25f1b188e45/research/clifford-bell-fibres", + "use": "Mathematical source of the normalized measurement, order-eight stabilizer, character certificate and deterministic plane-selection rule. The new implementation includes these choices and recomputes the final signed identity offline." + }, + { + "pr": 7789, + "author": "Ali Romman", + "head": "a5aa2ae21ae68338390f584b8fca58ecba0df409", + "use": "Bell-sector and Clifford provenance." + }, + { + "pr": 5727, + "path_at_base": "research/clifford-exact-contractions/README.md", + "use": "Comparison with compact affine-quadratic Clifford input." + } + ] +} diff --git a/research/clifford-sparse-row/TASK.json b/research/clifford-sparse-row/TASK.json new file mode 100644 index 0000000000..f3db0b3b76 --- /dev/null +++ b/research/clifford-sparse-row/TASK.json @@ -0,0 +1,101 @@ +{ + "schema_version": 1, + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "task_id": "uniform-transfer-audit", + "original_card": { + "id": "uniform-transfer-audit", + "question": "Can one of the selected record's five inherited assumptions be proved at its actual caller?", + "starting_points": [ + "docs/research/current-priorities.md", + "docs/research/research-family-status.md", + "certificates/selected-result.json", + "docs/research/pr-intake-evidence/pr5599-completion/PROOF-REVIEW.md" + ], + "methods": [ + "Construct and independently check one source-bound instance of the stated first experiment.", + "Seek an exact counterexample or target-specific complete-budget obstruction to that same proposed change." + ], + "acceptance_gate": "Identify the proposition and what would change downstream; do not equate a finite replay with a universal proof.", + "first_step": { + "command": [ + "python3", + "-B", + "scripts/research_selected_baseline.py" + ], + "expected": "PASS_RESEARCH_BASELINE_BINDINGS_ONLY", + "inspect": "Read revision 8, the selected review and live exact-source handoffs. Then follow this card's bounded first_experiment.", + "scope": "Source-bound orientation only, not a supplier replay or theorem proof." + }, + "first_experiment": "Choose one assumption ID (native_all_columns, owned_erasure, compiler, precision_tape, analytic_recovery), one quantified implication and exact dependency closure. Check current handoffs, including #5625 row reentry and #5707 root-prefix lowering, without treating their partial scope as the whole theorem. Prove or falsify that implication with a caller-bound argument; stop at the chosen obligation. Finite tests or root digits do not discharge an all-size statement.", + "bottleneck_link": "Judge the actual current supplier contract and complete signed target/paid bill; frozen-profile ceilings require an applicability proof.", + "allowed_variations": [ + "One exact source head, helper/cut region or quantified proposition and changed hypothesis; check live handoffs first. Different seeds are not different scopes." + ], + "scope_change_triggers": [ + "Changing source head, helper/cut domain, operation alphabet or caller boundary without recording the new scope.", + "Treating an archived proposal or local numerical pass as complete supplier admission." + ], + "overlap_terms": [ + "native_all_columns", + "owned_erasure", + "compiler", + "precision_tape", + "analytic_recovery" + ], + "existing_checks": [ + { + "scope": "PR #4100: proposed unconditional construction and finite checks, without independent acceptance.", + "evidence": "research/unconditional-batched-crt/README.md", + "remaining": "Independent proof audit of one caller-bound all-size implication; all other premises remain explicit.", + "status": "author-checked", + "source_commit": "337d04939571a637aeab54a0f58f54fde811663a", + "selected_record_sha256": "bb2eaa58647b353f88d0aec2eafb9d30df1be53589231b23e12ceef3e4bad129" + }, + { + "scope": "Selected PR5599: complete helper-subspace construction and independent caller replay; five framework assumptions remain.", + "evidence": "docs/research/pr-intake-evidence/pr5599-completion/PROOF-REVIEW.md", + "remaining": "The next experiment must identify uncovered source-specific work. Successor archive intake does not transfer this admission.", + "status": "reviewed", + "source_commit": "09dd0965711ca7eeb169057a420abab1c9052137", + "selected_record_sha256": "2a0220e866417774606e0f991e41b9c1d26b1f43b97857238cf478dbc7d330b5" + } + ] + }, + "priority_revision": 8, + "scope_key": "58d0403e3078b2c5ae8a", + "selection_nonce": "e4a62b9aeeca5ee84ffc5a46a697ad39", + "scope_status": "changed", + "actual_scope": "Compile the width-13 dyadic Clifford decoder from PR7799 and price its identity-output row in two explicit input layouts.", + "scope_change_reason": "This follows the finite implementation and observable-acquisition handoff from PR7799. The selected multiplier's all-size assumptions are outside this readout.", + "bottleneck_link": "Determines the number of corrected Bell reads, the cost of dense input acquisition, and exact row noise amplification for this decoder. No compact producer or priced multiplier is supplied.", + "stop_rule": "Publish one executable signed row, check cancellation over its entire group support, and derive attained dense-read counts for a declared consumer with direct checks of signs and normalization.", + "outcome": "completed", + "author": "apoursh", + "ai_assistance": "Substantial OpenAI Codex and separate agent assistance in proof, implementation and independent checks.", + "evidence": "PROOF.md, COST.md and the registered compiler, raw-address, literal-contraction and mixed-input checks.", + "family_decision": "Investigate the readout at the first possible width. The source's existence proof, larger stabilizer alphabet, and selected exponent are separate from its implementation cost.", + "claim": "https://github.com/CrocSwap/integer-mult-bounds/discussions/1166#discussioncomment-19753796", + "overlap": "Read the live #1163/#1166 board and #7799 handoff. All-state PR searches for 7799, Bell/acquisition and sparse Clifford decoding and recent direct PR records were checked. #5727 assumes compact operator inputs. The local helper and its sparse/cache inventory are incomplete.", + "open_questions": [ + { + "question": "Can a named compact producer supply these 22 shift geometries without materializing a dense observation?", + "why_it_matters": "A raw-coordinate lower bound does not price a structured producer.", + "first_step": "Specify one producer's output layout and evaluate one active Walsh cell including preparation, scratch and restoration.", + "blocked_by": "The selected caller has no established interface for these arbitrary normalized tensor observations." + }, + { + "question": "Can a different valid off-image extension realize a cheaper computational-basis coefficient row?", + "why_it_matters": "The 151 times 2^47 bound is sharp for the emitted identity row under dense coordinate access.", + "first_step": "Change one tuple representative, compile the new Walsh support and preserve the signed coset indicator on every touched symplectic element.", + "blocked_by": "Optimizing a single read without accounting for cross-term cancellations may increase total support." + } + ], + "upstream_refresh": { + "date_utc": "2026-11-19", + "entry": "pulled canonical main", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "selected_orientation": "PASS_RESEARCH_BASELINE_BINDINGS_ONLY", + "catalog_context": "Revision 8 refers to #5599; canonical selected result is #7000.", + "before_submission": "fetched canonical main, same commit" + } +} diff --git a/research/clifford-sparse-row/VERIFY.json b/research/clifford-sparse-row/VERIFY.json new file mode 100644 index 0000000000..32ef9bb70c --- /dev/null +++ b/research/clifford-sparse-row/VERIFY.json @@ -0,0 +1,117 @@ +{ + "schema_version": 1, + "status": "ready", + "python": "3.12", + "requirements": [], + "inputs": [], + "commands": [ + { + "argv": [ + "{python}", + "-E", + "-s", + "-W", + "error", + "-B", + "{package}/compile_row.py" + ], + "timeout_seconds": 90, + "checks": "Full signed group-support cancellation and normalized row bounds" + }, + { + "argv": [ + "{python}", + "-E", + "-s", + "-O", + "-W", + "error", + "-B", + "{package}/compile_row.py" + ], + "timeout_seconds": 90, + "checks": "Full signed group-support cancellation and normalized row bounds under optimized Python" + }, + { + "argv": [ + "{python}", + "-E", + "-s", + "-W", + "error", + "-B", + "{package}/raw_row.py" + ], + "timeout_seconds": 90, + "checks": "All raw Walsh cells, exact support and nonzero-address schedule" + }, + { + "argv": [ + "{python}", + "-E", + "-s", + "-O", + "-W", + "error", + "-B", + "{package}/raw_row.py" + ], + "timeout_seconds": 90, + "checks": "All raw Walsh cells, exact support and nonzero-address schedule under optimized Python" + }, + { + "argv": [ + "{python}", + "-E", + "-s", + "-W", + "error", + "-B", + "{package}/independent_check.py" + ], + "timeout_seconds": 90, + "checks": "Independent literal tensors, sparse input impulses and gate phases" + }, + { + "argv": [ + "{python}", + "-E", + "-s", + "-O", + "-W", + "error", + "-B", + "{package}/independent_check.py" + ], + "timeout_seconds": 90, + "checks": "Independent literal tensors, sparse input impulses and gate phases under optimized Python" + }, + { + "argv": [ + "{python}", + "-E", + "-s", + "-W", + "error", + "-B", + "{package}/mixture_check.py" + ], + "timeout_seconds": 90, + "checks": "Full signed recovery on coherent mixtures for two symplectic fibres" + }, + { + "argv": [ + "{python}", + "-E", + "-s", + "-O", + "-W", + "error", + "-B", + "{package}/mixture_check.py" + ], + "timeout_seconds": 90, + "checks": "Full signed recovery on coherent mixtures for two symplectic fibres under optimized Python" + } + ] +} diff --git a/research/clifford-sparse-row/bell_reads.py b/research/clifford-sparse-row/bell_reads.py new file mode 100644 index 0000000000..32b2ed2a94 --- /dev/null +++ b/research/clifford-sparse-row/bell_reads.py @@ -0,0 +1,128 @@ +"""Emit the phase-corrected Bell measurements for the compiled Clifford row. + +Use --emit for the identity fibre in order. Labels have four low Z bits +and four high X bits. apoursh with substantial OpenAI Codex assistance. +Apache-2.0. Phase correction is from PR7799. +""" +import argparse +from functools import cache +import json +from typing import NamedTuple + +from compile_row import DENOMINATOR, IDENTITY, SEED, apply, iter_terms, pairing + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def parity(value): + return value.bit_count() % 2 + + +def q0(v): + return parity((v >> 4) & v) + + +def transvection(axis, vector): + return vector ^ (axis if pairing(axis, vector) else 0) + + +def decompose(matrix): + """Write a symplectic map as a sequence of transvections in application order.""" + columns = list(matrix) + corrections = [] + for i, target in enumerate(IDENTITY): + source = columns[i] + if source == target: + continue + if pairing(source, target): + axes = (source ^ target,) + else: + middle = next(v for v in range(256) + if pairing(v, source) and pairing(v, target) + and all(pairing(source ^ v, fixed) == 0 for fixed in IDENTITY[:i])) + axes = (source ^ middle, middle ^ target) + for axis in axes: + columns = [transvection(axis, v) for v in columns] + corrections.append(axis) + require(tuple(columns) == IDENTITY, "transvection reduction failed") + return tuple(reversed(corrections)) + + +def step(axis, v, bell): + """Phase exponent modulo four of a transvection on one unphased Weyl label.""" + out = transvection(axis, v) + exponent = 0 + if out != v: + exponent = 1 + q0(axis) + 2 * parity((axis & 15) & (v >> 4)) + if bell: + if q0(axis): + exponent += 1 + else: + exponent += 2 + 2 * parity((out & 15) & (axis >> 4)) + out ^= axis + return out, exponent % 4 + + +def label_sum(labels): + total = 0 + for label in labels: + total ^= label + return total + + +@cache +def transported_seed(matrix): + """Return the six output labels and the seed's transport phase exponent.""" + labels = list(SEED) + weight = label_sum(SEED) + phase = 0 + for axis in decompose(matrix): + next_weight, gamma = step(axis, weight, False) + values = [step(axis, label, True) for label in labels] + labels = [value for value, _ in values] + phase += sum(theta for _, theta in values) - gamma + weight = next_weight + # Independent affine check. q(Sv+b)=q(v) fixes the offset b uniquely. + offset = labels[0] + require(all(q0(apply(matrix, u) ^ offset) == q0(u) for u in (0, *IDENTITY)), + "Bell offset violates transpose parity") + require(all(label == apply(matrix, v) ^ offset for v, label in zip(SEED, labels, strict=True)) + and weight == label_sum(labels), "misordered symplectic transport") + return tuple(labels), phase % 4 + + +class Read(NamedTuple): + numerator: int + input_labels: tuple[int, ...] + output_labels: tuple[int, ...] + correction_i: int + + +def iter_reads(target=IDENTITY): + """Weight is numerator/DENOMINATOR. Multiply the corrected singleton by i^correction_i.""" + for term in iter_terms(target): + i, phase_i = transported_seed(term.input_map) + j, phase_j = transported_seed(term.output_map) + yield Read(term.numerator, i, j, (phase_i - phase_j) % 4) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--emit", action="store_true", help="emit one JSON object per identity-fibre read") + args = parser.parse_args() + pairs = set() + for read in iter_reads(): + pair = read.input_labels, read.output_labels + require(pair not in pairs, "repeated literal Bell address") + pairs.add(pair) + if args.emit: + print(json.dumps(dict(read._asdict(), denominator=DENOMINATOR))) + if not args.emit: + print(f"PASS_BELL_READS distinct_pairs={len(pairs)}") + + +if __name__ == "__main__": + main() diff --git a/research/clifford-sparse-row/compile_row.py b/research/clifford-sparse-row/compile_row.py new file mode 100644 index 0000000000..daf35d6a26 --- /dev/null +++ b/research/clifford-sparse-row/compile_row.py @@ -0,0 +1,247 @@ +"""Compile the shear-character certificate in PR7799 into signed Bell reads. + +Binary vectors have four low Z bits and four high X bits, least significant +bit for qubit one. A matrix is the tuple of images of the standard basis. +apoursh, with substantial OpenAI Codex and separate agent assistance. +Apache-2.0. The seed, character cases and plane selection are from PR7799. +""" +import argparse +from collections import Counter, defaultdict +from functools import cache +from itertools import combinations, combinations_with_replacement +import json +from typing import NamedTuple + + +IDENTITY = tuple(1 << i for i in range(8)) +DENOMINATOR = 1024 +SEED = (0, 1, 2, 4, 8, 128) +UPPER = tuple(combinations_with_replacement(range(4), 2)) + + +class Term(NamedTuple): + numerator: int + input_map: tuple[int, ...] + output_map: tuple[int, ...] + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def apply(columns, vector): + result = 0 + while vector: + bit = vector & -vector + result ^= columns[bit.bit_length() - 1] + vector ^= bit + return result + + +def compose(left, right): + return tuple(apply(left, v) for v in right) + + +def pairing(u, v): + return (((u >> 4) & v) ^ ((v >> 4) & u)).bit_count() % 2 + + +def span(basis): + points = [0] + for v in basis: + points += [u ^ v for u in points] + return points + + +def is_symplectic(matrix): + return (len(matrix) == 8 and all(isinstance(v, int) and 0 <= v < 256 for v in matrix) + and all(pairing(matrix[i], matrix[j]) == pairing(IDENTITY[i], IDENTITY[j]) + for i, j in combinations(range(8), 2))) + + +@cache +def shear(mask): + """Send (z,x) to (z+B x,x), with B's upper triangle given by mask.""" + result = list(IDENTITY) + for index, (i, j) in enumerate(UPPER): + if mask & (1 << index): + result[4 + i] ^= 1 << j + if i != j: + result[4 + j] ^= 1 << i + return tuple(result) + + +def pair_mask(u, v): + return sum(((((u >> i) & (v >> j)) ^ ((u >> j) & (v >> i))) & 1) << k + for k, (i, j) in enumerate(UPPER)) + + +def quadratic_address(v): + return sum(1 << k for k, (i, j) in enumerate(UPPER) if v & (1 << i) and v & (1 << j)) + + +def select_plane(ch): + # Match the deterministic binary ordering used by the PR7799 verifier. + values = tuple((ch & quadratic_address(v)).bit_count() % 2 for v in range(16)) + + def polar(u, v): + return values[u] ^ values[v] ^ values[u ^ v] + + if any(all(polar(v, b) == 0 for b in (1, 2, 4, 8)) for v in range(1, 16)): + return next(w for w in combinations(range(1, 16), 3) + if len(set(span(w))) == 8 and all(polar(i, j) == 0 for i, j in combinations(w, 2))) + r = next(v for v in range(1, 16) if values[v] == 0) + hyperplane = [u for u in range(16) if polar(r, u) == 0] + z2 = next(v for v in hyperplane if v not in (0, r)) + dual = next(x for x in range(1, 16) if all((x & v).bit_count() % 2 == 0 for v in hyperplane)) + return r, z2, dual << 4 + + +def canonical_basis(points): + basis = [] + for v in sorted(points): + if v not in span(basis): + basis.append(v) + return tuple(basis) + + +def extend_basis(w): + z = list(w) + z.append(next(v for v in range(1, 256) if v not in span(z) and all(pairing(v, u) == 0 for u in z))) + x = [] + for i in range(4): + x.append(next(v for v in range(1, 256) + if all(pairing(v, u) == int(i == j) for j, u in enumerate(z)) + and all(pairing(v, b) == 0 for b in x))) + matrix = tuple(z + x) + require(is_symplectic(matrix), "plane transporter is not symplectic") + return matrix + + +def walsh(characters): + values = [0] * 1024 + for ch in characters: + values[ch] = 1 + step = 1 + while step < len(values): + for start in range(0, len(values), 2 * step): + for i in range(start, start + step): + j = i + step + values[i], values[j] = values[i] + values[j], values[i] - values[j] + step *= 2 + return values + + +def normalizer_representatives(w, p_basis): + if len(p_basis) == 3: + return [0] + dual = next(v for v in w if v >> 4) + p = span(p_basis) + representatives = {} + for mask in range(1024): + b_dual = apply(shear(mask), dual) ^ dual + key = min(b_dual ^ u for u in p) + representatives.setdefault(key, mask) + require(len(representatives) == 4, "mixed-plane normalizer index") + return sorted(representatives.values()) + + +def iter_terms(target=IDENTITY): + """Yield numerator / DENOMINATOR weights on transported coset *sums*. + + Apply the source and target transporters to SEED via the affine Bell + action and undo the singleton/transport phases as specified in PROOF.md. + The weighted sum of those 16-by-16 blocks is the target's fibre matrix + on the image of the observation map. Target defaults to the identity. + """ + require(is_symplectic(target), "invalid target symplectic matrix") + by_plane = defaultdict(list) + for ch in range(1024): + by_plane[canonical_basis(span(select_plane(ch)))].append(ch) + for w, chars in sorted(by_plane.items()): + pure = tuple(z for z in w if z < 16) + h = span(tuple(pair_mask(u, v) for u, v in combinations(pure, 2))) + representatives = normalizer_representatives(w, pure) + g = extend_basis(w) + values = walsh(chars) + divisor = 4 if len(pure) == 2 else 1 + for delta, value in enumerate(values): + if not value or delta != min(delta ^ offset for offset in h): + continue + require(value % divisor == 0, "coefficient needs a finer denominator") + for b in representatives: + right = compose(shear(b), g) + left = compose(target, compose(shear(delta ^ b), g)) + yield Term(value // divisor, right, left) + + +def seed_subgroup(): + hats = [pair_mask(1 << i, 1 << j) for i, j in combinations(range(3), 2)] + return tuple(shear(mask) for mask in span(hats)) + + +@cache +def inverse(matrix): + # Binary symplectic inverse from the images of a paired basis. + return tuple(sum(pairing(matrix[i ^ 4], u) << i for i in range(8)) for u in IDENTITY) + + +def bell_tuple(matrix): + # q(L v)=q(v) gives = q(u)+q(S^-1 u), hence b from the + # images of basis vectors under the inverse. q(e_j)=0. + inv = inverse(matrix) + offset = 0 + for j in range(8): + v = inv[j ^ 4] + offset |= (((v >> 4) & v).bit_count() % 2) << j + return tuple(apply(matrix, v) ^ offset for v in SEED) + + +def check(target): + accum = Counter() + seen = set() + terms = list(iter_terms(target)) + subgroup = seed_subgroup() + for weight, right, left in terms: + products = {compose(left, compose(c, inverse(right))) for c in subgroup} + key = frozenset(products) + require(len(products) == 8 and key not in seen, "repeated or malformed coset") + seen.add(key) + for item in products: + accum[item] += weight + require({k: v for k, v in accum.items() if v} == {target: DENOMINATOR}, + "signed coset sum is not the single target") + require(len(accum) == 8304, "expanded union size") + mass_by_input = Counter() + for term in terms: + mass_by_input[bell_tuple(term.input_map)] += abs(term.numerator) + require(Counter(mass_by_input.values()) == {128: 29, 192: 10, 224: 8, 240: 8, 288: 12}, + "absolute coefficient mass by input") + require(8 * sum(m*m for m in mass_by_input.values()) * 64 == 1319 * DENOMINATOR**2, + "simultaneous squared norm bound") + numerators = [term.numerator for term in terms] + require(len(terms) == 4265 and sum(abs(w) for w in numerators) == 12800, + "row sparsity or absolute mass") + require(sum(w*w for w in numerators) == DENOMINATOR**2 // 8, "squared row mass") + require(any(w % 2 for w in numerators), "denominator 1024 not attained") + return len(accum) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--emit", action="store_true", help="emit the identity row as JSON lines") + args = parser.parse_args() + if args.emit: + for term in iter_terms(): + print(json.dumps(term._asdict(), separators=(",", ":"))) + return + covered = check(IDENTITY) + # Hadamard on each qubit swaps the two coordinate registers. + require(check(IDENTITY[4:] + IDENTITY[:4]) == covered, "translated support") + print(f"PASS_COMPRESSED_CLIFFORD_ROW terms=4265 group_terms=34120 union={covered}" + " denominator=1024 absolute_mass=25/2 squared_mass=1/8 row_norm_squared=2^45") + + +if __name__ == "__main__": + main() diff --git a/research/clifford-sparse-row/independent_check.py b/research/clifford-sparse-row/independent_check.py new file mode 100644 index 0000000000..dedaf90d0e --- /dev/null +++ b/research/clifford-sparse-row/independent_check.py @@ -0,0 +1,362 @@ +"""Independent tests of Bell contraction from arbitrary computational entries. + +Small matrices use Gaussian-integer numerators and explicit denominators. +The full four-qubit address counts require no full-size tensor allocation. +apoursh with substantial OpenAI Codex assistance. Apache-2.0. +""" + +from functools import cache +from itertools import combinations_with_replacement, product +from math import isqrt, prod +from pathlib import Path +import sys + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def parity(v): + return v.bit_count() % 2 + + +def add(a, b): + return a[0] + b[0], a[1] + b[1] + + +def mul(a, b): + return a[0] * b[0] - a[1] * b[1], a[0] * b[1] + a[1] * b[0] + + +def conj(a): + return a[0], -a[1] + + +def scale(a, n): + return a[0] * n, a[1] * n + + +def xor_sum(labels): + value = 0 + for label in labels: + value ^= label + return value + + +def kron(a, b): + return [[u * v for u in row_a for v in row_b] for row_a in a for row_b in b] + + +def literal_weyl(label, qubits): + # Ordinary Kronecker construction; row and column signs are read from + # the resulting matrix, independently of the address allocator below. + d = 2**qubits + z, x = divmod(label, d) + w = [[1]] + for bit in reversed(range(qubits)): + sign = -1 if z & (1 << bit) else 1 + gate = [[0, sign], [1, 0]] if x & (1 << bit) else [[1, 0], [0, sign]] + w = kron(w, gate) + return w + + +def indexed_word(pairs, singleton, d): + index = 0 + for row, col in pairs: + index = (index * d + row) * d + col + return index * d + singleton + + +def signed_addresses(labels, d): + # Indices differ by the prescribed pair shifts. A base-d suffix is + # reserved for the singleton, so these are the start offsets of blocks. + parts = [divmod(label, d) for label in labels] + for cols in product(range(d), repeat=len(parts)): + pairs = [(col ^ x, col) for col, (_, x) in zip(cols, parts)] + sign = (-1) ** (sum(parity(z & col) for col, (z, _) in zip(cols, parts)) % 2) + yield indexed_word(pairs, 0, d), sign + + +def raw_singleton_row(inp, out, i, j, d): + # Weights are the *numerators* of Bell contractions. Multiplying by + # sqrt(d) accounts for raw observations of normalized tensor columns. + zw, xw = divmod(xor_sum(inp), d) + zv, xv = divmod(xor_sum(out), d) + row, col = i ^ xv, j ^ xw + endpoint_sign = (-1) ** (parity(zv & row) ^ parity(zw & col)) + inbound = tuple(signed_addresses(inp, d)) + return {(a + row, b + col): sa * sb * endpoint_sign + for a, sa in signed_addresses(out, d) for b, sb in inbound} + + +def literal_basis(labels, singleton, qubits): + d = 2**qubits + # Flatten each literal Weyl in row-major order and take their tensor + # product followed by a singleton unit vector; drop zeros only afterward. + numerators = [1] + for label in labels: + w = literal_weyl(label, qubits) + numerators = [a * b for a in numerators for row in w for b in row] + return {i*d + singleton: a for i, a in enumerate(numerators) if a} + + +def datum(i, j): + # An arbitrary observation, free of any promise of a Clifford mixture. + return ((i*i + 11*i*j + 7*j + 3) % 43 - 21, + (5*i + 3*j*j + i*j + 4) % 47 - 23) + + +def evaluate(row): + total = (0, 0) + for (i, j), a in row.items(): + total = add(total, scale(datum(i, j), a)) + return total + + +def reference_block(inp, out, qubits): + d = 2**qubits + left = [literal_basis(out, i, qubits) for i in range(d)] + right = [literal_basis(inp, j, qubits) for j in range(d)] + bare = [[evaluate({(a, b): sa*sb for a, sa in u.items() for b, sb in v.items()}) + for v in right] for u in left] + w_out = literal_weyl(xor_sum(out), qubits) + w_in = literal_weyl(xor_sum(inp), qubits) + result = [] + for u in w_out: + row = [] + for v in w_in: # right inverse of the input Weyl is its transpose + entry = (0, 0) + for i, s in enumerate(u): + for j, t in enumerate(v): + if s and t: + entry = add(entry, scale(bare[i][j], s * t)) + row.append(entry) + result.append(row) + return result + + +def targets(): + # Four-dimensional unitary numerators: identity, phase on qubit 1, + # one rephased Hadamard, and a two-qubit Walsh matrix. + for kind, denominator in (("I", 1), ("S", 1), ("h", 2), ("HH", 2)): + entries = {} + for i, j in product(range(4), repeat=2): + sign = (-1) ** parity(i & j) + if kind == "I" and i == j: + entries[i, j] = (1, 0) + elif kind == "S" and i == j: + entries[i, j] = (0, 1) if i & 1 else (1, 0) + elif kind == "h" and i >> 1 == j >> 1: + local = (-1) ** (i & j & 1) + entries[i, j] = (local, local) + elif kind == "HH": + entries[i, j] = (sign, 0) + require(sum(a*a+b*b for a, b in entries.values()) == 4 * denominator**2, + "target normalization") + yield entries, denominator + + +def compare(inp, out, with_traces): + d = 4 + ref = reference_block(inp, out, 2) + rows = {} + seen = set() + for i, j in product(range(d), repeat=2): + line = raw_singleton_row(inp, out, i, j, d) + require(len(line) == d**(2*len(inp)) and not seen.intersection(line), + "singleton support or disjointness") + require(evaluate(line) == ref[i][j], "computational-address contraction mismatch") + rows[i, j] = line + seen.update(line) + trace_cases = 0 + if with_traces: + for target, den in targets(): + # Actual scalar denominator is d*den. The common numerator + # scale is sqrt(d) from undoing column and Bell normalizations. + weights = {address: scale(conj(coeff), isqrt(d)*sgn) + for ij, coeff in target.items() for address, sgn in rows[ij].items()} + require(len(weights) == len(target)*d**(2*len(inp)), "trace read count") + actual = (0, 0) + for (a, b), coeff in weights.items(): + actual = add(actual, mul(coeff, datum(a, b))) + reference = (0, 0) + for (i, j), coeff in target.items(): + reference = add(reference, mul(conj(coeff), ref[i][j])) + # Literal Bell elements contribute 1/d^k for k input-output + # pairs after multiplying the two 1/sqrt(d) factors per pair. + k = len(inp) + require(scale(actual, d**k) == scale(reference, isqrt(d)**(2*k+1)), + "normalized raw-entry units") + require(d * den in (4, 8), "trace denominator") + trace_cases += 1 + return len(rows), trace_cases + + +def check_shears(): + # Literal diagonal Clifford phases. The phase ratio at each y relative + # to zero determines which Z-character it adds to the Bell label. + bits = 4 + d = 2**bits + positions = tuple(combinations_with_replacement(range(bits), 2)) + for mask in range(1 << len(positions)): + forms = [0] * bits + for k, (i, j) in enumerate(positions): + if mask & (1 << k): + forms[i] |= 1 << j + forms[j] |= 1 << i + diagonal = sum(((row >> i) & 1) << i for i, row in enumerate(forms)) + q = [] + for y in range(d): + phase = 0 + for k, (i, j) in enumerate(positions): + if mask & (1 << k) and y & (1 << i) and y & (1 << j): + phase += 1 if i == j else 2 + q.append(phase % 4) + for x in range(d): + add_z = diagonal ^ sum(parity(row & x) << i for i, row in enumerate(forms)) + for y in range(d): + require((q[y ^ x] + q[y] - q[x]) % 4 == 2*parity(y & add_z), + "affine shear changed a shift or gave a wrong Z-character") + # Two distinct frequencies with identical physical support can cancel. + a = raw_singleton_row((0,), (0,), 0, 0, 4) + b = raw_singleton_row((4,), (0,), 0, 0, 4) + c = raw_singleton_row((1,), (0,), 0, 0, 4) + require(a.keys() == b.keys() and not a.keys() & c.keys(), "shift class partition") + require(sum(a[k] + b[k] != 0 for k in a) * 2 == len(a), + "unmerged support-count control") + return (1 << len(positions))*d*d + + +ROOTS = ((1, 0), (0, 1), (-1, 0), (0, -1)) + + +@cache +def weyl4(label): + # The compiler numbers a Weyl as (X << 4) | Z. literal_weyl uses + # the opposite convention. Read the signs from the full 16x16 matrix. + x, z = divmod(label, 16) + return literal_weyl((z << 4) | x, 4) + + +def split_coordinate(index): + nibbles = tuple((index >> (4*j)) & 15 for j in reversed(range(13))) + return tuple(zip(nibbles[0:12:2], nibbles[1:12:2])), nibbles[12] + + +def impulse_read(read, output, inp): + outs, a = output + ins, b = inp + prefactor = prod(weyl4(t)[i][j] for t, (i, j) in zip(read.output_labels, outs)) + prefactor *= prod(weyl4(t)[i][j] for t, (i, j) in zip(read.input_labels, ins)) + if not prefactor: + return 0, 0 + left = weyl4(xor_sum(read.output_labels)) + right = weyl4(xor_sum(read.input_labels)) + singleton = sum(left[i][a] * right[i][b] for i in range(16)) + return scale(ROOTS[read.correction_i], read.numerator * prefactor * singleton) + + +def check_compiled_impulses(reads, coefficient_numerator): + # Coordinates count from zero in big-endian row/column base-16 order. + # The first impulse occurs in several reads whose contributions cancel. + points = ((0xddcc7700cc024, 0x88dd66ff99024, 0), + (0x55ff11bb5546b, 0x22225577bb31b, 128), + (0x5544cc7766576, 0xff99dd4466316, -128), + (0xffaadd01ff5df, 0xcc775598ee2af, 512), + (0xcc22eecd77e62, 0x8811bb76cc5d2, -512), + (0, 1, 0)) + for n, (i, j, expected) in enumerate(points): + output, inp = split_coordinate(i), split_coordinate(j) + direct = (0, 0) + supporting = 0 + for read in reads: + value = impulse_read(read, output, inp) + supporting += int(value != (0, 0)) + direct = add(direct, value) + require(direct == (expected, 0), "literal 13-copy impulse value") + require(coefficient_numerator(i, j) == expected, "compiled raw row impulse value") + if n == 0: + require(supporting >= 2, "cancellation control had no contributing reads") + elif n == len(points) - 1: + require(not supporting, "outside-support control unexpectedly contributed") + return len(points) + + +def transvection_numerator(axis): + # Twice the dyadic Clifford lift (1+i)(I+iP)/2, P=i^q W_axis. + x, z = divmod(axis, 16) + phase = mul((1, 1), ROOTS[1 + parity(x & z)]) + w = weyl4(axis) + return [[add((1, 1) if i == j else (0, 0), scale(phase, w[i][j])) + for j in range(16)] for i in range(16)] + + +def literal_action_column(gate, label, col, bell): + # One literal column of G W G^T or G W G*, with G twice the lift. + x, _ = divmod(label, 16) + w = weyl4(label) + result = [(0, 0)] * 16 + for k, right in enumerate(gate[col]): + if right == (0, 0): + continue + factor = scale(right if bell else conj(right), w[k ^ x][k]) + for i in range(16): + if gate[i][k ^ x] != (0, 0): + result[i] = add(result[i], mul(factor, gate[i][k ^ x])) + return result + + +def check_transvections(step): + cases = 0 + nonreal = 0 + for axis in (1, 0x10, 0x11, 0x23, 0x35, 0x55, 0x8f, 0xff): + gate = transvection_numerator(axis) + for label in range(256): + for bell in (False, True): + new_label, exponent = step(axis, label, bell) + expected = weyl4(new_label) + unit = scale(ROOTS[exponent], 4) + nonreal += exponent % 2 + for col in (0, 1, 2, 4, 8, 15): + actual = literal_action_column(gate, label, col, bell) + require(actual == [scale(unit, row[col]) for row in expected], + "transport phase or symplectic shift") + cases += 1 + require(nonreal > 0, "transport test lacks nonreal phases") + return cases + + +def main(): + # Local imports provide the product under test. The literal references + # above do not call its symplectic, phase or Walsh routines. + sys.path.insert(0, str(Path(__file__).resolve().parent)) + from bell_reads import iter_reads, step + from raw_row import coefficient_numerator + + impulses = check_compiled_impulses(tuple(iter_reads()), coefficient_numerator) + transported = check_transvections(step) + counts = [0, 0] + for a, b in product(range(16), repeat=2): + n, t = compare((a,), (b,), with_traces=True) + counts[0] += n + counts[1] += t + for a, b in (((9, 12), (5, 14)), ((2, 15), (4, 11))): + n, t = compare(a, b, with_traces=True) + counts[0] += n + counts[1] += t + shear_cases = check_shears() + d, k = 16, 6 + per_entry = prod([d, d] * k) + require(per_entry == 2**48 and d**2 * per_entry == 2**56, + "four-qubit block size") + require(isqrt(d)**(2*k+1) == 4*d**k and d*per_entry == 2**52, + "four-qubit scale and monomial trace size") + print("PASS_RAW_BELL_CONTRACTION", f"singleton_entries={counts[0]}", + f"target_traces={counts[1]}", f"literal_shear_phase_checks={shear_cases}", + f"four_qubit_reads_per_entry={per_entry}", f"literal_impulses={impulses}", + f"transvection_columns={transported}") + + +if __name__ == "__main__": + main() diff --git a/research/clifford-sparse-row/mixture_check.py b/research/clifford-sparse-row/mixture_check.py new file mode 100644 index 0000000000..977f9be8ff --- /dev/null +++ b/research/clifford-sparse-row/mixture_check.py @@ -0,0 +1,150 @@ +"""Run the complete sparse decoder against independently formed Bell observations. + +The fixture operators are literal monomial 16-by-16 Clifford matrices. All +entries and mixtures are Gaussian integers, with powers of i stored exactly. +apoursh with substantial OpenAI Codex and separate agent assistance. Apache-2.0. +""" +from functools import reduce +from operator import xor +from pathlib import Path +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from bell_reads import iter_reads +from compile_row import DENOMINATOR, IDENTITY + + +def require(condition, msg): + if not condition: + raise ValueError(msg) + + +def parity(x): + return x.bit_count() % 2 + + +def rotate(z, exponent): + a, b = z + return ((a, b), (-b, a), (-a, -b), (b, -a))[exponent % 4] + + +def add(z, w): + return z[0]+w[0], z[1]+w[1] + + +def scale(z, w): + return z[0]*w, z[1]*w + + +def make_section(kind): + """Specify the matrix by (row, quarter-phase exponent) in each column.""" + sections = [] + for j in range(16): + quarter = int(bool(kind & 1)) * (j & 1) + cz12 = (j & 1) * ((j >> 1) & 1) + cz13 = (j & 1) * ((j >> 2) & 1) + quarter += 2 * (int(bool(kind & 2))*cz12 + int(bool(kind & 4))*cz13) + # For kinds 8..15 add CNOT from qubit two to one after the phases. + row = j ^ ((j >> 1) & 1) if kind & 8 else j + sections.append((row, quarter % 4)) + return tuple(sections) + + +def representative(section, kind, p): + z, x = p & 15, p >> 4 + # An arbitrary but reproducible projective representative for each column. + gauge = (kind + 3*p + p.bit_count()) % 4 + return tuple((row ^ x, (phase + gauge + 2*parity(row & z)) % 4) + for row, phase in section) + + +def literal_bell(u, t): + """Apply U x U to all 16 entries of vec(X^x Z^z), then identify the output.""" + z, x = t & 15, t >> 4 + destination = [0]*16 + phases = [0]*16 + for k in range(16): + row, a = u[k ^ x] + col, b = u[k] + destination[col] = row + phases[col] = (a+b+2*parity(k & z)) % 4 + shift = destination[0] + theta = phases[0] + fourier = sum(1 << i for i in range(4) if (phases[1 << i]-theta) % 4 == 2) + require(all(destination[j] == (j ^ shift) + and phases[j] == (theta+2*parity(j & fourier)) % 4 for j in range(16)), + "literal Bell output was not a single signed label") + return (shift << 4) | fourier, theta + + +def materialize_fixture(): + operators = [] + sections = [make_section(k) for k in range(16)] + for kind, section in enumerate(sections): + for p in (0, 1, 18, 37): + u = representative(section, kind, p) + amplitude = ((kind+p) % 5-2, 1+(kind+2*p) % 3) + table = tuple(literal_bell(u, t) for t in range(256)) + operators.append((kind, p, u, amplitude, table)) + return sections, operators + + +def record(d, key, value): + d[key] = add(d.get(key, (0, 0)), value) + + +def test_fibre(kind, sections, operators): + reference = operators[4*kind][4] + offset = reference[0][0] + target = tuple(reference[t][0] ^ offset for t in IDENTITY) + recovered = {} + raw_terms = 0 + contributors = set() + nontrivial_phases = set() + reads = 0 + for read in iter_reads(target): + reads += 1 + xi, zi = reduce(xor, read.input_labels) >> 4, reduce(xor, read.input_labels) & 15 + xo, zo = reduce(xor, read.output_labels) >> 4, reduce(xor, read.output_labels) & 15 + observed = {} + # Form the raw singleton Y between the two compiled Bell tuples. Each + # matching column of U^(tensor 13) contributes i^beta U. Restoring + # the known 4^13 from normalized observations has been done here. + for source, p, u, amplitude, table in operators: + entries = [table[t] for t in read.input_labels] + if tuple(label for label, _ in entries) != read.output_labels: + continue + contributors.add(source) + beta = sum(theta for _, theta in entries) + raw_terms += 1 + for col, (row, phase) in enumerate(u): + record(observed, (row, col), rotate(amplitude, beta + phase)) + # Apply W_out Y W_in^{-1} literally to individual raw entries. The + # signs are evaluated before the output and input X permutations. + for (row, col), z in observed.items(): + if z == (0, 0): + continue + exponent = read.correction_i + 2*(parity(row & zo) + parity(col & zi)) + nontrivial_phases.add(exponent % 4) + record(recovered, (row ^ xo, col ^ xi), scale(rotate(z, exponent), read.numerator)) + + expected = {p: a for s, p, _, a, _ in operators if s == kind} + for p in range(256): + coefficient = (0, 0) + for col, (row, phase) in enumerate(representative(sections[kind], kind, p)): + coefficient = add(coefficient, rotate(recovered.get((row, col), (0, 0)), -phase)) + require(coefficient == scale(expected.get(p, (0, 0)), 16*DENOMINATOR), + f"bad output coefficient for shape {kind}, Pauli {p}") + require(reads == 4265 and kind in contributors and len(contributors) > 1, + "fixture did not exercise undesired coset contributions") + require(any(nontrivial_phases), "phase corrections were vacuous") + return reads, raw_terms, len(contributors) + + +if __name__ == "__main__": + sections, fixture = materialize_fixture() + runs = [test_fibre(k, sections, fixture) for k in (0, 1)] + print("PASS_COMPILED_BELL_MIXTURE", + f"terms={sum(n for n, _, _ in runs)} operators={len(fixture)} coefficients=512", + f"column_block_contributions={sum(n for _, n, _ in runs)}", + f"contributing_shapes={','.join(str(n) for _, _, n in runs)}") diff --git a/research/clifford-sparse-row/raw_row.py b/research/clifford-sparse-row/raw_row.py new file mode 100644 index 0000000000..1787feb76a --- /dev/null +++ b/research/clifford-sparse-row/raw_row.py @@ -0,0 +1,284 @@ +"""Exact computational-basis coefficients of the compiled identity decoder. + +A row or column address is a 52-bit integer, with the first register in +the most significant nibble. A returned numerator has denominator 4096. +apoursh, with substantial OpenAI Codex assistance. Apache-2.0. +""" +import argparse +from collections import Counter, defaultdict +from dataclasses import dataclass +from functools import cache +from itertools import islice +import json + +from bell_reads import iter_reads, label_sum +from compile_row import DENOMINATOR + + +BITS = 52 +RAW_DENOMINATOR = 4 * DENOMINATOR + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def pack(nibbles): + return sum(nibble << (4 * i) for i, nibble in enumerate(nibbles)) + + +def split_address(address): + if not isinstance(address, int) or not 0 <= address < 1 << BITS: + raise ValueError("row and column must be unsigned 52-bit addresses") + return tuple((address >> (4 * j)) & 15 for j in reversed(range(13))) + + +@dataclass(frozen=True) +class Bucket: + masks: tuple[int, ...] + numerators: tuple[int, ...] + + def signature(self, point): + return sum(((mask & point).bit_count() % 2) << j for j, mask in enumerate(self.masks)) + + def point_at(self, signature, index): + """Unrank the free bits, then solve the parity equations by leading bit.""" + pivots = sorted((mask.bit_length()-1, j) for j, mask in enumerate(self.masks)) + pivot_bits = {bit for bit, _ in pivots} + point = 0 + for bit in range(BITS): + if bit not in pivot_bits: + point |= (index & 1) << bit + index >>= 1 + for bit, j in pivots: + target = (signature >> j) & 1 + value = target ^ ((self.masks[j] & point).bit_count() % 2) + point |= value << bit + return point + + +def make_bucket(terms): + masks = [] + pivots = {} + weights = Counter() + for frequency, weight in terms: + address = 0 + while frequency: + bit = frequency.bit_length()-1 + if bit not in pivots: + pivots[bit] = len(masks) + masks.append(frequency) + j = pivots[bit] + frequency ^= masks[j] + address ^= 1 << j + weights[address] += weight + # Orthogonality of the independent masks makes every sign pattern attainable. + table = [weights[i] for i in range(1 << len(masks))] + step = 1 + while step < len(table): + for start in range(0, len(table), 2 * step): + for i in range(start, start + step): + a, b = table[i], table[i+step] + table[i], table[i+step] = a+b, a-b + step *= 2 + return Bucket(tuple(masks), tuple(table)) + + +@cache +def raw_plan(): + terms = defaultdict(list) + for read in iter_reads(): + labels = read.output_labels + read.input_labels + shifts = tuple(t >> 4 for t in labels) + singleton = label_sum(labels) + require(singleton < 16, "identity trace is not diagonal in this term") + require(read.correction_i == 0, "identity term has an unexpected phase") + frequency = pack([*(t & 15 for t in labels), singleton]) + terms[shifts].append((frequency, read.numerator)) + return {key: make_bucket(value) for key, value in sorted(terms.items())} + + +def coefficient_numerator(row, column): + r, c = split_address(row), split_address(column) + if r[-1] != c[-1]: + return 0 + pairs = r[:-1] + c[:-1] + shifts = tuple(a ^ b for a, b in zip(pairs[::2], pairs[1::2], strict=True)) + bucket = raw_plan().get(shifts) + if bucket is None: + return 0 + point = pack((*pairs[1::2], r[-1])) + return bucket.numerators[bucket.signature(point)] + + +def matrix_addresses(shifts, point): + addresses = [] + singleton = (point >> 48) & 15 + for start in (0, 6): + address = 0 + for index in range(start, start+6): + v = (point >> (4*index)) & 15 + address = (address << 8) | ((v ^ shifts[index]) << 4) | v + addresses.append((address << 4) | singleton) + return tuple(addresses) + + +def probe_at(index): + """One nonzero coordinate, in deterministic bucket/signature/free-bit order.""" + if not isinstance(index, int) or index < 0: + raise ValueError("probe index must be a nonnegative integer") + for shifts, bucket in raw_plan().items(): + size = 1 << (BITS-len(bucket.masks)) + for signature, numerator in enumerate(bucket.numerators): + if numerator != 0: + if index < size: + point = bucket.point_at(signature, index ^ (index >> 1)) + row, col = matrix_addresses(shifts, point) + return row, col, numerator + index -= size + raise ValueError("probe index outside the nonzero support") + + +def cell_geometry(shifts, bucket): + def address(signature, index): + row, column = matrix_addresses(shifts, bucket.point_at(signature, index)) + return (row << BITS) | column + + origin = address(0, 0) + directions = [origin ^ address(0, 1 << j) for j in range(BITS - len(bucket.masks))] + return address, directions + + +def iter_probes(): + """Stream the exact nonzero support of the identity row in probe_at order.""" + for shifts, bucket in raw_plan().items(): + address, directions = cell_geometry(shifts, bucket) + size = 1 << len(directions) + for signature, numerator in enumerate(bucket.numerators): + if not numerator: + continue + pointer = address(signature, 0) + for i in range(size): + row, col = divmod(pointer, 1 << BITS) + yield row, col, numerator + if i + 1 < size: + # Consecutive reflected Gray words flip this one free bit. + delta = i + 1 + pointer ^= directions[(delta & -delta).bit_length() - 1] + + +def first_last_addresses(): + """Extrema of the nonzero row on a row-major tape, over affine Walsh cells.""" + first, last = 1 << (2*BITS), -1 + for shifts, bucket in raw_plan().items(): + address, generators = cell_geometry(shifts, bucket) + pivots = {} + for v in generators: + while v: + bit = v.bit_length() - 1 + if bit not in pivots: + pivots[bit] = v + break + v ^= pivots[bit] + require(len(pivots) == BITS - len(bucket.masks), "address map lost a free bit") + directions = [pivots[bit] for bit in sorted(pivots, reverse=True)] + for i, n in enumerate(bucket.numerators): + if not n: + continue + lo = hi = address(i, 0) + for direction in directions: + lo = min(lo, lo ^ direction) + hi = max(hi, hi ^ direction) + first, last = min(first, lo), max(last, hi) + return first, last + + +def check_diagonal_columns(): + # For U=Z^z, the raw column is supported on equal row and column + # addresses. There r=s for every pair, leaving 24 pair bits and one + # free singleton. Push these free bits through the parity equations. + outputs = [0] * 16 + for shifts, bucket in raw_plan().items(): + require(shifts[:6] == shifts[6:], "diagonal fixture shift layout") + image = {0} + for bit in range(24): + basis_point = (1 << bit) | (1 << (bit+24)) + character = bucket.signature(basis_point) + image |= {s ^ character for s in image} + multiplicity = 2**24 // len(image) + shift_sum = label_sum(shifts[:6]) + for singleton in range(16): + offset = bucket.signature(singleton << 48) + total = sum(bucket.numerators[s ^ offset] for s in image) * multiplicity + for z in range(16): + sign = (-1) ** (((shift_sum ^ singleton) & z).bit_count() % 2) + outputs[z] += sign * total + require(outputs == [RAW_DENOMINATOR * 4**13] + [0]*15, + "normalized diagonal Clifford recovery from raw address weights") + + +def check(): + counts = Counter() + cells = 0 + checked = 0 + plan = raw_plan() + for shifts, bucket in plan.items(): + size = 1 << (BITS - len(bucket.masks)) + cells += len(bucket.numerators) + for signature, n in enumerate(bucket.numerators): + counts[n] += size + for index in (0, size-1): + point = bucket.point_at(signature, index) + require(bucket.signature(point) == signature, "unranking a Walsh class") + require(coefficient_numerator(*matrix_addresses(shifts, point)) == n, + "raw address lookup mismatch") + checked += 1 + expected = {0: 77827831060496384, 128: 10133099161583616, -128: 10133099161583616, + 512: 492581209243648, -512: 492581209243648} + require(counts == expected and len(plan) == 22, "raw coefficient multiplicities") + support = sum(count for n, count in counts.items() if n) + require(support == 151 * 2**47, "raw query bill") + require(sum(n*n*count for n,count in counts.items()) == RAW_DENOMINATOR**2 * 2**45, + "computational and Bell row norms disagree") + for index in (0, 1, support//2, support-2, support-1): + row, col, n = probe_at(index) + require(n == coefficient_numerator(row, col) and n != 0, "nonzero-support unranking") + require(list(islice(iter_probes(), 64)) == [probe_at(i) for i in range(64)], + "stream order disagrees with indexed access") + check_diagonal_columns() + first, last = first_last_addresses() + require(first == 0x00000000000210000000000021 and first + last == (1 << (2*BITS)) - 1, + "row-major tape extrema") + for address in (first, last): + require(coefficient_numerator(*divmod(address, 1 << BITS)) != 0, "inactive tape endpoint") + print(f"PASS_RAW_IDENTITY_ROW buckets={len(plan)} Walsh_cells={cells}" + f" boundary_lookups={checked} nonzero_coordinates={support} squared_norm=2^45" + f" first={first:026x} last={last:026x}") + + +def integer(text): + return int(text, 0) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + action = parser.add_mutually_exclusive_group() + action.add_argument("--entry", type=integer, nargs=2, metavar=("ROW", "COLUMN")) + action.add_argument("--probe-index", type=integer, + help="unrank one nonzero coordinate, starting at zero") + args = parser.parse_args() + if args.entry is not None: + row, col = args.entry + numerator = coefficient_numerator(row, col) + elif args.probe_index is not None: + row, col, numerator = probe_at(args.probe_index) + else: + check() + return + print(json.dumps({"row": row, "column": col, "numerator": numerator, + "denominator": RAW_DENOMINATOR})) + + +if __name__ == "__main__": + main()