Q100PUBLIC WORKBENCH

Download the English note and replication files (.md)

When an equivalent-looking change alters training

Research note · December 2, 2026. Three controlled examples from preference optimization and packed attention.

A training optimization can preserve the wrong invariant. Two dropout masks can each remain fair while their joint distribution changes. Two packed batches can have the same token count and valid query–key pair count while a tiled kernel performs different work. An accumulation scheme can preserve every example but change the weight of each one. Below are reproducible counterexamples. They establish mathematical and CPU results, not faster GPU execution or improved model quality.

1. Two fair masks can reverse a DPO gradient

For a fixed preference pair, let (m,n) be the preferred and rejected response masks. With an equal-probability reference model and β=1, the margin is z=log Pθ(y+|m)−log Pθ(y−|n), the loss is log(1+exp(−z)), and its derivative is −σ(−z) dz/dθ. Independent fair masks give each of 00, 01, 10, 11 probability 1/4; a shared mask admits only 00 and 11; opposite masks admit only 01 and 10. The marginal for each mask is the same in all three cases.

Three-response construction

For mask bit x, let the preferred response have probability 0.1 exp(θ(x−a)), the rejected response 0.1·3^x, and a third response the remainder. This is a valid local probability model near θ=0. At that point the derivative is g(m,n)=−(m−a)·3^n/(1+3^n). Its means are 5a/8−5/16 with independent masks and 5a/8−3/8 with shared masks. These have opposite signs throughout 1/2<a<3/5. At a=11/20 they are +1/32 and −1/32.

Ordinary two-class softmax

Use logits [x log 3+θ(1−8x/3),0]. At θ=0, the first class has probabilities 1/2 or 3/4, and the first-logit slopes are t₀=1,t₁=−5/3. For first-class probabilities p_m,p_n, the margin derivative is (1−p_m)t_m+p_n t_n, multiplied by the loss derivative with respect to the margin, −(1−p_n)/(1−p_n+p_m).

Mask pair or expectation Three responses Two-class softmax
00 11/40 −1/2
01 33/80 1/4
10 −9/40 −1/30
11 −27/80 5/12
Independent 1/32 1/30
Shared −1/32 −1/24
Opposite 3/32 13/120

If both bits remain fair and q=P(m=n), the two expectations are (3−4q)/32 and (13−18q)/120; they cross zero at 3/4 and 13/18. This is a one-parameter result at the stated checkpoint, not a training trajectory or language-model quality measurement. Exact fraction enumeration, symmetric finite differences at step 10⁻⁵, and CPU PyTorch float64 autograd agree at the precision reported in the appendices.

Unsloth already documented the underlying coupling problem and a late-adapter dropout inspection fix. The accompanying unit test verified the guard on three pinned versions: before appending dropout the guard was false in every version; afterward, in training mode, the original PR head still returned false while the fix and tested main snapshot returned true. In evaluation mode all returned false; back in training the two newer versions again returned true. This is an extracted-function test, not an end-to-end reproduction of Unsloth’s training kernels. The contribution here is a compact numerical regression case, not a first-discovery claim. DPO paper · Prefix-sharing paper · Original PR · Guard fix

2. Identical token and causal-pair counts, different packed-attention work

A causal sequence of length L has L(L+1)/2 legal query–key pairs per head. Packing with no cross-sequence attention gives (ΣL²+ΣL)/2. For forward self-attention with locally aligned query blocks of size Bq, key blocks of size Bk, equal query and key sequence lengths, and no local window, the query block with one-based index i reaches ceil(min(i Bq,L)/Bk) key blocks. Sum that over the active query blocks and all sequences. For square tiles of size B, the per-sequence result is T(ceil(L/B)), with T(x)=x(x+1)/2. This counts each inner-loop iteration equally, not its latency.

Sequence lengths Tokens Valid pairs Active Q blocks (64×64) K/V iterations (64×64)
62, 65, 65 192 6,243 5 7
63, 63, 66 192 6,243 4 5
60, 64, 68 192 6,256 4 5
62, 65, 65, 68 260 8,589 7 10
63, 63, 66, 68 260 8,589 6 8
1, 66, 118, 129 314 17,618 8 13
22, 34, 129, 129 314 17,618 8 14
30, 33, 33, 36 132 2,253 4 4
31, 31, 34, 36 132 2,253 4 4

The last pair is a boundary control at 64×64; it differs at 64×32. An exhaustive search of 1,198,144 nondecreasing triples with lengths 1–192 found 148,414 token-and-square-sum groups with more than one 64×64 count; the largest ratio was 12/7 in that search. Requiring equal active query-block counts left 23,270 such groups, with largest ratio 8/7. These are search-space statistics, not a claim about real workload frequency. Independent tile enumerations agreed with the formula in 6,400 general cases and in 804 cases for the pinned-loop comparison.

An infinite family: for integer k≥1, B≥3, and integer 1≤d<B/2, set a=kB. The packs (a−2d,a+d,a+d) and (a−d,a−d,a+2d) have equal sums 3a and squared sums 3a²+6d², but the first uses k+1 more square-tile iterations. Conversely, if every length in both equal-moment packs is at least mB, the ratio of larger to smaller count is strictly below 1+2/m. For x=L/B, use T(x)≤T(ceil(x))<T(x)+x+1 and x+1=2T(x)/x≤2T(x)/m, then sum. At tile size 64 and minimum length 4,096 this yields a bound below 3.125% on iteration counts, not on GPU time.

Reversal in a pinned FlashAttention forward-loop model

In FlashAttention 2.8.3 commit 060c9188beec3a8b62b33a3bfa6d5d2d44975fab, the non-split causal forward path skips inactive query blocks and bounds its backward traversal of key blocks by both sequence length and the end of the active query block. The counted iterations include both masked and masking-free sections of that loop. For packs A = (16,137,187,193) and B = (19,128,193,193), both have 533 tokens, 45,888 legal pairs per head, four sequences, and maximum length 193.

Q×K tile A K/V iterations B K/V iterations Launched work units per head, either pack
64×64 23 24 16
128×64 17 15 8
128×128 10 8 8
128×32 31 27 8

At 64×64 there are 11 active query blocks in each pack; at the three 128-row geometries there are 7 versus 6. Counts at 128×32 provide an additional arithmetic check, not a claim about which public API call selects that kernel. The original GPU probe’s head dimension 64 can take a 128×128 path where the original three-sequence pair ties. The revised probe defaults to head dimension 128 and the stronger four-sequence pair. In the pinned source, a relevant dropout-free causal branch uses 64×64 on compute capability 8.x with nonzero minor version and 128×64 in its alternate branch. Actual dispatch depends on the installed code and configuration. Pinned loop bounds · Pinned dispatch

Simulated scheduling

In a simple pair-per-worker example, grouping two packs with 7 iterations on one worker and two packs with 5 on another gives 14 versus 10; splitting them gives 12 versus 12. In the full simulation, each of 2,048 fixed-seed windows per workload contains sixteen equal-token packs and eight workers, with two packs per worker. Pairing smallest and largest costs minimizes the maximum pair sum in this additive two-job model: replacing pairs (a,x),(z,y) by (a,z),(x,y) for minimum a and maximum z cannot exceed the old maximum max(a+x,z+y). Repeat on the remainder. The included code also checked 512 six-job cases exhaustively.

Mean reduction in maximum modeled iterations versus sorting by squared sequence lengths was 4.697%–7.171% across block shapes in the short workload and below 0.3% in the longer workload. The wrong geometry made the short-workload 64×64 case 0.774% worse on average; the correctly aligned 64×64 control showed no gain. All sixteen workload/geometry results, medians and counts of better or worse windows are in the JSON. No GPU step time, communication, training cost or gain versus a hardware-calibrated scheduler was measured. WLB-LLM · Hydraulis

GPU replication wanted

Can you run a short FlashAttention comparison on a CUDA GPU you already have permission to use? Please contact Q100 privately with your GPU model, CUDA/PyTorch/FlashAttention versions, and whether profiling is available. Do not send credentials, server access, or private data. A null result is useful.

The probe uses synthetic tensors, warms up the kernel, alternates A/B order, and saves individual timings and medians. Compare A with B within each configuration; report the actual dispatched kernel and block shape alongside results. CPU checks and source inspection support the count prediction. The GPU probe was checked for syntax and command-line interface only and no GPU timing is reported. Training savings would require an additional full-step evaluation against a calibrated baseline.

3. Microbatch means can invert a three-pair gradient

Let the DPO margins be θ·[-3,2,2]. At zero, the per-pair gradients are [3/2,−1,−1]. The equal-pair mean is −1/6. Split into microbatches of sizes 1 and 2 and average their means equally, and it becomes +1/4. Sum losses and divide by the global number of pairs to restore −1/6.

For m nonempty groups, n_i pairs in group i, N=Σn_i, and group mean gradients g_i, the error is Σ(1/m−n_i/N)g_i. If ‖g_i‖≤G, its norm is at most G Σ|1/m−n_i/N|. The bound is sharp: choose collinear gradients of size G with the coefficient’s sign. The code checked the witness in 9,330 group-size patterns. Where a reducer averages over R workers, scaling each local sum by R/N gives each pair weight 1/N, assuming there is no additional averaging factor. The applicable denominator depends on the intended objective.

Exact arithmetic and local CPU autograd reproduced the sign flip and the repair. A calculated mean of two local gradients agreed. The two-process Gloo DDP attempt did not complete because the environment did not allow the communication channel; it is not a measured distributed result. Accelerate accumulation guide · PyTorch DDP

Reproduction

The seven scripts and five recorded output files below are retained byte-for-byte from the research artifact. The scripts include CPU checks, pinned-source audits and proposed GPU probes. Anyone reproducing a check should inspect the script and run it under their own permissions; network and GPU are not needed for the basic mathematical checks.

To extract the appendices from the downloadable Markdown, save it as training-equivalence.md, then run:

python3 - training-equivalence.md <<'PY'
from pathlib import Path
import re, sys
article = Path(sys.argv[1]).read_text(encoding="utf-8")
blocks = re.findall(r"^<!-- FILE: ([a-z][a-z0-9_]*\.(?:py|json)) -->\n\x60{3}(?:python|json)\n(.*?)^\x60{3}\n", article, re.M | re.S)
assert len(blocks) == len(dict(blocks)) == 12
target = Path("reproduction")
target.mkdir()
for filename, contents in blocks:
    (target / filename).write_bytes(contents.encode())
PY

The minimal CPU entry points are dpo_dropout_counterexample.py, attention_tile_checks.py, and attention_geometry_replay.py. The autograd and GPU scripts require their respective optional dependencies. Recorded JSON includes the initial and fixed guard states, exact and numerical results, all scheduling scenarios, and local normalization evidence.

Appendices: source and recorded outputs

dpo_dropout_counterexample.py

SHA-256: 69bbb41877a38019f4583f0ccc9be141566233881e10865ea14ea10450aa831d

<!– FILE: dpo_dropout_counterexample.py –>

#!/usr/bin/env python3
"""Enumerate a one-parameter DPO example with shared or independent dropout."""

from fractions import Fraction
from itertools import product
import json
import math


def mask_states(shared):
    if shared:
        return [(0, 0), (1, 1)]
    return list(product((0, 1), repeat=2))


def policy(theta, mask, slope_offset):
    good = 0.1 * math.exp(theta * (mask - float(slope_offset)))
    bad = 0.1 * (3 if mask else 1)
    other = 1.0 - good - bad
    assert min(good, bad, other) > 0
    return good, bad, other


def expected_loss(theta, shared, slope_offset):
    states = mask_states(shared)
    losses = []
    for good_mask, bad_mask in states:
        good = policy(theta, good_mask, slope_offset)[0]
        bad = policy(theta, bad_mask, slope_offset)[1]
        # The fixed reference assigns both replies equal probability.
        losses.append(math.log1p(bad / good))
    return sum(losses) / len(states)


def exact_gradient_at_zero(shared, slope_offset):
    derivatives = []
    for good_mask, bad_mask in mask_states(shared):
        ratio = 3 if bad_mask else 1
        weight = Fraction(ratio, 1 + ratio)
        derivatives.append(-weight * (good_mask - slope_offset))
    return sum(derivatives) / len(derivatives)


def logistic_model_gradient(shared):
    # A masked scalar feature x produces the logit x*log(3) + theta*(1 - 8*x/3).
    states = mask_states(shared)
    good_probabilities = [Fraction(1, 2), Fraction(3, 4)]
    logit_slopes = [Fraction(1), Fraction(-5, 3)]
    gradients = []
    for m, n in states:
        good_probability = good_probabilities[m]
        bad_probability = 1 - good_probabilities[n]
        weight = bad_probability / (good_probability + bad_probability)
        score_slope = (1 - good_probability) * logit_slopes[m] + good_probabilities[n] * logit_slopes[n]
        gradients.append(-weight * score_slope)
    return sum(gradients) / len(states)


def logistic_model_loss(theta, shared):
    def logit(mask):
        return mask * math.log(3) + theta * (1 - 8 * mask / 3)

    states = mask_states(shared)
    loss = 0
    for m, n in states:
        good = 1 / (1 + math.exp(-logit(m)))
        bad = 1 / (1 + math.exp(logit(n)))
        loss += math.log1p(bad / good)
    return loss / len(states)


def main():
    offset = Fraction(11, 20)
    epsilon = 1e-5
    output = {}
    for name, shared, expected in (
        ("independent", False, Fraction(1, 32)),
        ("shared", True, Fraction(-1, 32)),
    ):
        exact = exact_gradient_at_zero(shared, offset)
        finite_difference = (
            expected_loss(epsilon, shared, offset)
            - expected_loss(-epsilon, shared, offset)
        ) / (2 * epsilon)
        assert exact == expected
        assert abs(finite_difference - float(exact)) < 1e-9
        output[name] = {"exact": str(exact), "finite_difference": finite_difference}
    for numerator in range(51, 60):
        offset = Fraction(numerator, 100)
        assert exact_gradient_at_zero(False, offset) > 0
        assert exact_gradient_at_zero(True, offset) < 0
    output["tested_offsets_with_reversal"] = ["0.51", "0.52", "0.53", "0.54", "0.55", "0.56", "0.57", "0.58", "0.59"]
    output["two_class_linear_softmax"] = {}
    for name, shared, expected in (
        ("independent", False, Fraction(1, 30)),
        ("shared", True, Fraction(-1, 24)),
    ):
        exact = logistic_model_gradient(shared)
        numerical = (logistic_model_loss(epsilon, shared) - logistic_model_loss(-epsilon, shared)) / (2 * epsilon)
        assert exact == expected and abs(float(exact) - numerical) < 1e-9
        output["two_class_linear_softmax"][name] = {"exact": str(exact), "finite_difference": numerical}
    print(json.dumps(output, indent=2))


if __name__ == "__main__":
    main()

dpo_cpu_autograd_and_guard.py

SHA-256: 294350aca9c80545de564551b916c937af8e091e676566ec8c023fb16ca573f2

<!– FILE: dpo_cpu_autograd_and_guard.py –>

#!/usr/bin/env python3
"""Verify DPO examples with autograd and exercise the upstream Unsloth guard on CPU."""
import argparse
import ast
import hashlib
from fractions import Fraction
from itertools import product
import json
import math
from pathlib import Path
from types import SimpleNamespace
from urllib.request import urlopen

import torch
from torch.nn import functional as F


SOURCES = {
    "initial_prefix_sharing_pr": (
        "988ed46a817332ec04ee0581432241b062fe8877",
        "cf50f229fe6d3184f8009062bafad52636fbe4484a60bffe73ca59020859079b",
    ),
    "late_adapter_fix_pr": (
        "1180e5795c24edfb8cd418412265d5d5bf11510f",
        "e087143c6cb27243e039ecebc455370e54aa9da94dd4f6e9cfeecf139d667445",
    ),
    "main_snapshot": (
        "ca92fc2fd4afaad4912b4266874648bffdf061f5",
        "9d698ef3ddb626649bff53c615e90666391d36eee0e129855fdca8ae4a6ae7b3",
    ),
}


def gradient(model, states):
    theta = torch.tensor(0.0, dtype=torch.float64, requires_grad=True)
    states = torch.tensor(states, dtype=torch.float64)
    chosen, rejected = states.T
    if model == "three_answers":
        margin = theta * (chosen - 0.55) - rejected * math.log(3)
    else:
        logits = states * math.log(3) + theta * (1 - 8 * states / 3)
        margin = F.logsigmoid(logits[:, 0]) - F.logsigmoid(-logits[:, 1])
    return torch.autograd.grad(-F.logsigmoid(margin).mean(), theta)[0].item()


def checked_source(revision, digest, source_dir):
    if source_dir:
        content = (source_dir / f"{revision}.py").read_bytes()
    else:
        root = "https://raw.githubusercontent.com/unslothai/unsloth/"
        path = f"{revision}/unsloth/models/dpo_prefix_share.py"
        with urlopen(root + path, timeout=15) as response:
            content = response.read()
    if hashlib.sha256(content).hexdigest() != digest:
        raise RuntimeError(f"Unexpected source digest for {revision}")
    return content.decode()


def dropout_guard(source):
    node, = (x for x in ast.parse(source).body if isinstance(x, ast.FunctionDef) and x.name == "_dropout_active")
    tree = ast.Module(body=[node], type_ignores=[])
    namespace = {"torch": torch}
    exec(compile(tree, "<digest-verified upstream _dropout_active>", "exec"), namespace)
    return namespace[node.name]


def probe_guard(guard):
    model = torch.nn.Sequential(torch.nn.Linear(2, 2))
    initial = guard(model)
    model.add_module("adapter_dropout", torch.nn.Dropout(0.5))
    model.peft_config = {"late_adapter": SimpleNamespace(lora_dropout=0.5)}
    after_add = guard(model)
    model.eval()
    eval_result = guard(model)
    model.train()
    after_train = guard(model)
    return [initial, after_add, eval_result, after_train]


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--source-dir", type=Path, help="Use SHA-256-verified local copies named COMMIT.py.")
    args = parser.parse_args()
    torch.set_num_threads(1)
    independent = list(product((0, 1), repeat=2))
    shared = [(0, 0), (1, 1)]
    anti = [(0, 1), (1, 0)]
    models = {}
    for model, expected in {
        "three_answers": (1 / 32, -1 / 32, 3 / 32),
        "two_answer_softmax": (1 / 30, -1 / 24, 13 / 120),
    }.items():
        results = {name: gradient(model, pairs) for name, pairs in (
            ("independent", independent), ("shared", shared), ("opposite", anti)
        )}
        for actual, value in zip(results.values(), expected):
            assert math.isclose(actual, value, abs_tol=1e-12)
        assert math.isclose(results["independent"], (results["shared"] + results["opposite"]) / 2, abs_tol=1e-12)
        tied = Fraction(results["shared"]).limit_denominator()
        opposite = Fraction(results["opposite"]).limit_denominator()
        results["zero_gradient_probability_of_equal_masks"] = str(opposite / (opposite - tied))
        models[model] = results
    guards = {}
    for name, (revision, digest) in SOURCES.items():
        source = checked_source(revision, digest, args.source_dir)
        states = probe_guard(dropout_guard(source))
        expected = [False, False, False, False] if name == "initial_prefix_sharing_pr" else [False, True, False, True]
        assert states == expected, (name, states)
        guards[name] = {"revision": revision, "sha256": digest, "guard_states": states}
    print(json.dumps({
        "torch": torch.__version__,
        "expected_gradients": models,
        "guard_state_order": ["before_adapter", "after_late_adapter_in_train", "eval", "train_again"],
        "upstream_guard": guards,
    }, indent=2))


if __name__ == "__main__":
    main()

attention_tile_checks.py

SHA-256: 9aa01d183ef8a7703c8c5dca1f34401c84f0234506091270dedba96b8cc5a2ac

<!– FILE: attention_tile_checks.py –>

#!/usr/bin/env python3
"""Reproduce causal self-attention tile counts without third-party packages."""

import argparse
from fractions import Fraction
from itertools import combinations
import json


def ceil_div(value, divisor):
    return (value + divisor - 1) // divisor


def tiles(length, query_block=64, key_block=64):
    """Count inner-loop iterations across valid query blocks for one sequence."""
    return sum(
        ceil_div(min(start + query_block, length), key_block)
        for start in range(0, length, query_block)
    )


def grid_count(length, query_block, key_block):
    """Independently count tiles containing at least one valid causal pair."""
    return sum(
        key_start <= min(query_start + query_block, length) - 1
        for query_start in range(0, length, query_block)
        for key_start in range(0, length, key_block)
    )


def describe(pack, query_block=64, key_block=64):
    total = sum(pack)
    squares = sum(length * length for length in pack)
    return {
        "lengths": pack,
        "tokens": total,
        "squares": squares,
        "valid_pairs": (squares + total) // 2,
        "query_blocks": sum(ceil_div(length, query_block) for length in pack),
        "tiles": sum(tiles(length, query_block, key_block) for length in pack),
    }


def examples(query_block, key_block):
    first = (62, 65, 65)
    second = (63, 63, 66)
    third = (60, 64, 68)
    return {
        "equal_moments": [describe(pack, query_block, key_block) for pack in (first, second)],
        "strict_reversal_for_64_by_64": [describe(pack, query_block, key_block) for pack in (first, third)],
        "equal_maximum": [describe((*pack, 68), query_block, key_block) for pack in (first, second)],
        "equal_maximum_and_query_blocks": [
            describe(pack, query_block, key_block)
            for pack in ((1, 66, 118, 129), (22, 34, 129, 129))
        ],
        "below_64_boundary": [
            describe(pack, query_block, key_block)
            for pack in ((30, 33, 33, 36), (31, 31, 34, 36))
        ],
    }


def exact_search(max_length, query_block, key_block):
    # Each group keeps two extreme tile counts and the input that realizes each.
    scores = [tiles(i, query_block, key_block) for i in range(max_length + 1)]
    query_blocks = [ceil_div(i, query_block) for i in range(max_length + 1)]
    fields = ("same_tokens_and_squares", "also_same_query_blocks")
    totals = {name: 0 for name in fields}
    champions = {}
    count = 0
    for total in range(3, 3 * max_length + 1):
        groups_for_total = {name: {} for name in fields}
        for a in range(max(1, total - 2 * max_length), total // 3 + 1):
            for b in range(max(a, total - a - max_length), (total - a) // 2 + 1):
                c = total - a - b
                count += 1
                squares = a * a + b * b + c * c
                query_count = query_blocks[a] + query_blocks[b] + query_blocks[c]
                point = (scores[a] + scores[b] + scores[c], (a, b, c))
                for name, key in zip(fields, (squares, (squares, query_count))):
                    groups = groups_for_total[name]
                    low, high = groups.get(key, (point, point))
                    groups[key] = (min(low, point), max(high, point))
        for name, groups in groups_for_total.items():
            for low, high in groups.values():
                if low[0] == high[0]:
                    continue
                totals[name] += 1
                ratio = Fraction(high[0], low[0])
                if name not in champions or ratio > champions[name][0]:
                    champions[name] = (ratio, low, high)

    from math import comb

    assert count == comb(max_length + 2, 3)
    summarized = {"max_length": max_length, "triples_checked": count}
    for name in fields:
        summary = {"groups_with_different_tile_counts": totals[name]}
        if name in champions:
            ratio, low, high = champions[name]
            summary.update(
                maximum_ratio=str(ratio),
                example=[describe(point[1], query_block, key_block) for point in (low, high)],
            )
        summarized[name] = summary
    return summarized


def schedule_example():
    packs = [(62, 65, 65)] * 2 + [(63, 63, 66)] * 2
    counts = [describe(pack)["tiles"] for pack in packs]
    possibilities = [
        (sum(counts[i] for i in worker_one), sum(counts[i] for i in range(4) if i not in worker_one))
        for worker_one in combinations(range(4), 2)
    ]
    return {
        "fixed_packs": packs,
        "first_two_to_worker_one": possibilities[0],
        "optimal_with_two_packs_on_each_worker": min(possibilities, key=max),
    }


def checks():
    comparisons = 0
    for query_block in (8, 16, 32, 64, 128):
        for key_block in (8, 16, 32, 64, 128):
            for length in range(1, 257):
                assert tiles(length, query_block, key_block) == grid_count(length, query_block, key_block)
                comparisons += 1
    for block in (8, 32, 64, 128):
        for k in range(1, 65):
            for d in range(1, block // 2):
                a = k * block
                left = describe((a - 2 * d, a + d, a + d), block, block)
                right = describe((a - d, a - d, a + 2 * d), block, block)
                assert left["valid_pairs"] == right["valid_pairs"]
                assert left["tiles"] - right["tiles"] == k + 1
    return comparisons


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--max-length", type=int, default=192)
    args = parser.parse_args()
    if args.max_length < 1:
        parser.error("--max-length must be positive")
    results = {
        "independent_grid_comparisons": checks(),
        "examples_64_by_64": examples(64, 64),
        "examples_64_by_32": examples(64, 32),
        "examples_128_by_128": examples(128, 128),
        "exhaustive_search_64_by_64": exact_search(args.max_length, 64, 64),
        "two_worker_example": schedule_example(),
    }
    print(json.dumps(results, indent=2))


if __name__ == "__main__":
    main()

attention_geometry_replay.py

SHA-256: 27a2a3693e4bb412f0d99d70382be13c45582b75e18e6744f18c0ee1dd3dfebe

<!– FILE: attention_geometry_replay.py –>

#!/usr/bin/env python3
"""Reproduce a pinned FlashAttention forward-loop audit and synthetic worker pairing."""
import hashlib
import json
import random
from functools import cache
from itertools import combinations, product
from statistics import mean, median
from urllib.request import urlopen

PIN = "060c9188beec3a8b62b33a3bfa6d5d2d44975fab"
SOURCE_HASHES = {
    "src/flash_fwd_kernel.h": "765dd3ef217bc9d79c9c0494ba52ea63767099be737c14604bec748d85f0dde3",
    "src/flash_fwd_launch_template.h": "d9e9f4b92cb731d7955b514449e59b8e411bf7a0c929aafb454f2402d41fe976",
    "flash_api.cpp": "7fcefdccf0d08ad0f6cceab48383560202ca6dc2bc1ffd50e8a43aa1c2eea14a",
}
GEOMETRIES = ((64, 64), (128, 64), (128, 128), (128, 32))
ORIGINAL = ((62, 65, 65), (63, 63, 66))
REVERSAL = ((16, 137, 187, 193), (19, 128, 193, 193))


def ceildiv(value, block):
    return (value + block - 1) // block


@cache
def loop_count(length, geometry):
    """Number of K/V iterations that the pinned non-split causal path would execute."""
    block_m, block_n = geometry
    return sum(
        min(ceildiv(length, block_n), ceildiv((query + 1) * block_m, block_n))
        for query in range(ceildiv(length, block_m))
    )


def enumerate_mask_cells(length, geometry):
    """Independent enumeration of distinct blocks reached by valid causal pairs."""
    block_m, block_n = geometry
    return len({(i // block_m, j // block_n) for i in range(length) for j in range(i + 1)})


def signature(lengths):
    return sum(lengths), sum(length * length for length in lengths)


def pack_cost(pack, geometry):
    return sum(loop_count(length, geometry) for length in pack)


def examples(packs):
    lengths = [signature(pack) for pack in packs]
    assert lengths[0] == lengths[1]
    total, squared = lengths[0]
    return {
        "packs": packs, "tokens": total, "valid_causal_pairs": (total + squared) // 2,
        "max_lengths": [max(pack) for pack in packs],
        "counts": {f"{m}x{n}": [pack_cost(pack, (m,n)) for pack in packs] for m, n in GEOMETRIES},
        "launched_ctas_per_head": {
            f"{m}x{n}": [len(pack) * ceildiv(max(pack), m) for pack in packs]
            for m, n in GEOMETRIES
        },
    }


def pair_by_score(packs, score):
    """Give each worker two intact packs from the same existing batch."""
    ranked = sorted(packs, key=score)
    workers = len(ranked) // 2
    return [(ranked[i], ranked[-1 - i]) for i in range(workers)]


def maximum_cost(pairs, geometry):
    return max(pack_cost(first, geometry) + pack_cost(second, geometry) for first, second in pairs)


def composition(total, floor, rng):
    available = total - 3 * (floor - 1)
    first, second = sorted(rng.sample(range(1, available), 2))
    return first + floor - 1, second - first + floor - 1, available - second + floor - 1


def scenarios(kind, rng):
    if kind == "near_boundaries":
        center = rng.choice((64, 128, 192))
        perturbations = [(a,b,-a-b) for a,b in product(range(-6,7), repeat=2) if abs(a+b)<=6]
        return [tuple(center + value for value in rng.choice(perturbations)) for _ in range(16)]
    if kind == "short_compositions":
        return [composition(384, 8, rng) for _ in range(16)]
    if kind == "long_compositions":
        return [composition(8192, 1024, rng) for _ in range(16)]
    return [tuple(64 * value for value in composition(24, 1, rng)) for _ in range(16)]


def replay(repetitions=2048):
    output = {}
    for name, kind in enumerate(("near_boundaries", "short_compositions", "long_compositions", "aligned_control")):
        rng = random.Random(20261202 + name)
        batches = [scenarios(kind, rng) for _ in range(repetitions)]
        summary = {}
        for geometry in GEOMETRIES:
            wrong_geometry = (128, 128) if geometry != (128, 128) else (64, 64)
            gains, wrong_gains = [], []
            for batch in batches:
                assert len({sum(pack) for pack in batch}) == 1
                baseline = maximum_cost(pair_by_score(batch, lambda pack: signature(pack)[1]), geometry)
                optimum = maximum_cost(pair_by_score(batch, lambda pack: pack_cost(pack, geometry)), geometry)
                wrong = maximum_cost(pair_by_score(batch, lambda pack: pack_cost(pack, wrong_geometry)), geometry)
                assert optimum <= min(baseline, wrong)
                gains.append(100 * (baseline - optimum) / baseline)
                wrong_gains.append(100 * (baseline - wrong) / baseline)
            summary[f"{geometry[0]}x{geometry[1]}"] = {
                "mean_optimal_reduction_pct": mean(gains),
                "median_optimal_reduction_pct": median(gains),
                "windows_with_strict_gain": sum(value > 0 for value in gains),
                "windows_where_wrong_geometry_worsens": sum(value < 0 for value in wrong_gains),
                "mean_wrong_geometry_reduction_pct": mean(wrong_gains),
            }
        output[kind] = summary
    return output


def test():
    comparisons = 0
    for geometry in GEOMETRIES:
        for length in range(1, 202):
            assert loop_count(length, geometry) == enumerate_mask_cells(length, geometry)
            comparisons += 1
    # Check the opposite pairing against every pairing of six small jobs.
    def exhaustive(values):
        if not values:
            return 0
        return min(max(values[0] + other, exhaustive(values[1:i] + values[i+1:]))
                   for i, other in enumerate(values[1:], 1))

    rng = random.Random(91)
    for _ in range(512):
        values = tuple(rng.randrange(1, 20) for _ in range(6))
        order = sorted(values)
        assert max(order[i] + order[-1-i] for i in range(3)) == exhaustive(values)
    return {"mask_grid_cases": comparisons, "exhaustive_pairing_cases": 512}


def verify_public_sources():
    root = f"https://raw.githubusercontent.com/Dao-AILab/flash-attention/{PIN}/csrc/flash_attn/"
    for path, digest in SOURCE_HASHES.items():
        with urlopen(root + path, timeout=20) as response:
            actual = hashlib.sha256(response.read()).hexdigest()
        if actual != digest:
            raise RuntimeError(f"Unexpected SHA-256 for {path}: {actual}")


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--verify-source", action="store_true", help="Verify pinned public sources via HTTPS.")
    args = parser.parse_args()
    if args.verify_source:
        verify_public_sources()
    print(json.dumps({
        "flash_attention_commit": PIN,
        "verified_source_hashes": SOURCE_HASHES if args.verify_source else None,
        "cpu_checks": test(),
        "previous_example": examples(ORIGINAL),
        "equal_maximum_cross_geometry_reversal": examples(REVERSAL),
        "windows_per_workload": 2048,
        "replay": replay(),
    }, indent=2))

attention_geometry_gpu_probe.py

SHA-256: 9b8c603624a640b518f2627324e3eaa4cfe99180a6417047e76ffbda7265fa58

<!– FILE: attention_geometry_gpu_probe.py –>

#!/usr/bin/env python3
"""Measure matched packs whose FlashAttention tile counts change order."""

import argparse
import json
import statistics

from itertools import accumulate


CASES = {
    "cross_geometry_reversal": ((16, 137, 187, 193), (19, 128, 193, 193)),
    "equal_pairs": ((62, 65, 65), (63, 63, 66)),
    "equal_pairs_and_max_length": ((62, 65, 65, 68), (63, 63, 66, 68)),
    "equal_pairs_and_query_blocks": ((1, 66, 118), (22, 34, 129)),
    "equal_pairs_query_blocks_and_max_length": ((1, 66, 118, 129), (22, 34, 129, 129)),
    "lengths_below_boundary": ((30, 33, 33, 36), (31, 31, 34, 36)),
}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--case", choices=CASES, default="cross_geometry_reversal")
    parser.add_argument("--copies", type=int, default=256, help="Repeat each pack as independent sequences.")
    parser.add_argument("--heads", type=int, default=8)
    parser.add_argument("--head-dim", type=int, default=128)
    parser.add_argument("--repeats", type=int, default=20)
    parser.add_argument("--inner", type=int, default=20)
    parser.add_argument("--backward", action="store_true", help="Measure forward and backward together.")
    args = parser.parse_args()
    if min(args.copies, args.heads, args.head_dim, args.repeats, args.inner) <= 0:
        parser.error("All counts must be positive.")

    try:
        import torch
        from flash_attn import flash_attn_varlen_func
    except ImportError as error:
        parser.exit(2, f"Install compatible PyTorch and flash-attn packages to run this probe: {error}\n")

    if not torch.cuda.is_available():
        parser.exit(2, "A compatible CUDA GPU is required.\n")

    packs = CASES[args.case]
    totals = [sum(pack) for pack in packs]
    if totals[0] != totals[1]:
        parser.error("Matched workloads must contain equal token counts.")

    torch.manual_seed(42)
    shape = (totals[0] * args.copies, args.heads, args.head_dim)
    inputs = tuple(
        torch.randn(shape, dtype=torch.float16, device="cuda", requires_grad=args.backward)
        for _ in range(3)
    )
    output_gradient = torch.randn_like(inputs[0]) if args.backward else None

    def setup(pack):
        offsets = torch.tensor(
            [0, *accumulate(pack * args.copies)], device="cuda", dtype=torch.int32
        )
        return offsets, max(pack)

    layouts = [setup(pack) for pack in packs]

    def attention(layout):
        offsets, maximum = layout
        output = flash_attn_varlen_func(
            *inputs, offsets, offsets, maximum, maximum, dropout_p=0.0, causal=True
        )
        if args.backward:
            torch.autograd.grad(output, inputs, output_gradient)

    for _ in range(5):
        for layout in layouts:
            attention(layout)
    torch.cuda.synchronize()

    samples = [[], []]
    for trial in range(args.repeats):
        order = (0, 1) if trial % 2 == 0 else (1, 0)
        for index in order:
            start = torch.cuda.Event(enable_timing=True)
            end = torch.cuda.Event(enable_timing=True)
            start.record()
            for _ in range(args.inner):
                attention(layouts[index])
            end.record()
            end.synchronize()
            samples[index].append(start.elapsed_time(end) / args.inner)

    from importlib.metadata import version

    installed_version = version("flash-attn")

    print(json.dumps({
        "case": args.case,
        "packs": packs,
        "copies": args.copies,
        "heads": args.heads,
        "head_dim": args.head_dim,
        "timed_calls_per_trial": args.inner,
        "includes_backward": args.backward,
        "gpu": torch.cuda.get_device_name(),
        "gpu_compute_capability": torch.cuda.get_device_capability(),
        "torch": torch.__version__,
        "cuda": torch.version.cuda,
        "flash_attn": installed_version,
        "milliseconds_per_call": samples,
        "median_milliseconds_per_call": [statistics.median(group) for group in samples],
        "note": "The package chooses its own tile shapes. Inspect the kernel in a profiler before attributing differences to tile boundaries.",
    }, indent=2))


if __name__ == "__main__":
    main()

attention_tile_gpu_probe.py

SHA-256: b228ae72cc5313b649037f1a9e620bf076c389bd37d6323ff9e4aceef3971d70

<!– FILE: attention_tile_gpu_probe.py –>

#!/usr/bin/env python3
"""Optional CUDA probe for the matched sequence packs in the research note."""

import argparse
import json
import statistics

from itertools import accumulate


CASES = {
    "equal_pairs": ((62, 65, 65), (63, 63, 66)),
    "equal_pairs_and_max_length": ((62, 65, 65, 68), (63, 63, 66, 68)),
    "equal_pairs_and_query_blocks": ((1, 66, 118), (22, 34, 129)),
    "equal_pairs_query_blocks_and_max_length": ((1, 66, 118, 129), (22, 34, 129, 129)),
    "lengths_below_boundary": ((30, 33, 33, 36), (31, 31, 34, 36)),
}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--case", choices=CASES, default="equal_pairs_and_max_length")
    parser.add_argument("--copies", type=int, default=256, help="Repeat each pack as independent sequences.")
    parser.add_argument("--heads", type=int, default=8)
    parser.add_argument("--head-dim", type=int, default=64)
    parser.add_argument("--repeats", type=int, default=20)
    parser.add_argument("--inner", type=int, default=20)
    parser.add_argument("--backward", action="store_true", help="Measure forward and backward together.")
    args = parser.parse_args()
    if min(args.copies, args.heads, args.head_dim, args.repeats, args.inner) <= 0:
        parser.error("All counts must be positive.")

    try:
        import torch
        from flash_attn import flash_attn_varlen_func
    except ImportError as error:
        parser.exit(2, f"Install compatible PyTorch and flash-attn packages to run this probe: {error}\n")

    if not torch.cuda.is_available():
        parser.exit(2, "A compatible CUDA GPU is required.\n")

    packs = CASES[args.case]
    totals = [sum(pack) for pack in packs]
    if totals[0] != totals[1]:
        parser.error("Matched workloads must contain equal token counts.")

    torch.manual_seed(42)
    shape = (totals[0] * args.copies, args.heads, args.head_dim)
    inputs = tuple(
        torch.randn(shape, dtype=torch.float16, device="cuda", requires_grad=args.backward)
        for _ in range(3)
    )
    output_gradient = torch.randn_like(inputs[0]) if args.backward else None

    def setup(pack):
        offsets = torch.tensor(
            [0, *accumulate(pack * args.copies)], device="cuda", dtype=torch.int32
        )
        return offsets, max(pack)

    layouts = [setup(pack) for pack in packs]

    def attention(layout):
        offsets, maximum = layout
        output = flash_attn_varlen_func(
            *inputs, offsets, offsets, maximum, maximum, dropout_p=0.0, causal=True
        )
        if args.backward:
            torch.autograd.grad(output, inputs, output_gradient)

    for _ in range(5):
        for layout in layouts:
            attention(layout)
    torch.cuda.synchronize()

    samples = [[], []]
    for trial in range(args.repeats):
        order = (0, 1) if trial % 2 == 0 else (1, 0)
        for index in order:
            start = torch.cuda.Event(enable_timing=True)
            end = torch.cuda.Event(enable_timing=True)
            start.record()
            for _ in range(args.inner):
                attention(layouts[index])
            end.record()
            end.synchronize()
            samples[index].append(start.elapsed_time(end) / args.inner)

    from importlib.metadata import version

    print(json.dumps({
        "case": args.case,
        "packs": packs,
        "copies": args.copies,
        "heads": args.heads,
        "head_dim": args.head_dim,
        "timed_calls_per_trial": args.inner,
        "includes_backward": args.backward,
        "gpu": torch.cuda.get_device_name(),
        "torch": torch.__version__,
        "cuda": torch.version.cuda,
        "flash_attn": version("flash-attn"),
        "milliseconds_per_call": samples,
        "median_milliseconds_per_call": [statistics.median(group) for group in samples],
        "note": "The package chooses its own tile shapes. Inspect the kernel in a profiler before attributing differences to tile boundaries.",
    }, indent=2))


if __name__ == "__main__":
    main()

dpo_pair_normalization_ddp.py

SHA-256: 85754932d570571b66690e72624fe665117ef65ad5b7a9c502fee9b880a092b7

<!– FILE: dpo_pair_normalization_ddp.py –>

#!/usr/bin/env python3
"""Compare flat DPO normalization with uneven accumulation and two CPU DDP ranks."""
import argparse
from datetime import timedelta
from fractions import Fraction
from itertools import product
import json
import math
from pathlib import Path
from tempfile import TemporaryDirectory


def imbalance(sizes):
    total = sum(sizes)
    return sum(abs(Fraction(1, len(sizes)) - Fraction(size, total)) for size in sizes)


def assert_sharp_bound():
    count = 0
    for num_chunks in range(1, 6):
        for sizes in product(range(1, 7), repeat=num_chunks):
            differences = [Fraction(1, num_chunks) - Fraction(size, sum(sizes)) for size in sizes]
            witness = [1 if weight >= 0 else -1 for weight in differences]
            assert sum(a * b for a, b in zip(differences, witness)) == imbalance(sizes)
            count += 1
    return count


def local_gradients():
    import torch
    from torch.nn import functional as F

    theta = torch.zeros((), dtype=torch.float64, requires_grad=True)
    feature = torch.tensor([-3.0, 2.0, 2.0], dtype=torch.float64)
    # Equal reference probabilities and two policy logits [theta * feature, 0].
    # The difference of policy log probabilities is exactly theta * feature.
    losses = -F.logsigmoid(theta * feature)
    parts = losses.split([1, 2])
    objectives = {
        "full_batch": losses.mean(),
        "equal_microbatch_means": sum(part.mean() for part in parts) / len(parts),
        "global_pair_normalization": sum(part.sum() for part in parts) / len(losses),
    }
    return {name: torch.autograd.grad(obj, theta, retain_graph=True)[0].item()
            for name, obj in objectives.items()}


def replay_rank_average():
    import torch
    from torch.nn import functional as F

    rank_features = ([-3.0], [2.0, 2.0])
    total = sum(map(len, rank_features))
    gradients = {"equal_rank_means": [], "global_pair_normalization": []}
    for features in rank_features:
        theta = torch.zeros((), dtype=torch.float64, requires_grad=True)
        losses = -F.logsigmoid(theta * torch.tensor(features, dtype=torch.float64))
        gradients["equal_rank_means"].append(
            torch.autograd.grad(losses.mean(), theta, retain_graph=True)[0].item()
        )
        gradients["global_pair_normalization"].append(
            torch.autograd.grad(losses.sum() * len(rank_features) / total, theta)[0].item()
        )
    return {name: sum(values) / len(values) for name, values in gradients.items()}


def ddp_worker(rank, directory):
    import torch
    from torch import distributed as dist
    from torch.nn import functional as F
    from torch.nn.parallel import DistributedDataParallel

    torch.set_num_threads(1)
    address = (Path(directory) / "rendezvous").as_uri()
    dist.init_process_group("gloo", init_method=address, rank=rank, world_size=2, timeout=timedelta(seconds=30))
    try:
        model = torch.nn.Linear(1, 1, bias=False, dtype=torch.float64)
        with torch.no_grad():
            model.weight.zero_()
        model = DistributedDataParallel(model)
        feature = torch.tensor([[-3.0]] if rank == 0 else [[2.0], [2.0]], dtype=torch.float64)
        count = torch.tensor(len(feature), dtype=torch.int64)
        dist.all_reduce(count)
        results = {}
        for name in ("equal_rank_means", "global_pair_normalization"):
            model.zero_grad(set_to_none=True)
            losses = -F.logsigmoid(model(feature).flatten())
            if name == "equal_rank_means":
                loss = losses.mean()
            else:
                loss = losses.sum() * dist.get_world_size() / count.item()
            loss.backward()
            results[name] = model.module.weight.grad.item()
        (Path(directory) / f"rank{rank}.json").write_text(json.dumps(results))
    finally:
        dist.destroy_process_group()


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--math-only", action="store_true")
    parser.add_argument("--ddp", action="store_true", help="Also run two Gloo ranks; requires local sockets.")
    args = parser.parse_args()
    if args.math_only and args.ddp:
        parser.error("--math-only and --ddp are mutually exclusive")
    output = {
        "sharp_bound_size_patterns_checked": assert_sharp_bound(),
        "sizes": [1, 2],
        "pair_gradient_weights_l1_difference": str(imbalance([1, 2])),
        "exact_full_gradient": "-1/6",
        "exact_naive_gradient": "1/4",
    }
    if not args.math_only:
        import torch
        from torch.multiprocessing import spawn
        torch.set_num_threads(1)
        local = local_gradients()
        rank_replay = replay_rank_average()
        assert math.isclose(local["full_batch"], -1/6, abs_tol=1e-12)
        assert math.isclose(local["equal_microbatch_means"], 1/4, abs_tol=1e-12)
        assert math.isclose(local["global_pair_normalization"], -1/6, abs_tol=1e-12)
        assert math.isclose(rank_replay["equal_rank_means"], 1/4, abs_tol=1e-12)
        assert math.isclose(rank_replay["global_pair_normalization"], -1/6, abs_tol=1e-12)
        output.update(pytorch=torch.__version__, cpu_autograd=local, cpu_rank_average_replay=rank_replay)
        if args.ddp:
            with TemporaryDirectory() as directory:
                spawn(ddp_worker, args=(directory,), nprocs=2, join=True)
                ddp = [json.loads((Path(directory) / f"rank{rank}.json").read_text()) for rank in range(2)]
            for result in ddp:
                for name, target in rank_replay.items():
                    assert math.isclose(result[name], target, abs_tol=1e-12)
            output["ddp_gloo"] = ddp
    print(json.dumps(output, indent=2))


if __name__ == "__main__":
    main()

dpo_dropout_results.json

SHA-256: 8bb3c5fa81a1d5952c3dc5f90cbbdb0615417940a7f432ac937b18be3e4da0fc

<!– FILE: dpo_dropout_results.json –>

{
  "independent": {
    "exact": "1/32",
    "finite_difference": 0.031249999998816943
  },
  "shared": {
    "exact": "-1/32",
    "finite_difference": -0.031249999998816943
  },
  "tested_offsets_with_reversal": [
    "0.51",
    "0.52",
    "0.53",
    "0.54",
    "0.55",
    "0.56",
    "0.57",
    "0.58",
    "0.59"
  ],
  "two_class_linear_softmax": {
    "independent": {
      "exact": "1/30",
      "finite_difference": 0.033333333340768156
    },
    "shared": {
      "exact": "-1/24",
      "finite_difference": -0.0416666666558374
    }
  }
}

dpo_cpu_autograd_and_guard_results.json

SHA-256: dc0e36f4fff14fed526293946b78bfbfca8b8366d013dd05e8dd666fcf7f368b

<!– FILE: dpo_cpu_autograd_and_guard_results.json –>

{
  "torch": "2.7.1+cpu",
  "expected_gradients": {
    "three_answers": {
      "independent": 0.031250000000000014,
      "shared": -0.031249999999999972,
      "opposite": 0.09375000000000003,
      "zero_gradient_probability_of_equal_masks": "3/4"
    },
    "two_answer_softmax": {
      "independent": 0.03333333333333327,
      "shared": -0.04166666666666674,
      "opposite": 0.10833333333333325,
      "zero_gradient_probability_of_equal_masks": "13/18"
    }
  },
  "guard_state_order": [
    "before_adapter",
    "after_late_adapter_in_train",
    "eval",
    "train_again"
  ],
  "upstream_guard": {
    "initial_prefix_sharing_pr": {
      "revision": "988ed46a817332ec04ee0581432241b062fe8877",
      "sha256": "cf50f229fe6d3184f8009062bafad52636fbe4484a60bffe73ca59020859079b",
      "guard_states": [
        false,
        false,
        false,
        false
      ]
    },
    "late_adapter_fix_pr": {
      "revision": "1180e5795c24edfb8cd418412265d5d5bf11510f",
      "sha256": "e087143c6cb27243e039ecebc455370e54aa9da94dd4f6e9cfeecf139d667445",
      "guard_states": [
        false,
        true,
        false,
        true
      ]
    },
    "main_snapshot": {
      "revision": "ca92fc2fd4afaad4912b4266874648bffdf061f5",
      "sha256": "9d698ef3ddb626649bff53c615e90666391d36eee0e129855fdca8ae4a6ae7b3",
      "guard_states": [
        false,
        true,
        false,
        true
      ]
    }
  }
}

attention_tile_results.json

SHA-256: 9859cdf09f7ae98a8d14729eb5f656ecc4ecc8d907009b2db9bd5e091cb002a4

<!– FILE: attention_tile_results.json –>

{
  "independent_grid_comparisons": 6400,
  "examples_64_by_64": {
    "equal_moments": [
      {
        "lengths": [
          62,
          65,
          65
        ],
        "tokens": 192,
        "squares": 12294,
        "valid_pairs": 6243,
        "query_blocks": 5,
        "tiles": 7
      },
      {
        "lengths": [
          63,
          63,
          66
        ],
        "tokens": 192,
        "squares": 12294,
        "valid_pairs": 6243,
        "query_blocks": 4,
        "tiles": 5
      }
    ],
    "strict_reversal_for_64_by_64": [
      {
        "lengths": [
          62,
          65,
          65
        ],
        "tokens": 192,
        "squares": 12294,
        "valid_pairs": 6243,
        "query_blocks": 5,
        "tiles": 7
      },
      {
        "lengths": [
          60,
          64,
          68
        ],
        "tokens": 192,
        "squares": 12320,
        "valid_pairs": 6256,
        "query_blocks": 4,
        "tiles": 5
      }
    ],
    "equal_maximum": [
      {
        "lengths": [
          62,
          65,
          65,
          68
        ],
        "tokens": 260,
        "squares": 16918,
        "valid_pairs": 8589,
        "query_blocks": 7,
        "tiles": 10
      },
      {
        "lengths": [
          63,
          63,
          66,
          68
        ],
        "tokens": 260,
        "squares": 16918,
        "valid_pairs": 8589,
        "query_blocks": 6,
        "tiles": 8
      }
    ],
    "equal_maximum_and_query_blocks": [
      {
        "lengths": [
          1,
          66,
          118,
          129
        ],
        "tokens": 314,
        "squares": 34922,
        "valid_pairs": 17618,
        "query_blocks": 8,
        "tiles": 13
      },
      {
        "lengths": [
          22,
          34,
          129,
          129
        ],
        "tokens": 314,
        "squares": 34922,
        "valid_pairs": 17618,
        "query_blocks": 8,
        "tiles": 14
      }
    ],
    "below_64_boundary": [
      {
        "lengths": [
          30,
          33,
          33,
          36
        ],
        "tokens": 132,
        "squares": 4374,
        "valid_pairs": 2253,
        "query_blocks": 4,
        "tiles": 4
      },
      {
        "lengths": [
          31,
          31,
          34,
          36
        ],
        "tokens": 132,
        "squares": 4374,
        "valid_pairs": 2253,
        "query_blocks": 4,
        "tiles": 4
      }
    ]
  },
  "examples_64_by_32": {
    "equal_moments": [
      {
        "lengths": [
          62,
          65,
          65
        ],
        "tokens": 192,
        "squares": 12294,
        "valid_pairs": 6243,
        "query_blocks": 5,
        "tiles": 12
      },
      {
        "lengths": [
          63,
          63,
          66
        ],
        "tokens": 192,
        "squares": 12294,
        "valid_pairs": 6243,
        "query_blocks": 4,
        "tiles": 9
      }
    ],
    "strict_reversal_for_64_by_64": [
      {
        "lengths": [
          62,
          65,
          65
        ],
        "tokens": 192,
        "squares": 12294,
        "valid_pairs": 6243,
        "query_blocks": 5,
        "tiles": 12
      },
      {
        "lengths": [
          60,
          64,
          68
        ],
        "tokens": 192,
        "squares": 12320,
        "valid_pairs": 6256,
        "query_blocks": 4,
        "tiles": 9
      }
    ],
    "equal_maximum": [
      {
        "lengths": [
          62,
          65,
          65,
          68
        ],
        "tokens": 260,
        "squares": 16918,
        "valid_pairs": 8589,
        "query_blocks": 7,
        "tiles": 17
      },
      {
        "lengths": [
          63,
          63,
          66,
          68
        ],
        "tokens": 260,
        "squares": 16918,
        "valid_pairs": 8589,
        "query_blocks": 6,
        "tiles": 14
      }
    ],
    "equal_maximum_and_query_blocks": [
      {
        "lengths": [
          1,
          66,
          118,
          129
        ],
        "tokens": 314,
        "squares": 34922,
        "valid_pairs": 17618,
        "query_blocks": 8,
        "tiles": 23
      },
      {
        "lengths": [
          22,
          34,
          129,
          129
        ],
        "tokens": 314,
        "squares": 34922,
        "valid_pairs": 17618,
        "query_blocks": 8,
        "tiles": 25
      }
    ],
    "below_64_boundary": [
      {
        "lengths": [
          30,
          33,
          33,
          36
        ],
        "tokens": 132,
        "squares": 4374,
        "valid_pairs": 2253,
        "query_blocks": 4,
        "tiles": 7
      },
      {
        "lengths": [
          31,
          31,
          34,
          36
        ],
        "tokens": 132,
        "squares": 4374,
        "valid_pairs": 2253,
        "query_blocks": 4,
        "tiles": 6
      }
    ]
  },
  "examples_128_by_128": {
    "equal_moments": [
      {
        "lengths": [
          62,
          65,
          65
        ],
        "tokens": 192,
        "squares": 12294,
        "valid_pairs": 6243,
        "query_blocks": 3,
        "tiles": 3
      },
      {
        "lengths": [
          63,
          63,
          66
        ],
        "tokens": 192,
        "squares": 12294,
        "valid_pairs": 6243,
        "query_blocks": 3,
        "tiles": 3
      }
    ],
    "strict_reversal_for_64_by_64": [
      {
        "lengths": [
          62,
          65,
          65
        ],
        "tokens": 192,
        "squares": 12294,
        "valid_pairs": 6243,
        "query_blocks": 3,
        "tiles": 3
      },
      {
        "lengths": [
          60,
          64,
          68
        ],
        "tokens": 192,
        "squares": 12320,
        "valid_pairs": 6256,
        "query_blocks": 3,
        "tiles": 3
      }
    ],
    "equal_maximum": [
      {
        "lengths": [
          62,
          65,
          65,
          68
        ],
        "tokens": 260,
        "squares": 16918,
        "valid_pairs": 8589,
        "query_blocks": 4,
        "tiles": 4
      },
      {
        "lengths": [
          63,
          63,
          66,
          68
        ],
        "tokens": 260,
        "squares": 16918,
        "valid_pairs": 8589,
        "query_blocks": 4,
        "tiles": 4
      }
    ],
    "equal_maximum_and_query_blocks": [
      {
        "lengths": [
          1,
          66,
          118,
          129
        ],
        "tokens": 314,
        "squares": 34922,
        "valid_pairs": 17618,
        "query_blocks": 5,
        "tiles": 6
      },
      {
        "lengths": [
          22,
          34,
          129,
          129
        ],
        "tokens": 314,
        "squares": 34922,
        "valid_pairs": 17618,
        "query_blocks": 6,
        "tiles": 8
      }
    ],
    "below_64_boundary": [
      {
        "lengths": [
          30,
          33,
          33,
          36
        ],
        "tokens": 132,
        "squares": 4374,
        "valid_pairs": 2253,
        "query_blocks": 4,
        "tiles": 4
      },
      {
        "lengths": [
          31,
          31,
          34,
          36
        ],
        "tokens": 132,
        "squares": 4374,
        "valid_pairs": 2253,
        "query_blocks": 4,
        "tiles": 4
      }
    ]
  },
  "exhaustive_search_64_by_64": {
    "max_length": 192,
    "triples_checked": 1198144,
    "same_tokens_and_squares": {
      "groups_with_different_tile_counts": 148414,
      "maximum_ratio": "12/7",
      "example": [
        {
          "lengths": [
            45,
            101,
            114
          ],
          "tokens": 260,
          "squares": 25222,
          "valid_pairs": 12741,
          "query_blocks": 5,
          "tiles": 7
        },
        {
          "lengths": [
            65,
            66,
            129
          ],
          "tokens": 260,
          "squares": 25222,
          "valid_pairs": 12741,
          "query_blocks": 7,
          "tiles": 12
        }
      ]
    },
    "also_same_query_blocks": {
      "groups_with_different_tile_counts": 23270,
      "maximum_ratio": "8/7",
      "example": [
        {
          "lengths": [
            1,
            66,
            118
          ],
          "tokens": 185,
          "squares": 18281,
          "valid_pairs": 9233,
          "query_blocks": 5,
          "tiles": 7
        },
        {
          "lengths": [
            22,
            34,
            129
          ],
          "tokens": 185,
          "squares": 18281,
          "valid_pairs": 9233,
          "query_blocks": 5,
          "tiles": 8
        }
      ]
    }
  },
  "two_worker_example": {
    "fixed_packs": [
      [
        62,
        65,
        65
      ],
      [
        62,
        65,
        65
      ],
      [
        63,
        63,
        66
      ],
      [
        63,
        63,
        66
      ]
    ],
    "first_two_to_worker_one": [
      14,
      10
    ],
    "optimal_with_two_packs_on_each_worker": [
      12,
      12
    ]
  }
}

attention_geometry_replay_results.json

SHA-256: 05b2c48891cb5450e0573b0ac4818dda65c6aaee1f1fca42601e054d193d5b87

<!– FILE: attention_geometry_replay_results.json –>

{
  "flash_attention_commit": "060c9188beec3a8b62b33a3bfa6d5d2d44975fab",
  "verified_source_hashes": {
    "src/flash_fwd_kernel.h": "765dd3ef217bc9d79c9c0494ba52ea63767099be737c14604bec748d85f0dde3",
    "src/flash_fwd_launch_template.h": "d9e9f4b92cb731d7955b514449e59b8e411bf7a0c929aafb454f2402d41fe976",
    "flash_api.cpp": "7fcefdccf0d08ad0f6cceab48383560202ca6dc2bc1ffd50e8a43aa1c2eea14a"
  },
  "cpu_checks": {
    "mask_grid_cases": 804,
    "exhaustive_pairing_cases": 512
  },
  "previous_example": {
    "packs": [
      [
        62,
        65,
        65
      ],
      [
        63,
        63,
        66
      ]
    ],
    "tokens": 192,
    "valid_causal_pairs": 6243,
    "max_lengths": [
      65,
      66
    ],
    "counts": {
      "64x64": [
        7,
        5
      ],
      "128x64": [
        5,
        4
      ],
      "128x128": [
        3,
        3
      ],
      "128x32": [
        8,
        7
      ]
    },
    "launched_ctas_per_head": {
      "64x64": [
        6,
        6
      ],
      "128x64": [
        3,
        3
      ],
      "128x128": [
        3,
        3
      ],
      "128x32": [
        3,
        3
      ]
    }
  },
  "equal_maximum_cross_geometry_reversal": {
    "packs": [
      [
        16,
        137,
        187,
        193
      ],
      [
        19,
        128,
        193,
        193
      ]
    ],
    "tokens": 533,
    "valid_causal_pairs": 45888,
    "max_lengths": [
      193,
      193
    ],
    "counts": {
      "64x64": [
        23,
        24
      ],
      "128x64": [
        17,
        15
      ],
      "128x128": [
        10,
        8
      ],
      "128x32": [
        31,
        27
      ]
    },
    "launched_ctas_per_head": {
      "64x64": [
        16,
        16
      ],
      "128x64": [
        8,
        8
      ],
      "128x128": [
        8,
        8
      ],
      "128x32": [
        8,
        8
      ]
    }
  },
  "windows_per_workload": 2048,
  "replay": {
    "near_boundaries": {
      "64x64": {
        "mean_optimal_reduction_pct": 6.303934509500916,
        "median_optimal_reduction_pct": 7.6923076923076925,
        "windows_with_strict_gain": 1216,
        "windows_where_wrong_geometry_worsens": 214,
        "mean_wrong_geometry_reduction_pct": 1.7601018772893773
      },
      "128x64": {
        "mean_optimal_reduction_pct": 4.974416731654784,
        "median_optimal_reduction_pct": 2.9411764705882355,
        "windows_with_strict_gain": 1216,
        "windows_where_wrong_geometry_worsens": 214,
        "mean_wrong_geometry_reduction_pct": 2.351278757241533
      },
      "128x128": {
        "mean_optimal_reduction_pct": 2.762276785714286,
        "median_optimal_reduction_pct": 0.0,
        "windows_with_strict_gain": 396,
        "windows_where_wrong_geometry_worsens": 0,
        "mean_wrong_geometry_reduction_pct": 2.762276785714286
      },
      "128x32": {
        "mean_optimal_reduction_pct": 3.7388223315042164,
        "median_optimal_reduction_pct": 1.5625,
        "windows_with_strict_gain": 1216,
        "windows_where_wrong_geometry_worsens": 214,
        "mean_wrong_geometry_reduction_pct": 2.1713499038938493
      }
    },
    "short_compositions": {
      "64x64": {
        "mean_optimal_reduction_pct": 4.696976348872067,
        "median_optimal_reduction_pct": 5.2631578947368425,
        "windows_with_strict_gain": 1585,
        "windows_where_wrong_geometry_worsens": 843,
        "mean_wrong_geometry_reduction_pct": -0.7742925804198589
      },
      "128x64": {
        "mean_optimal_reduction_pct": 7.170676019001002,
        "median_optimal_reduction_pct": 7.6923076923076925,
        "windows_with_strict_gain": 1853,
        "windows_where_wrong_geometry_worsens": 53,
        "mean_wrong_geometry_reduction_pct": 5.087917499591668
      },
      "128x128": {
        "mean_optimal_reduction_pct": 5.6213669549851195,
        "median_optimal_reduction_pct": 6.666666666666667,
        "windows_with_strict_gain": 1356,
        "windows_where_wrong_geometry_worsens": 150,
        "mean_wrong_geometry_reduction_pct": 0.7698142921531593
      },
      "128x32": {
        "mean_optimal_reduction_pct": 6.543754179831762,
        "median_optimal_reduction_pct": 8.333333333333334,
        "windows_with_strict_gain": 1904,
        "windows_where_wrong_geometry_worsens": 82,
        "mean_wrong_geometry_reduction_pct": 5.178372484464502
      }
    },
    "long_compositions": {
      "64x64": {
        "mean_optimal_reduction_pct": 0.0821428939203957,
        "median_optimal_reduction_pct": 0.0,
        "windows_with_strict_gain": 524,
        "windows_where_wrong_geometry_worsens": 638,
        "mean_wrong_geometry_reduction_pct": -0.11705751252731968
      },
      "128x64": {
        "mean_optimal_reduction_pct": 0.2584623793925582,
        "median_optimal_reduction_pct": 0.0,
        "windows_with_strict_gain": 883,
        "windows_where_wrong_geometry_worsens": 23,
        "mean_wrong_geometry_reduction_pct": 0.25766314728394873
      },
      "128x128": {
        "mean_optimal_reduction_pct": 0.27272427434757124,
        "median_optimal_reduction_pct": 0.0,
        "windows_with_strict_gain": 874,
        "windows_where_wrong_geometry_worsens": 191,
        "mean_wrong_geometry_reduction_pct": 0.07461702252264353
      },
      "128x32": {
        "mean_optimal_reduction_pct": 0.2546125858656055,
        "median_optimal_reduction_pct": 0.0,
        "windows_with_strict_gain": 878,
        "windows_where_wrong_geometry_worsens": 32,
        "mean_wrong_geometry_reduction_pct": 0.25398763859726864
      }
    },
    "aligned_control": {
      "64x64": {
        "mean_optimal_reduction_pct": 0.0,
        "median_optimal_reduction_pct": 0.0,
        "windows_with_strict_gain": 0,
        "windows_where_wrong_geometry_worsens": 1370,
        "mean_wrong_geometry_reduction_pct": -1.8318173785628733
      },
      "128x64": {
        "mean_optimal_reduction_pct": 1.0452702670544243,
        "median_optimal_reduction_pct": 0.9523809523809523,
        "windows_with_strict_gain": 1044,
        "windows_where_wrong_geometry_worsens": 61,
        "mean_wrong_geometry_reduction_pct": 0.9871564522534333
      },
      "128x128": {
        "mean_optimal_reduction_pct": 1.4884850604905489,
        "median_optimal_reduction_pct": 1.0526315789473684,
        "windows_with_strict_gain": 1172,
        "windows_where_wrong_geometry_worsens": 0,
        "mean_wrong_geometry_reduction_pct": 0.0
      },
      "128x32": {
        "mean_optimal_reduction_pct": 1.0452702670544243,
        "median_optimal_reduction_pct": 0.9523809523809523,
        "windows_with_strict_gain": 1044,
        "windows_where_wrong_geometry_worsens": 61,
        "mean_wrong_geometry_reduction_pct": 0.9871564522534333
      }
    }
  }
}

dpo_pair_normalization_ddp_results.json

SHA-256: b262e9a92454b01f90f03dadb692949ee3c0c55c5c3fdbf43a37db3ca0937f83

<!– FILE: dpo_pair_normalization_ddp_results.json –>

{
  "sharp_bound_size_patterns_checked": 9330,
  "sizes": [
    1,
    2
  ],
  "pair_gradient_weights_l1_difference": "1/3",
  "exact_full_gradient": "-1/6",
  "exact_naive_gradient": "1/4",
  "pytorch": "2.7.1+cpu",
  "cpu_autograd": {
    "full_batch": -0.16666666666666663,
    "equal_microbatch_means": 0.25,
    "global_pair_normalization": -0.16666666666666663
  },
  "cpu_rank_average_replay": {
    "equal_rank_means": 0.25,
    "global_pair_normalization": -0.16666666666666663
  }
}