6. Exercises#

Several have computed answers: the computation is hidden below the exercise (click to show) and the answer is checked by the build.

6.1. Attention residuals contain PreNorm#

Show that with all \(\alpha_{i,j} = 1\) (no softmax) attention residuals reduce to the PreNorm recursion (1). Then show that with uniform softmax weights (all queries zero, their initial value in the released code: modeling_arloop.py, lines 112 and 115, torch.zeros) block attention residuals without a window produce exactly the same updates as PreNorm, because the RMSNorm before each sublayer removes the positive factor (exactly for \(\varepsilon = 0\); up to the RMSNorm’s \(\varepsilon\) otherwise). Does this survive the released code’s first block, which starts from the embedding (finding F6)?

Hide code cell content

rng = np.random.default_rng(1)
d, n, S = 64, 12, 4                                    # width, sublayers, block size (sublayers)
Ws = [rng.standard_normal((d, d)) / np.sqrt(d) for _ in range(n)]
f = lambda j, x: np.tanh(x @ Ws[j])                    # sublayer j
norm = lambda x: x / np.sqrt((x ** 2).mean())          # RMSNorm (eps = 0, unit weight)
h0 = rng.standard_normal(d)

def prenorm():
    h, Z = h0.copy(), []
    for j in range(n):
        Z.append(f(j, norm(h)))
        h = h + Z[-1]
    return Z

def attnres_ones():                                    # every alpha = 1
    sources, Z = [h0], []
    for j in range(n):
        Z.append(f(j, norm(sum(sources))))
        sources.append(Z[-1])
    return Z

def block_uniform(first_block_has_embedding):          # zero queries -> uniform weights, full history
    blocks, partial, Z = [h0], (h0.copy() if first_block_has_embedding else None), []
    for j in range(n):
        sources = blocks + ([partial] if partial is not None else [])
        x = norm(np.mean(sources, axis=0))
        if j > 0 and j % S == 0:                       # commit after the routing of an attention sublayer
            blocks.append(partial)
            partial = None
        Z.append(f(j, x))
        partial = Z[-1] if partial is None else partial + Z[-1]
    return Z

ref = prenorm()
dev = lambda Z: max(np.abs(a - b).max() for a, b in zip(Z, ref))
print("largest deviation of the updates z from PreNorm's:")
print(f"    alpha = 1:                           {dev(attnres_ones()):.1e}")
print(f"    uniform weights, eq. (4) blocks:     {dev(block_uniform(False)):.1e}")
print(f"    uniform weights, code's first block: {dev(block_uniform(True)):.2f}")
largest deviation of the updates z from PreNorm's:
    alpha = 1:                           0.0e+00
    uniform weights, eq. (4) blocks:     1.0e-15
    uniform weights, code's first block: 1.28
Answer

With \(\alpha_{i,j} = 1\) the state is \(h_i = h_0 + \sum_{j\le i} z_j\), the unrolled form of (1). With uniform weights over the embedding, the completed blocks and the partial block, the mixture is \((h_0 + \sum_j z_j)/(k+1)\) for \(k+1\) sources: PreNorm’s state times a positive number, which the RMSNorm removes. With the code’s first block the embedding is counted twice, the mixture is \((2h_0 + \sum_j z_j)/(k+1)\), and the identity fails from the second sublayer on. In the toy above the first two deviations are at rounding level and the third is not. [num]

6.2. A softmax mixture cannot grow the stream#

Let \(s_0, \dots, s_m\) be sources with \(\|s_j\| \le B\) and \(\alpha\) a softmax vector. Show \(\big\|\sum_j \alpha_j s_j\big\| \le B\). Then compute \(\|h\|\) at the read-out of PreNorm when the embedding and all updates are orthonormal, at the depths of both released ARLoop models.

Hide code cell content

for name in ("ARLoop-0.6B", "ARLoop-1.2B"):
    n = lib.effective_sublayers(lib.config(name))
    print(f"{name}: {n} updates, read-out norm sqrt({n + 1}) = {math.sqrt(n + 1):.2f}, "
          f"newest share {1 / math.sqrt(n + 1):.3f}")
ARLoop-0.6B: 108 updates, read-out norm sqrt(109) = 10.44, newest share 0.096
ARLoop-1.2B: 144 updates, read-out norm sqrt(145) = 12.04, newest share 0.083
Answer

By the triangle inequality, \(\|\sum_j\alpha_j s_j\| \le \sum_j \alpha_j\|s_j\| \le B\sum_j\alpha_j = B\). For orthonormal \(h_0, z_1, \dots, z_n\), \(\|h_0 + \sum z_j\|^2 = 1 + n\): \(\sqrt{109} \approx 10.44\) for the 108 sublayers of the 0.6B model and \(\sqrt{145} \approx 12.04\) for the 144 of the 1.2B model, while attention residuals stay at or below the norm of their largest source. The stream norms of the real PreNormLoop-0.6B are measured in E1.4. [num]

6.3. Count the routing parameters of ARLoop-1.2B#

From its configuration (book/data/hf/ARLoop-1.2B/config.json), count the depth-indexed routing parameters and compare with the parameter count of the checkpoint (the list of the other modules is in One query per effective sublayer: what it costs, what it fixes).

Hide code cell content

c12 = lib.config("ARLoop-1.2B")
routing = lib.routing_parameters(c12)
backbone = sum(lib.backbone_parameters(c12).values())
print(f"2 x {c12['physical_layers']} x {c12['loop_count']} = {lib.effective_sublayers(c12)} sublayers")
print(f"(2 x {lib.effective_sublayers(c12)} + 2) x {c12['hidden_size']} = {routing:,} routing parameters")
print(f"backbone {backbone:,} + routing {routing:,} = {backbone + routing:,}")
print(f"checkpoint (HF API): {lib.CHECKPOINTS['ARLoop-1.2B']['parameters']:,}")
2 x 24 x 3 = 144 sublayers
(2 x 144 + 2) x 2048 = 593,920 routing parameters
backbone 1,208,061,440 + routing 593,920 = 1,208,655,360
checkpoint (HF API): 1,208,655,360
Answer

\(2 \times 24 \times 3 = 144\) effective sublayers, each with a query and a norm weight, plus the read-out pair: \(290 \times 2048 = 593{,}920\) routing parameters. Together with the backbone counted from the same configuration this gives 1,208,655,360, exactly the checkpoint’s count (see One query per effective sublayer: what it costs, what it fixes). [code + num]

6.4. When does the first block leave the window?#

For block size \(S\) sublayers and a window of \(W\) sources besides the embedding, at which effective layer is \(b_1\) read for the last time? Check the formula against the replay of the forward pass for the 0.6B model and windows \(W = 2, \dots, 6\).

Hide code cell content

c06 = lib.config("ARLoop-0.6B")
per_block = c06["attnres_block_size"] // 2
last = {}
for W in range(2, 7):
    calls = lib.schedule({**c06, "sw_blocks": W})
    seen = [c for c in calls if "b1" in c["labels"]]
    last[W] = seen[-1]["layer"] if seen[-1]["kind"] != "readout" else "never dropped"
    n_sub = lib.effective_sublayers(c06)
    if last[W] == "never dropped":
        print(f"W = {W}: b1 is never dropped (still read by the read-out, call {n_sub} = 2 × {n_sub // 2})")
    else:
        print(f"W = {W}: b1 last read at layer {last[W]} (formula W × S/2 = {W * per_block})")
W = 2: b1 last read at layer 18 (formula W × S/2 = 18)
W = 3: b1 last read at layer 27 (formula W × S/2 = 27)
W = 4: b1 last read at layer 36 (formula W × S/2 = 36)
W = 5: b1 last read at layer 45 (formula W × S/2 = 45)
W = 6: b1 is never dropped (still read by the read-out, call 108 = 2 × 54)
Answer

Blocks are committed every \(S/2\) layers, \(b_k\) at the start of layer \(kS/2\). At the FFN sublayer of layer \(WS/2\) the router sees \(b_1, \dots, b_W\) and a partial block, one source too many, and \(b_1\) drops out; its last reader is the attention sublayer of layer \(WS/2\). For the 0.6B model (\(S/2 = 9\)): layers 18, 27, 36, 45 for \(W = 2, 3, 4, 5\); with \(W = 6\) the 54 layers end before \(b_1\) is dropped. With the released \(W = 3\) that is layer 27 (and layer 36 for ARLoop-1.2B, where \(S/2 = 12\)). [num]

6.5. How large must the GSM8K gap be?#

The paper’s GSM8K scores of the 0.6B pair are 40.9 and 35.7 on 1,319 items. Which numbers of solved items are consistent with these rounded percentages? If E1 finds the same net gap, for which numbers of discordant items (solved by exactly one model) is the exact McNemar test significant at 5%?

Hide code cell content

N = 1319
ar = [k for k in range(N + 1) if f"{100 * k / N:.1f}" == "40.9"]
pn = [k for k in range(N + 1) if f"{100 * k / N:.1f}" == "35.7"]
nets = sorted({a - p for a in ar for p in pn})
print("ARLoop solved", ar, "items; PreNormLoop solved", pn, "items; net gap", nets)
limit = {}                     # the largest discordant count the totals allow: no item solved by both models
for a in ar:
    for p in pn:
        limit[a - p] = max(limit.get(a - p, 0), a + p)
allowed = {net: list(range(net, limit[net] + 1, 2)) for net in nets}     # same parity as the gap
for net in nets:
    sig = all(lib.mcnemar_exact((D + net) // 2, (D - net) // 2) < 0.05 for D in allowed[net])
    print(f"net gap {net}: discordant counts {net}–{limit[net]:,} (same parity) are possible; "
          f"p < 0.05 for {'every one of them' if sig else 'not all of them'}")
ARLoop solved [539, 540] items; PreNormLoop solved [471] items; net gap [68, 69]
net gap 68: discordant counts 68–1,010 (same parity) are possible; p < 0.05 for every one of them
net gap 69: discordant counts 69–1,011 (same parity) are possible; p < 0.05 for every one of them
Answer

40.9% of 1,319 is 539 or 540 items, 35.7% is 471, so the paper’s gap is a net 68 or 69 items. The number of discordant items has the parity of the gap and is at most the sum of the two totals (when no item is solved by both models). For every discordant count the totals allow (the ranges are printed above) the exact McNemar test is significant at 5%: if E1 reproduces a gap of that size, it is not noise. Whether it reproduces is the question of E1.1 (E1: the released checkpoints, re-measured). [num]