diff --git a/research/clifford-compact-pauli-fibre/PROOF.md b/research/clifford-compact-pauli-fibre/PROOF.md new file mode 100644 index 0000000000..c28ab61399 --- /dev/null +++ b/research/clifford-compact-pauli-fibre/PROOF.md @@ -0,0 +1,56 @@ +# One accumulation per Bell read for the entire identity fibre + +Use the compiled, normalized four-qubit decoder of #7800, at width 13, with identity symplectic target and real unphased lifts $W_{x,z}=X^xZ^z$. Its 256 outputs are indexed by $16x+z$. All statements concern its specified linear extension on arbitrary observations, including inputs outside the Clifford column span. The compiler supplies 4,265 signed numerators $n$ of total absolute mass 12,800. Output and input tuples each have six Weyl labels. Write $w_o=(t_o,z_o)$ and $w_i=(t_i,z_i)$ for their binary sums. The compiler verifies $t_o=t_i=t$ and unit transport phase on these reads. [Pinned block and phase conventions](https://github.com/apoursh/integer-mult-bounds/blob/fdc90699f4a64139ed6d84cdbf9a606ff0ccd32e/research/clifford-sparse-row/PROOF.md) + +## Partial Bell transform + +At a 104-bit raw address let $s$ be the twelve 4-bit XORs of adjacent row/column pairs, $v$ the twelve second nibbles and $y=(a,b)$ the two singleton nibbles. These are independent linear coordinates of lengths 48, 48 and 8. For each read take its shift $s$ from the X bits and its frequency $w$ from the Z bits of the twelve ordered labels. Define the partial Walsh transform +$$ +T(s,w,y)=\sum_v(-1)^{w\cdot v}Y(s,v,y). +$$ +The actual Bell block is $4T$ after undoing column normalization. Applying its singleton corrections translates $y$ by $d=(t_o,t_i)$ and multiplies the entry at the raw location by $(-1)^{\sigma\cdot y}$, where $\sigma=(z_o,z_i)$. Indeed $(W_o T W_i^{-1})_{a+t_o,b+t_i}=(-1)^{z_o\cdot a+z_i\cdot b}T_{a,b}$. Accumulate each corrected block with integer weight $n$. For each $x$ extract the shifted diagonal indexed by corrected column $c$ and apply its four-bit Walsh transform in $c$. Dividing the final array by 4,096 accounts for the Bell factor $4$, compiler denominator $1,024$ and trace factor $1/16$. + +Suppose the chart gives $Y[o+Dh]=c_0 i^{q(h)}$ for independent columns of $D$ and zero elsewhere. The scalar is complex and the contraction is linear in it. Let $Lh$ be the $(s,y)$ projection of $Dh$ and $Vh$ its $v$ projection. Write $K$ for a kernel basis of $L$, $k=\dim\ker L$. Because $D$ is injective, $VK$ is injective and $k\le48$. Choose a binary echelon section of $L$. On *all* right sides it returns a linear pair (remainder, preimage); the remainder vanishes exactly on the image. The section tested on $(s,y)+o_{sy}$ returns its remainder and $h$. On the consistent slices the chart parameters are exactly $h+Ku$. + +Let $B$ be the polar matrix of $q$, including the parity of its linear coefficients on the diagonal. Set $p(u)=q(Ku)-q(0)$ and $H=K^TBK$. Use the common anchor $m_0$ of #7801, satisfying $m_0\cdot z=p(z)/2$ on $\ker H$. Translation in the finite sum proves +$$ +\sum_u i^{p(u)}(-1)^{m\cdot u} += i^{-p(l)}(-1)^{m_0\cdot l}G,\qquad +G=\sum_u i^{p(u)}(-1)^{m_0\cdot u}, +$$ +when $Hl=m+m_0$; otherwise the sum is zero by pairing with a radical vector. The anchor exists since $p/2$ is linear on the radical, and $|G|^2=2^{k+\dim\ker H}$ by orthogonality. [Pinned scalar spectrum and retained Gauss routine](https://github.com/apoursh/integer-mult-bounds/blob/9d15f66abc9ccf760ca5f7ea442adeb87b8f7115/research/clifford-chart-contraction/PROOF.md) + +Here $m=K^TBh+(VK)^T w$. Apply a fixed echelon section of $H$ to $m+m_0$, giving a second remainder and preimage $l$. Combining the two remainders gives an affine binary syndrome $E(s,w,y)$. The following expression is a quadratic polynomial on *all* addresses, including the inconsistent ones: +$$ +P(s,w,y)=q(h)+2w\cdot(o_v+Vh)-p(l)+2m_0\cdot l\pmod4. +$$ +Both sections are linear, so all mixed terms remain even after affine substitution. The exact transformed entry is $c_0G\,i^{P(s,w,y)}$ when $E=0$, and zero otherwise. This requires one Gauss sum per chart and avoids storing the full transformed observation. + +## A shared basis on the eight singleton bits + +Holding $(s,w)$ fixed leaves the same linear part of $E$ on $y$ for every read. Let $U$ be its kernel, with independent columns $u_1,\ldots,u_e$, $0\le e\le8$. A consistent read occupies a single affine coset of $U$, even after the read-dependent singleton translation. Choose the canonical representative $a_0$ of that corrected coset. Its raw representative is $y_0=a_0+d$. Put $v_0=(s,w,y_0)$ and define the common chirp +$$ +p_U(h)=P(0,0,Uh)-P(0,0,0). +$$ +Writing $B_P$ for the polar form of $P$, the corrected slice at $a_0+Uh$ has scalar phase +$$ +i^{P(v_0)+2\sigma\cdot y_0}\,i^{p_U(h)}(-1)^{f\cdot h},\qquad +f_j=B_P(v_0,(0,0,u_j))+\sigma\cdot u_j. +$$ +This follows by polarization. In implementing the formula the coset representative and the internal basis indices are separate. The $e$ binary functionals $B_P(-,(0,0,u_j))$ are tabulated once from the differences at zero and the 104 unit vectors. + +There are $2^{8-e}$ cosets and $2^e$ modulations per coset. Consequently **one signed Gaussian-unit accumulation in exactly one of 256 bins suffices for a supported read**. Inconsistent reads have no bin. On each coset do a length-$2^e$ Walsh transform on its bins and multiply by the shared pointwise chirp. This reconstructs the full weighted singleton matrix. The sixteen length-16 trace transforms then give all outputs using the absolute scalar $c_0G/4096$. The disjoint coset supports and Walsh orthogonality show that these chirped modulations constitute an orthogonal basis. Its shape depends on the chart but is shared across all reads. + +After the chart and fixed list are available, this takes at most 4,265 Gaussian accumulator updates and exactly $256(e+4)\le3,072$ complex additions/subtractions in the two transform stages. Further operations include the binary sections, coefficient projections and phase evaluations, chirp rotations, and the shared final scalar multiplication. The algorithm uses one elimination for each of the two large maps, a radical-anchor solve, and maps on at most eight coordinates. The implementation also reconstructs a section of the polar map after the retained anchor routine. Forming the $e$ polar functionals needs at most $e\cdot104$ extra phase evaluations on sums of basis vectors plus the unit-vector and origin evaluations. Each read computes the syndrome, finds its coset, evaluates its phase, and takes at most eight polar dot products. All of these steps have polynomial cost in the chart parameters; the actual 4,265-term list remains independent of those parameters. Each internal Walsh component has magnitude at most 12,800. Before applying the common scalar, a final trace component has magnitude at most $16\cdot12,800$. The Gaussian anchor has components bounded by $2^k$. Materializing arbitrary dense observations or applying the full normal matrix from #7809 is outside this interface. + +## Exact dense and mask-input costs + +For a raw address with $x=a+b$, only the outputs with Pauli X label $x$ are affected. All sixteen Pauli Z labels in that sector differ by the fixed sign $(-1)^{z\cdot(b+t)}$, since $t$ depends only on that bucket's X shifts. For $z=0$, translate **every column nibble** by $x$. This keeps all pair shifts fixed, translates each free column nibble by $x$, and sets its singleton to $a$. It therefore adds $z_i\cdot x$ to the pair signs of the old identity row, exactly replacing its singleton sign $(z_o+z_i)\cdot a$ by $z_o\cdot a+z_i\cdot b$. Thus each X sector's nonzero weight set is a bijective translate of the #7800 identity support. The sectors are pairwise disjoint. Together their support size is $16\cdot151\cdot2^{47}=340,021,771,866,472,448$. Reading those addresses suffices. On the all-zero dense observation any unread supported address can be perturbed to change an answer, proving a matching lower bound for deterministic exact adaptive coordinate probes. [Scalar support census and enumerator](https://github.com/apoursh/integer-mult-bounds/blob/fdc90699f4a64139ed6d84cdbf9a606ff0ccd32e/research/clifford-sparse-row/COST.md) + +The #7801 coupled full-support producer instead supplies $Y_h(A)=2^{-52}(-1)^{h\cdot A+\sum r_j\cdot s_j}$, where $r_j,s_j$ are the free second row and column nibbles. Write $A,B$ for the singleton row and column nibbles of the mask $h$, and $\alpha,\beta$ for its two sides' adjacent-XOR masks. Let $\theta$ be the dot product of the twelve first mask nibbles with the twelve Bell shifts. Summing each free row/column pair yields $16(-1)^{(w'_j+\alpha_j)\cdot(w_j+\beta_j)}$. Summing over the remaining singleton nibble forces $z=z_o+z_i+A+B$. For $k=z_o+A$ put the signed weight +$$ +n(-1)^{\theta+z\cdot t+\sum_j(w'_j+\alpha_j)\cdot(w_j+\beta_j)} +$$ +into bin $(z,k)$. Sixteen final length-16 Walsh transforms in $k$ give the output numerators, with denominator $2^{36}$ from $16^7\cdot2^{-52}/4096$. This specialization uses 4,265 signed integer accumulator updates and 1,024 binary Walsh additions/subtractions. A signed 15-bit register per bin suffices as every transform intermediate is bounded by 12,800. Each fixed record can be encoded with 48 shift bits, 48 Z bits and nine signed weight bits; remaining XOR summaries derive from those fields. The implementation stores additional precomputed summaries. + +On a read-only track provide $h$ in ascending bit order, start and finish at bit zero, and charge movement in adjacent-symbol steps. Read all 104 bits into working memory and return across the 103 links. This uses 104 probes and 206 head moves. On the **same** mask `e90447f9b4d1553cfdce84821d` in hexadecimal, flipping any one of the 104 input bits changes the output vector. The executable checks the 104 inequalities using exact integers. An adaptive deterministic decoder must probe every symbol on that mask because the unchanged answers to all earlier reads cannot distinguish the corresponding neighbor. In particular it must visit bit 103 and return, proving the 206-move lower bound. These are sharp costs for this producer encoding and head contract. Constructing the mask from another producer and moving local arithmetic or output tapes carry separate costs. [Specialized consumer](phase_mask.py) · [Literal singleton matrix check](check_phase_masks.py) diff --git a/research/clifford-compact-pauli-fibre/README.md b/research/clifford-compact-pauli-fibre/README.md new file mode 100644 index 0000000000..fea2ddb568 --- /dev/null +++ b/research/clifford-compact-pauli-fibre/README.md @@ -0,0 +1,31 @@ +# Joint compact contraction of all 256 Pauli coefficients + +All 256 outputs of the four-qubit width-13 identity symplectic fibre can be evaluated together on a 104-bit affine-quadratic chart with **one Gauss sum in at most 48 variables and at most one accumulator update per Bell read**. Each of the 4,265 compiled reads contributes to one of 256 bins or vanishes. All bins use a common basis of quadratic phases on the eight singleton bits. Two sets of Walsh transforms recover the requested coefficients using at most 3,072 further complex additions/subtractions. These counts exclude chart preparation, binary linear algebra, phase evaluation and the fixed compiler. [Proof and resource model](PROOF.md) · [Consumer](fibre.py) + +| Supplied observation | Exact result for the complete fibre | +|---|---| +| Affine-quadratic chart from the #5704 constructor | One shared Gauss scalar and one scan of the compiled list. Complex mixture coefficients retain their phase. | +| Full-support coupled phase mask from #7801, supplied as 104 bits | **104 symbol probes and 206 head moves**, both optimal. One mask witnesses that all 104 symbols are essential. | +| Arbitrary dense array with exact coordinate probes | Exactly **151 × 2⁵¹** probes. The sixteen X sectors have disjoint supports, each a translate of the scalar row from #7800. | + +The previous compact contraction handled one identity coefficient and priced one active Walsh cell on a tape. The new procedure produces a full symplectic fibre and prices the entire output vector on the coupled-mask tape. A Gram application in #7809 operates across symplectic fibres and remains unpriced. The selected multiplication bound is unchanged. [Previous one-row contraction](https://github.com/apoursh/integer-mult-bounds/blob/9d15f66abc9ccf760ca5f7ea442adeb87b8f7115/research/clifford-chart-contraction/PROOF.md) · [Coordination claim](https://github.com/CrocSwap/integer-mult-bounds/discussions/1166#discussioncomment-19756125) + +## Reproduce + +From the repository root use CPython 3.12 and the standard library. + +~~~sh +python3.12 -B scripts/research_package.py --package research/clifford-compact-pauli-fibre +~~~ + +To evaluate a chart from a circuit, run `python3.12 -B research/clifford-compact-pauli-fibre/fibre.py input.json` with the #5704 JSON circuit format. The optional `initial` field selects a computational-basis input. The result contains 256 exact real/imaginary pairs in order $16x+z$ for $X^x Z^z$ and reports the internal support rank and operation counts. A circuit with an empty gate list gives the computational basis chart at its initial address. + +The checks cover all nine possible singleton ranks, off-image inputs, complex phases, six one-hot Pauli columns, a different symplectic fibre, and dense address weights obtained directly from Bell corrections. A second checker evaluates the full 16-by-16 corrected matrix for each read on eleven rank-104 phase masks and compares every output. It also verifies the shared 104-neighbor access witness. [Sparse and dense controls](verify.py) · [Full-support controls](check_phase_masks.py) + +## Open next questions + +Can a batch of transported fibres share a partial Bell transform and a low-cost output layout? Begin with two distinct nonidentity actions, account for their different singleton corrections and fixed tables, and compare exact values on off-image charts. A complete application of the Gram matrix requires a proved composition across its whole coefficient domain and an observation producer supplying it. + +## Credit + +Ali Romman supplied the absolute-phase affine-quadratic signature and Gaussian contraction routines in #5704 and #5727, following the retained predecessor notices. The Bell compiler, coordinate support and earlier one-row contraction are from apoursh's #7800 and #7801, building on #7799 and the earlier Clifford work of Ali Romman, alephnan and Nick Petalas. The predecessor subtree is pinned to its source bytes. The shared singleton basis, sharp full-fibre access counts and verification were prepared by apoursh with substantial OpenAI Codex assistance under Apache-2.0. [Source pins](SOURCE-PINS.json) · [Upstream notices and license](predecessor/source/engine/source/) diff --git a/research/clifford-compact-pauli-fibre/SOURCE-PINS.json b/research/clifford-compact-pauli-fibre/SOURCE-PINS.json new file mode 100644 index 0000000000..15c09450dc --- /dev/null +++ b/research/clifford-compact-pauli-fibre/SOURCE-PINS.json @@ -0,0 +1,74 @@ +{ + "repository": "apoursh/integer-mult-bounds", + "commit": "9d15f66abc9ccf760ca5f7ea442adeb87b8f7115", + "pull_request": 7801, + "predecessor_files": [ + { + "local": "predecessor/RETAINED.json", + "source_path": "research/clifford-chart-contraction/RETAINED.json", + "git_blob": "520317e6511abc0b97674d4b9938e45abbfca51b", + "sha256": "4bac919b0b78bfd312c6e6f5642644267f38ab6d6aa7125dc45b6d718ccfc046" + }, + { + "local": "predecessor/contract.py", + "source_path": "research/clifford-chart-contraction/contract.py", + "git_blob": "11df2cef1492019bfc52f073fcfd3b02192b39f9", + "sha256": "ad127f9bb72b57360c2e93471c988488721848047e3c9914af094ad36701612e" + }, + { + "local": "predecessor/source/engine/INPUTS.json", + "source_path": "research/clifford-chart-contraction/source/engine/INPUTS.json", + "git_blob": "f9d4fd920651b002370ffb5084dbef2abaa5ed44", + "sha256": "c62bd55fd36c136ba2ec34f6d91ed481497932fadc7134d0b7e5c10009fd588c" + }, + { + "local": "predecessor/source/engine/contractions.py", + "source_path": "research/clifford-chart-contraction/source/engine/contractions.py", + "git_blob": "76c807deceea0b1a6b64b50735253959b07c144d", + "sha256": "a2fc065d6f293ddcffe5b6eec7fff0fdf57c8e3d4c6be355bd92e87d3f1865ef" + }, + { + "local": "predecessor/source/engine/source/LICENSE", + "source_path": "research/clifford-chart-contraction/source/engine/source/LICENSE", + "git_blob": "261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64", + "sha256": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4" + }, + { + "local": "predecessor/source/engine/source/PR5698-NOTICE.md", + "source_path": "research/clifford-chart-contraction/source/engine/source/PR5698-NOTICE.md", + "git_blob": "56712e3195faf8c83319100065183b8b2488809d", + "sha256": "1f55b3e4bb80a60611b1fca0622da5a99fe7877446f03d0edd1dc8f3a5abadd2" + }, + { + "local": "predecessor/source/engine/source/PR5704-NOTICE.md", + "source_path": "research/clifford-chart-contraction/source/engine/source/PR5704-NOTICE.md", + "git_blob": "b96b400e5ca04b3a9003a8b2c70a2461972d39d7", + "sha256": "a77adc71861e3b9c73c703c5db5b671f61a1101d85d14cca08547e21d6d8dce4" + }, + { + "local": "predecessor/source/engine/source/PR5704-quadratic.py", + "source_path": "research/clifford-chart-contraction/source/engine/source/PR5704-quadratic.py", + "git_blob": "ce3c86ec07fd5767741e02ff0c88b93ba9164fb4", + "sha256": "d406584aed1479b75c387bc964b9e797b2f4f75e5f8c6bbea00df07f7d590a91" + }, + { + "local": "predecessor/source/row/bell_reads.py", + "source_path": "research/clifford-chart-contraction/source/row/bell_reads.py", + "git_blob": "32b2ed2a94dc77d04709fedb420bf0ffd6d74f73", + "sha256": "44942462cd7778d23042bf827fb313d0e7acf99aa5b9793e411503e83d3421b7" + }, + { + "local": "predecessor/source/row/compile_row.py", + "source_path": "research/clifford-chart-contraction/source/row/compile_row.py", + "git_blob": "daf35d6a26993ed00cfc25a9e16c9136fba2a275", + "sha256": "4e6420f6dcccfd76d64a3b14d94dbdd4803bfd780c921a225d8f29b5d9f0565b" + }, + { + "local": "predecessor/source/row/raw_row.py", + "source_path": "research/clifford-chart-contraction/source/row/raw_row.py", + "git_blob": "1787feb76acf78e3fd314bf3e0ecbe6cb2432316", + "sha256": "40fb7b900409d1908e01683830f44670417338412753ba77a37ea203f94aafa7" + } + ], + "upstream_origins": "Original #5704, #5727 and #7800 pins and retained notices are recorded in predecessor/RETAINED.json and predecessor/source/engine/INPUTS.json." +} diff --git a/research/clifford-compact-pauli-fibre/SOURCES.json b/research/clifford-compact-pauli-fibre/SOURCES.json new file mode 100644 index 0000000000..d8b8f606b7 --- /dev/null +++ b/research/clifford-compact-pauli-fibre/SOURCES.json @@ -0,0 +1,62 @@ +{ + "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": 5704, + "head": "daa4d9dbd102d2a3677afc5614c56466bd2cf3a2", + "author": "aliromman", + "title": "Make complete Clifford replay 5.17x faster with exact quadratic states", + "url": "https://github.com/CrocSwap/integer-mult-bounds/pull/5704" + }, + { + "pr": 5727, + "head": "8b74ecd0eea26d95b400e56435d35fbd261dc49b", + "author": "aliromman", + "title": "Add exact phase-sensitive Clifford contractions and attained finite-span errors", + "url": "https://github.com/CrocSwap/integer-mult-bounds/pull/5727" + }, + { + "pr": 7799, + "head": "7f08a74037788311cc6b7da27297b25f1b188e45", + "author": "apoursh", + "title": "Prove the sharp Gaussian-dyadic four-qubit Clifford tensor width is 13 (no κ)", + "url": "https://github.com/CrocSwap/integer-mult-bounds/pull/7799" + }, + { + "pr": 7800, + "head": "fdc90699f4a64139ed6d84cdbf9a606ff0ccd32e", + "author": "apoursh", + "title": "Compile the width-13 Clifford decoder into 4,265 Bell reads and certify its dense input cost (no κ)", + "url": "https://github.com/CrocSwap/integer-mult-bounds/pull/7800" + }, + { + "pr": 7801, + "head": "9d15f66abc9ccf760ca5f7ea442adeb87b8f7115", + "author": "apoursh", + "title": "Evaluate the 4,265-term Clifford identity row on a compact input with one Gauss sum", + "url": "https://github.com/CrocSwap/integer-mult-bounds/pull/7801" + }, + { + "pr": 7809, + "head": "7efc2c67b32e305d20e484dc3afa9229ab119269", + "author": "apoursh", + "title": "Prove sharp 52- and 51-pass bounds for width-13 Clifford decoding", + "url": "https://github.com/CrocSwap/integer-mult-bounds/pull/7809" + } + ] +} diff --git a/research/clifford-compact-pauli-fibre/TASK.json b/research/clifford-compact-pauli-fibre/TASK.json new file mode 100644 index 0000000000..96f65e47c3 --- /dev/null +++ b/research/clifford-compact-pauli-fibre/TASK.json @@ -0,0 +1,93 @@ +{ + "schema_version": 1, + "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, + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "selection_nonce": "efe8d624ffd6ee6938d28a575a09c32e", + "scope_key": "cdee6027333168fe48af", + "scope_status": "changed", + "actual_scope": "Evaluate all 256 Pauli outputs of the four-qubit width-13 identity symplectic fibre on a single affine-quadratic observation, and determine the input costs on a named phase-mask interface.", + "scope_change_reason": "The one-row contraction in #7801 left open whether a whole fibre can share its reduction and what access is required to produce all its outputs.", + "bottleneck_link": "Supplies a priced concrete output block on the phase-mask producer and establishes the corresponding dense-probe cost.", + "stop_rule": "Prove common contraction bounds, test all phases and targets against independent literal matrix actions, and give attainable access counts and matching lower bounds under the stated interfaces.", + "outcome": "completed", + "evidence": "The package README, proof and registered verification commands describe the exact scope and controls.", + "author": "apoursh", + "ai_assistance": "Substantial OpenAI Codex assistance with mathematical derivation, verification and review.", + "open_questions": [ + { + "question": "Can the same preprocessing serve distinct symplectic fibres of a compact observation?", + "why_it_matters": "A decoder needs more than one fibre to handle an arbitrary target.", + "first_step": "Transport the shift equations for a second specified symplectic element and compare both kernels and affine phases.", + "blocked_by": "The current accounting covers all Pauli translations of one fibre." + } + ], + "claim": "https://github.com/CrocSwap/integer-mult-bounds/discussions/1166#discussioncomment-19756125", + "overlap": "Read #1163, recent #1166 handoffs, active #7111 work and recent PRs; checked relevant all-state PR searches. The local overlap cache and sparse inventory have limited coverage. Checked #7804 and the #7786 continuations for a distinct boundary.", + "upstream_refresh": { + "date_utc": "2026-11-19", + "canonical_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "selected_orientation": "PASS_RESEARCH_BASELINE_BINDINGS_ONLY", + "selected": "The selected result is #7000. The revision-8 catalogue refers to the earlier #5599.", + "before_submission": "Fetched canonical main again and checked the current work against the live PR queue." + } +} diff --git a/research/clifford-compact-pauli-fibre/VERIFY.json b/research/clifford-compact-pauli-fibre/VERIFY.json new file mode 100644 index 0000000000..f280facc40 --- /dev/null +++ b/research/clifford-compact-pauli-fibre/VERIFY.json @@ -0,0 +1,63 @@ +{ + "schema_version": 1, + "status": "ready", + "python": "3.12", + "requirements": [], + "inputs": [], + "commands": [ + { + "argv": [ + "{python}", + "-E", + "-s", + "-W", + "error", + "-B", + "{package}/verify.py" + ], + "timeout_seconds": 180, + "checks": "All nine singleton support ranks, off-image charts, Pauli and nonidentity-fibre columns, dense raw weights and shared-basis reduction" + }, + { + "argv": [ + "{python}", + "-E", + "-s", + "-O", + "-W", + "error", + "-B", + "{package}/verify.py" + ], + "timeout_seconds": 180, + "checks": "All nine singleton support ranks, off-image charts, Pauli and nonidentity-fibre columns, dense raw weights and shared-basis reduction under optimized Python" + }, + { + "argv": [ + "{python}", + "-E", + "-s", + "-W", + "error", + "-B", + "{package}/check_phase_masks.py" + ], + "timeout_seconds": 180, + "checks": "Literal 16-by-16 corrected singleton matrices on 11 phase masks and a 104-neighbor input-access lower-bound witness" + }, + { + "argv": [ + "{python}", + "-E", + "-s", + "-O", + "-W", + "error", + "-B", + "{package}/check_phase_masks.py" + ], + "timeout_seconds": 180, + "checks": "Literal 16-by-16 corrected singleton matrices on 11 phase masks and a 104-neighbor input-access lower-bound witness under optimized Python" + } + ] +} diff --git a/research/clifford-compact-pauli-fibre/check_phase_masks.py b/research/clifford-compact-pauli-fibre/check_phase_masks.py new file mode 100644 index 0000000000..8f5932773a --- /dev/null +++ b/research/clifford-compact-pauli-fibre/check_phase_masks.py @@ -0,0 +1,95 @@ +"""Independent literal nibble contraction for the phase-mask producer. + +On each of the 4,265 Bell reads, form its 16 x 16 singleton matrix using +ordinary Weyl matrix actions. Trace against every output Weyl explicitly. +Prepared by apoursh with substantial OpenAI Codex assistance. Apache-2.0. +""" +from fractions import Fraction +from functools import cache +from pathlib import Path +from random import Random +import sys + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from fibre import fibre +from phase_mask import Tape, decode, numerators +from contract import Q, iter_reads, label_sum, RAW_DENOMINATOR + + +def sign(number): + return -1 if number.bit_count() & 1 else 1 + + +@cache +def literal_pair(a, b): + return sum(sign((r & s) ^ (a & r) ^ (b & s)) for r in range(16) for s in range(16)) + + +def producer(mask): + gates = [('C', 1 << j, 1) for j in range(104)] + rows = [1 << j for j in range(104)] + for first in range(4, 52, 8): + for j in range(first, first + 4): + rows[j] |= 1 << (j + 52) + rows[j + 52] |= 1 << j + gates.append(('D', rows, [1+2*((mask >> j) & 1) for j in range(104)])) + return Q.signature(104, gates) + + +def literal(mask): + # The 52-bit row and column addresses both end at their singleton nibble. + rowmask, colmask = mask >> 52, mask & ((1 << 52)-1) + matrix = [[0]*16 for _ in range(16)] + for read in iter_reads(): + if read.correction_i: + raise ValueError("Unexpected identity-fibre transport phase") + weight = read.numerator + for j, (out, inp) in enumerate(zip(read.output_labels, read.input_labels, strict=True)): + pos = 4*(11-2*j) + row_second, row_first = (rowmask >> pos) & 15, (rowmask >> (pos+4)) & 15 + col_second, col_first = (colmask >> pos) & 15, (colmask >> (pos+4)) & 15 + weight *= sign((row_first & (out >> 4)) ^ (col_first & (inp >> 4))) + weight *= literal_pair((out & 15) ^ row_first ^ row_second, + (inp & 15) ^ col_first ^ col_second) + left, right = label_sum(read.output_labels), label_sum(read.input_labels) + left_scale = [sign(((left ^ rowmask) & 15) & r) for r in range(16)] + right_scale = [sign(((right ^ colmask) & 15) & c) for c in range(16)] + for r, a in enumerate(left_scale): + dest = matrix[r ^ (left >> 4)] + for c, b in enumerate(right_scale): + dest[c ^ (right >> 4)] += weight*a*b + denominator = RAW_DENOMINATOR << 52 + return [(Fraction(sum(sign(z & c)*matrix[c ^ x][c] for c in range(16)), denominator), 0) + for x in range(16) for z in range(16)] + + +def main(): + rng = Random(104) + witness = 0xe90447f9b4d1553cfdce84821d + masks = [witness, 0, 1, 1 << 52, *[rng.getrandbits(104) for _ in range(7)]] + outputs = set() + for mask in masks: + reference = literal(mask) + actual, _ = fibre(producer(mask)) + if list(actual) != reference: + raise ValueError("Literal Bell contractions disagree with shared-fibre calculation") + tape = Tape(mask) + streamed = decode(tape) + if [(a, 0) for a in streamed] != reference or (tape.head,tape.reads,tape.moves) != (0,104,206): + raise ValueError("Tape answers, access or head restoration") + outputs.add(tuple(reference)) + if mask == 0 and reference[0] != (Fraction(1, 1 << 29), 0): + raise ValueError("Incorrect reference normalization") + expect = numerators(witness) + for j in range(104): + if numerators(witness ^ (1 << j)) == expect: + raise ValueError("Input symbol is invisible on the sharp probe witness") + print("PASS all 104 single-bit flips change the output on the common witness; 206 moves with head restoration") + if len(outputs) < 4: + raise ValueError("Insufficient distinct phase-mask controls") + print(f"PASS literal 16-by-16 singleton matrices on {len(masks)} masks, {256*len(masks)} exact outputs") + + +if __name__ == "__main__": + main() diff --git a/research/clifford-compact-pauli-fibre/fibre.py b/research/clifford-compact-pauli-fibre/fibre.py new file mode 100644 index 0000000000..414fbb37a7 --- /dev/null +++ b/research/clifford-compact-pauli-fibre/fibre.py @@ -0,0 +1,177 @@ +"""All 256 Pauli outputs of the width-13 identity symplectic fibre, exactly.""" +import argparse +from fractions import Fraction +from functools import cache +import json +from pathlib import Path +import sys + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE / "predecessor")) +from contract import BinaryMap, Q, Spectrum, apply, iter_reads, label_sum, pack, parity, polar, split_address, transpose + +MASK48 = (1 << 48) - 1 + + +def separate(address): + rows, cols = map(split_address, divmod(address, 1 << 52)) + pairs = rows[:-1] + cols[:-1] + shifts = pack([a ^ b for a, b in zip(pairs[::2], pairs[1::2], strict=True)]) + singleton = rows[-1] | (cols[-1] << 4) + return (shifts << 8) | singleton, pack(pairs[1::2]) + + +@cache +def plan(): + records = [] + for read in iter_reads(): + labels = read.output_labels + read.input_labels + fixed = pack([t >> 4 for t in labels]) + wave = pack([t & 15 for t in labels]) + out, inp = label_sum(read.output_labels), label_sum(read.input_labels) + move = (out >> 4) | ((inp >> 4) << 4) + sign = (out & 15) | ((inp & 15) << 4) + Q.need(read.correction_i == 0 and out >> 4 == inp >> 4, "Identity-fibre conventions") + records.append(((wave << 56) | (fixed << 8), move, sign, read.numerator)) + return tuple(records) + + +class Section(BinaryMap): + """Linear reduction, including a canonical remainder for inconsistent right sides.""" + def split(self, word): + witness = 0 + for bit, (pivot, preimage) in self.descending: + if word >> bit & 1: + word ^= pivot + witness ^= preimage + return word, witness + + def __init__(self, columns): + super().__init__(columns) + self.descending = sorted(self.pivots.items(), reverse=True) + + +class PartialWalsh: + """Return affine support equations and a quadratic phase on all Bell/singleton bits.""" + def __init__(self, state): + n, offset, cols, terms, real, imag, denominator = state + Q.need(n == 104, "This decoder consumes 104-bit charts") + self.offset, self.free_offset = separate(offset) + parts = [separate(c) for c in cols] + self.fixed = Section(f for f, _ in parts) + self.free = [v for _, v in parts] + self.phase = dict(terms) + kernel = self.fixed.kernel + restricted = Q.substitute(self.phase, [transpose(kernel, 1 << j) << 1 for j in range(len(cols))]) + restricted.pop(0, None) + spectrum = Spectrum(len(kernel), restricted) + self.spectrum_map = Section(polar(len(kernel), restricted)) + self.restricted = restricted + self.anchor = spectrum.origin + self.scalar = Q.multiply((real, imag), spectrum.value) + self.denominator = denominator + 12 # numerator / 4096 after the final trace + self.free_kernel = [apply(self.free, k) for k in kernel] + polar_columns = polar(len(cols), self.phase) + self.twist_columns = [transpose(kernel, col) for col in polar_columns] + + def slice(self, word): + fixed, wave = word & ((1 << 56)-1), word >> 56 + rem, t = self.fixed.split(fixed ^ self.offset) + free = self.free_offset ^ apply(self.free, t) + frequency = apply(self.twist_columns, t) ^ transpose(self.free_kernel, wave) + residual, u = self.spectrum_map.split(frequency ^ self.anchor) + syndrome = rem | (residual << 56) + phase = (Q.value(self.phase, t) + 2*parity(wave & free) + - Q.value(self.restricted, u) + 2*parity(self.anchor & u)) % 4 + return syndrome, phase + + +def walsh(values): + """Unnormalized binary Walsh transform in place, on real Gaussian components.""" + stride = 1 + while stride < len(values): + for start in range(0, len(values), 2*stride): + for i in range(start, start + stride): + a, b = values[i], values[i + stride] + values[i], values[i + stride] = a + b, a - b + stride *= 2 + + +class SingletonBasis: + def __init__(self, transform): + self.transform = transform + zero_syndrome, zero_phase = transform.slice(0) + singletons = [transform.slice(1 << i) for i in range(104)] + self.affine = Section(s ^ zero_syndrome for s, _ in singletons[:8]) + self.support = self.affine.kernel + self.cosets = Section(self.support) + # The extension of the phase off its support is a quadratic polynomial. + # Its polar columns restricted to the eight singleton directions identify + # each read's modulating sign without a separate phase fit at each output. + self.twists = [] + for h in self.support: + twist = 0 + slope = (transform.slice(h)[1] - zero_phase) % 4 + for i, (_, base) in enumerate(singletons): + delta = (transform.slice((1 << i) ^ h)[1] - base - slope) % 4 + Q.need(delta in (0, 2), "Non-quadratic phase derivative") + twist |= (delta // 2) << i + self.twists.append(twist) + self.points = [apply(self.support, u) for u in range(1 << len(self.support))] + self.chirp = [(transform.slice(v)[1] - zero_phase) % 4 for v in self.points] + + def locate(self, labels, move, sign): + syndrome, _ = self.transform.slice(labels) + remainder, witness = self.affine.split(syndrome) + if remainder: + return None + representative, _ = self.cosets.split(witness ^ move) + raw_point = representative ^ move + word = labels | raw_point + frequency = transpose(self.twists, word) ^ transpose(self.support, sign) + phase = (self.transform.slice(word)[1] + 2*parity(raw_point & sign)) % 4 + return representative, frequency, phase + + +def fibre(state): + """Return the linear decoder as pairs of Fractions at index 16*x+z.""" + transform = PartialWalsh(state) + basis = SingletonBasis(transform) + size = len(basis.points) + bins = {s: ([0]*size, [0]*size) for s in range(256) if basis.cosets.split(s)[0] == s} + supported = 0 + for labels, move, sign, weight in plan(): + hit = basis.locate(labels, move, sign) + if hit is not None: + s, freq, phase = hit + bins[s][phase % 2][freq] += weight if phase < 2 else -weight + supported += 1 + matrices = [[0]*256, [0]*256] + for s, (real, imag) in bins.items(): + walsh(real) + walsh(imag) + for i, v in enumerate(basis.points): + a, b = Q.multiply_i((real[i], imag[i]), basis.chirp[i]) + matrices[0][s ^ v], matrices[1][s ^ v] = a, b + outputs = [] + for x in range(16): + real, imag = [[m[(b ^ x) | (b << 4)] for b in range(16)] for m in matrices] + walsh(real) + walsh(imag) + for item in zip(real, imag, strict=True): + value = Q.multiply(transform.scalar, item) + outputs.append(tuple(Fraction(a, 1 << transform.denominator) for a in value)) + stats = dict(gauss=1, gauss_variables=len(transform.fixed.kernel), + singleton_dimension=len(basis.support), supported_terms=supported, + accumulation_updates=supported, walsh_adds=256*(len(basis.support)+4)) + return outputs, stats + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("input", type=Path, help="JSON with a #5704 circuit and optional initial address") + data = parser.parse_args().input.read_bytes() + request = json.loads(data) + state = Q.signature(104, request["circuit"], initial=request.get("initial", 0)) + values, stats = fibre(state) + print(json.dumps({"input_bytes":len(data), "outputs":[[str(a),str(b)] for a,b in values], **stats})) diff --git a/research/clifford-compact-pauli-fibre/phase_mask.py b/research/clifford-compact-pauli-fibre/phase_mask.py new file mode 100644 index 0000000000..755b3ca6ff --- /dev/null +++ b/research/clifford-compact-pauli-fibre/phase_mask.py @@ -0,0 +1,64 @@ +"""Single-scan full-fibre decoder for the coupled phase-mask family of #7801.""" +from fractions import Fraction +from pathlib import Path +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from fibre import MASK48, pack, parity, plan, split_address, walsh + + +def read_mask(tape): + """Consume exactly 104 least-significant-first bits, then restore the read head.""" + word = 0 + for j in range(104): + bit = tape.read() + if bit not in (0,1): + raise ValueError("Expected one binary input symbol") + word |= bit << j + if j < 103: + tape.move(1) + for _ in range(103): + tape.move(-1) + return word + + +def numerators(mask): + """Return all 256 exact numerators, each with denominator 2^36.""" + row, col = map(split_address, divmod(mask, 1 << 52)) + firsts = pack(row[:-1:2] + col[:-1:2]) + alpha, beta = (pack([s ^ t for s,t in zip(side[:-1:2], side[1:-1:2], strict=True)]) + for side in (row, col)) + bins = [[0]*16 for _ in range(16)] + for labels, move, sign, weight in plan(): + shifts = (labels >> 8) & MASK48 + wave = labels >> 56 + out, inp = wave & ((1 << 24)-1), wave >> 24 + zout, zin = sign & 15, sign >> 4 + k = zout ^ row[-1] + z = k ^ zin ^ col[-1] + neg = parity((firsts & shifts) ^ ((out ^ alpha) & (inp ^ beta)) ^ (z & move & 15)) + bins[z][k] += -weight if neg else weight + for values in bins: + walsh(values) + return tuple(bins[z][x] for x in range(16) for z in range(16)) + + +def decode(tape): + return [Fraction(v, 1 << 36) for v in numerators(read_mask(tape))] + + +class Tape: + """Finite read-only binary input followed by the end position, with a move counter.""" + def __init__(self, word): + self.bits = tuple((word >> j) & 1 for j in range(104)) + self.head = self.reads = self.moves = 0 + + def read(self): + self.reads += 1 + return self.bits[self.head] + + def move(self, delta): + self.head += delta + self.moves += abs(delta) + if not 0 <= self.head <= 104: + raise ValueError("Moved outside the input track") diff --git a/research/clifford-compact-pauli-fibre/predecessor/RETAINED.json b/research/clifford-compact-pauli-fibre/predecessor/RETAINED.json new file mode 100644 index 0000000000..520317e651 --- /dev/null +++ b/research/clifford-compact-pauli-fibre/predecessor/RETAINED.json @@ -0,0 +1,74 @@ +[ + { + "local": "source/engine/INPUTS.json", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/clifford-exact-contractions/INPUTS.json", + "sha256": "c62bd55fd36c136ba2ec34f6d91ed481497932fadc7134d0b7e5c10009fd588c", + "git_blob": "f9d4fd920651b002370ffb5084dbef2abaa5ed44" + }, + { + "local": "source/engine/contractions.py", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/clifford-exact-contractions/contractions.py", + "sha256": "a2fc065d6f293ddcffe5b6eec7fff0fdf57c8e3d4c6be355bd92e87d3f1865ef", + "git_blob": "76c807deceea0b1a6b64b50735253959b07c144d" + }, + { + "local": "source/engine/source/LICENSE", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/clifford-exact-contractions/source/LICENSE", + "sha256": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4", + "git_blob": "261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64" + }, + { + "local": "source/engine/source/PR5698-NOTICE.md", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/clifford-exact-contractions/source/PR5698-NOTICE.md", + "sha256": "1f55b3e4bb80a60611b1fca0622da5a99fe7877446f03d0edd1dc8f3a5abadd2", + "git_blob": "56712e3195faf8c83319100065183b8b2488809d" + }, + { + "local": "source/engine/source/PR5704-NOTICE.md", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/clifford-exact-contractions/source/PR5704-NOTICE.md", + "sha256": "a77adc71861e3b9c73c703c5db5b671f61a1101d85d14cca08547e21d6d8dce4", + "git_blob": "b96b400e5ca04b3a9003a8b2c70a2461972d39d7" + }, + { + "local": "source/engine/source/PR5704-quadratic.py", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/clifford-exact-contractions/source/PR5704-quadratic.py", + "sha256": "d406584aed1479b75c387bc964b9e797b2f4f75e5f8c6bbea00df07f7d590a91", + "git_blob": "ce3c86ec07fd5767741e02ff0c88b93ba9164fb4" + }, + { + "local": "source/row/bell_reads.py", + "repository": "apoursh/integer-mult-bounds", + "commit": "fdc90699f4a64139ed6d84cdbf9a606ff0ccd32e", + "path": "research/clifford-sparse-row/bell_reads.py", + "sha256": "44942462cd7778d23042bf827fb313d0e7acf99aa5b9793e411503e83d3421b7", + "git_blob": "32b2ed2a94dc77d04709fedb420bf0ffd6d74f73" + }, + { + "local": "source/row/compile_row.py", + "repository": "apoursh/integer-mult-bounds", + "commit": "fdc90699f4a64139ed6d84cdbf9a606ff0ccd32e", + "path": "research/clifford-sparse-row/compile_row.py", + "sha256": "4e6420f6dcccfd76d64a3b14d94dbdd4803bfd780c921a225d8f29b5d9f0565b", + "git_blob": "daf35d6a26993ed00cfc25a9e16c9136fba2a275" + }, + { + "local": "source/row/raw_row.py", + "repository": "apoursh/integer-mult-bounds", + "commit": "fdc90699f4a64139ed6d84cdbf9a606ff0ccd32e", + "path": "research/clifford-sparse-row/raw_row.py", + "sha256": "40fb7b900409d1908e01683830f44670417338412753ba77a37ea203f94aafa7", + "git_blob": "1787feb76acf78e3fd314bf3e0ecbe6cb2432316" + } +] diff --git a/research/clifford-compact-pauli-fibre/predecessor/contract.py b/research/clifford-compact-pauli-fibre/predecessor/contract.py new file mode 100644 index 0000000000..11df2cef14 --- /dev/null +++ b/research/clifford-compact-pauli-fibre/predecessor/contract.py @@ -0,0 +1,195 @@ +"""Contract #7800's identity row with a #5704 affine-quadratic observation. + +apoursh with substantial OpenAI Codex assistance. Apache-2.0. +""" +from collections import Counter, defaultdict +from fractions import Fraction +from hashlib import sha256 +import json +from functools import cache +from pathlib import Path +import sys + +HERE = Path(__file__).resolve().parent +for record in json.loads((HERE / "RETAINED.json").read_text()): + if sha256((HERE / record["local"]).read_bytes()).hexdigest() != record["sha256"]: + raise ValueError("Changed retained source: " + record["local"]) +sys.path[:0] = [str(HERE / "source" / "engine"), str(HERE / "source" / "row")] +from contractions import Q, gauss, solution +from raw_row import RAW_DENOMINATOR, iter_reads, label_sum, pack, split_address + + +def parity(bits): + return bits.bit_count() & 1 + + +def transpose(columns, vector): + return sum(parity(column & vector) << j for j, column in enumerate(columns)) + + +def apply(columns, vector): + out = 0 + for j in Q.bits(vector): + out ^= columns[j] + return out + + +class BinaryMap: + """One elimination: a kernel basis and a right inverse on the image.""" + def __init__(self, columns): + self.pivots = {} + self.kernel = [] + for j, column in enumerate(columns): + word, witness = column, 1 << j + while word: + bit = word.bit_length() - 1 + if bit not in self.pivots: + self.pivots[bit] = (word, witness) + break + pivot, preimage = self.pivots[bit] + word ^= pivot + witness ^= preimage + if not word: + self.kernel.append(witness) + + def preimage(self, word): + witness = 0 + while word: + pivot = self.pivots.get(word.bit_length() - 1) + if pivot is None: + return None + word ^= pivot[0] + witness ^= pivot[1] + return witness + + +def polar(dimension, phase): + columns = [0] * dimension + for mask, coefficient in phase.items(): + if mask.bit_count() == 2: + a, b = Q.bits(mask) + columns[a] ^= 1 << b + columns[b] ^= 1 << a + elif mask and coefficient & 1: + columns[mask.bit_length() - 1] ^= mask + return columns + + +class Spectrum: + """Return a Fourier coefficient as a rotation of one exact Gauss sum.""" + def __init__(self, dimension, phase): + self.phase = phase + self.map = BinaryMap(polar(dimension, phase)) + equations = [] + for r in self.map.kernel: + q = Q.value(phase, r) + Q.need(q % 2 == 0, "An element of the radical has even phase") + equations.append((r, q // 2)) + _, forms = solution(dimension, equations) + self.origin = sum((form & 1) << j for j, form in enumerate(forms)) + twisted = dict(phase) + Q.affine(twisted, self.origin << 1, 2) + self.value = gauss(dimension, twisted) + Q.need(self.value != (0, 0), "Nonzero Fourier anchor") + + def rotation(self, frequency): + u = self.map.preimage(self.origin ^ frequency) + if u is None: + return None + return (2 * parity(self.origin & u) - Q.value(self.phase, u)) % 4 + + +def address_parts(address): + """Linear map from raw 104 bits to (52 shift bits, 52 free bits).""" + row, col = divmod(address, 1 << 52) + r, c = split_address(row), split_address(col) + pairs = r[:-1] + c[:-1] + shifts = [a ^ b for a, b in zip(pairs[::2], pairs[1::2], strict=True)] + return pack([*shifts, r[-1] ^ c[-1]]), pack([*pairs[1::2], r[-1]]) + + +@cache +def read_plan(): + plan = defaultdict(list) + for read in iter_reads(): + labels = read.output_labels + read.input_labels + singleton = label_sum(labels) + Q.need(singleton < 16 and read.correction_i == 0, "Identity trace convention") + shift = pack([t >> 4 for t in labels]) + frequency = pack([*(t & 15 for t in labels), singleton]) + plan[shift].append((frequency, read.numerator)) + return {s: tuple(terms) for s, terms in sorted(plan.items())} + + +def contract(state, plan=None, denominator=RAW_DENOMINATOR): + """Linear (unconjugated) observation contraction on a signature() output. + + A plan maps a packed shift to (frequency, signed integer weight) pairs. + Each weight has the stated common denominator. + """ + n, offset, cols, terms, real, imag, exponent = state + Q.need(n == 104, "This row consumes a 104-bit state") + if plan is None: + plan = read_plan() + shift0, point0 = address_parts(offset) + parts = [address_parts(c) for c in cols] + support = BinaryMap(s for s, _ in parts) + points = [v for _, v in parts] + intersections = [] + for shift, table in plan.items(): + witness = support.preimage(shift ^ shift0) + if witness is not None: + intersections.append((witness, table)) + counts = Counter(buckets=len(intersections), dimension=len(support.kernel), gauss=0) + if not intersections: + return (Fraction(0), Fraction(0)), dict(counts) + + kernel = support.kernel + phase = dict(terms) + restricted = Q.substitute(phase, [transpose(kernel, 1 << j) << 1 for j in range(len(cols))]) + restricted.pop(0, None) + spectrum = Spectrum(len(kernel), restricted) + counts["gauss"] = 1 + polar_cols = polar(len(cols), phase) + point_directions = [apply(points, k) for k in kernel] + total = [0, 0] + for witness, table in intersections: + point = point0 ^ apply(points, witness) + twist = transpose(kernel, apply(polar_cols, witness)) + constant = Q.value(phase, witness) + for frequency, weight in table: + counts["terms"] += 1 + exponent_i = spectrum.rotation(twist ^ transpose(point_directions, frequency)) + if exponent_i is None: + continue + counts["supported"] += 1 + angle = (constant + 2 * parity(point & frequency) + exponent_i) % 4 + total[angle % 2] += weight if angle < 2 else -weight + numerator = Q.multiply((real, imag), Q.multiply(spectrum.value, total)) + return tuple(Fraction(x, denominator << exponent) for x in numerator), dict(counts) + + +def one_cell(state, shifts, masks, signature, numerator): + """Contract the actual weight numerator/4096 on a single Walsh cell.""" + frequencies = [(apply(masks, w), numerator * (-1)**parity(w & signature)) + for w in range(1 << len(masks))] + return contract(state, {pack(shifts): frequencies}, RAW_DENOMINATOR << len(masks)) + + +def main(): + """Evaluate a literal #5704 circuit on one computational basis input.""" + import argparse + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("input", type=Path, help="JSON with circuit and optional initial address") + args = parser.parse_args() + data = args.input.read_bytes() + request = json.loads(data) + counters = {} + state = Q.signature(104, request["circuit"], initial=request.get("initial", 0), counters=counters) + result, execution = contract(state) + print(json.dumps({"real": str(result[0]), "imag": str(result[1]), "input_bytes": len(data), + "producer": counters, "consumer": execution}, sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/research/clifford-compact-pauli-fibre/predecessor/source/engine/INPUTS.json b/research/clifford-compact-pauli-fibre/predecessor/source/engine/INPUTS.json new file mode 100644 index 0000000000..f9d4fd9206 --- /dev/null +++ b/research/clifford-compact-pauli-fibre/predecessor/source/engine/INPUTS.json @@ -0,0 +1,72 @@ +[ + { + "local": "PR5704-quadratic.py", + "origin": "research/exact-clifford-quadratic-replay/quadratic.py", + "head": "daa4d9dbd102d2a3677afc5614c56466bd2cf3a2", + "sha256": "d406584aed1479b75c387bc964b9e797b2f4f75e5f8c6bbea00df07f7d590a91", + "git_blob": "ce3c86ec07fd5767741e02ff0c88b93ba9164fb4" + }, + { + "local": "PR5704-PROOF.md", + "origin": "research/exact-clifford-quadratic-replay/PROOF.md", + "head": "daa4d9dbd102d2a3677afc5614c56466bd2cf3a2", + "sha256": "e5039414a02e36cdeab82fb9803fc4de0c3e0f3997e8812ef9d227e5d417ec91", + "git_blob": "559f9f4b207783c6eb908450b63eed3431594c22" + }, + { + "local": "PR5704-NOTICE.md", + "origin": "research/exact-clifford-quadratic-replay/NOTICE.md", + "head": "daa4d9dbd102d2a3677afc5614c56466bd2cf3a2", + "sha256": "a77adc71861e3b9c73c703c5db5b671f61a1101d85d14cca08547e21d6d8dce4", + "git_blob": "b96b400e5ca04b3a9003a8b2c70a2461972d39d7" + }, + { + "local": "PR5526-PROOF.md", + "origin": "research/clifford-pointwise-faithfulness/PROOF.md", + "head": "df0137efd35e11b4445734bf612bdd4c7ebc330c", + "sha256": "45483e4b5f604a5e70602c5caaa4394d4a0d0d1a6d0b6e8a93b836d50b23f764", + "git_blob": "465009d9d1b6947e80e6f1e868022f47ddab1f3c" + }, + { + "local": "clifford_exact.py", + "origin": "research/exact-clifford-quadratic-replay/source/source/clifford_exact.py", + "head": "daa4d9dbd102d2a3677afc5614c56466bd2cf3a2", + "sha256": "2982ead07721e83358dc67c6f49c2b4c16a236a6bebdfd72f58221be1f5d0962", + "git_blob": "166841a037f069249f6f7f6dedb89248812f59e2" + }, + { + "local": "prune_native.py", + "origin": "research/exact-clifford-quadratic-replay/source/source/prune_native.py", + "head": "daa4d9dbd102d2a3677afc5614c56466bd2cf3a2", + "sha256": "f2b37c183a10922eabc8e0436b426a08866430e96bd0adc7e178951c7fbb5257", + "git_blob": "8c3e11b2408fa96eefa3ebe7952d1b11b90b772b" + }, + { + "local": "PHYSICAL.json", + "origin": "research/exact-clifford-quadratic-replay/source/PHYSICAL.json", + "head": "daa4d9dbd102d2a3677afc5614c56466bd2cf3a2", + "sha256": "f78ba861d23ff33f2c9ffeca8c3ab6a7f1ec906f38adff5d325c13efb187c7c3", + "git_blob": "375b30b8c7aa16df521deaec04f16d1af8532abd" + }, + { + "local": "CONSTRUCTION.json.gz", + "origin": "research/exact-clifford-quadratic-replay/source/CONSTRUCTION.json.gz", + "head": "daa4d9dbd102d2a3677afc5614c56466bd2cf3a2", + "sha256": "00d13d7774adf087f93bc58d4c5860e296f8408c0ee25a4db254a056f8da7dec", + "git_blob": "31c6d481dd8b32e30d3c137bd2561a59a9d9fcc0" + }, + { + "local": "PR5698-NOTICE.md", + "origin": "research/exact-clifford-quadratic-replay/source/NOTICE.md", + "head": "daa4d9dbd102d2a3677afc5614c56466bd2cf3a2", + "sha256": "1f55b3e4bb80a60611b1fca0622da5a99fe7877446f03d0edd1dc8f3a5abadd2", + "git_blob": "56712e3195faf8c83319100065183b8b2488809d" + }, + { + "local": "LICENSE", + "origin": "research/exact-clifford-quadratic-replay/source/source/LICENSE", + "head": "daa4d9dbd102d2a3677afc5614c56466bd2cf3a2", + "sha256": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4", + "git_blob": "261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64" + } +] diff --git a/research/clifford-compact-pauli-fibre/predecessor/source/engine/contractions.py b/research/clifford-compact-pauli-fibre/predecessor/source/engine/contractions.py new file mode 100644 index 0000000000..76c807dece --- /dev/null +++ b/research/clifford-compact-pauli-fibre/predecessor/source/engine/contractions.py @@ -0,0 +1,236 @@ +"""Exact Clifford contractions with absolute phase. Apache-2.0. + +Classical affine-support and quadratic Gauss-sum methods. Prepared by +Ali Romman with substantial OpenAI Codex assistance. +""" +from fractions import Fraction +from hashlib import sha256 +import importlib.util +import json +from pathlib import Path +import sys + +ROOT = Path(__file__).resolve().parent + + +def load_source(name, filename): + records = json.loads((ROOT / 'INPUTS.json').read_text()) + record = next(x for x in records if x['local'] == filename) + path = ROOT / 'source' / filename + if sha256(path.read_bytes()).hexdigest() != record['sha256']: + raise ValueError('Changed frozen input: ' + filename) + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + spec.loader.exec_module(module) + return module + + +Q = load_source('contraction_quadratic', 'PR5704-quadratic.py') + + +def add(a, b): + return a[0] + b[0], a[1] + b[1] + + +def conjugate(a): + return a[0], -a[1] + + +def power(a, exponent): + Q.need(type(exponent) is int and exponent >= 0, 'Nonnegative integral exponent') + result = (1, 0) + while exponent: + if exponent & 1: + result = Q.multiply(result, a) + a = Q.multiply(a, a) + exponent >>= 1 + return result + + +def solution(n, equations): + """Return every binary solution as affine coordinate forms, or None.""" + rows = {} + for mask, rhs in equations: + Q.validate_integer(mask, 1 << n, 'Equation variable mask') + Q.validate_integer(rhs, 2, 'Equation right side') + while mask: + pivot = mask.bit_length() - 1 + if pivot not in rows: + rows[pivot] = (mask, rhs) + break + other, value = rows[pivot] + mask ^= other + rhs ^= value + if not mask and rhs: + return None + free = [j for j in range(n) if j not in rows] + forms = [0] * n + for k, j in enumerate(free): + forms[j] = 1 << (k + 1) + for pivot in sorted(rows): + mask, rhs = rows[pivot] + forms[pivot] = rhs + for j in Q.bits(mask ^ (1 << pivot)): + forms[pivot] ^= forms[j] + return len(free), forms + + +def gauss(n, poly): + """Return sum_x i**q(x) as an exact Gaussian integer.""" + Q.need(type(n) is int and n >= 0, 'Nonnegative Gauss dimension') + for mask, coefficient in poly.items(): + Q.validate_integer(mask, 1 << n, 'Phase variable mask') + Q.need(type(coefficient) is int and 0 < coefficient < 4, + 'Canonical nonzero phase coefficient') + Q.need(mask.bit_count() <= 2 and (mask.bit_count() != 2 or coefficient == 2), + 'Only even quadratic terms') + poly = dict(poly) + scalar = (1, 0) + while n: + last = 1 << (n - 1) + a = poly.pop(last, 0) + linear = 0 + for mask in list(poly): + if mask & last: + linear ^= mask ^ last + del poly[mask] + n -= 1 + if a & 1: + scalar = Q.multiply(scalar, (1, 1 if a == 1 else -1)) + Q.affine(poly, linear << 1, -a) + elif linear: + resolved = solution(n, [(linear, a // 2)]) + Q.need(resolved is not None, 'A nonzero linear form takes both values') + n, forms = resolved + poly = Q.substitute(poly, forms) + scalar = (2 * scalar[0], 2 * scalar[1]) + elif a: + return (0, 0) + else: + scalar = (2 * scalar[0], 2 * scalar[1]) + return Q.multiply_i(scalar, poly.get(0, 0)) + + +def inner(left, right): + """Return the exact inner product of two valid engine states. + + Inputs come from signature or choi. Arbitrary serialized states are not + admitted without the source engine's construction contract. + """ + n, offset, cols, terms, a, b, den = left + m, other, cols2, terms2, c, d, den2 = right + Q.need(n == m, 'Equal state dimensions') + r = len(cols) + allcols = cols + cols2 + equations = [(sum(((v >> i) & 1) << j for j, v in enumerate(allcols)), + ((offset ^ other) >> i) & 1) for i in range(n)] + resolved = solution(len(allcols), equations) + if resolved is None: + return Fraction(0), Fraction(0) + dimension, forms = resolved + phase = Q.substitute(dict(terms2), forms[r:]) + for mask, coefficient in Q.substitute(dict(terms), forms[:r]).items(): + Q.term(phase, mask, -coefficient) + total = Q.multiply(Q.multiply((a, -b), (c, d)), gauss(dimension, phase)) + return Fraction(total[0], 1 << (den + den2)), Fraction(total[1], 1 << (den + den2)) + + +def choi(n, circuit): + """Return a normalized Choi state, retaining one common Bell phase.""" + Q.need(type(n) is int and n >= 0, 'Nonnegative circuit width') + preparation = [('C', (1 << j) | (1 << (n + j)), 1) for j in range(n)] + preparation.append(('D', tuple(1 << j if j < n else 0 for j in range(2 * n)), + (1,) * n + (0,) * n)) + expanded = [] + for gate in circuit: + # Validate the original arity and domain before extension. + Q.signature(n, [gate]) + kind = gate[0] + if kind == 'P': + expanded.append(('P', tuple(gate[1]) + tuple(1 << j for j in range(n, 2 * n)))) + elif kind == 'D': + expanded.append(('D', tuple(gate[1]) + (0,) * n, tuple(gate[2]) + (0,) * n)) + else: + expanded.append(gate) + return Q.signature(2 * n, preparation + expanded) + + +def trace(n, circuit): + result = inner(choi(n, []), choi(n, circuit)) + return result[0] * (1 << n), result[1] * (1 << n) + + +def kernel(states): + """Return normalized trace(U_i^* U_j) for valid equal-width circuits.""" + return [[inner(a, b) for b in states] for a in states] + + +def residual_norm(gram, coefficients, width): + """Return ||sum c_i U_i^(tensor width)||_HS^2 / d^width.""" + Q.need(type(width) is int and width > 0, 'Positive tensor width') + size = len(coefficients) + Q.need(len(gram) == size and all(len(row) == size for row in gram), 'Gram dimensions') + result = (Fraction(0), Fraction(0)) + for i, a in enumerate(coefficients): + for j, b in enumerate(coefficients): + result = add(result, Q.multiply(Q.multiply(conjugate(a), b), power(gram[i][j], width))) + Q.need(result[1] == 0 and result[0] >= 0, 'A valid Gram norm is real and nonnegative') + return result[0] + + +def decide(n, circuits, coefficients): + """Apply the credited four-width theorem to one fixed expanded residual.""" + Q.need(len(circuits) == len(coefficients), 'One fixed coefficient per circuit') + for a in coefficients: + Q.need(len(a) == 2 and all(type(x) in (int, Fraction) for x in a), + 'Exact rational real and imaginary coefficients') + gram = kernel([choi(n, c) for c in circuits]) + first = 4 * n + 4 if n else 1 + norms = [residual_norm(gram, coefficients, f) for f in range(first, first + 4)] + return dict(widths=list(range(first, first + 4)), norms=norms, + all_positive_widths_zero=all(x == 0 for x in norms)) + + +def divide(a, b): + scale = b[0] ** 2 + b[1] ** 2 + Q.need(scale != 0, 'Nonzero complex pivot') + value = Q.multiply(a, conjugate(b)) + return Fraction(value[0]) / scale, Fraction(value[1]) / scale + + +def best_approximation(states, target, width): + """Minimize the normalized squared residual in the supplied finite span. + + Coefficients may depend on this width. Dependent columns are permitted. + This operation does not admit a physical readout or new native queries. + """ + Q.need(type(width) is int and width > 0, 'Positive tensor width') + size = len(states) + gram = kernel(states + [target]) + matrix = [[power(gram[i][j], width) for j in range(size)] + + [power(gram[i][size], width)] for i in range(size)] + pivots = [] + for col in range(size): + row = next((r for r in range(len(pivots), size) if matrix[r][col] != (0, 0)), None) + if row is None: continue + k = len(pivots) + matrix[k], matrix[row] = matrix[row], matrix[k] + pivot = matrix[k][col] + matrix[k] = [divide(x, pivot) for x in matrix[k]] + for r in range(size): + if r != k: + factor = matrix[r][col] + matrix[r] = [add(x, Q.multiply((-factor[0], -factor[1]), y)) + for x, y in zip(matrix[r], matrix[k])] + pivots.append(col) + Q.need(all(row[-1] == (0, 0) for row in matrix[len(pivots):]), 'Consistent Gram normal equations') + coefficients = [(Fraction(0), Fraction(0))] * size + for row, col in enumerate(pivots): coefficients[col] = matrix[row][-1] + residual = residual_norm(gram, [(-x, -y) for x, y in coefficients] + [(1, 0)], width) + # Orthogonality is an independently inspectable optimum certificate. + for i in range(size): + value = (Fraction(0), Fraction(0)) + for j in range(size): value = add(value, Q.multiply(power(gram[i][j], width), coefficients[j])) + Q.need(value == power(gram[i][size], width), 'Exact residual orthogonality') + return dict(coefficients=coefficients, squared_residual=residual, span_rank=len(pivots)) diff --git a/research/clifford-compact-pauli-fibre/predecessor/source/engine/source/LICENSE b/research/clifford-compact-pauli-fibre/predecessor/source/engine/source/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/research/clifford-compact-pauli-fibre/predecessor/source/engine/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/clifford-compact-pauli-fibre/predecessor/source/engine/source/PR5698-NOTICE.md b/research/clifford-compact-pauli-fibre/predecessor/source/engine/source/PR5698-NOTICE.md new file mode 100644 index 0000000000..56712e3195 --- /dev/null +++ b/research/clifford-compact-pauli-fibre/predecessor/source/engine/source/PR5698-NOTICE.md @@ -0,0 +1,9 @@ +# Attribution + +Ali Romman with substantial OpenAI Codex assistance. Apache-2.0. + +Dugongue PR5687 supplies the actual two-line C coframe proposal and its complete profile, source interpretation and moment/tail proof. The native-dual-suppliers source supplies the actual restriction, native maps and main normalizers. Preserve Cao Yifan PR4610/4470, Cinna Davis and the native/frame/helper/ROW/controller lineage, DaysSky, Nick Petalas, Ryanson Jonathan, zxv, Jacob Alan Sussman, and every retained phase, scalar, compiler, precision, stock and analytic notice. + +Seventeen source files are retained byte for byte. Their original comments and attribution remain unchanged. INPUTS.json and SOURCES.json give exact commits, paths, Git objects and SHA256 hashes. Dinic's integral flow algorithm and the submodular graph-cut construction are classical methods, not new mathematics claimed here. + +The new work is the complete 423-frame binary optimization, four additional folds, exact emitted physical program and phase certificates, finite optimality headroom bound, stronger full gain, and charged higher-moment transfer. No global literature priority, independent human acceptance or new kappa is claimed. diff --git a/research/clifford-compact-pauli-fibre/predecessor/source/engine/source/PR5704-NOTICE.md b/research/clifford-compact-pauli-fibre/predecessor/source/engine/source/PR5704-NOTICE.md new file mode 100644 index 0000000000..b96b400e5c --- /dev/null +++ b/research/clifford-compact-pauli-fibre/predecessor/source/engine/source/PR5704-NOTICE.md @@ -0,0 +1,33 @@ +# Attribution + +Ali Romman with substantial OpenAI Codex assistance. Apache-2.0. + +The affine-support and quadratic-phase representation is classical stabilizer +simulation. Credit Jeroen Dehaene and Bart De Moor, Physical Review A 68, 042318 +(2003), and the phase-sensitive stabilizer literature, including Bravyi, Browne, +Calpin, Campbell, Gosset and Howard (arXiv:1808.00128). The proof gives a direct +induction for this exact Gaussian-dyadic gate grammar. No discovery or optimal +simulation-complexity claim is made. + +Charles Bethin PR662 supplies the byte-exact table evaluator and prior runtime +work. Its retained NOTICE credits icekylinx, DreamingOfClouds, chafreaky, Jeremy +Kothe and the prior Clifford/wrapper/compiler lineage. Its source and notice +are frozen in tables/. They are used as a comparison engine and finite oracle. + +Ali Romman PR5698 supplies the complete actual restricted-C coframe construction, +source replay and proof checks. Its 32 package files and all nested notices are +frozen in source/. replay.py and verify_source.py are explicitly marked derived +copies with only source paths and state-equality calls changed. Preserve +Dugongue PR5687, Cao Yifan PR4610/4470, Cinna Davis, DaysSky, Nick Petalas, +Ryanson Jonathan, zxv, Jacob Alan Sussman and all native/helper/phase/ROW/controller, +compiler, precision and stock attribution in those retained files. + +BigCactusLabs PR702 and Joshua Snider's cold-wrapper quadratic certificate are +related independent finite amplitude/phase audits. Their scopes and credit are +separate from this implementation. No source contribution is reassigned here. + +The new contribution is the exact polynomial-state engine, explicit full-source +integration, proof-check preservation binding, independent representation tests, +all-actual-state cross-check and complete same-fixture runtime evidence. There +is no change to the mathematical construction, selected result or physical bill. +No independent human review or proof-kernel acceptance is claimed. diff --git a/research/clifford-compact-pauli-fibre/predecessor/source/engine/source/PR5704-quadratic.py b/research/clifford-compact-pauli-fibre/predecessor/source/engine/source/PR5704-quadratic.py new file mode 100644 index 0000000000..ce3c86ec07 --- /dev/null +++ b/research/clifford-compact-pauli-fibre/predecessor/source/engine/source/PR5704-quadratic.py @@ -0,0 +1,283 @@ +"""Exact affine-support states for the retained Gaussian-dyadic gate grammar. + +The method is classical stabilizer simulation. This implementation keeps the +absolute Gaussian-integer scalar. Ali Romman with substantial OpenAI Codex +assistance. Apache-2.0. +""" + + +def need(condition, message): + if not condition: + raise ValueError(message) + + +def bits(mask): + while mask: + bit = mask & -mask + yield bit.bit_length() - 1 + mask ^= bit + + +def term(poly, mask, value): + value = (poly.get(mask, 0) + value) % 4 + if value: + poly[mask] = value + else: + poly.pop(mask, None) + + +def affine(poly, form, coefficient): + """Add a coefficient times an affine Boolean form, modulo four.""" + coefficient %= 4 + if not coefficient: + return + constant = form & 1 + term(poly, 0, coefficient * constant) + signed = coefficient * (1 - 2 * constant) + indices = list(bits(form >> 1)) + for i in indices: + term(poly, 1 << i, signed) + if coefficient & 1: + for k, i in enumerate(indices): + for j in indices[k + 1:]: + term(poly, (1 << i) | (1 << j), 2) + + +def product(poly, left, right): + """Add twice the product of two affine Boolean forms.""" + a, b = left & 1, right & 1 + u, v = list(bits(left >> 1)), list(bits(right >> 1)) + term(poly, 0, 2 * a * b) + if b: + for i in u: + term(poly, 1 << i, 2) + if a: + for j in v: + term(poly, 1 << j, 2) + for i in u: + for j in v: + term(poly, (1 << i) | (1 << j), 2) + + +def substitute(poly, forms): + result = {} + for mask, coefficient in poly.items(): + if not mask: + term(result, 0, coefficient) + elif mask.bit_count() == 1: + affine(result, forms[mask.bit_length() - 1], coefficient) + else: + need(mask.bit_count() == 2 and coefficient == 2, + 'A phase must have only even quadratic terms') + i, j = bits(mask) + product(result, forms[i], forms[j]) + return result + + +def value(poly, argument): + return sum(c for mask, c in poly.items() if argument & mask == mask) % 4 + + +def basis(columns): + """Return reduced binary columns with their original coordinates.""" + rows = {} + for j, column in enumerate(columns): + vector, coordinates = column, 1 << j + while vector: + pivot = vector.bit_length() - 1 + if pivot not in rows: + rows[pivot] = (vector, coordinates) + break + other, witness = rows[pivot] + vector ^= other + coordinates ^= witness + need(vector != 0, 'Support columns must be independent') + for pivot in sorted(rows): + vector, witness = rows[pivot] + for other in sorted(rows): + if other > pivot and rows[other][0] >> pivot & 1: + x, y = rows[other] + rows[other] = (x ^ vector, y ^ witness) + return rows + + +def coordinates(rows, vector): + result = 0 + for pivot in sorted(rows, reverse=True): + if vector >> pivot & 1: + column, witness = rows[pivot] + vector ^= column + result ^= witness + return None if vector else result + + +def multiply_i(pair, power): + a, b = pair + return ((a, b), (-b, a), (-a, -b), (b, -a))[power % 4] + + +def multiply(left, right): + a, b = left + c, d = right + return a * c - b * d, a * d + b * c + + +def normalize(pair, denominator): + need(pair != (0, 0), 'A unitary state cannot be zero') + while denominator and not ((pair[0] | pair[1]) & 1): + pair = (pair[0] // 2, pair[1] // 2) + denominator -= 1 + return pair, denominator + + +def matrix_vector(rows, vector): + return sum(((row & vector).bit_count() & 1) << j for j, row in enumerate(rows)) + + +def validate_integer(value_, limit, message): + need(type(value_) is int and 0 <= value_ < limit, message) + + +def signature(n, circuit, initial=0, counters=None): + """Return a canonical exact state without an exponential vector. + + A state is scalar times i^q(z) at offset xor columns*z. The columns + remain independent. The returned tuple describes every amplitude. + """ + need(type(n) is int and n >= 0, 'The width must be a nonnegative integer') + validate_integer(initial, 1 << n, 'Initial basis index') + columns, offset, poly = [], initial, {} + scalar, denominator = (1, 0), 0 + counts = counters if counters is not None else {} + + def count(key): + counts[key] = counts.get(key, 0) + 1 + + for gate in circuit: + need(isinstance(gate, (tuple, list)) and gate, 'Nonempty gate record') + kind = gate[0] + r = len(columns) + if kind == 'P': + need(len(gate) == 2 and len(gate[1]) == n, 'Permutation dimensions') + rows = gate[1] + for row in rows: + validate_integer(row, 1 << n, 'Binary permutation row') + basis(rows) + offset = matrix_vector(rows, offset) + columns = [matrix_vector(rows, x) for x in columns] + elif kind == 'X': + need(len(gate) == 2, 'Translation record') + validate_integer(gate[1], 1 << n, 'Translation mask') + offset ^= gate[1] + elif kind == 'phase': + need(len(gate) == 2 and type(gate[1]) is int, 'Global phase record') + term(poly, 0, gate[1]) + elif kind == 'D': + need(len(gate) == 3 and len(gate[1]) == len(gate[2]) == n, + 'Diagonal dimensions') + rows, linear = gate[1], gate[2] + for i in range(n): + validate_integer(rows[i], 1 << n, 'Binary diagonal row') + need(type(linear[i]) is int and linear[i] % 2 == (rows[i] >> i & 1), + 'Diagonal parity lift') + for j in range(i): + need((rows[i] >> j & 1) == (rows[j] >> i & 1), + 'Symmetric diagonal matrix') + forms = [(offset >> i & 1) | + sum((column >> i & 1) << (j + 1) for j, column in enumerate(columns)) + for i in range(n)] + for i, coefficient in enumerate(linear): + affine(poly, forms[i], coefficient) + for j in bits(rows[i] >> (i + 1)): + product(poly, forms[i], forms[i + 1 + j]) + elif kind == 'C': + need(len(gate) == 3 and type(gate[2]) is int and gate[2] in (-1, 1), + 'Translation-root record and sign') + q, sign = gate[1:] + validate_integer(q, 1 << n, 'Translation-root mask') + witness = coordinates(basis(columns), q) + scalar = multiply(scalar, (1, sign)) + denominator += 1 + term(poly, 1 << r, -sign) + if witness is None: + columns.append(q) + count('independent_root') + else: + # The last variable has zero output after this substitution. + forms = [(1 << (i + 1)) | (((witness >> i) & 1) << (r + 1)) + for i in range(r)] + [1 << (r + 1)] + poly = substitute(poly, forms) + last = 1 << r + coefficient = poly.pop(last, 0) + neighbours = 0 + for mask in list(poly): + if mask & last: + need(mask.bit_count() == 2 and poly[mask] == 2, + 'Dependent-root quadratic term') + neighbours ^= mask ^ last + del poly[mask] + if coefficient & 1: + scalar = multiply(scalar, (1, 1 if coefficient == 1 else -1)) + affine(poly, neighbours << 1, -coefficient) + count('odd_elimination') + else: + scalar = (2 * scalar[0], 2 * scalar[1]) + constant = coefficient // 2 + if neighbours: + pivot = (neighbours & -neighbours).bit_length() - 1 + free = [i for i in range(r) if i != pivot] + forms = [0] * r + for j, i in enumerate(free): + forms[i] = 1 << (j + 1) + forms[pivot] = constant | sum( + 1 << (j + 1) for j, i in enumerate(free) if neighbours >> i & 1) + poly = substitute(poly, forms) + if constant: + offset ^= columns[pivot] + columns = [columns[i] ^ (columns[pivot] if neighbours >> i & 1 else 0) + for i in free] + count('even_restriction') + else: + need(constant == 0, 'A unitary root cannot annihilate the state') + count('even_free') + scalar, denominator = normalize(scalar, denominator) + else: + raise ValueError('Unknown gate: ' + str(kind)) + need(len(columns) <= n, 'Support dimension cannot exceed width') + counts['peak_support_rank'] = max(counts.get('peak_support_rank', 0), len(columns)) + + rows = basis(columns) + reduced_offset, shift = offset, 0 + for pivot in sorted(rows, reverse=True): + if reduced_offset >> pivot & 1: + column, witness = rows[pivot] + reduced_offset ^= column + shift ^= witness + ordered = [rows[p] for p in sorted(rows)] + forms = [(shift >> i & 1) | sum(((witness >> i) & 1) << (j + 1) + for j, (_, witness) in enumerate(ordered)) for i in range(len(columns))] + poly = substitute(poly, forms) + scalar = multiply_i(scalar, poly.pop(0, 0)) + scalar, denominator = normalize(scalar, denominator) + return (n, reduced_offset, tuple(x for x, _ in ordered), tuple(sorted(poly.items())), + scalar[0], scalar[1], denominator) + + +def amplitude(state, index): + n, offset, columns, terms, real, imag, denominator = state + validate_integer(index, 1 << n, 'Amplitude index') + argument = coordinates(basis(columns), index ^ offset) + if argument is None: + return (0, 0), 0 + pair = multiply_i((real, imag), value(dict(terms), argument)) + return pair, denominator + + +def equal_operators(left, right): + """Compare valid retained Clifford objects, including absolute phase. + + Their tableaus must be derived from their circuits by the retained exact + constructors. An arbitrary supplied tableau is not a valid input contract. + """ + return (left.n == right.n and left.tab == right.tab and + signature(left.n, left.circuit) == signature(right.n, right.circuit)) diff --git a/research/clifford-compact-pauli-fibre/predecessor/source/row/bell_reads.py b/research/clifford-compact-pauli-fibre/predecessor/source/row/bell_reads.py new file mode 100644 index 0000000000..32b2ed2a94 --- /dev/null +++ b/research/clifford-compact-pauli-fibre/predecessor/source/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-compact-pauli-fibre/predecessor/source/row/compile_row.py b/research/clifford-compact-pauli-fibre/predecessor/source/row/compile_row.py new file mode 100644 index 0000000000..daf35d6a26 --- /dev/null +++ b/research/clifford-compact-pauli-fibre/predecessor/source/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-compact-pauli-fibre/predecessor/source/row/raw_row.py b/research/clifford-compact-pauli-fibre/predecessor/source/row/raw_row.py new file mode 100644 index 0000000000..1787feb76a --- /dev/null +++ b/research/clifford-compact-pauli-fibre/predecessor/source/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() diff --git a/research/clifford-compact-pauli-fibre/verify.py b/research/clifford-compact-pauli-fibre/verify.py new file mode 100644 index 0000000000..301921a0fe --- /dev/null +++ b/research/clifford-compact-pauli-fibre/verify.py @@ -0,0 +1,150 @@ +"""Cross-check public full-fibre contraction against signed dense coordinates.""" +from collections import defaultdict +from fractions import Fraction +from hashlib import sha256 +import json +from functools import reduce +from operator import xor +from pathlib import Path +from random import Random +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from fibre import Q, apply, fibre, parity, iter_reads, label_sum +from raw_row import coefficient_numerator, matrix_addresses, probe_at, raw_plan, split_address + + +def require(ok, message): + if not ok: + raise ValueError(message) + + +def repeat_nibble(x): + return x * ((2**52 - 1) // 15) + + +def dense_entry(row, column): + """The full vector of integer weights at one raw address, using #7800 only.""" + x = (row ^ column) & 15 + corrected_col = column ^ repeat_nibble(x) + n = coefficient_numerator(row, corrected_col) + actual = split_address(column) + t = reduce(xor, actual[:-1], 0) + return x, actual[-1] ^ t, n + + +def literal(chart): + _, offset, cols, terms, a, b, den = chart + out = [[0, 0] for _ in range(256)] + for param in range(1 << len(cols)): + address = offset ^ apply(cols, param) + x, column, n = dense_entry(*divmod(address, 1 << 52)) + if not n: + continue + scalar = Q.multiply_i((a*n, b*n), Q.value(dict(terms), param)) + for z in range(16): + sign = (-1)**parity(z & column) + for j in range(2): + out[16*x+z][j] += scalar[j]*sign + return [tuple(Fraction(v, 4096 << den) for v in val) for val in out] + + +def support_and_literal(): + rng = Random(7801) + count = 0 + hits = set() + total = 0 + for shifts, bucket in raw_plan().items(): + total += sum(bool(n) for n in bucket.numerators) << (52-len(bucket.masks)) + # Mix independent pair/singleton directions, a second shift, complex + # phases and a translation into each of the 16 Pauli X sectors. + sig = next(i for i, n in enumerate(bucket.numerators) if n) + anchors = [bucket.point_at(sig, j) for j in (0, 1, 2, 4)] + raw = [(r << 52) | c for r,c in (matrix_addresses(shifts, p) for p in anchors)] + offset = raw[0] ^ repeat_nibble(count % 16) + dirs = [v ^ raw[0] for v in raw[1:]] + [1, 2, 2 << 52, 1 << 27] + circuit = [('C', v, rng.choice((-1,1))) for v in dirs] + [('phase', count % 4)] + chart = Q.signature(104, circuit, initial=offset) + result, stats = fibre(chart) + require(result == literal(chart), "Off-image literal contraction in every Pauli component") + require(any(q != (0,0) for q in result), "Degenerate fixture") + hits.add(stats['singleton_dimension']) + count += 1 + require(total == 151 * 2**47 and total * 16 == 340021771866472448, "Dense support union") + return count, hits + + +def literal_bell_weights(): + groups = defaultdict(list) + for read in iter_reads(): + labels = read.output_labels + read.input_labels + groups[tuple(q >> 4 for q in labels)].append(read) + checked = 0 + for shifts, bucket in raw_plan().items(): + sig = next(i for i, n in enumerate(bucket.numerators) if n) + for x in range(16): + row, diag = matrix_addresses(shifts, bucket.point_at(sig, 17*x)) + col = diag ^ repeat_nibble(x) + a, b = row & 15, col & 15 + frees = split_address(row)[1:12:2] + split_address(col)[1:12:2] + outputs = [0]*16 + for read in groups[shifts]: + wo, wi = label_sum(read.output_labels), label_sum(read.input_labels) + # Trace against the Pauli matrix at *corrected* row and column. + column = b ^ (wi >> 4) + require((a ^ (wo >> 4) ^ column) == x, "Singleton trace diagonal") + sign = parity((wo & a) ^ (wi & b)) + labels = read.output_labels + read.input_labels + sign ^= reduce(xor, (parity(f & lab) for f, lab in zip(frees, labels, strict=True)), 0) + for z in range(16): + outputs[z] += read.numerator * (-1)**(sign ^ parity(z & column)) + xx, cc, n = dense_entry(row, col) + require(xx == x and n and outputs == [n*(-1)**parity(z & cc) for z in range(16)], + "Direct Bell corrections disagree with translated scalar weights") + checked += 16 + return checked + + +def all_slice_ranks(): + r, c, _ = probe_at(0) + offset = (r << 52) | c + for e in range(9): + gates = [('C', 1 << (i if i < 4 else 52+i-4), (-1)**i) for i in range(e)] + state = Q.signature(104, gates, initial=offset) + out, stats = fibre(state) + require(stats['singleton_dimension'] == e and out == literal(state), + "Singleton Walsh rank or a complex component changed") + out, stats = fibre(Q.signature(104, [])) + require(not stats['supported_terms'] and out == [(0,0)]*256, "Empty Bell intersection") + + +def pauli_columns(): + for x,z,phase in [(0,0,0),(1,2,1),(7,7,2),(15,3,3),(14,15,0),(3,13,1)]: + # The X^x Z^z columns are assembled directly in computational coordinates. + shift = repeat_nibble(x) << 52 + phases = tuple((1 << j,2) for j in Q.bits(repeat_nibble(z))) + scalar = Q.multiply_i((1,0), phase) + state = (104,shift,tuple((1<