From 57bb6efed1be1dda9eb1a0f622ec2773bc8b0047 Mon Sep 17 00:00:00 2001 From: Ali Romman <226877337+aliromman@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:14:27 -0500 Subject: [PATCH] Prove optimal linear-bit canonical rotation switch query --- .../.gitattributes | 1 + .../rotation-switch-closed-descent/CREDITS.md | 30 ++ .../rotation-switch-closed-descent/PROOF.md | 158 +++++++++++ .../rotation-switch-closed-descent/README.md | 78 ++++++ .../RESULT.json | 73 +++++ .../SOURCE-PINS.json | 50 ++++ .../SOURCES.json | 18 ++ .../rotation-switch-closed-descent/TASK.json | 89 ++++++ .../VERIFY.json | 32 +++ .../rotation-switch-closed-descent/query.py | 50 ++++ .../retained/base/LICENSE | 201 +++++++++++++ .../retained/pr4100/NOTICE.md | 38 +++ .../retained/pr4100/check_batched_crt.py | 265 ++++++++++++++++++ .../retained/pr7504/PROOF.md | 238 ++++++++++++++++ .../retained/pr7504/README.md | 132 +++++++++ .../retained/pr7504/rotation_query.py | 56 ++++ .../rotation-switch-closed-descent/verify.py | 180 ++++++++++++ 17 files changed, 1689 insertions(+) create mode 100644 research/rotation-switch-closed-descent/.gitattributes create mode 100644 research/rotation-switch-closed-descent/CREDITS.md create mode 100644 research/rotation-switch-closed-descent/PROOF.md create mode 100644 research/rotation-switch-closed-descent/README.md create mode 100644 research/rotation-switch-closed-descent/RESULT.json create mode 100644 research/rotation-switch-closed-descent/SOURCE-PINS.json create mode 100644 research/rotation-switch-closed-descent/SOURCES.json create mode 100644 research/rotation-switch-closed-descent/TASK.json create mode 100644 research/rotation-switch-closed-descent/VERIFY.json create mode 100644 research/rotation-switch-closed-descent/query.py create mode 100644 research/rotation-switch-closed-descent/retained/base/LICENSE create mode 100644 research/rotation-switch-closed-descent/retained/pr4100/NOTICE.md create mode 100644 research/rotation-switch-closed-descent/retained/pr4100/check_batched_crt.py create mode 100644 research/rotation-switch-closed-descent/retained/pr7504/PROOF.md create mode 100644 research/rotation-switch-closed-descent/retained/pr7504/README.md create mode 100644 research/rotation-switch-closed-descent/retained/pr7504/rotation_query.py create mode 100644 research/rotation-switch-closed-descent/verify.py diff --git a/research/rotation-switch-closed-descent/.gitattributes b/research/rotation-switch-closed-descent/.gitattributes new file mode 100644 index 0000000000..130a3ecaa2 --- /dev/null +++ b/research/rotation-switch-closed-descent/.gitattributes @@ -0,0 +1 @@ +retained/** -text whitespace=cr-at-eol diff --git a/research/rotation-switch-closed-descent/CREDITS.md b/research/rotation-switch-closed-descent/CREDITS.md new file mode 100644 index 0000000000..939b2827ff --- /dev/null +++ b/research/rotation-switch-closed-descent/CREDITS.md @@ -0,0 +1,30 @@ +# Credit and exact sources + +Prepared by Ali Romman with substantial OpenAI Codex assistance in research, +implementation, verification and writing. New work is Apache-2.0. + +- Nick Petalas supplied the canonical endpoint formulas and child recurrence + in [PR #7504](https://github.com/CrocSwap/integer-mult-bounds/pull/7504). + The [source proof](https://github.com/petalas/integer-mult-bounds/blob/7efb9a84277ec31abe2a934aeef8c8a70548aa5b/research/canonical-rotation-switch-query/PROOF.md) + and [query](https://github.com/petalas/integer-mult-bounds/blob/7efb9a84277ec31abe2a934aeef8c8a70548aa5b/research/canonical-rotation-switch-query/rotation_query.py) + are retained unchanged. The source README retains its related-work credit. +- Cinna Davis supplied the deterministic compiler in + [PR #4100](https://github.com/CrocSwap/integer-mult-bounds/pull/4100). + The [canonical source](https://github.com/CrocSwap/integer-mult-bounds/blob/337d04939571a637aeab54a0f58f54fde811663a/research/unconditional-batched-crt/check_batched_crt.py) + is called unchanged for finite table comparisons. Its NOTICE is retained. + The full unconditional construction is not an accepted premise here. +- Jerry Chen supplied the fourteen-tape implementation in + [PR #7593](https://github.com/CrocSwap/integer-mult-bounds/pull/7593), + head `56335a406469fad85e88ff72820d506d8bea6f63`. It is related physical + work, not a consumed executable or a claimed automatic speedup. + +The new contribution is the two-length closed descent, direct query and +matching bit-probe lower bound. The endpoint formulas retain their source +credit. The canonical compiler is a separate finite oracle; the recurrence +comparison shares the mathematical predecessor. Neither is an independent +human review. + +`SOURCE-PINS.json` binds six retained files byte for byte. `SOURCES.json` +binds the base catalogue and selected record as provenance. No unmerged +source ancestry is asserted. The base license is retained. All predecessor +authors named in the retained notices keep their credit. diff --git a/research/rotation-switch-closed-descent/PROOF.md b/research/rotation-switch-closed-descent/PROOF.md new file mode 100644 index 0000000000..65f3702b10 --- /dev/null +++ b/research/rotation-switch-closed-descent/PROOF.md @@ -0,0 +1,158 @@ +# A closed formula for canonical rotation switch queries + +This proof changes the arithmetic query in Nick Petalas's +[PR #7504](https://github.com/CrocSwap/integer-mult-bounds/pull/7504). +Its endpoint formulas and child-closure theorem are cited premises, retained +with exact bytes in `retained/pr7504/PROOF.md`. The new result is a closed +descent formula, a linear bit-cost query, and a matching worst-case lower +bound. No new kappa or complete compiler follows. + +## 1. Contract + +Let `h>=1`, `N=2^h`, `1<=s<=N`, and `0<=a0` as a nonidentity +child gives a wrong central switch already at `(h,s,a,j,x)=(2,2,1,1,1)`. + +## 3. Collapse any number of child steps + +The child branches of a table query are the low bits of its current wire: +`c_i=(x>>i) mod 2`. For any depth `0<=d>d`. After exactly `d` +interior descents, the requested row is an endpoint of height `H`. +The query uses the pair in Section 3 once. If either length is zero, +return zero. If `H=1`, both positive integer lengths must be one; return +one. Otherwise set `S=A_d+B_d` and `A=A_d`. + +For the first endpoint, when `j=d`, return + +```text +[S and A are odd] [floor(y/2)=floor(S/2)]. +``` + +For the last endpoint, return + +```text +[A is odd] [y=2`, `s=2^h-1`, `j=2h-2`, and `x=0`. With an `h`-bit offset field, +the all-zero offset returns zero. Changing any one offset bit `k` with +`1<=k=3`, +fix `x=a=2^(h-1)`, the same odd `s` and last row. The baseline answer is +zero. Changing any offset bit `1<=k>d` gives the answer. This uses a fixed +number of linear binary operations. A family of inputs needs at least +`h-1` offset-bit probes with padded fields, or `h-2` with minimal positive +encodings, so the worst-case order of growth is sharp. + +Read [PROOF.md](PROOF.md), [query.py](query.py), [RESULT.json](RESULT.json), +[SOURCE-PINS.json](SOURCE-PINS.json) and [CREDITS.md](CREDITS.md). The proof +covers every positive height. The executable has a height limit of 65536. + +## Evidence and reproduction + +Use Python 3.12 and the standard library: + +```sh +python3.12 -B scripts/research_package.py --package research/rotation-switch-closed-descent +``` + +Both registered commands print: + +```text +PASS_ROTATION_SWITCH_CLOSED_DESCENT optimal O(h) bit query +``` + +The verifier checks all 1,633,182 switch entries in 2,793 networks against +the retained canonical compiler and source recurrence. It routes 152,526 +addresses and checks 892,854 descent states. Further checks cover 420 wide +source queries, the 544-bit historical row, explicit height-65536 cases, +bit sensitivities, twelve invalid domains and five wrong-formula controls. +The retained sources are authenticated before use. No historical research +entry point is executed. The finite checks corroborate the written proof. + +## Scope + +This changes an arithmetic query. Jerry Chen's PR7593 already supplies a +fourteen-tape implementation of the earlier recurrence; its literal program +and quadratic bound remain separate. This package supplies no physical +instruction count, caller runtime measurement, or supplier admission. +All five selected framework assumptions remain. Historical suites, physical +caller replay, selected cold replay, Lean and Docker were not run. + +## Open next questions + +- Lower the closed formula to a literal fixed-tape program. Preserve the + borrowed descriptors, return one owned bit, and price clearing and head + returns. Start with the existing `(h,s,j)=(5,17,6)` boundary. The present + arithmetic proof does not provide that owned-work contract. +- Compose the query with actual current-state CRT offsets and compare a + complete workload against retained row-ROM reuse. Start with the existing + exceptional-key producer. Offset production, descriptor conversion and + payload consumption remain required costs. + +`TASK.json` records the changed audit-card scope and these questions. The +base is canonical main `e54523517d0f03e58352e647c403a5af3e525a57`, priority +revision 8. Selected bindings pass; the catalogue assessment is older than +the selected record. The selected frontier is unchanged. + +Prepared by Ali Romman with substantial OpenAI Codex assistance. Nick +Petalas supplied the endpoint and child formulas; Cinna Davis supplied the +canonical compiler; Jerry Chen supplied related physical lowering. See the +retained notices and credit file. This is source-aware author checking, +not independent human or formal-kernel acceptance. Apache-2.0. diff --git a/research/rotation-switch-closed-descent/RESULT.json b/research/rotation-switch-closed-descent/RESULT.json new file mode 100644 index 0000000000..f8fdd91935 --- /dev/null +++ b/research/rotation-switch-closed-descent/RESULT.json @@ -0,0 +1,73 @@ +{ + "canonical_entries": 1633182, + "descent_states": 892854, + "domain_rejections": 12, + "h5_s17_layer6_entries": 544, + "h5_s17_layer6_sha256": "bc0ab563e6d8fdfa24ee89b50dbe3f9a3a6f23681f491e883c6b5aeef07d4104", + "minimal_encoding_sensitivity_checks": 4237, + "networks": 2793, + "one_bit_sensitivity_checks": 4242, + "queries_beyond_source_cap": 6, + "recursive_entries": 1633182, + "routed_addresses": 152526, + "scope": "O(h) arithmetic bit query; no physical caller or new kappa", + "semantic_mutants": { + "lost carry": { + "expected": 1, + "mutant": 0, + "query": [ + 2, + 3, + 1, + 1, + 1 + ] + }, + "lost identity": { + "expected": 0, + "mutant": 1, + "query": [ + 2, + 2, + 1, + 1, + 1 + ] + }, + "unshifted wire": { + "expected": 1, + "mutant": 0, + "query": [ + 3, + 3, + 1, + 3, + 3 + ] + }, + "wrong complement": { + "expected": 0, + "mutant": 1, + "query": [ + 2, + 2, + 1, + 1, + 1 + ] + }, + "wrong path": { + "expected": 1, + "mutant": 0, + "query": [ + 2, + 3, + 1, + 1, + 1 + ] + } + }, + "table_sha256": "a03bef31f1c4d89ada71e74120ba6cf3ce329153abcb6b38860242d7d95f1863", + "wide_recursive_queries": 420 +} diff --git a/research/rotation-switch-closed-descent/SOURCE-PINS.json b/research/rotation-switch-closed-descent/SOURCE-PINS.json new file mode 100644 index 0000000000..f7c05e1baf --- /dev/null +++ b/research/rotation-switch-closed-descent/SOURCE-PINS.json @@ -0,0 +1,50 @@ +[ + { + "path": "retained/pr7504/rotation_query.py", + "source_repository": "petalas/integer-mult-bounds", + "source_commit": "7efb9a84277ec31abe2a934aeef8c8a70548aa5b", + "source_path": "research/canonical-rotation-switch-query/rotation_query.py", + "git_blob": "d9501b0425b432ff9d2a49b0a4514d7ff9914969", + "sha256": "f38e6a92be46a620d1a8faca9b013fcb44e55dfad329735a30ceb64a413f5cc2" + }, + { + "path": "retained/pr7504/PROOF.md", + "source_repository": "petalas/integer-mult-bounds", + "source_commit": "7efb9a84277ec31abe2a934aeef8c8a70548aa5b", + "source_path": "research/canonical-rotation-switch-query/PROOF.md", + "git_blob": "80a8295201d5aea4e37016075ed8df10eca44656", + "sha256": "cd886b0ed8a49153babd2a49887da0abf819902461268bf48f0a1cb6d427bdb1" + }, + { + "path": "retained/pr7504/README.md", + "source_repository": "petalas/integer-mult-bounds", + "source_commit": "7efb9a84277ec31abe2a934aeef8c8a70548aa5b", + "source_path": "research/canonical-rotation-switch-query/README.md", + "git_blob": "f17282a6377a5e7d9acc56a25704a3c59eac1eba", + "sha256": "4fb7c3dcd2421f26833810b789e47e9ff2c2c719cd435a110c657da711f12969" + }, + { + "path": "retained/pr4100/check_batched_crt.py", + "source_repository": "CrocSwap/integer-mult-bounds", + "source_commit": "337d04939571a637aeab54a0f58f54fde811663a", + "source_path": "research/unconditional-batched-crt/check_batched_crt.py", + "git_blob": "1cf78abccd5e06beecc3ed21ba55f7c03b65fdbc", + "sha256": "681e2e3d71fa74c8b9b326f3860104fd9d89590a222e26ae6ee718d1fd40ff2e" + }, + { + "path": "retained/pr4100/NOTICE.md", + "source_repository": "CrocSwap/integer-mult-bounds", + "source_commit": "337d04939571a637aeab54a0f58f54fde811663a", + "source_path": "research/unconditional-batched-crt/NOTICE.md", + "git_blob": "886a8fdee275f01b459cbd68ae2815dc9269502f", + "sha256": "924109837e71c52392191710d49c9deb42780878d1094f0b01e8690dbe799461" + }, + { + "path": "retained/base/LICENSE", + "source_repository": "CrocSwap/integer-mult-bounds", + "source_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "source_path": "LICENSE", + "git_blob": "261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64", + "sha256": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4" + } +] diff --git a/research/rotation-switch-closed-descent/SOURCES.json b/research/rotation-switch-closed-descent/SOURCES.json new file mode 100644 index 0000000000..5335fa97d9 --- /dev/null +++ b/research/rotation-switch-closed-descent/SOURCES.json @@ -0,0 +1,18 @@ +{ + "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" + } + ] +} diff --git a/research/rotation-switch-closed-descent/TASK.json b/research/rotation-switch-closed-descent/TASK.json new file mode 100644 index 0000000000..1dfb0c98d0 --- /dev/null +++ b/research/rotation-switch-closed-descent/TASK.json @@ -0,0 +1,89 @@ +{ + "schema_version": 1, + "task_id": "uniform-transfer-audit", + "priority_revision": 8, + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "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" + } + ] + }, + "scope_status": "changed", + "actual_scope": "Closed descent and optimal linear-bit canonical padded-rotation switch query for the exact PR7504 rule", + "scope_change_reason": "The broad source proof audit has prior follow-ups. This result gives a new arithmetic construction for the compiler interface and does not claim a full framework assumption.", + "bottleneck_link": "Reduce the arithmetic cost of one exact canonical switch predicate from the published O(h^2) bound to O(h); physical offset production and owned-work integration remain separate.", + "budget_minutes": 60, + "stop_rule": "Prove the closed formula and linear bit bound, compare with both exact source definitions, and stop before physical caller integration.", + "outcome": "completed", + "evidence": "PROOF.md, RESULT.json, query.py, verify.py and SOURCE-PINS.json", + "author": "Ali Romman", + "ai_assistance": "Substantial OpenAI Codex assistance in research, implementation, verification and writing.", + "open_questions": [ + { + "question": "Can the closed formula return an owned predicate on literal fixed tape roles with linear transition cost?", + "why_it_matters": "The arithmetic gain does not automatically change the physical caller bill.", + "first_step": "Lower the h=5,s=17,j=6 query while preserving descriptors and restoring all heads.", + "blocked_by": "No physical program or owned-work proof is supplied here." + }, + { + "question": "Does the direct query improve the complete current-state CRT workload compared with row-ROM reuse?", + "why_it_matters": "Offset generation and repeated queries can dominate one predicate.", + "first_step": "Compose one existing exceptional-key offset producer with the new query and count all work.", + "blocked_by": "Producer, descriptor conversion and payload costs remain outside this result." + } + ] +} diff --git a/research/rotation-switch-closed-descent/VERIFY.json b/research/rotation-switch-closed-descent/VERIFY.json new file mode 100644 index 0000000000..dd7110d650 --- /dev/null +++ b/research/rotation-switch-closed-descent/VERIFY.json @@ -0,0 +1,32 @@ +{ + "schema_version": 1, + "status": "ready", + "python": "3.12", + "requirements": [], + "inputs": [], + "commands": [ + { + "argv": [ + "{python}", + "-W", + "error", + "-B", + "{package}/verify.py" + ], + "timeout_seconds": 120, + "checks": "Complete small canonical tables, source recurrence, routed addresses, descent states, wide queries, source hashes and semantic/domain controls" + }, + { + "argv": [ + "{python}", + "-W", + "error", + "-O", + "-B", + "{package}/verify.py" + ], + "timeout_seconds": 120, + "checks": "Complete small canonical tables, source recurrence, routed addresses, descent states, wide queries, source hashes and semantic/domain controls" + } + ] +} diff --git a/research/rotation-switch-closed-descent/query.py b/research/rotation-switch-closed-descent/query.py new file mode 100644 index 0000000000..5d5aa278a6 --- /dev/null +++ b/research/rotation-switch-closed-descent/query.py @@ -0,0 +1,50 @@ +"""Query one canonical switch with a closed descent formula. + +Prepared by Ali Romman with substantial OpenAI Codex assistance. Apache-2.0. +Nick Petalas supplied the child recurrence and endpoint formulas. +""" + +MAX_HEIGHT = 65536 + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def interval_pair(modulus, offset, depth, address): + """Return the two unreduced interval lengths after the specified descent.""" + mask = (1 << depth) - 1 + tail = address & mask + return ((offset + tail) >> depth, + (modulus - offset + mask - tail) >> depth) + + +def endpoint(left, right, address, height, last): + """Evaluate the endpoint, including every identity child.""" + if left == 0 or right == 0: + return 0 + if height == 1: + return 1 + modulus = left + right + if not last: + return int((modulus & left & 1) and address // 2 == modulus // 2) + if modulus % 2 == 0: + return int(left % 2 == 1 and address < modulus) + if left % 2 == 0: + return int(address < left) + return int(left - 1 <= address <= modulus) + + +def switch_bit(height, modulus, offset, layer, address): + """Return the source's current-wire table bit with O(height) bit work.""" + require(all(type(v) is int for v in (height, modulus, offset, layer, address)), + "integer parameters") + require(1 <= height <= MAX_HEIGHT, "height outside the executable limit") + require(1 <= modulus <= 1 << height, "modulus outside the address domain") + require(0 <= offset < modulus, "offset outside the canonical interval") + require(0 <= layer < 2 * height - 1, "layer outside the network") + require(0 <= address < 1 << height, "address outside the network") + depth = min(layer, 2 * height - 2 - layer) + left, right = interval_pair(modulus, offset, depth, address) + return endpoint(left, right, address >> depth, height - depth, layer != depth) diff --git a/research/rotation-switch-closed-descent/retained/base/LICENSE b/research/rotation-switch-closed-descent/retained/base/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/research/rotation-switch-closed-descent/retained/base/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/rotation-switch-closed-descent/retained/pr4100/NOTICE.md b/research/rotation-switch-closed-descent/retained/pr4100/NOTICE.md new file mode 100644 index 0000000000..886a8fdee2 --- /dev/null +++ b/research/rotation-switch-closed-descent/retained/pr4100/NOTICE.md @@ -0,0 +1,38 @@ +# Attribution and source boundaries + +New construction and audit: Cinna Davis, with substantial OpenAI Codex +assistance. Apache-2.0. No independent human or new formal-kernel review +is claimed. SOURCES.json and EXPORTED-SOURCES.json retain exact identities. +Source-specific notices are unchanged. + +- Douglas Colkitt and OpenAI's framework: stream algorithms, compact controls, + ordinary interchange, row-volume and tape contracts. +- Jose Manuel (jmbarrancoml), selected recursive/physical BIT and complex + closure packages: class-indexed callers, ring descriptors, fixed-state + compilation, common-grid precision and source integration. +- DreamingOfClouds, eumemic, Dugongue, Rohan Arun, alephnan and the retained + PR589/PR1627 lineage: the finite BIT word and chronological hosting. +- commdata2338, Ross Richardson and source527 contributors: normal forms, + fallback covariance, weighted leaves and recursive parking. +- PR2915's selected fast-primitive work: replacing both the weighted leaf + and the reached owner-header sites with a completed previous stage. +- Vlado Vojdanovski, PR1673 and its credited contributors: capped Gaussian + cells, finite LDU, shallow Toeplitz circuits, tensor compilation, support + routing, sparse layouts and conditioning audits. +- Chafik Boukhalfa, PR1758/1786: shifted Gaussian accretivity, per-visit + union scheduling, fine prime intervals and separate setup precision. +- PR4088 and its NOTICE retain the mixed-provider lineage, including Rohan + Arun, David Ganz/Dugongue, Nick Petalas, Ross Richardson, dataisfire, + Erwan Secousses, Sagar Thakrar, roger-sato, Marius-Paul Dumitrean and the + native compiler/geometry contributors. +- Tekalign, Ali Romman, Charles Bethin and the native source notices: + exact native replay and sparse Clifford-state evaluation. +- Tim Trudgian: the explicit unconditional prime-counting estimate. +- David Harvey and Joris van der Hoeven: the established O(N log N) + multiplier used on the shorter numerical records. + +This package contributes batched nonlinear CRT and its enlarged-guard cost; +independent full-ring normal-form and fallback derivations; the retuned BIT +assembly; the mixed-provider free-algebra lift with external spectators; +conservative position-dependent halos; cached chirps; and the proposed outer +composition. The predecessor words, identities and compilers retain their credit. diff --git a/research/rotation-switch-closed-descent/retained/pr4100/check_batched_crt.py b/research/rotation-switch-closed-descent/retained/pr4100/check_batched_crt.py new file mode 100644 index 0000000000..1cf78abccd --- /dev/null +++ b/research/rotation-switch-closed-descent/retained/pr4100/check_batched_crt.py @@ -0,0 +1,265 @@ +"""Exact finite controls for the draft; not a machine-cost certificate.""" +import itertools +import json +import math + + +def need(condition, message): + if not condition: + raise ValueError(message) + + +def benes(permutation): + """Return (bit, switch table) layers on precisely len(permutation) wires.""" + size = len(permutation) + need(size >= 2 and size & (size - 1) == 0, "dyadic network size") + need(sorted(permutation) == list(range(size)), "permutation") + if size == 2: + return [(0, (permutation[0],) * 2)] + inverse = [0] * size + for x, y in enumerate(permutation): + inverse[y] = x + color = [-1] * size + for initial in range(size): + if color[initial] >= 0: + continue + color[initial] = 0 + stack = [initial] + while stack: + x = stack.pop() + for other in (x ^ 1, inverse[permutation[x] ^ 1]): + if color[other] < 0: + color[other] = color[x] ^ 1 + stack.append(other) + need(color[other] == color[x] ^ 1, "even cycle coloring") + first = tuple(color[x] ^ (x & 1) for x in range(size)) + last = tuple(color[inverse[y]] ^ (y & 1) for y in range(size)) + children = [] + for c in (0, 1): + child = [None] * (size // 2) + for x in range(size): + if color[x] == c: + child[x // 2] = permutation[x] // 2 + children.append(benes(child)) + result = [(0, first)] + for left, right in zip(*children): + need(left[0] == right[0], "common network schedule") + table = tuple((left, right)[x & 1][1][x // 2] for x in range(size)) + result.append((left[0] + 1, table)) + result.append((0, last)) + return result + + +def run_network(layers, value): + for bit, table in layers: + value ^= table[value] << bit + return value + + +def rotation(size, modulus, offset): + return tuple((x + offset) % modulus if x < modulus else x for x in range(size)) + + +def decode_group(values, moduli): + """Recover the integer from locally scaled CRT residues.""" + product = math.prod(moduli) + answer = 0 + prefix = 1 + for value, modulus in zip(values, moduli): + complement = product // modulus + residue = value * prefix % modulus + answer += residue * complement * pow(complement, -1, modulus) + prefix *= modulus + return answer % product + + +def balanced(values, moduli, reverse=False, compiled=False): + count = len(moduli) + need(count > 0 and count & (count - 1) == 0, "power-of-two axis count") + state = list(values) + levels = list(range(1, count.bit_length())) + for level in reversed(levels) if reverse else levels: + width = 1 << level + half = width // 2 + for start in range(0, count, width): + middle = start + half + valid = all(state[i] < moduli[i] for i in range(start, middle)) + lower = decode_group(state[start:middle], moduli[start:middle]) if valid else 0 + prefix = math.prod(moduli[start:middle]) + for i in range(middle, start + width): + offset = lower * pow(prefix, -1, moduli[i]) % moduli[i] + if reverse: + offset = -offset % moduli[i] + if compiled: + size = 1 << (moduli[i] - 1).bit_length() + state[i] = run_network(benes(rotation(size, moduli[i], offset)), state[i]) + elif state[i] < moduli[i]: + state[i] = (state[i] + offset) % moduli[i] + prefix *= moduli[i] + return tuple(state) + + +def direct(values, moduli): + prefix = 1 + integer = 0 + prefixes = [] + for value, modulus in zip(values, moduli): + prefixes.append(prefix) + integer += value * prefix + prefix *= modulus + return tuple(integer * pow(prefix, -1, modulus) % modulus + for prefix, modulus in zip(prefixes, moduli)) + + +def primitive_f(u, t, y, bits, positions, ybits, control_bits): + radix = 1 << bits + control_mask = (1 << control_bits) - 1 + ymask = (1 << ybits) - 1 + z = [(u >> (bits * i)) & 1 for i in range(len(positions))] + digits = [(t >> (bits * i)) & (radix - 1) for i in range(len(positions))] + y = (y + sum(2 * bit * digit * (1 << pos) + for bit, digit, pos in zip(z, digits, positions))) & ymask + t = (t + sum(((y >> pos) & 1) << (bits * i) + for i, pos in enumerate(positions))) & control_mask + digits = [(t >> (bits * i)) & (radix - 1) for i in range(len(positions))] + y = (y + sum(bit * (1 - 2 * digit) * (1 << pos) + for bit, digit, pos in zip(z, digits, positions))) & ymask + t = (t - sum((((y >> pos) & 1) ^ z[i]) << (bits * i) + for i, pos in enumerate(positions))) & control_mask + return u, t, y + + +def compact(u, t, y, source, bits=2, positions=(0,), ybits=6, control_bits=2): + need(control_bits >= bits * len(positions), "control field capacity") + mask = (1 << control_bits) - 1 + u, t, y = primitive_f(u, t, y, bits, positions, ybits, control_bits) + u = (u + sum(value << (bits * i) for i, value in enumerate(source(y)))) & mask + u, t, y = primitive_f(u, t, y, bits, positions, ybits, control_bits) + u = (u - sum(value << (bits * i) for i, value in enumerate(source(y)))) & mask + return u, t, y + + +def good(u, t, y, bits=2, positions=(0,), guard=6): + radix = 1 << bits + return all(((u >> (bits * i)) & (radix - 1)) != radix - 1 + and ((t >> (bits * i)) & (radix - 1)) != radix - 1 + and 2 * radix <= ((y >> (pos + 1)) & ((1 << (guard - 1)) - 1)) + < (1 << (guard - 1)) - 2 * radix + for i, pos in enumerate(positions)) + + +def linear_guard(u, t, y, bits=2, positions=(0,), guard=6, + control_bits=2, ybits=6): + """Bit-by-bit guard predicate; source functions are never evaluated.""" + steps = 0 + accepted = True + for word in (u, t): + for digit in range(len(positions)): + all_ones = True + for bit in range(bits): + all_ones = all_ones and bool((word >> (digit * bits + bit)) & 1) + steps += 1 + accepted = accepted and not all_ones + for pos in positions: + lower = 2 * (1 << bits) + upper = (1 << (guard - 1)) - lower + comparison = [0, 0] + for bit in range(guard - 2, -1, -1): + value = (y >> (pos + 1 + bit)) & 1 + for index, bound in enumerate((lower, upper)): + if comparison[index] == 0: + comparison[index] = value - ((bound >> bit) & 1) + steps += 2 + accepted = accepted and comparison[0] >= 0 and comparison[1] < 0 + need(steps <= 2 * control_bits + 2 * ybits, "linear tested-bit budget") + return accepted + + +def check(): + network_count = address_count = 0 + for bits in range(1, 7): + size = 1 << bits + for modulus in range(max(2, size // 2), size): + for offset in range(modulus): + permutation = rotation(size, modulus, offset) + layers = benes(permutation) + need(len(layers) == 2 * bits - 1, "network depth") + for bit, table in layers: + need(all(table[x] == table[x ^ (1 << bit)] for x in range(size)), + "switch control omits its target bit") + need(tuple(run_network(layers, x) for x in range(size)) == permutation, + "all-column modular rotation") + network_count += 1 + address_count += size + crt_addresses = valid_addresses = 0 + for moduli in ((3,), (3, 5), (3, 5, 7, 11)): + sizes = [1 << (s - 1).bit_length() for s in moduli] + seen = set() + for source in itertools.product(*(range(size) for size in sizes)): + target = balanced(source, moduli) + need(target not in seen, "padded CRT injection") + seen.add(target) + need(balanced(target, moduli, reverse=True) == source, "padded CRT inverse") + valid = all(x < s for x, s in zip(source, moduli)) + need(valid == all(x < s for x, s in zip(target, moduli)), "padding invariance") + if valid: + need(target == direct(source, moduli), "scaled CRT endpoint") + valid_addresses += 1 + need(balanced(source, moduli, compiled=True) == target, "compiled CRT endpoint") + crt_addresses += 1 + compact_cases = good_cases = repair_cases = 0 + functions = [lambda y: (0,), lambda y: (1,), lambda y: ((y >> 2) & 1,), + lambda y: ((y >> 1).bit_count() & 1,), + lambda y: ((((y >> 1) & 1) & ((y >> 4) & 1)),)] + for source_function, control_bits in itertools.product(functions, (2, 4)): + actual = {} + ideal = {} + for u, t, y in itertools.product(range(1 << control_bits), + range(1 << control_bits), range(64)): + start = (u, t, y) + end = compact(*start, source_function, control_bits=control_bits) + wanted = (u, t, y ^ source_function(y)[0]) + need(end not in actual, "actual gadget bijection") + need(wanted not in ideal, "ideal switch bijection") + actual[end] = start + ideal[wanted] = start + is_good = good(*start) + need(linear_guard(*start, control_bits=control_bits) == is_good, + "linear guard agrees with interval predicate") + need(good(*end) == is_good and good(*wanted) == is_good, "good/bad invariance") + if is_good: + need(end == wanted, "compact endpoint on good addresses") + good_cases += 1 + compact_cases += 1 + # Each arbitrary dirty input column follows S, then T S^-1 on bad holes. + for end, start in actual.items(): + u, t, y = start + repaired = (u, t, y ^ source_function(y)[0]) if not good(*end) else end + need(ideal[repaired] == start, "sparse correction column") + repair_cases += not good(*end) + multi_cases = 0 + def source_pair(y): + return (y >> 3) & 1, (y & ~65).bit_count() & 1 + for u, t in ((0, 0), (0, 15), (5, 5), (10, 10), (15, 0), (15, 15)): + for y in range(1 << 12): + start = (u, t, y) + end = compact(*start, source_pair, positions=(0, 6), ybits=12, control_bits=4) + f0, f1 = source_pair(y) + wanted = (u, t, y ^ f0 ^ (f1 << 6)) + is_good = good(*start, positions=(0, 6)) + need(linear_guard(*start, positions=(0, 6), control_bits=4, ybits=12) == is_good, + "two-target linear guard") + need(good(*end, positions=(0, 6)) == is_good, "two-target guard invariance") + if is_good: + need(end == wanted, "two-target compact endpoint") + multi_cases += 1 + return dict(status="PASS_FINITE_BATCHED_CRT_CONTROLS", network_count=network_count, + network_addresses=address_count, crt_addresses=crt_addresses, + valid_crt_addresses=valid_addresses, compact_addresses=compact_cases, + good_addresses=good_cases, repaired_bad_addresses=repair_cases, + two_target_addresses=multi_cases, linear_guard_verified=True, + machine_cost_verified=False, multiplication_kappa_claimed=False) + + +if __name__ == "__main__": + print(json.dumps(check(), sort_keys=True, indent=2)) diff --git a/research/rotation-switch-closed-descent/retained/pr7504/PROOF.md b/research/rotation-switch-closed-descent/retained/pr7504/PROOF.md new file mode 100644 index 0000000000..80a8295201 --- /dev/null +++ b/research/rotation-switch-closed-descent/retained/pr7504/PROOF.md @@ -0,0 +1,238 @@ +# Direct canonical switch queries for padded rotations + +This scoped written proof gives a new arithmetic construction of the precise +deterministic tables in Cinna Davis's #4100 `check_batched_crt.py:benes`. +The source is pinned at canonical main +`e54523517d0f03e58352e647c403a5af3e525a57` in SOURCES.json. Its generic +permutation-routing theorem is a cited premise. No predecessor replay is a +deliverable of this package. This contribution was produced by Nick Petalas. + +## 1. Domain and result + +Let `N=2^h`, `h>=1`, `1<=s<=N`, and `0<=a1`, the first row is + +``` +F(x) = [s and a are odd] [floor(x/2)=floor(s/2)]. (1) +``` + +The last row is + +``` +L(x) = [a is odd] [x (h-1,s_(x mod 2),a_(x mod 2),j-1,floor(x/2)). (4) +``` + +At `h=1`, the only row has constant bit `a`. If `a=0`, the entire network +is identity. Equations (1)-(4) compute one canonical bit by at most `h` +iterations, with `O(h^2)` elementary bit operations and `O(h)` working bits. +These are bounds for bounded-integer arithmetic, not a physical tape bill. + +## 2. Canonical component colors + +The source colors the graph with the two perfect matchings + +``` +A(x)=x xor 1, B(x)=P^{-1}(P(x) xor 1). +``` + +It starts each uncolored component at its least vertex with color zero. +For an even-cycle component, fixing that first color uniquely determines +all colors. DFS neighbor order therefore does not affect the result. The +source's endpoint rows are + +``` +F(x)=color(x) xor (x mod 2), +L(y)=color(P^{-1}(y)) xor (y mod 2). (5) +``` + +Call `A` pairs with coincident `B` edges doubled pairs. Every doubled pair +whose least endpoint is even has colors equal to address parity. +Write `s=2m+epsilon`, `a=2b+delta`. + +If `s` and `a` are both even, all components are doubled pairs. If `s` is +even and `a` is odd, the active interval `[0,s-1]` forms one alternating +cycle: its `B` edges are `(1,2),(3,4),...,(s-3,s-2),(s-1,0)`. +All remaining components are doubled pairs. Both cases give +`color(x)=x mod 2` everywhere. The size-two cycle may itself be doubled. + +Suppose `s` is odd and `a` is even. The component containing the first +padded vertex `s` is the interval `[s-a-1,s]`. Its edges alternate along +successive vertices, with one closing `B` edge between the interval's +endpoints. Its least vertex `s-a-1` is even. Every other component is a +doubled pair. Again `color(x)=x mod 2` everywhere. For `a=0` the named +interval is just the doubled pair `(s-1,s)`. + +Finally suppose `s` and `a` are odd. Put `t=s-a`, which is even and at +least two. The exceptional component has vertices + +``` +0,1,...,t-1, s, s-1. +``` + +There are alternating consecutive edges on `[0,t-1]`, the `B` edges +`(t-1,s)` and `(s-1,0)`, and the `A` edge `(s-1,s)`. +Starting at zero gives parity colors on `[0,t-1]`, color zero at `s`, +and color one at `s-1`. All other components are doubled pairs. Hence + +``` +color(x) = (x mod 2) xor [x in {s-1,s}]. (6) +``` + +These descriptions follow directly by substituting the rotation and its +inverse into `B`; they list all edges because each vertex has one `A` +neighbor and one `B` neighbor. In particular they also identify each +component's least vertex and settle the source's orientation convention. +Substitution in the first equation of (5) proves (1). + +## 3. The last row + +For `y=a`, and `y+s-a` when `y=s` the inverse is `y`. + +When `s` is even, the active inverse changes parity exactly when `a` is +odd, giving the first line of (2). When `s` is odd and `a` even, precisely +`y (x+a) mod s` on +`x1`, the first row is zero except for the pair `{s-1,s}` when both +`s` and `a` are odd. The last row has the following one-bit predicate at +the current wire address `x`. + +| Parameters | Last-row bit | +| --- | --- | +| s even | `[a odd] [x None: + if not condition: + raise ValueError(message) + + +def endpoint_bit(modulus: int, offset: int, address: int, last: bool) -> int: + """Internal endpoint formula; the public query validates the domain.""" + if not last: + return int((modulus & offset & 1) and address // 2 == modulus // 2) + if modulus % 2 == 0: + return int(offset % 2 == 1 and address < modulus) + if offset % 2 == 0: + return int(address < offset) + return int(offset - 1 <= address <= modulus) + + +def child_parameters(modulus: int, offset: int, branch: int) -> tuple[int, int]: + """Internal recurrence, including an empty identity child.""" + child_modulus = modulus // 2 + int(modulus % 2 == 1 and branch == offset % 2) + raw_offset = offset // 2 + branch * (offset % 2) + child_offset = 0 if raw_offset == child_modulus else raw_offset + return child_modulus, child_offset + + +def switch_bit(h: int, modulus: int, offset: int, layer: int, address: int) -> int: + """Return a bit of precisely the source's deterministic network. + + The conceptual domain is every h >= 1. The executable caps h at 4096 + to bound interpreter allocation and work. No permutation or ROM is built. + """ + require(all(type(value) is int for value in (h, modulus, offset, layer, address)), + "integer parameters") + require(1 <= h <= 4096, "1 <= h <= 4096") + require(1 <= modulus <= 1 << h, "modulus in occupied address domain") + require(0 <= offset < modulus, "canonical offset") + require(0 <= layer < 2 * h - 1, "network layer") + require(0 <= address < 1 << h, "network address") + for _ in range(h): + if offset == 0: + return 0 + if h == 1: + return offset + if layer == 0 or layer == 2 * h - 2: + return endpoint_bit(modulus, offset, address, layer != 0) + modulus, offset = child_parameters(modulus, offset, address & 1) + require(0 <= offset < modulus, "nonidentity child has positive modulus") + h -= 1 + layer -= 1 + address //= 2 + raise ArithmeticError("unreachable after one descent per address bit") diff --git a/research/rotation-switch-closed-descent/verify.py b/research/rotation-switch-closed-descent/verify.py new file mode 100644 index 0000000000..ad3d4e5d32 --- /dev/null +++ b/research/rotation-switch-closed-descent/verify.py @@ -0,0 +1,180 @@ +"""Check the new query against the retained canonical network and recurrence. + +Prepared by Ali Romman with substantial OpenAI Codex assistance. Apache-2.0. +""" + +import argparse +import hashlib +import importlib.util +import json +from pathlib import Path +import random + +from query import MAX_HEIGHT, endpoint, interval_pair, require, switch_bit + +PACKAGE = Path(__file__).resolve().parent + + +def load_sources(): + pins = json.loads((PACKAGE / "SOURCE-PINS.json").read_text()) + for row in pins: + require(hashlib.sha256((PACKAGE / row["path"]).read_bytes()).hexdigest() + == row["sha256"], "retained source hash") + modules = [] + for name, path in [("canonical", "retained/pr4100/check_batched_crt.py"), + ("recursive", "retained/pr7504/rotation_query.py")]: + spec = importlib.util.spec_from_file_location(name, PACKAGE / path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + modules.append(module) + return modules + + +def wrong_query(h, s, a, j, x, change): + depth = min(j, 2 * h - 2 - j) + mask = (1 << depth) - 1 + tail = x & mask + left, right = interval_pair(s, a, depth, x) + if change == "wrong complement": + right = (s - a + tail) >> depth + elif change == "lost carry": + left = a >> depth + elif change == "wrong path": + left, right = interval_pair(s, a, depth, x >> depth) + elif change == "unshifted wire": + return endpoint(left, right, x, h - depth, j != depth) + elif change == "lost identity": + right = max(1, right) + return endpoint(left, right, x >> depth, h - depth, j != depth) + + +def census(canonical, recursive): + totals = {"networks": 0, "canonical_entries": 0, "recursive_entries": 0, + "routed_addresses": 0, "descent_states": 0} + changes = ("wrong complement", "lost carry", "wrong path", + "unshifted wire", "lost identity") + witnesses = {} + digest = hashlib.sha256() + for h in range(1, 7): + size = 1 << h + for s in range(1, size + 1): + for a in range(s): + permutation = canonical.rotation(size, s, a) + layers = canonical.benes(permutation) + for j, (_, row) in enumerate(layers): + for x, expected in enumerate(row): + args = h, s, a, j, x + bit = switch_bit(*args) + require(bit == expected, "canonical table mismatch") + require(bit == recursive.switch_bit(*args), "recursive query mismatch") + digest.update(bytes((bit,))) + totals["canonical_entries"] += 1 + totals["recursive_entries"] += 1 + for change in changes: + if change not in witnesses and wrong_query(*args, change) != expected: + witnesses[change] = {"query": list(args), "expected": expected, + "mutant": wrong_query(*args, change)} + for original in range(size): + current = original + for j in range(2 * h - 1): + current ^= switch_bit(h, s, a, j, current) << min(j, 2*h-2-j) + require(current == permutation[original], "routed endpoint mismatch") + totals["routed_addresses"] += 1 + left, right = a, s - a + child_s, child_a = s, a + for depth in range(h): + require(interval_pair(s, a, depth, original) == (left, right), + "closed interval pair mismatch") + if left and right: + require((child_s, child_a) == (left + right, left), + "nonidentity child mismatch") + else: + require(child_a == 0, "identity child mismatch") + totals["descent_states"] += 1 + branch = (original >> depth) & 1 + left, right = (left + branch) // 2, (right + 1 - branch) // 2 + child_s, child_a = recursive.child_parameters(child_s, child_a, branch) + totals["networks"] += 1 + require(set(witnesses) == set(changes), "undetected semantic mutation") + totals.update(table_sha256=digest.hexdigest(), semantic_mutants=witnesses) + return totals + + +def domain_controls(): + cases = [(0, 1, 0, 0, 0), (MAX_HEIGHT+1, 1, 0, 0, 0), + (2, 0, 0, 0, 0), (2, 5, 0, 0, 0), (2, 3, -1, 0, 0), + (2, 3, 3, 0, 0), (2, 3, 0, -1, 0), (2, 3, 0, 3, 0), + (2, 3, 0, 0, -1), (2, 3, 0, 0, 4), + (True, 1, 0, 0, 0), (2, 3.0, 0, 0, 0)] + for case in cases: + try: + switch_bit(*case) + except ValueError: + continue + raise ValueError("invalid domain accepted") + return len(cases) + + +def wide_checks(recursive): + rng = random.Random(6107504) + queries = 0 + for h in (7, 31, 65, 127, 511, 1024, 4096): + for _ in range(60): + s = rng.randrange(1, (1 << h) + 1) + args = h, s, rng.randrange(s), rng.randrange(2*h-1), rng.getrandbits(h) + require(switch_bit(*args) == recursive.switch_bit(*args), "wide source query") + queries += 1 + sensitivity = 0 + for h in (2, 3, 17, 129, 4096): + s = (1 << h) - 1 + require(switch_bit(h, s, 0, 2*h-2, 0) == 0, "lower-bound base input") + for k in range(1, h): + require(switch_bit(h, s, 1 << k, 2*h-2, 0) == 1, + "lower-bound one-bit neighbor") + sensitivity += 1 + minimal_sensitivity = 0 + for h in (3, 17, 129, 4096): + s, a = (1 << h) - 1, 1 << (h - 1) + require(switch_bit(h, s, a, 2*h-2, a) == 0, "minimal-encoding base input") + for k in range(1, h - 1): + require(switch_bit(h, s, a + (1 << k), 2*h-2, a) == 1, + "minimal-encoding one-bit neighbor") + minimal_sensitivity += 1 + for h in (8192, MAX_HEIGHT): + require(switch_bit(h, (1 << h)-1, 1, 0, (1 << h)-1) == 1, + "large padded boundary") + require(switch_bit(h, 1 << h, 1 << (h-1), h-1, 0) == 1, + "large nonidentity center") + require(switch_bit(h, (1 << h)-1, 0, h-1, 0) == 0, + "large identity center") + return {"wide_recursive_queries": queries, "one_bit_sensitivity_checks": sensitivity, + "minimal_encoding_sensitivity_checks": minimal_sensitivity, + "queries_beyond_source_cap": 6} + + +def calculate(): + canonical, recursive = load_sources() + result = census(canonical, recursive) + result.update(wide_checks(recursive)) + result["domain_rejections"] = domain_controls() + bits = bytes(switch_bit(5, 17, a, 6, x) for a in range(17) for x in range(32)) + result["h5_s17_layer6_entries"] = len(bits) + result["h5_s17_layer6_sha256"] = hashlib.sha256(bits).hexdigest() + result["scope"] = "O(h) arithmetic bit query; no physical caller or new kappa" + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--write-result", action="store_true") + args = parser.parse_args() + result = calculate() + if args.write_result: + (PACKAGE / "RESULT.json").write_text(json.dumps(result, indent=2, sort_keys=True) + "\n") + else: + require(result == json.loads((PACKAGE / "RESULT.json").read_text()), "result mismatch") + print("PASS_ROTATION_SWITCH_CLOSED_DESCENT optimal O(h) bit query") + + +if __name__ == "__main__": + main()