composite.py

Checks: REDUNDANT: The many-stream theorem theorem; rule; observation; REDUNDANT: The pole units theorem; rule.

Cited on: REDUNDANT.

To run it: save composite.py, with manystream.py, redundant.py beside it; standard library only.

"""
composite.py -- does the many-stream law price a composite unit whose
output digit set is wider than its input's, and do the published
composites sit at that floor?

QUESTION. The many-stream theorem reads a C^2 map of k streams of
D = {-a-, ..., a+} in radix b, writing its output in D too. The
published composites (a x + b at delay 1, x^2 + y^2 + z^2 at delay 0,
a merged multiply-add at delay 2) write an output set E = {-g-, ...,
g+} wider than D, g >= b. (A) Does the law carry to two sets, and is
it exact there? (B) Priced by it at their own cells and ranges, how
many of the three published delays sit at the floor, how many above?

BY HAND (before any engine code). Write |I| = a- + a+, M+- = a+-/(b-1),
w = M- + M+ for the input; rho_E = g- + g+ + 1 - b >= 1, N+- =
g+-/(b-1), w_E = N- + N+ for the output.
  (a) THE TILE LEMMA OVER E. In units b^(o-t) the level-t tiles are
  [p - N-, p + N+]; tiles p and p+1 meet in the zone [p + 1 - N-,
  p + N+], of length w_E - 1 = rho_E/(b-1). An interval [lo, hi] lies
  in some tile iff some integer p lies in [hi - N+, lo + N-], which
  fails iff some integer n has lo + N- - 1 < n < hi - N+, iff [lo, hi]
  strictly contains zone n. At g >= b
  zones of tiles two apart overlap too (w_E - 1 >= 1 once g >= b - 1);
  the iff never used their disjointness. The children bQ + e, e in E,
  cover [bQ - g- - N-, bQ + g+ + N+] = b times Q's tile, since
  g + g/(b-1) = bg/(b-1), and a fitting p clamped into [bQ - g-,
  bQ + g+] still fits. (Property, as at E = D.)
  (b) SUFFICIENCY. A box's image is at most Lam w b^(-n) wide, a zone
  (w_E - 1) b^(o-t) long, n = t + c, L = c + o: alive when Lam w <=
  (w_E - 1) b^L, that is

      b^L rho_E >= Lam |I|        (the margin law over two sets).

  (c) NECESSITY. The theorem's argument reads only the zone grid
  (spacing 1, zone length w_E - 1) and an image overshooting a zone:
  an interval of length l in (w_E - 1, w_E] strictly contains a zone at
  the offsets of an arc of positive measure, and at overshoot >= 1 at
  every offset. Equidistribution of the offsets is the inputs', and
  unchanged. So a curved map is dead at L* - 1, L* the least L with
  b^L rho_E >= Lam |I|. (Re-derived, to be read by the scan.)
  (d) THE LEAD. o is the least lead with [-N- b^o, N+ b^o] holding the
  range; the delay is c = L - o. As g grows, L* falls by log_b of
  rho_E and o by log_b of N, and N/rho_E tends to 1/(2(b - 1)) from
  above: over-redundancy buys a bounded number of digits, c tending to
  log_b(Lam |I| / (2 (b-1) R)) up to the two ceilings, R = max |f| on
  the box (symmetric ranges). At (2, 1, 1) the sum of squares on the
  root box, Lam = 6, R = 3: c = 1 at g = 7 to 11, c = 2 at g = 6
  (L* = 1, o = -1) and 12 (L* = 0, o = -2). The delay is not monotone
  in g.
  (e) TRANSPLANT, to re-derive per composite: an operand range
  narrower than D's (|x| < 1/2, say) replaces the root box; sufficiency
  carries with Lam over that box, necessity wants the gradient's peak
  where boxes of prefixes lie inside the range.

FAMILY (the carry, A). Input: the 20 census cells (radices 2 to 5,
1 <= a+- <= b - 1, rho >= 1). Output: the symmetric E with g = b,
b + 1, 2b - 1 and 2b. Maps: the nine of manystream.py (x^2, x^3, x y,
x^2 + y, x y + z, x^2 + x y, x^2 y, x y z, x(1 - y^2)) and x^2 + y^2 +
z^2. Each (map, in-cell, g) scanned at L* - 1 to manystream.py's NMAX
and BUDGET.

CONTROLS (read before any verdict).
  SAME-SET: at E = D the two-set scan's L*, o and kill depth equal
  manystream.py's scan at every census cell for x^2, x y and x y + z.
  ZONE-PLANT: an image one part in b^n wider than a zone at g = 2b
  (w_E - 1 > 1) is a kill, and one exactly a zone wide is not.

KILL (A), frozen: the print "CARRY: N (map, cell, g), dead at L* - 1 at
D, unkilled with the scan emptied at E, past the budget at P". E > 0:
the law over two sets is wrong (the scan emptied means every box was
read alive by the law's own sufficiency bound, so a positive E is a
necessity failure only if the pruning is sound: the law prunes a box
at rate <= Lam_law, the sufficiency side). Unreadable unless every
control passes.

HALF B, frozen after the carry ran and before its code; each cell read
from the full text, each delay in its own convention.
  (f) THE OMA (Tenca and Ercegovac, Proc. SPIE 2914 (1996)): y = a x +
  b, a parallel, x and b serial, 1/2 <= a, x, b < 1; inputs on
  {-(r-1), ..., r-1} (borrow-save), r = 2, 4, 8, 16, 32; output
  {-g, ..., g}, g >= r, its digit floor(z) of z = r W + r^-1(a x_j +
  b_j), W in [0, 1). The sums x[j], b[j] and y[j] all index from weight
  r^0, so its delta = 1 is a weight gap: our L. Lam = 1 + a < 2, the sup
  2 unattained, so the floor over the a's is the least L with r^L rho_E
  >= 2 |I|, |I| = 2(r - 1) (an a near 1 with a fine lattice is dead
  below it: TRANSPLANT from the curved case, the scan read at a =
  255/256). Read at g = r, the least the paper allows, and at the set
  its truncation reaches, z in (-2 + 2/r, r + 2 - 2/r): {-1, ..., 2} at
  r = 2, {-2, ..., r + 1} above. By hand: L* = 1 at every r and both
  sets. Beside it, not counted: the recoded unit (output on the input's
  set, delta + 3 at r = 2, delta + 2 above, p = 0), whose floor is
  L = 2 at r = 2 and 1 above.
  (g) THE SUM OF SQUARES (Ercegovac, DDECS 2020 slides 33 to 35): radix
  2, inputs in [1/2, 1), output s_j in {0, ..., 8}; slide 34's s_(j+1)
  weighs 2^-(j+1) and reads j + 1 digits of each input, so its
  delta = 0 is L, o = 0. The inputs' set is not on the slides; the unit's
  paper (Huang and Ercegovac, FCCM 2001) reads them as bits {0, 1}
  (and prints delta = 1, indexing from digit 0). Lam = 6 (unattained),
  |I| = 1, rho_E = 7: L* = 0. With signed inputs {-1, 0, 1} the law asks
  L = 1, so a published 0 there would be the kill's A + B < 3.
  (h) THE MERGED MULTIPLY-ADD (arXiv:2606.25562, after Gorgin et al.,
  Asilomar 2023): S = sum over 32 channels of w_i a_i, activations
  serial bits {0, 1} MSB first, weights parallel 8-bit (read as two's
  complement fractions, [-1, 127/128]), output radix 2 on {-1, 0, 1},
  21 bits, 5 above the 16 fractional. Its delta = 2 counts the digits
  read before the first output digit, which weighs 2^4: in our terms
  c = 2 at o = 5, L = 7. Lam = 32 (all weights -1), |I| = 1, rho_E = 1:
  L* = 5, c* = 0. Dead at L = 4 by a hand witness: weights 127/128 at
  20 channels and -1 at 12, the root box's image [-12, 19.84] strictly
  holds the level-1 zone [0, 16] (o = 5). Unscanned: 32 streams.

KILL (B), frozen before the run: the print "COMPOSITE: A of 3 published
delays at the law's floor, B above it" (OMA at g = r; the sum of
squares on bit inputs; the merged unit at c), at A + B < 3 or B == 0.
Beside it, the floor's exactness at each: a kill at L* - 1 by the scan
(the OMA at a = 255/256, r = 2, 4, 8; the sum of squares on [0, 1]^3,
its killing box inside [1/2, 1]^3) or the hand witness (the merged
unit).

PREDICTIONS. E == 0 (strongly: (c)). P small, at x y z and x y + z at
radix 2 as at E = D (moderately). The composites (B): two at the floor
and one above, the merged multiply-add a selection digit above (weakly:
the published multipliers sit a digit above theirs). Refined at half B's
freeze, by hand (f) to (h): A = 2, B = 1, the merged unit two digits
above.
FINDINGS (entered after each run; every number is a print).
  (A) CONTROLS  SAME-SET PASS ("0 differ"), ZONE-PLANT PASS (named:
  read at (3, 1, 1), g = 6, widened by 3^-5 at depth 2, not one part in
  b^n).
  KILL (A): "CARRY: 800 (map, cell, g), dead at L* - 1 at 800, unkilled
  with the scan emptied at 0, past the budget at 0": E == 0, the law
  over two sets is exact at every case read. Kill depths {1: 435, 2:
  245, 3: 78, 4: 33, 5: 8, 6: 1}; L* below the lead at 0. PREDICTIONS:
  E == 0 held; P small held (P = 0: no pair ran past the budget).
  5.1 s, 127.7 MB peak commit. Checked since: "CARRY: every (map, cell,
  g) dead at L* - 1, ... (800 of 800)", 790 distinct by hand (b + 1 = 2b - 1
  at b = 2, so gs(2) reads g = 3 twice), and (d)'s lead read at (2, 1, 1),
  x^2 + y^2 + z^2: "c* at g = 6..12 [2, 1, 1, 1, 1, 1, 2]".
  (B) KILL (B): "COMPOSITE: 2 of 3 published delays at the law's floor,
  1 above it": A + B = 3 and B = 1, it MISSES. The OMA: "L* 1 at g = r,
  1 at the truncation's set, published 1" at r = 2, 4, 8, 16, 32; at
  a = 255/256 a kill at L* - 1 on [1/2, 1]^2 (r = 2, 4) and [1/2,
  3/4]^2 (r = 8), output depth 2. Recoded, beside: "L* 2, published 4"
  at r = 2, "L* 1, published 3" above: the recoder's digits, two at
  every r. The sum of squares: "Lam 6, o -1, L* 0", dead at L* - 1 on
  [1/2, 1]^3 at output depth 1; on signed inputs "L* 1; at L* - 1 a
  kill at output depth 1 (55 boxes) inside [1/2, 1]^3", so the
  published 0 needs bit inputs. The merged multiply-add: "Lam 32, o 5,
  L* 5, c* 0, published c 2 (L 7)", the hand witness a kill at L* - 1:
  two digits above the floor at the paper's delta = 2.
  READ AFTER THE RUN. (i) The miss rests on that one
  figure. If arXiv:2606.25562's latency formula, delta + p_out +
  ceil(log2 T_N) with p_out = 21 and T_N = 32, gives its "26 cycles per
  output", then delta = 0, the floor, where B = 0 and the kill fires;
  at its stated delta = 2 the formula gives 28. Other readings stay
  open (a throughput count, a misprint). Read with "delta counts the
  digits read before the first output" excluding the committing step,
  the unit is one digit above, not two. The unit's own paper (Gorgin,
  Golamrezaei, Lee and Ercegovac, Asilomar 2023) is closed access, and
  the citing paper states delta = 2 with no recurrence or indexing, so
  the reading is unsettled; its adder tree is carry-propagate, its
  residual exact, each output digit selected from the top 7 bits of a
  14-bit sum. (ii) The cell is an equality of the law (2^5 * 1 = 32).
  Whether an estimate costs a digit there is open: the estimate's cost
  is proved for the multiplier, whose residual gains a digit of
  precision each step; this residual stays on a finite lattice (8-bit
  weights against bits), so an exact estimate of finitely many bits
  may reach c = 0. (iii) Changed from the first freeze, named: it
  priced a x + b at the affine criterion's floor; (f) prices the OMA
  at Lam's sup over its range
  of a, the two agreeing over the range by the kill at a = 255/256
  (read at r = 2, 4, 8, g = r).
  (iv) The scans read the OMA at r = 2, 4, 8 at g = r alone; the
  recoded floors and the merged unit's are the law's, one hand witness
  beside. Half B's cells sit outside the carry's family (bit inputs,
  g = 1, the asymmetric {0, ..., 8}): exactness there is the per-unit
  kill's, the law over E elsewhere (c)'s argument, read by the carry
  over its family alone. PREDICTIONS: A = 2, B = 1 held at the stated
  delta = 2, the merged unit two digits above there ((i)). 7/7 checks,
  0.3 s, 27.6 MB; the whole run "9/9 checks, 5.0 s".

RUN: python composite.py, the controls, the carry and the composites
(about 5 s); --b skips the carry.
"""
import math
import os
import sys
import time
from fractions import Fraction as Fr

os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import manystream as MS  # noqa: E402

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)


SQ3 = ("x^2 + y^2 + z^2", 3,
       lambda B: MS.iadd(MS.ipow(B[0], 2), MS.ipow(B[1], 2),
                         MS.ipow(B[2], 2)),
       lambda B: [MS.iscale(2, B[0]), MS.iscale(2, B[1]),
                  MS.iscale(2, B[2])],
       lambda M: 6 * M)
MAPS = MS.MAPS + [SQ3]


class Two:
    """Input digits {-am..ap}, output digits {-gm..gp}, radix b."""

    def __init__(self, b, am, ap, gm, gp):
        self.inp = MS.Cell(b, am, ap)
        self.b, self.am, self.ap, self.gm, self.gp = b, am, ap, gm, gp
        self.I = am + ap
        self.w = self.inp.w
        self.Mh = self.inp.Mh
        self.rhoE = gm + gp + 1 - b
        self.Nm, self.Np = Fr(gm, b - 1), Fr(gp, b - 1)
        self.wE = self.Nm + self.Np
        assert self.rhoE >= 1

    def lam_law(self, L):
        return (self.wE - 1) * Fr(self.b) ** L / self.w

    def law_L(self, lam):
        B, need = Fr(self.b), lam * self.I
        return self.inp.least(need / self.rhoE,
                              lambda L: B ** L * self.rhoE >= need)

    def lead(self, rng):
        assert (self.Nm or rng[0] >= 0) and (self.Np or rng[1] <= 0)
        B = Fr(self.b)
        x = max(-rng[0] / self.Nm if self.Nm else 0,
                rng[1] / self.Np if self.Np else 0)
        return self.inp.least(x, lambda o: rng[0] >= -self.Nm * B ** o
                              and rng[1] <= self.Np * B ** o)

    def kills(self, img, n, L):
        e = Fr(self.b) ** (L - n)
        lo, hi = img[0] / e, img[1] / e
        return math.floor(lo + self.Nm) < hi - self.Np


def law_of(t, mp, box=None):
    """(Lam, o, L*) with L* unclamped by the lead (the pole units)."""
    name, d, image, partials, lamf = mp
    lam = lamf(t.Mh)
    o = t.lead(image(box or MS.root_box(t.inp, d)))
    return lam, o, t.law_L(lam)


def inside(B, region):
    return all(r[0] <= x[0] and x[1] <= r[1] for x, r in zip(B, region))


def meets(B, region):
    return all(x[0] < r[1] and r[0] < x[1] for x, r in zip(B, region))


def scan(t, mp, L, o, budget=None, region=None, where=None):
    """Least output depth of a kill at L, or None; boxes read; and
    whether the scan emptied (every box pruned alive by the law). With
    a region, boxes off it are dropped and a kill counts only on a box
    inside it; where, a list, receives the killing box."""
    name, d, image, partials, _ = mp
    c = L - o
    law = t.lam_law(L)
    tuples = MS.digit_tuples(range(-t.am, t.ap + 1), d)
    level = [(0,) * d]
    read = 0
    for n in range(0, MS.NMAX + 1):
        kept = []
        for u in level:
            B = [t.inp.box(ui, n) for ui in u]
            read += 1
            if region and not meets(B, region):
                continue
            if MS.rate(partials(B)) <= law:
                continue
            if (n - c >= 1 and (not region or inside(B, region))
                    and t.kills(image(B), n, L)):
                if where is not None:
                    where.append(B)
                return n - c, read, False
            kept.append(u)
        if not kept:
            return None, read, True
        if read > (budget or MS.BUDGET):
            return None, read, False
        level = [tuple(t.b * ui + e for ui, e in zip(u, es))
                 for u in kept for es in tuples]
    return None, read, False


def gs(b):
    return (b, b + 1, 2 * b - 1, 2 * b)


def controls():
    print("CONTROLS")
    bad = []
    for mp in (MS.MAPS[0], MS.MAPS[2], MS.MAPS[4]):
        for (b, am, ap) in MS.census():
            cell, t = MS.Cell(b, am, ap), Two(b, am, ap, am, ap)
            lam0, o0, L0 = MS.law_of(cell, mp)
            lam1, o1, L1 = law_of(t, mp)
            k0, _ = MS.scan(cell, mp, L0 - 1, o0)
            k1, _, _ = scan(t, mp, max(L1, o1) - 1, o1)
            if (lam0, o0, L0, k0) != (lam1, o1, max(L1, o1), k1):
                bad.append((mp[0], (b, am, ap), (o0, L0, k0),
                            (o1, L1, k1)))
    check("SAME-SET: at E = D, Lam, o, L* and the kill depth at L* - 1 "
          "equal manystream.py's at the 20 cells for x^2, x y, x y + z",
          not bad, f"{len(bad)} differ {bad[:3]}")
    t = Two(3, 1, 1, 6, 6)
    z = (1 - t.Nm, t.Np)
    eps = Fr(1, 3 ** 5)
    check("ZONE-PLANT: at (3, 1, 1), g = 6 (w_E - 1 = 5), an image a hair "
          "wider than zone 0 is a kill, zone 0 itself is not",
          t.kills((z[0] - eps, z[1] + eps), 2, 2)
          and not t.kills(z, 2, 2), f"zone {z}")


def carry():
    print("CARRY  the ten maps at the 20 cells, g = b, b + 1, 2b - 1, 2b")
    t0 = time.time()
    dead, emptied, past, depths, low = 0, [], [], {}, 0
    for mp in MAPS:
        name = mp[0]
        for (b, am, ap) in MS.census():
            for g in gs(b):
                t = Two(b, am, ap, g, g)
                lam, o, Ls = law_of(t, mp)
                low += Ls < o
                k, r, em = scan(t, mp, Ls - 1, o)
                if k is not None:
                    dead += 1
                    depths[k] = depths.get(k, 0) + 1
                elif em:
                    emptied.append((name, (b, am, ap), g))
                else:
                    past.append((name, (b, am, ap), g, r))
        print(f"    {name}: {time.time() - t0:.1f} s", flush=True)
    n = dead + len(emptied) + len(past)
    print(f"\nCARRY: {n} (map, cell, g), dead at L* - 1 at {dead}, "
          f"unkilled with the scan emptied at {len(emptied)}, past the "
          f"budget at {len(past)}")
    print(f"  kill depths {dict(sorted(depths.items()))}; L* below the "
          f"lead at {low}")
    print(f"  emptied: {emptied}")
    print(f"  past: {past}")
    check("CARRY: every (map, cell, g) dead at L* - 1, none emptied, "
          "none past the budget", n == 800 and dead == n,
          f"{dead} of {n}")
    cs = []
    for g in range(6, 13):
        t = Two(2, 1, 1, g, g)
        lam, o, Ls = law_of(t, SQ3)
        cs.append(Ls - o)
    print(f"  x^2 + y^2 + z^2 at (2, 1, 1): c* at g = 6..12 {cs}")
    check("THE LEAD: c* not monotone in g at (2, 1, 1), x^2 + y^2 + z^2",
          cs == [2, 1, 1, 1, 1, 1, 2], str(cs))
    return emptied


def affine(a):
    return (f"{a} x + b", 2,
            lambda B: MS.iadd(MS.iscale(a, B[0]), B[1]),
            lambda B: [(a, a), MS.ONE], lambda M: 1 + a)


def composites():
    print("COMPOSITES  three published units at their own cells")
    rows = []
    half = (Fr(1, 2), Fr(1))
    # (f) the OMA: Lam's sup 2, unattained; its delta = 1 a weight gap
    oma = []
    for r in (2, 4, 8, 16, 32):
        t = Two(r, r - 1, r - 1, r, r)
        tr = (Two(r, r - 1, r - 1, 1, 2) if r == 2
              else Two(r, r - 1, r - 1, 2, r + 1))
        rc = Two(r, r - 1, r - 1, r - 1, r - 1)
        Lg, Lt, Lr = t.law_L(2), tr.law_L(2), rc.law_L(2)
        oma.append(Lg)
        pub_r = 1 + (3 if r == 2 else 2)
        print(f"    OMA r = {r}: L* {Lg} at g = r, {Lt} at the truncation's "
              f"set, published 1; recoded (beside): L* {Lr}, published "
              f"{pub_r}")
    rows.append(("OMA a x + b, r = 2..32", "L", 1, min(oma), max(oma)))
    for r in (2, 4, 8):
        t = Two(r, r - 1, r - 1, r, r)
        mp = affine(Fr(255, 256))
        L = t.law_L(2)
        o = t.lead(mp[2]([half, half]))
        box = []
        k, nread, em = scan(t, mp, L - 1, o, region=[half, half],
                            where=box)
        print(f"    OMA r = {r}, a = 255/256: L* {L}, o {o}; at L* - 1 a "
              f"kill at output depth {k} ({nread} boxes) on {box}")
        check(f"OMA r = {r}: dead at L* - 1 inside [1/2, 1]^2",
              k is not None)
    # (g) the sum of squares: bit inputs, output {0..8}, delta = 0 = L
    t = Two(2, 0, 1, 0, 8)
    lam, o, L = law_of(t, SQ3)
    box = []
    k, nread, em = scan(t, SQ3, L - 1, o, region=[half] * 3, where=box)
    print(f"    SUM OF SQUARES: Lam {lam}, o {o}, L* {L}, published 0 (the "
          f"slides), 1 (FCCM, indexed from digit 0); at L* - 1 a kill at "
          f"output depth {k} ({nread} boxes) on {box}")
    check("SUM OF SQUARES: dead at L* - 1 inside [1/2, 1]^3",
          k is not None)
    ts = Two(2, 1, 1, 0, 8)
    lam_s, o_s, L_s = law_of(ts, SQ3)
    k_s, n_s, _ = scan(ts, SQ3, L_s - 1, o_s, region=[half] * 3)
    print(f"    on signed inputs {{-1, 0, 1}}: L* {L_s}; at L* - 1 a kill "
          f"at output depth {k_s} ({n_s} boxes) inside [1/2, 1]^3")
    rows.append(("x^2 + y^2 + z^2", "L", 0, L, L))
    # (h) the merged multiply-add: 32 bit streams, Lam 32, c = L - o
    t = Two(2, 0, 1, 1, 1)
    rng = (Fr(-32), 32 * Fr(127, 128))
    L, o = t.law_L(32), t.lead(rng)
    wit = t.kills((Fr(-12), 20 * Fr(127, 128)), 0, L - 1)
    print(f"    MERGED MULTIPLY-ADD: Lam 32, o {o}, L* {L}, c* {L - o}, "
          f"published c 2 (L {2 + o}); the hand witness at L* - 1 a kill: "
          f"{wit}")
    check("MERGED: the witness kills at L* - 1 (c = -1)", wit)
    rows.append(("merged multiply-add", "c", 2, L - o, L - o))
    A = sum(pub == hi for _, _, pub, lo, hi in rows if lo == hi)
    B = sum(pub > hi for _, _, pub, lo, hi in rows)
    for name, conv, pub, lo, hi in rows:
        print(f"    {name}: published {conv} = {pub}, floor {lo}..{hi}")
    print(f"\nCOMPOSITE: {A} of 3 published delays at the law's floor, "
          f"{B} above it")
    return A, B


if __name__ == "__main__":
    t0 = time.time()
    controls()
    if not all(CHECKS):
        print("CONTROL FAILED: nothing below is read.")
        sys.exit(1)
    if "--b" not in sys.argv[1:]:
        carry()
    composites()
    print(f"\n{sum(CHECKS)}/{len(CHECKS)} checks, {time.time() - t0:.1f} s")