From 460eb0c026649b28ab3b00f45de136599d0570fa Mon Sep 17 00:00:00 2001 From: Ali Romman <226877337+aliromman@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:34:00 -0500 Subject: [PATCH] Implement canonical switch queries in linear tape transitions --- .../.gitattributes | 1 + .../linear-tape-rotation-switch/CREDITS.md | 33 ++ research/linear-tape-rotation-switch/PROOF.md | 265 ++++++++++++++++ .../linear-tape-rotation-switch/README.md | 79 +++++ .../linear-tape-rotation-switch/RESULT.json | 284 ++++++++++++++++++ .../SOURCE-PINS.json | 90 ++++++ .../linear-tape-rotation-switch/SOURCES.json | 18 ++ .../linear-tape-rotation-switch/TASK.json | 89 ++++++ .../linear-tape-rotation-switch/VERIFY.json | 32 ++ .../independent.py | 69 +++++ .../linear-tape-rotation-switch/program.py | 219 ++++++++++++++ .../retained/pr4100/NOTICE.md | 38 +++ .../retained/pr4100/check_batched_crt.py | 265 ++++++++++++++++ .../retained/pr7593/LICENSE | 201 +++++++++++++ .../retained/pr7593/NOTICE.md | 21 ++ .../retained/pr7593/PROOF.md | 268 +++++++++++++++++ .../retained/pr7593/README.md | 61 ++++ .../retained/pr7593/hardware.py | 85 ++++++ .../retained/pr7593/switch.py | 225 ++++++++++++++ .../retained/pr7734/CREDITS.md | 30 ++ .../retained/pr7734/PROOF.md | 158 ++++++++++ .../retained/pr7734/query.py | 50 +++ .../linear-tape-rotation-switch/sources.py | 19 ++ .../linear-tape-rotation-switch/verify.py | 188 ++++++++++++ 24 files changed, 2788 insertions(+) create mode 100644 research/linear-tape-rotation-switch/.gitattributes create mode 100644 research/linear-tape-rotation-switch/CREDITS.md create mode 100644 research/linear-tape-rotation-switch/PROOF.md create mode 100644 research/linear-tape-rotation-switch/README.md create mode 100644 research/linear-tape-rotation-switch/RESULT.json create mode 100644 research/linear-tape-rotation-switch/SOURCE-PINS.json create mode 100644 research/linear-tape-rotation-switch/SOURCES.json create mode 100644 research/linear-tape-rotation-switch/TASK.json create mode 100644 research/linear-tape-rotation-switch/VERIFY.json create mode 100644 research/linear-tape-rotation-switch/independent.py create mode 100644 research/linear-tape-rotation-switch/program.py create mode 100644 research/linear-tape-rotation-switch/retained/pr4100/NOTICE.md create mode 100644 research/linear-tape-rotation-switch/retained/pr4100/check_batched_crt.py create mode 100644 research/linear-tape-rotation-switch/retained/pr7593/LICENSE create mode 100644 research/linear-tape-rotation-switch/retained/pr7593/NOTICE.md create mode 100644 research/linear-tape-rotation-switch/retained/pr7593/PROOF.md create mode 100644 research/linear-tape-rotation-switch/retained/pr7593/README.md create mode 100644 research/linear-tape-rotation-switch/retained/pr7593/hardware.py create mode 100644 research/linear-tape-rotation-switch/retained/pr7593/switch.py create mode 100644 research/linear-tape-rotation-switch/retained/pr7734/CREDITS.md create mode 100644 research/linear-tape-rotation-switch/retained/pr7734/PROOF.md create mode 100644 research/linear-tape-rotation-switch/retained/pr7734/query.py create mode 100644 research/linear-tape-rotation-switch/sources.py create mode 100644 research/linear-tape-rotation-switch/verify.py diff --git a/research/linear-tape-rotation-switch/.gitattributes b/research/linear-tape-rotation-switch/.gitattributes new file mode 100644 index 0000000000..130a3ecaa2 --- /dev/null +++ b/research/linear-tape-rotation-switch/.gitattributes @@ -0,0 +1 @@ +retained/** -text whitespace=cr-at-eol diff --git a/research/linear-tape-rotation-switch/CREDITS.md b/research/linear-tape-rotation-switch/CREDITS.md new file mode 100644 index 0000000000..18d278e967 --- /dev/null +++ b/research/linear-tape-rotation-switch/CREDITS.md @@ -0,0 +1,33 @@ +# Credit and source boundaries + +Prepared by Ali Romman with substantial OpenAI Codex assistance in research, +implementation, verification and writing. New work is Apache-2.0. + +- Jerry Chen supplied the physical ABI, builder primitives, primary hardware + and quadratic graph in [PR #7593](https://github.com/CrocSwap/integer-mult-bounds/pull/7593). + The [program source](https://github.com/CubeJerry/integer-mult-bounds/blob/56335a406469fad85e88ff72820d506d8bea6f63/research/literal-canonical-rotation-switch/switch.py), + [hardware](https://github.com/CubeJerry/integer-mult-bounds/blob/56335a406469fad85e88ff72820d506d8bea6f63/research/literal-canonical-rotation-switch/hardware.py) + and [proof](https://github.com/CubeJerry/integer-mult-bounds/blob/56335a406469fad85e88ff72820d506d8bea6f63/research/literal-canonical-rotation-switch/PROOF.md) + are retained unchanged. Initialization in the new emitter adapts this + source. Its Builder and cleanup are called without mutation. The old + complete graph is replayed on the same 544 service fixtures. +- Ali Romman's [PR #7734](https://github.com/CrocSwap/integer-mult-bounds/pull/7734) + supplied the [closed descent proof](https://github.com/aliromman/integer-mult-bounds/blob/57bb6efed1be1dda9eb1a0f622ec2773bc8b0047/research/rotation-switch-closed-descent/PROOF.md) + and [arithmetic oracle](https://github.com/aliromman/integer-mult-bounds/blob/57bb6efed1be1dda9eb1a0f622ec2773bc8b0047/research/rotation-switch-closed-descent/query.py). + Nick Petalas's [PR #7504](https://github.com/CrocSwap/integer-mult-bounds/pull/7504) + supplied the endpoint and child formulas. These are predecessor results. +- Cinna Davis's [PR #4100](https://github.com/CrocSwap/integer-mult-bounds/pull/4100) + supplied the [canonical network compiler](https://github.com/CrocSwap/integer-mult-bounds/blob/337d04939571a637aeab54a0f58f54fde811663a/research/unconditional-batched-crt/check_batched_crt.py). + Its unchanged finite function supplies expected table bits. Its full + unconditional claim is not an accepted premise here. + +The new contribution is the physical closed-descent program, canonical +countdown and carry-scan lowering, linear complete service bill, and +separate sparse instruction interpretation. No predecessor formula or +physical ABI is claimed anew. Shared code and mathematical premises are +explicit; separate interpretation is not independent human acceptance. + +`SOURCE-PINS.json` records eleven retained files. The source notices and +license are unchanged, including ToikY, JoyboyBrian, Douglas Colkitt and +their predecessor lineages. `SOURCES.json` binds only base provenance. +No unmerged ancestry or full historical replay is asserted. diff --git a/research/linear-tape-rotation-switch/PROOF.md b/research/linear-tape-rotation-switch/PROOF.md new file mode 100644 index 0000000000..f17652c50b --- /dev/null +++ b/research/linear-tape-rotation-switch/PROOF.md @@ -0,0 +1,265 @@ +# A linear-transition physical switch query + +## 1. Result and dependencies + +One fixed graph with 3,237 instruction locations and fourteen tapes computes +the canonical padded-rotation switch at every legal `(h,s,a,j,x)`. On the +unchanged PR7593 entry contract it returns one owned Boolean, preserves five +borrowed descriptors, clears eight private bodies and their temporary guards, +and returns every head. Its successful bounds are + +```text +T <= 1024(h+4), +K_after <= K_entry + 16(h+4). +``` + +`T` counts every read, write, unit move, jump and halt. `K` counts historical +visited cells; clearing does not release history. The new time bound is +linear in `h`. The earlier graph's published bound is `1024(h+3)^2`. +This comparison concerns the supplied query service. It is not a full CRT +caller bound, a measured runtime speedup, a new kappa, or a selected-frontier +change. The word "linear" includes validation, preparation and cleanup. + +Jerry Chen's PR7593 supplies the physical ABI, unchanged builder primitives, +primary interpreter and cleanup routine. Nick Petalas supplies the endpoint +and child formulas through PR7504. Ali Romman's PR7734 supplies the closed +descent and bit-probe lower bound. Cinna Davis's PR4100 compiler defines the +finite canonical-table oracle. See `CREDITS.md` and `SOURCE-PINS.json`. + +The new graph digest, with the retained compact sorted-JSON convention, is +`530e83add1f22dcbb2b207e7ede64b2cecc44cce71db5fb26706ce18b842f92c`. +The optional mutation argument emits separate control graphs. It is never +a runtime input. No input integer reaches a generated instruction operand. + +## 2. Entry and return contract + +The fixed alphabet is `0,1,B,L,E`, encoded by `0,1,2,3,4`. `B` is blank, +`L` is the left marker and `E` is a private end marker. Put `W=h+1`. + +| Tapes | Entry state | +| --- | --- | +| 0 | Borrowed positive canonical LSB-first binary `h`, then blank | +| 1..4 | Borrowed `s,a,j,x`, each exactly `W` LSB-first bits, then blank | +| 5 | Owned output body and its next cell blank | +| 6..13 | Disjoint private windows, blank through relative position `h+2` | + +Every head starts at its own first body cell. Origins can differ. Tapes 0..5 +have a permanent `L` immediately before the body. That cell is initially +blank on tapes 6..13; the graph installs and later erases their guards. +The supplied windows and distinct owners are preconditions. No row-label +count is treated as free physical storage. Opaque exteriors are not used. +Input bodies have no interior `L` markers. + +The legal numeric domain is `h>=1`, `1<=s<=2^h`, `0<=a empty zero`. + +The graph uses at most `12(k+1)` transitions for this operation. A sequence +from `n` to zero costs less than `24n`, because + +```text +sum_(v=1)^n (v2(v)+1) + = n + sum_(r>=1) floor(n/2^r) < 2n. +``` + +This bound includes head returns. It does not charge a full-width zero scan +at every step. `compact` converts a supplied padded private word to this +representation: scan to its end, erase high zero digits, put the new end +after the highest one, and return. Zero receives an end at the origin. +Every cell removed from the representation is cleared. + +The graph copies and validates `h`, then uses the canonical countdown to +produce `W` unary guide cells. This takes linear work even though the height +is supplied in binary. The guide initializes six `W`-bit numeric records +and validates/copies the four padded descriptors. The retained binary +primitives compute `R=2h-2`, create `2^h` by setting the high temporary bit, +and perform all domain comparisons. The borrowed originals remain intact. + +## 4. A single pair of carry scans + +After validation, the graph computes `b=s-a` and `r=2h-2-j`. A comparison +between `j` and `r` selects one of three fixed control branches: + +```text +jr: last endpoint, d=r. +``` + +The chosen `d` is compacted on the private `J` tape. There is no runtime +recursive call or child-descent loop. The two data scans have this invariant: + +- Before low-digit step `i=2` bits. The wire head already selects the suffix +`y=x>>d`; copy it to a spare private record. Form `S=A_d+B_d` with one +equal-width addition. These are literal scans, not variable shifts or +unit-cost integer operations. + +The earlier full-width data beyond a shortened end remain allocated until +cleanup. They have no role in arithmetic. They contain only digits or old +end markers, with no blank gap before the original frontier. Cleanup thus +erases them as well. Compacted counters are different: their shortened +tails are already blank. This establishes the cleanup precondition in both +cases; it does not discard hidden storage. + +## 5. Canonical answer and restoration + +PR7734 proves that the pair in Section 4 is the exact unreduced interval +pair after `d` source child steps. If either quotient is zero, the whole +child is identity. The graph tests both and returns zero. At the center, +both positive quotients must be one, so the one-row switch is one. + +Otherwise the first-endpoint graph returns + +```text +[S and A_d are odd] [floor(y/2)=floor(S/2)]. +``` + +The last-endpoint graph returns + +```text +[A_d is odd] [y= 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/linear-tape-rotation-switch/retained/pr7593/LICENSE b/research/linear-tape-rotation-switch/retained/pr7593/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/research/linear-tape-rotation-switch/retained/pr7593/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/linear-tape-rotation-switch/retained/pr7593/NOTICE.md b/research/linear-tape-rotation-switch/retained/pr7593/NOTICE.md new file mode 100644 index 0000000000..86f6b001dc --- /dev/null +++ b/research/linear-tape-rotation-switch/retained/pr7593/NOTICE.md @@ -0,0 +1,21 @@ +# Attribution and scope + +Prepared for Jerry Chen / @CubeJerry with substantial OpenAI assistance. +Apache-2.0. No independent human or formal-kernel acceptance is claimed. + +Nick Petalas, CrocSwap/integer-mult-bounds#7504 at +4eece58f5cebdb70a92d65447974f1c02383f60b, supplied the direct canonical +padded-rotation predicate, endpoint formulas and exact child closure. +His unmodified proof, source manifest and evaluator are retained. These +mathematical results and arithmetic complexity are credited prior work. + +Cinna Davis / 1337isnot1337 #4100 supplied the original deterministic Beneš +compiler and padded rotation. Its canonical check_batched_crt.py and NOTICE +remain unmodified. ToikY #4192 supplied generic arena lowering; JoyboyBrian +#5092/#5496 and successors supplied the encoded ROM/current-row context. +#7388's live CRT caller and #7390's sort fusion remain separate work. + +The new contribution is the2096-location,14-tape graph, its format/domain +validation, owned-Boolean/cleanup/guard contracts, complete scan costs and +historical-backing bound. No predecessor formula is claimed anew. No full +caller or selected assumption is discharged and no new kappa is claimed. diff --git a/research/linear-tape-rotation-switch/retained/pr7593/PROOF.md b/research/linear-tape-rotation-switch/retained/pr7593/PROOF.md new file mode 100644 index 0000000000..b886214a59 --- /dev/null +++ b/research/linear-tape-rotation-switch/retained/pr7593/PROOF.md @@ -0,0 +1,268 @@ +# A literal canonical padded-rotation switch predicate + +## 1. Claim, source and credited arithmetic + +Canonical base: e54523517d0f03e58352e647c403a5af3e525a57. Nick Petalas's +[#7504](https://github.com/CrocSwap/integer-mult-bounds/pull/7504), exact head +4eece58f5cebdb70a92d65447974f1c02383f60b, proves the arithmetic formulas and +child closure for Cinna Davis's #4100 canonical Beneš compiler. Its proof +and evaluator are retained byte-for-byte. The canonical compiler SHA256 is +681e2e3d71fa74c8b9b326f3860104fd9d89590a222e26ae6ee718d1fd40ff2e. +Those formulas and their canonical orientation are credited prior results. + +For h>=1, N=2^h, 1<=s<=N, 0<=a0, s<=2^h, aS rejects. The credited child theorem +proves A<=S. Since this branch has prior A>0, S>=2 and the child modulus is +positive. J decreases once, R twice and X is halved. The invariant now holds +at eta-1 and the requested canonical bit is unchanged. At most h loop +entrances occur. This induction proves all-height correctness independently +of finite fixtures. No recursion stack or whole permutation is produced. + +The caller still owes the current-wire payload update between queries. +This predicate does not silently advance x or convert original-token labels. + +## 5. Complete instruction and historical-backing bounds + +Every R/W/M/J/H costs one; labels have no action. For at most W-bit records, +direct counts of the emitted loops give these safe complete bounds: + +| Macro | Instructions including returns | +| --- | ---: | +| Rewind from relative position <=W+1 |3W+6| +| Zero test including destination jump |6W+5| +| Increment/decrement |7W+5| +| Zero a number |7W+4| +| Copy a number and return both heads |11W+7| +| Right shift |9W+2| +| Left shift |7W+5| +| Compare and branch |11W+10| + +For example comparison uses two reads, two moves and one jump per bit, +then two frontier reads, two full rewinds and its destination jump. Right +shift has six transitions per following-bit transfer, plus its first move, +high zero and return. These counts include scanning erased spans to return. + +The canonical height has ell<=h=1<>i)&1 for i in range(width)] + +def fixture(h,s,a,j,x,overrides=None): + if h<0: raise ValueError('fixture h domain') + width=h+1 + bodies=[bits(h,max(1,h.bit_length())),bits(s,width),bits(a,width),bits(j,width),bits(x,width)] + if overrides: + for key,value in overrides.items(): bodies[key]=list(value) + tapes=[Tape(body,origin=3+i%4) for i,body in enumerate(bodies)] + tapes.append(Tape((),origin=4,capacity=1)) + # Capacity includes current blank frontier and guard retirement. + tapes.extend(Tape((),origin=3+i%5,private=True,capacity=max(h+2,len(bodies[0])+1)) for i in range(8)) + return tapes + +def check_return(tapes,before,outcome,expected=None): + if any(t.head!=t.origin for t in tapes): raise ValueError('head return') + for t,old in zip(tapes[:5],before[:5]): + if t.cells!=old or t.writes: raise ValueError('borrowed descriptor changed') + if outcome=='DONE': + old=list(before[5]);old[tapes[5].origin]=expected + if tapes[5].cells!=old or tapes[5].writes!=1: raise ValueError('owned Boolean output') + elif outcome=='REJECT': + if tapes[5].cells!=before[5] or tapes[5].writes: raise ValueError('rejected output modified') + else: raise ValueError('unknown outcome') + for t,old in zip(tapes[6:],before[6:]): + if t.cells!=old: raise ValueError('private capacity or exterior not restored') + if t.guard_writes!=[L,B]: raise ValueError('private guard lifetime') + if any(t.low=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> 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/linear-tape-rotation-switch/sources.py b/research/linear-tape-rotation-switch/sources.py new file mode 100644 index 0000000000..aecd53a532 --- /dev/null +++ b/research/linear-tape-rotation-switch/sources.py @@ -0,0 +1,19 @@ +"""Load only named, byte-pinned predecessor modules. Apache-2.0.""" + +import hashlib +import importlib.util +import json +from pathlib import Path + +PACKAGE = Path(__file__).resolve().parent + + +def load(name, relative): + pins = {row["path"]: row for row in json.loads((PACKAGE / "SOURCE-PINS.json").read_text())} + path = PACKAGE / relative + if hashlib.sha256(path.read_bytes()).hexdigest() != pins[relative]["sha256"]: + raise ValueError("retained module hash") + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module diff --git a/research/linear-tape-rotation-switch/verify.py b/research/linear-tape-rotation-switch/verify.py new file mode 100644 index 0000000000..3631341aec --- /dev/null +++ b/research/linear-tape-rotation-switch/verify.py @@ -0,0 +1,188 @@ +"""Check literal transitions, ownership, controls and source table bits. + +Prepared by Ali Romman with substantial OpenAI Codex assistance. Apache-2.0. +""" + +import argparse +import hashlib +import json +from pathlib import Path + +import independent +from program import compile_query, source +from sources import load + +PACKAGE = Path(__file__).resolve().parent + + +def need(condition, message): + if not condition: + raise ValueError(message) + + +def graph_check(code): + size = len(code) + for ins in code: + kind = ins[0] + need(kind in ('R', 'W', 'M', 'J', 'H'), 'literal instruction alphabet') + if kind in ('R', 'W', 'M'): + need(type(ins[1]) is int and 0 <= ins[1] < 14, 'literal tape role') + if kind == 'R': + need(set(ins[2]) == set(range(5)), 'complete read alphabet') + need(all(type(v) is int and 0 <= v < size for v in ins[2].values()), 'read targets') + elif kind == 'W': + need(type(ins[2]) is int and 0 <= ins[2] < 5, 'literal write') + need(ins[1] >= 5, 'borrowed descriptor write in graph') + elif kind == 'M': + need(type(ins[2]) is int and ins[2] in (-1, 1), 'unit move') + elif kind == 'J': + need(type(ins[1]) is int and 0 <= ins[1] < size, 'jump target') + else: + need(ins[1] in ('DONE', 'REJECT'), 'terminal state') + + +def execute(hw, code, labels, args, expected, overrides=None, outcome='DONE'): + tapes = hw.fixture(*args, overrides=overrides) + before = [t.cells[:] for t in tapes] + limit = 1024 * (args[0] + 4) + separate = independent.run(code, tapes, limit) + need(separate['outcome'] == outcome, 'separate outcome') + independent.check_return(separate, tapes, before, expected) + cpu = hw.CPU(code, tapes, labels) + need(cpu.run(limit) == outcome, 'primary outcome') + span = hw.check_return(tapes, before, outcome, expected) + need(span <= 16 * (args[0] + 4), 'historical span bound') + need(cpu.steps == separate['steps'], 'instruction-count disagreement') + need([t.cells for t in tapes] == separate['cells'], 'interpreter state disagreement') + need([t.head for t in tapes] == separate['heads'], 'interpreter head disagreement') + need([t.low for t in tapes] == separate['low'] and [t.high for t in tapes] == separate['high'], + 'interpreter historical-span disagreement') + return cpu.steps, span + + +def finite_checks(hw, canonical, query, code, labels): + entries = networks = total = 0 + peak = [0, None] + trace = hashlib.sha256() + for h in range(1, 4): + for s in range(1, (1 << h) + 1): + for a in range(s): + layers = canonical.benes(canonical.rotation(1 << h, s, a)) + for j, (_, row) in enumerate(layers): + for x, bit in enumerate(row): + args = h, s, a, j, x + need(query.switch_bit(*args) == bit, 'arithmetic versus canonical') + steps, span = execute(hw, code, labels, args, bit) + trace.update(json.dumps([list(args), bit, steps, span]).encode()) + total += steps; entries += 1 + if steps > peak[0]: peak = [steps, list(args)] + networks += 1 + old_code, old_labels = source.compile_query() + row_total = old_total = row_peak = 0 + row_bits = [] + for a in range(17): + row = canonical.benes(canonical.rotation(32, 17, a))[6][1] + for x, bit in enumerate(row): + args = 5, 17, a, 6, x + steps, _ = execute(hw, code, labels, args, bit) + row_total += steps; row_peak = max(row_peak, steps); row_bits.append(bit) + tapes = hw.fixture(*args); before = [t.cells[:] for t in tapes] + cpu = hw.CPU(old_code, tapes, old_labels) + need(cpu.run(1024 * 8**2) == 'DONE', 'retained physical query') + hw.check_return(tapes, before, 'DONE', bit); old_total += cpu.steps + need(old_total == 1473152, 'retained 544-query service count') + return {'complete_networks': networks, 'canonical_entries_per_interpreter': entries, + 'small_primary_transitions': total, 'small_peak': peak, + 'small_trace_sha256': trace.hexdigest(), 'historical_row_queries': len(row_bits), + 'historical_row_new_transitions': row_total, 'historical_row_old_transitions': old_total, + 'historical_row_new_peak': row_peak, + 'historical_row_bits_sha256': hashlib.sha256(bytes(row_bits)).hexdigest()} + + +def wide_checks(hw, query, code, labels): + rows = [] + for h in (7, 17, 65, 129, 513, 1025, 4096): + n = 1 << h + cases = [(n, n//2, h-1, 0), (n-1, 1, 0, n-1), + (n-1, n//2, 2*h-2, n//2+1), (n-1, n//2-1, h, n//3), + (n, n-1, h//2, n-1), (n-1, 0, h-1, n-1)] + for s, a, j, x in cases: + steps, span = execute(hw, code, labels, (h, s, a, j, x), + query.switch_bit(h, s, a, j, x)) + rows.append({'height': h, 'row': j, 'steps': steps, 'span': span}) + return rows + + +def controls(hw, query, code, labels): + bad = [((0, 0, 0, 0, 0), None), ((2, 0, 0, 0, 0), None), + ((2, 5, 0, 0, 0), None), ((2, 3, 3, 0, 0), None), + ((2, 3, 0, 3, 0), None), ((2, 3, 0, 0, 4), None), + ((2, 3, 0, 0, 0), {0: []}), ((2, 3, 0, 0, 0), {0: [0]}), + ((2, 3, 0, 0, 0), {0: [0, 1, 0]}), + ((2, 3, 0, 0, 0), {1: [1, 1]}), + ((2, 3, 0, 0, 0), {2: [0, 0, 0, 0]}), + ((2, 3, 0, 0, 0), {3: [0, 4, 0]}), + ((2, 3, 0, 0, 0), {4: [0, 2, 0]})] + for args, override in bad: + execute(hw, code, labels, args, None, overrides=override, outcome='REJECT') + witnesses = {'wrong_complement': (2, 2, 1, 1, 1), + 'lost_carry': (2, 3, 1, 1, 1), + 'lost_identity': (2, 2, 1, 1, 1)} + for name, args in witnesses.items(): + changed, positions = compile_query(name) + try: + execute(hw, changed, positions, args, query.switch_bit(*args)) + except ValueError as exc: + need('owner state' in str(exc), 'semantic mutation failed for wrong reason') + else: + raise ValueError('undetected semantic graph mutation') + changed = list(code) + index = next(i for i in range(labels['success'], len(code)) if code[i] == ('W', 6, 2)) + changed[index] = ('W', 6, 0) + try: + execute(hw, tuple(changed), labels, (2, 3, 1, 1, 1), 1) + except ValueError as exc: + need('owner state' in str(exc), 'retirement control failed for wrong reason') + else: + raise ValueError('uncleared private body accepted') + tapes = hw.fixture(2, 3, 1, 1, 1); tapes[7] = tapes[6] + for constructor in (lambda: hw.CPU(code, tapes, labels), + lambda: independent.run(code, tapes, 10000)): + try: + constructor() + except ValueError: + continue + raise ValueError('aliased owners accepted') + return {'domain_rejections_per_interpreter': len(bad), 'semantic_graph_mutants': 3, + 'retirement_mutants': 1, 'alias_rejections': 2} + + +def calculate(): + for row in json.loads((PACKAGE / 'SOURCE-PINS.json').read_text()): + need(hashlib.sha256((PACKAGE / row['path']).read_bytes()).hexdigest() == row['sha256'], + 'retained source hash') + hw = load('physical_source_hardware', 'retained/pr7593/hardware.py') + query = load('closed_query_reference', 'retained/pr7734/query.py') + canonical = load('canonical_network_reference', 'retained/pr4100/check_batched_crt.py') + code, labels = compile_query(); graph_check(code) + result = {'instructions': len(code), 'graph_sha256': source.digest(code), 'tapes': 14, + 'transition_bound': '1024*(h+4)', 'historical_span_bound': '16*(h+4)'} + result.update(finite_checks(hw, canonical, query, code, labels)) + result['wide_queries'] = wide_checks(hw, query, code, labels) + result.update(controls(hw, query, code, labels)) + 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: + need(result == json.loads((PACKAGE / 'RESULT.json').read_text()), 'result mismatch') + print('PASS_LINEAR_TAPE_ROTATION_SWITCH 14 tapes; 1024*(h+4) transitions') + + +if __name__ == '__main__': + main()