selection.py

Checks: REDUNDANT: The selection estimate known; property; rule; observation.

Cited on: REDUNDANT.

To run it: save selection.py; standard library only.

"""selection.py -- which selection estimate reads the merged
multiply-add at its floor c = 0, where its cell is an equality of the
margin law?

QUESTION. The merged multiply-add (arXiv:2606.25562) reads S = sum of
T = 32 products w_i a_i, the activations serial bit streams {0, 1}
MSB first, the weights parallel q = 8-bit (read as two's complement
fractions in [-1, 1 - 2^(1-q)]; the paper says "8-bit"), and writes radix 2 on E = {-1, 0, 1}. The margin
law over two sets prices it at Lam = 32, |I| = 1, rho_E = 1: L* = 5,
lead o = 5, c* = 0, an equality (2^5 * 1 = 32), against its stated
delta = 2 (its latency formula gives 28 beside a stated 26, which delta
= 0 would give; its source is closed). The
estimate's cost at an equality is proved where the residual gains a
digit of precision each step; this residual stays on a finite lattice.
Which estimate, of how many bits, reaches c = 0, and which c = 1?

BY HAND (before any engine code). Units u_t = 2^(o-t) at output level
t, read after n = t + c digits of every stream. The box of n-digit
prefixes has image [lo_n, lo_n + |w|_1 2^(-n)], of width W = (|w|_1/T)
2^(-c) in units u_t; the tile of the committed value p is [p - 1,
p + 1] (N = g/(b - 1) = 1). The state y = lo_n/u_t - p must stay in
[-1, 1 - W]; s = 1 - W is the SLACK.
  (a) THE RECURRENCE. y' = z - e, z = 2y + delta, e in E, delta =
  2^(-c) A/T, A a subset sum of the |w_i| (each channel adds w_i a_i
  if w_i > 0, |w_i|(1 - a_i) if w_i < 0), so delta in [0, W]. Start
  t = 0, p = 0, y_0 = lo_c/2^o, inside [-1, 1 - W] since the range
  is [-T, T(1 - 2^(1-q))].
  (b) THE RULE. e = clamp(floor(zh) + 1, -1, 1) on an estimate zh <= z.
  y' <= 1 - W iff z - floor(zh) <= 2 - W (unclamped), and y' >= -1 iff
  floor(zh) <= z. EXACT (zh = z): z - floor(z) < 1 <= 2 - W, alive at
  every W <= 1, so c = 0 is read at every weight vector. The rule
  reads only z's integer part, {-2, -1, 0, 1}, but that part carries
  out of all of z's bits: z lies on the grid g = 2^(1-q-c)/T, so
  EXACT reads 2 + (q - 1 + o + c) bits through a carry chain: 14 at
  the cell, c = 0.
  (c) TWO WORDS. z = z_s + z_c, each truncated to m fractional bits,
  the split the adversary's: z - zh in [0, 2^(1-m) - 2g], zh on the
  2^(-m) grid. With z = k + r, r its fractional part, zh can reach
  k - 2^(-m) iff r <= 2^(-m) - 2g, and then z - floor(zh) = 1 + r. So
  the rule fails iff some reachable z, k in {-1, 0, 1}, has s < r <=
  2^(-m) - 2g (k = -2 is saved by the clamp). SUFFICIENT: 2^(-m) - 2g
  <= s. At c = 0, s = (T - |w|_1)/T is a multiple of g, zero only at
  all weights -1, where z lies on 2^(-o) and m >= o suffices (the
  words stay on the datapath's grid g); else s >= g and m >= q + o - 2
  suffices (2^(-m) <= 3g), so the least m is at most q + o - 2 at every
  vector when q >= 2. NECESSARY
  at m = q + o - 3 iff the WITNESS, a vector with s = g (T - 1
  weights -1 and one 1 - 2^(1-q)), reaches some z, k in {-1, 0, 1},
  with r = 2g. At c = 1, s >= 1/2 and m >= 1 suffices. The estimate's
  bits B = 3 + m (zh in [-2 - 2^(1-m), 2)): at the cell 14 at c = 0,
  4 at c = 1.
  (d) c = -1 is dead: at all weights -1, W = 2 > 1 at the root box
  (the many-stream hand witness, at another vector). [False as a
  kill: W = 2 pins y = -1 and dies only off the tile grid; FINDINGS.]

THE BAR: an estimate of at most 16 bits reading the cell below the
stated lookahead (c < 2) makes the floor's digits buildable; none
leaves them unbuilt.

FAMILY. The game (b) and (c) solved exactly, every reachable state on
its grid, every delta, every allowed zh: small cells T in {2, 4},
q in {2, 3, 4} and T = 8, q in {2, 3}, every multiset of weights,
c in {-1, 0, 1}; m from 0 up. At the cell (T = 32, q = 8) the
witness alone, c = 0 and 1, sufficiency being (c)'s proof at every
vector.

CONTROLS (read before any verdict).
  LAW: at every small cell EXACT dies at c = -1 (the theorem's floor;
  a known answer, by (d)). [Changed after the run to the cell's hand
  witness; FINDINGS.]
  PLANT-RULE: e = clamp(floor(z), -1, 1), the +1 dropped, dies at
  c = 0 under EXACT at some multiset of every small cell.
  SPLITS: two_words's allowed estimates are exactly the sums of the
  two truncated words over every split Z = Z_s + Z_c on the grid, at
  every residual Z of a period and every truncation unit U to 2^6.
  The cell's c = 1 reading uses U to 2^13, past the control's reach,
  where the set is right by hand: {Z - r, Z - r - U}, r = Z mod U,
  the second iff r <= U - 2.
  BIT-TRUE: the cell's unit run on integers, 200 random weight vectors
  and activations (seeded) plus the witness and all -1, EXACT at
  c = 0: every y in [-1, 1 - W], and the committed digits' value
  within one unit of the last level of the exact dot product.

KILL (frozen; what the script PRINTS): "SELECTION: at the cell c = 0
by EXACT (B_x bits) and by two words at m >= M (B bits), dead at
M - 1 at the witness; c = 1 at m >= M1 (B1 bits)", then "c < 2
within 16 bits: False" iff min(B_x, B) > 16 and B1 > 16.
Beside it, the small cells' least m at c = 0 and 1 against (c).

PREDICTIONS. EXACT alive at c = 0 everywhere (strongly: (b)). The
least m at c = 0 equals q + o - 2 at every small cell (sufficiency
strongly; necessity, the witness reaching r = 2g, moderately), and 1
at c = 1 (moderately). At the cell M = 11, B = 14, B_x = 14, M1 = 1,
B1 = 4: c < 2 within 16 bits.

FINDINGS (entered after each run; every number is a print).
  CHANGED AFTER THE FREEZE, named: the LAW control's premise (d) was a
  TRANSPLANT from the curved case. At (T, q) = (2, 2) every one of the
  10 multisets reads at c = -1 under EXACT. A vector's own width W =
  2|w|_1/T at c = -1 decides most of it: at W <= 1, (b) reads it, and
  no such vector dies at any small cell; the deaths all lie among the
  W > 1 vectors, of which some read at c = -1 at every cell, the
  affine discount per vector (only all -1 at (2, 2) by increments on
  the tile grid: K = 2, Delta in {0, 2, 4}). By (T, q, dead, W > 1,
  W > 1 alive): "[(2, 2, 0, 3, 3), (2, 3, 5, 14, 9), (2, 4, 37, 60,
  23), (4, 2, 6, 13, 7), (4, 3, 93, 142, 49), (4, 4, 1455, 1790, 335),
  (8, 2, 49, 70, 21), (8, 3, 2387, 2942, 555)]". At (2, 2) the family
  reads one digit under the law's c* = 0. LAW now reads the cell's
  hand witness (127/128 at 20 channels, -1 at 12), whose kill
  composite.py prints.
  CONTROLS  LAW PASS; PLANT-RULE PASS ("missed at []"); SPLITS PASS
  (a scratch copy allowing 2U - 1 of truncation: 28 mismatches);
  BIT-TRUE PASS ("0 of 202 vectors").
  SMALL CELLS: "EXACT alive at c = 0 at every small cell: True"; "least
  m at c = 0 equal to q + o - 2 at 8 of 8 small cells; least m at c = 1
  equal to 1 at 8 of 8" (m0 = 1, 2, 3, 2, 3, 4, 3, 4 in SMALL's order).
  THE CELL: "EXACT at c = 0 (witness, all -1): True; at c = -1 any
  alive: False"; two words at c = 0 at the witness "{9: False, 10:
  False, 11: True, 12: True}"; at c = 1, witness and all -1, "{0:
  False, 1: True, 2: True}".
  KILL: "SELECTION: at the cell c = 0 by EXACT (14 bits) and by two
  words at m >= 11 (14 bits), dead at M - 1 at the witness: True; c = 1
  at m >= 1 (4 bits)": c < 2 within 16 bits. PREDICTIONS: every
  one held. The two-word floor at the cell is (c)'s proof at every
  vector beside the witness's game; the small cells read every
  multiset. The estimate model is the adversary's split of two words
  on the datapath grid, a bound on a real carry-save residual, not one.
  4/4 checks, 3.5 s, 14.8 MB peak commit.

RUN: python selection.py.
"""
import itertools
import os
import random
import sys
import time
from fractions import Fraction as Fr

os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
CHECKS = []


def check(name, ok, detail=""):
    CHECKS.append(bool(ok))
    tail = f"  ({detail})" if detail else ""
    print(f"  {'PASS' if ok else 'FAIL'}  {name}{tail}", flush=True)


def subset_sums(mags):
    s = {0}
    for x in mags:
        if x:
            s |= {y + x for y in s}
    return sorted(s)


def exact(Z, K):
    return [Z]


def two_words(m, o, q, c):
    """Allowed estimates of Z (units of the grid g): multiples of
    U = 2^(o + q - 1 + c - m) in [Z - (2U - 2), Z]; U = 1 is exact."""
    U = 2 ** max(o + q - 1 + c - m, 0)

    def est(Z, K):
        top = Z - Z % U
        return list(range(top, Z - (2 * U - 2) - 1, -U))
    return est


def splits(top=6):
    """Every truncation unit U = 2^u, u <= top: the set two_words
    allows at Z equals {floor(Zs/U) U + floor((Z - Zs)/U) U} over every
    split, Z over two periods either side of 0. The count of mismatches."""
    bad = 0
    for u in range(top + 1):
        U = 2 ** u
        est = two_words(0, u, 1, 0)
        for Z in range(-2 * U, 2 * U):
            real = {(Zs // U) * U + ((Z - Zs) // U) * U
                    for Zs in range(Z - 2 * U, Z + 2 * U)}
            bad += set(est(Z, 1)) != real
    return bad


def rule(ZH, K):
    return max(-1, min(1, ZH // K + 1))


def plant_rule(ZH, K):
    return max(-1, min(1, ZH // K))


def game(v, T, q, c, est, sel=rule):
    """Solve the reader's game at lookahead c for integer weights v
    (w = v / 2^(q-1)): True iff every reachable state stays in
    [-K, K - V]. Units: the grid g = 1/K, K = T 2^(q - 1 + c)."""
    K = T * 2 ** (q - 1 + c)
    V = sum(abs(x) for x in v)
    if V > 2 * K:
        return False
    sub = subset_sums([abs(x) for x in v])
    neg = sum(-x for x in v if x < 0)
    if c == -1:
        Zs = {-neg}
    else:
        Ys = {-neg}
        for _ in range(c):
            Ys = {2 * y + d for y in Ys for d in sub}
        Zs = {2 * y + d for y in Ys for d in sub}
    seen = set()
    while Zs:
        new = set()
        for Z in Zs:
            for ZH in est(Z, K):
                Y = Z - sel(ZH, K) * K
                if not (-K <= Y <= K - V):
                    return False
                if Y not in seen:
                    seen.add(Y)
                    new.add(Y)
        Zs = {2 * y + d for y in new for d in sub}
    return True


def multisets(T, q):
    lo, hi = -2 ** (q - 1), 2 ** (q - 1) - 1
    return itertools.combinations_with_replacement(range(lo, hi + 1), T)


def least_m(T, q, c, vectors):
    o = T.bit_length() - 1
    for m in range(0, o + q + c + 1):
        est = two_words(m, o, q, c)
        if all(game(v, T, q, c, est) for v in vectors):
            return m
    return None


SMALL = [(2, 2), (2, 3), (2, 4), (4, 2), (4, 3), (4, 4), (8, 2), (8, 3)]


def small_cells():
    print("SMALL CELLS  every multiset of weights, c = -1, 0, 1")
    law_bad, plant_missed, exact_bad, rows = [], [], [], []
    for T, q in SMALL:
        o = T.bit_length() - 1
        vs = list(multisets(T, q))
        K1 = T * 2 ** (q - 2)
        wide = [v for v in vs if sum(map(abs, v)) > K1]
        law_bad.append((T, q, sum(not game(v, T, q, -1, exact)
                                  for v in vs), len(wide),
                        sum(game(v, T, q, -1, exact) for v in wide)))
        if all(game(v, T, q, 0, exact, plant_rule) for v in vs):
            plant_missed.append((T, q))
        if not all(game(v, T, q, 0, exact) for v in vs):
            exact_bad.append((T, q))
        m0, m1 = least_m(T, q, 0, vs), least_m(T, q, 1, vs)
        rows.append((T, q, o, len(vs), m0, m1))
        print(f"    T = {T}, q = {q}, o = {o}: {len(vs)} multisets; least "
              f"m at c = 0: {m0} (q + o - 2 = {q + o - 2}), at c = 1: {m1}",
              flush=True)
    return law_bad, plant_missed, exact_bad, rows


def bit_true(T=32, q=8, n_rand=200, steps=21, seed=1):
    """The cell's unit on integers at c = 0, EXACT: every state in
    range and the committed value within 2^(o - steps) of the exact
    dot product."""
    o = T.bit_length() - 1
    K = T * 2 ** (q - 1)
    rng = random.Random(seed)
    lo, hi = -2 ** (q - 1), 2 ** (q - 1) - 1
    vecs = [[lo] * T, [lo] * (T - 1) + [hi]]
    vecs += [[rng.randint(lo, hi) for _ in range(T)] for _ in range(n_rand)]
    bad = 0
    for v in vecs:
        acts = [rng.randrange(256) for _ in range(T)]
        bits = [[(a >> (7 - j)) & 1 if j < 8 else 0 for j in range(steps)]
                for a in acts]
        V = sum(abs(x) for x in v)
        Y = -sum(-x for x in v if x < 0)
        P = Fr(0)
        for t in range(1, steps + 1):
            D = sum(x * bits[i][t - 1] if x > 0 else -x * (1 - bits[i][t - 1])
                    for i, x in enumerate(v))
            Z = 2 * Y + D
            e = rule(Z, K)
            Y = Z - e * K
            P += e * Fr(2) ** (o - t)
            if not (-K <= Y <= K - V):
                bad += 1
                break
        dot = sum(Fr(x, 2 ** (q - 1)) * Fr(a, 256) for x, a in zip(v, acts))
        if abs(dot - P) > Fr(2) ** (o - steps):
            bad += 1
    return len(vecs), bad


def cell():
    print("THE CELL  T = 32, q = 8 (o = 5)")
    T, q, o = 32, 8, 5
    wit = [-128] * 31 + [127]
    neg = [-128] * 32
    ex0 = game(wit, T, q, 0, exact) and game(neg, T, q, 0, exact)
    exm = game(wit, T, q, -1, exact) or game(neg, T, q, -1, exact)
    alive = {}
    for m in (q + o - 4, q + o - 3, q + o - 2, q + o - 1):
        alive[m] = game(wit, T, q, 0, two_words(m, o, q, 0))
    M = min((m for m, a in alive.items() if a and all(
        alive[k] for k in alive if k > m)), default=None)
    a1 = {m: (game(wit, T, q, 1, two_words(m, o, q, 1))
              and game(neg, T, q, 1, two_words(m, o, q, 1)))
          for m in (0, 1, 2)}
    M1 = min((m for m, a in a1.items() if a), default=None)
    print(f"    EXACT at c = 0 (witness, all -1): {ex0}; at c = -1 any "
          f"alive: {exm}")
    print(f"    two words at c = 0, witness, alive by m: {alive}")
    print(f"    two words at c = 1, witness and all -1, alive by m: {a1}")
    Bx = 2 + (q - 1 + o)
    B = 3 + M if M is not None else None
    B1 = 3 + M1 if M1 is not None else None
    dead = M is not None and not alive.get(M - 1, True)
    print(f"\nSELECTION: at the cell c = 0 by EXACT ({Bx} bits) and by two "
          f"words at m >= {M} ({B} bits), dead at M - 1 at the witness: "
          f"{dead}; c = 1 at m >= {M1} ({B1} bits)")
    none = (not ex0 or Bx > 16) and (B is None or B > 16) and (
        B1 is None or B1 > 16)
    print(f"  c < 2 within 16 bits: {not none}")
    return ex0, exm, M, dead, M1


if __name__ == "__main__":
    t0 = time.time()
    print("CONTROLS")
    law_bad, plant_missed, exact_bad, rows = small_cells()
    hw = [127] * 20 + [-128] * 12
    check("LAW: EXACT dies at c = -1 at the cell's hand witness (weights "
          "127/128 at 20 channels, -1 at 12)", not game(hw, 32, 8, -1, exact))
    check("PLANT-RULE: floor(z) without the +1 dies at c = 0 at every "
          "small cell", not plant_missed, f"missed at {plant_missed}")
    check("SPLITS: two words' allowed estimates are every split's sum of "
          "truncations, U = 1 to 64", splits() == 0)
    n, bad = bit_true()
    check("BIT-TRUE: the cell's unit at c = 0, EXACT, in range and within "
          "one last-level unit of the dot product", bad == 0,
          f"{bad} of {n} vectors")
    if not all(CHECKS):
        print("CONTROL FAILED: nothing below is read.")
        sys.exit(1)
    print(f"  EXACT alive at c = 0 at every small cell: {not exact_bad} "
          f"{exact_bad}")
    print(f"  at c = -1 under EXACT, by (T, q, dead, W > 1, W > 1 alive): "
          f"{law_bad}")
    hit = sum(m0 == q + o - 2 for T, q, o, _, m0, _ in rows)
    one = sum(m1 == 1 for *_, m1 in rows)
    print(f"  least m at c = 0 equal to q + o - 2 at {hit} of {len(rows)} "
          f"small cells; least m at c = 1 equal to 1 at {one} of "
          f"{len(rows)}")
    cell()
    print(f"\n{sum(CHECKS)}/{len(CHECKS)} checks, {time.time() - t0:.1f} s")