Correctness and contracts report · NVIDIA/hyperflare-inference #673

Raw Markdown for agents: https://autobot.eidonix.com/p/7e684435-1716-4bd1-802e-7d4967cbe0a2.md

PR #673 — Correctness, Contracts & System-Level Consequences review

Scope: ignition/components/logprobs.py (+39/−22) and the new tests/components/test_logprobs.py (+278), read at head 1337213 and compared against ignition/components/logprobs.py at ref main.

Key findings


1. Correctness, Safety & Platform Parity — verified sound

I proved the merge exact and checked every adjacent contract; I report no defect in this area.

The chunked merge is bit-exact. ignition/components/logprobs.py:136-150:

            k = tl.arange(0, BLOCK)
            total: tl.constexpr = TILES * CANDIDATES
            base = pos * total
            keys = tl.load(Keys + base + k, k < total, other=0)
            keys = tl.sort(keys, descending=True)
            if total > BLOCK:
                step: tl.constexpr = BLOCK - CANDIDATES
                for offset in range(BLOCK, total, step):
                    idx = offset + (k - CANDIDATES)
                    incoming = tl.load(Keys + base + idx, (k >= CANDIDATES) & (idx < total), other=0)
                    keys = tl.where(k < CANDIDATES, keys, incoming)
                    keys = tl.sort(keys, descending=True)

Induction: after iteration i the buffer holds the descending sort of the top-32 of (first BLOCK keys ∪ chunks 1..i). The centre k < CANDIDATES is 32 slots and the tail (k >= CANDIDATES, i.e. up to 480 entries) is exactly one chunk, so no candidate is dropped and no non-candidate is fabricated; the 32 keys displaced out of the tail were already folded into the head on the previous step. The (idx < total) mask is not redundant — it is what makes the final short chunk (e.g. V=16,385 → tiles 17, total 544, one iteration loading only 32 entries) exact. other=0 sorts last: a finite-logit key is ≥ 0x007FFFFF<<32, and -inf encodes as 0x007FFFFF<<32|…, both > 0. MIN/MAX-free, so no NaN-induced nondeterminism is introduced beyond what main had.

Keeping 32 crossings is not a fixed-candidate truncation, so docs/core-design.md:1276-1279 ("threshold ties must never be truncated to a fixed number of candidates") is respected exactly as on main: _TILE_CANDIDATES = 32 ≥ MAX_TOP_LOGPROBS = 20 (logprobs.py:20, completion.py:15).

Argument positions after the constexpr→runtime move are still aligned. width occupies the slot WIDTH held (logprobs.py:112-117), so the downstream index arithmetic in prepare()/run() — start = 3 if operation is self.normalization else 4 (logprobs.py:215, :241) — still lands on (slots, epochs, live) and args[0] = logits still skips the None-ed Records. _statistics' (vocab, width, tiles, SLOTS, FIELDS, BLOCK) and _normalization's shorter tail all line up.

No ABI, buffer, or exported-core change. Scratch layout, shapes and dtypes are byte-identical to main (logprobs.py:167-171 vs main :149-153): stats [b,w,tiles,2] f32, lse [b,w] f32, keys [b,w,tiles,32] u64. _merge (logprobs.py:248-261) and the constructor signature are untouched. The new runtime width operand is a plain Python int, which ignition/preparation/aot.py:242-245 maps to an int signature entry and :264-294 shares across storage descriptors, so the operand serializes into the core without an ABI bump — the PR's "no runtime core format or ABI changes" claim holds. Previously exported cores embed their own cubins and never recompile, so they continue to load.

do_not_specialize is an established pattern on the pinned stack, already used at ignition/components/engram.py:23 and helios/tests/fixed_core_fixture.py:27 (not opened),33; no new dependency.

int64 promotion cannot change an address here. pos = row.to(tl.int64) * width + col (logprobs.py:66,83,101,121) with pos ≤ batch*width ≈ 2^20; this is defensive and costless at the shapes in play. Gating is unchanged: _position and the count > 0 / count == 0 split (logprobs.py:127, :135) are byte-identical to main; only pos widened.

No new concurrency, failure-propagation or memory hazard. _finish is one program per (row, col) (logprobs.py:118); the added loop introduces no barrier, lock, allocation, or host round-trip, and the scratch is allocated outside the kernel, so CUDA-graph capture safety is preserved. No memory amplification, no unbounded buffering, no cross-program dependency, and therefore no head-of-line blocking or blast radius from a slow/cancelled peer. This area is genuinely clean.


2. Unintended system-level consequences

2.1 Major — the chunked merge changes the launch for every vocabulary ≥ 16,385, but only V=262,144 is measured

ignition/components/logprobs.py:164:

        merge_block = min(triton.next_power_of_2(tiles * _TILE_CANDIDATES), _MERGE_BLOCK)

main ignition/components/logprobs.py:164-167 passed the unbounded value:

            (_finish, (*common, self.lse, self.keys, completion.logprobs, completion.token_ids,
                completion.token_id_counts, *dimensions,
                triton.next_power_of_2(tiles * _TILE_CANDIDATES), _TILE_CANDIDATES,

so the before/after _finish launch table is:

vocab tiles total keys main (BLOCK / warps) PR (BLOCK / warps) extra serial sorts
1,024 1 32 32 / 8 32 / 4 0
8,192 8 256 256 / 8 256 / 4 0
16,384 16 512 512 / 8 512 / 4 0
16,385 17 544 1024 / 8 512 / 4 1
131,072 128 4,096 4096 / 8 512 / 4 8
262,144 256 8,192 8192 / 8 512 / 4 16

The PR body reports exactly one row for _finish, at V=262,144, and its own limitations list concedes:

- **Limitations:** `SM103`/`SM120`/`SM121` GPUs, end-to-end `ignition export` / `flare run` serving benchmarks, and Orin Nano's old `BLOCK=8192` runtime latency were not measured in this pass.

Impact. 32k–128k vocabularies are the ones Flare actually serves on the targeted workstations. At V=131,072 the PR replaces one 4,096-element bitonic block sort with nine serial 512-element sorts on 4 warps: total compare-exchange work falls, but serialization depth rises, and which dominates at that tile count is precisely what was not measured. The PR is presented as a pure win on a path that changed for essentially every model.

Rules. docs/performance-work.md:1-7 ("Measure each optimization against a baseline with the same checkpoint, GPU assignment, activation precision, graph capacity, sampling settings, cache conditions, and completed work. Correctness failures block performance claims"), :119-124 ("Do not infer a speedup from draft depth or a component benchmark alone"), and docs/logprobs-design.md:128-130 ("Performance claims about the reduction require complete replay and service measurements").

Fix. Add a _finish latency row (or a full prepared row) for V ∈ {32,768, 131,072, 262,144} at width 1 and max width, plus one exported-core comparison per docs/performance-work.md:45-51; or land only the width de-specialization, which is measured and unambiguous, and move the merge change to docs/TODO.txt per AGENTS.md:57-58.

2.2 Major — _MERGE_WARPS 8→4 silently changes the launch for every vocabulary, unmeasured

ignition/components/logprobs.py:21-26:

# Merge per-tile candidates in bounded chunks so large vocabularies (e.g. 256k -> 8192 keys)
# do not unroll an 8192-element bitonic network in Triton/PTX while keeping bit-exact ordering.
_MERGE_BLOCK = 512
assert _MERGE_BLOCK > _TILE_CANDIDATES and (_MERGE_BLOCK & (_MERGE_BLOCK - 1)) == 0
_REDUCTION_WARPS = 4
_MERGE_WARPS = 4

versus main ignition/components/logprobs.py:21-22: _REDUCTION_WARPS = 4 / _MERGE_WARPS = 8.

The PR body frames this only inside the cap bullet:

- **Chunked top-32 merge in `_finish` (`ignition/components/logprobs.py`):** Capped `_finish`'s sort block at `512` elements (`4` warps). Instead of growing up to `8,192`...

But the two edits are independent, and they have different blast radii. The 512 cap is inert for V ≤ 16,384 (see table); the 8 → 4 warp change applies at every vocabulary including the small ones, where _finish now runs a 32-lane sort on 4 warps instead of 8 — three quarters of the lanes idle around the same scalar _sort_pair/_position/store work. Nothing in the PR measures any vocabulary below 262,144, and no width-1 latency is reported at all.

Impact. A silent launch-shape change on the common small/medium vocabulary path, bundled under a headline about large vocabularies, with no before/after. It is also the exact kind of change docs/performance-work.md:1-7 requires an A/B for.

Fix. Either report _finish latency for a small (V ≤ 16,384) and a mid (V ≈ 128k) vocabulary before/after, or revert _MERGE_WARPS to 8 and keep only the cap — they are separable — and note the pair explicitly as two changes in the description.

2.3 Minor — _finish is still specialized per vocabulary; the bound is per sort block, not per vocabulary

ignition/components/logprobs.py:137-143 (quoted in §1) keeps TILES as tl.constexpr (logprobs.py:114), fed from tiles = triton.cdiv(vocab, _VOCAB_TILE) (logprobs.py:163). Because total and step are tl.constexpr, range(BLOCK, total, step) unrolls at trace time: V=262,144 emits 1 + 16 unrolled 512-element sorts in a single cubin, and a 1M vocabulary would emit 1 + 66.

Impact. Compile cost was bounded, not made vocabulary-independent; a core still carries one _finish cubin per prepared vocabulary, exactly as on main. The title ("Bound PreparedLogprobs merge block") and the single-vocabulary table can read as if the specialization were gone.

Fix. Description-only: state that _finish remains specialized per vocabulary because the merge depth follows the tile count. No code change required.


3. Architecture, contracts & charter compliance

3.1 Major — the design document that governs this code still describes the pre-PR behavior, and the PR updates no docs

docs/logprobs-design.md:90-100:

## Preparation and scratch

Four prepared Triton launches reduce requested positions. Vocabulary tiles first
compute FP32 maxima and exponential sums, then a small reduction writes each
position's normalization. Tiles retain their best 32 integer sort keys; a final
merge stores K pairs and the chosen token. Keys rank the reported FP32 logprobs
and inverse token ID, including ties introduced by subtraction.

After this PR the final launch is not one merge: BLOCK is capped at 512 (logprobs.py:23, :164) and the remaining candidates are folded in 480-key chunks with up to 16 additional tl.sort calls at V=262,144 (logprobs.py:141-147). The document also says nothing about the four launches now being width-agnostic (do_not_specialize at logprobs.py:59,76,93,112). The PR changes only ignition/components/logprobs.py and adds a test file — no doc is touched.

Rules. AGENTS.md:232 assigns docs/logprobs-design.md as the required guidance for "Change speculative decoding, log probabilities"; AGENTS.md:52-60 requires the documentation to specify the architecture and says design documents carry qualification text, not measurements; AGENTS.md:166 makes inaccurate documentation a valid contribution basis.

Fix. Two or three sentences in "Preparation and scratch": the merge is bounded (first 512 packed keys, then 480-key chunks retaining the running top 32), and the four launches are shared across speculative widths. No numbers in the design doc — unrun checks and pending measurements belong in docs/TODO.txt (AGENTS.md:57-58).

docs/api.md:107-122 (ties ordered by decreasing logprob then increasing token ID) remains accurate and needs no edit.

3.2 Charter compliance — aligned on layering, incomplete on the hardware matrix

The change is in a shared ignition component: no model branch, no flag, no config knob, no new dependency, and no per-model behavior (charter "Keep the runtime small and model-agnostic"). It rests on a measured problem, which AGENTS.md:165-169 accepts as a contribution basis. Two qualifications, already covered above: the roadmap's named targets SM103/SM120/SM121 were not exercised (docs/performance-work.md matrix; the PR says so), and the headline evidence is component-level rather than served-workload A/B (#210). Charter line 28 makes broad arbitrary-GPU coverage a non-goal, so the untested arches are a stated limitation rather than a scope violation — they are named honestly in the PR body.

3.3 No captured-graph op contract was added or altered

The op set, grid shapes ((batch, width, tiles) / (batch, width, 1)), buffers, and the PreparedLogprobs public methods (prepare/functional/run) are unchanged, so no owner sign-off is triggered for a new captured-graph op. The do_not_specialize edit changes Triton's program-cache identity, which is worth watching: issue #231 documents an "undeclared programs" preparation failure when specializations shift. A stale on-disk Triton cache after upgrade is a plausible operator-visible side effect, but nothing in this diff makes it more likely than any recompile, and I found no in-repo evidence of a stale-cache path. Reported as a note, not a finding.


4. Tests & claim accuracy

4.1 Verified accurate — the _finish latency row is not misattributed

PR body Result table:

| Jetson Thor (`SM110`) cold `PreparedLogprobs.prepare()` | `65.40 s` | `4.46 s` | **14.7× faster** |
| Jetson Thor (`SM110`) `_finish` GPU latency (width 6) | `84.2 us` | `38.2 us` | **2.2× faster** |
| Jetson Orin Nano 8 GiB (`SM87`) cold `PreparedLogprobs.prepare()` | ~19.5 min | 11.83 s | **~100× faster** |

Because main passed the unbounded next_power_of_2(tiles * 32) as BLOCK (main logprobs.py:166), V=262,144 on main sorted 8,192 keys in one network, and this PR sorts 512 keys then folds 16 chunks. So the 84.2 → 38.2 µs gain is attributable to the chunked merge (as well as to _MERGE_WARPS). I checked this specifically and found the claim direction correct; the deficiency is coverage (§2.1), not misattribution. I also could not reproduce the 65.40 s → 4.46 s cold-prepare() figures: they need 3-D logits (in-repo paths are all width == 1, logprobs.py:156-157) plus a Jetson; scripts/benchmark_logprobs.py is the in-repo harness and the PR does not cite it. The strength of that row is that it is a whole-prepare() measurement, which is the right scope; the weakness is that no artifact or command line is given.

4.2 Major — no CI-gating test can detect a merge regression

All three behavioral tests are opt-in: tests/components/test_logprobs.py:71 (and :122, :210):

@pytest.mark.skipif(os.environ.get("FLARE_RUN_CUDA_TESTS") != "1", reason="CUDA opt-in")

CI runs the CPU suite with the GPU masked (CUDA_VISIBLE_DEVICES: ""), so test_chunked_finish_matches_exact_top20_tie_ordering_and_preserves_inactive_slots, test_logprobs_kernels_share_one_specialization_and_execute_across_widths and test_logprobs_requested_token_ids_gating_and_functional_graph_capture never execute there. The one CI-visible test asserts a private-config integer, tests/components/test_logprobs.py:60-68:

def test_finish_merge_block_is_bounded_for_large_vocabularies(vocab, expected_block):
    completion, frame = _setup_completion("meta")
    logits = torch.empty((2, 6, vocab), dtype=torch.bfloat16, device="meta")
    ...
    finish_args = dict(zip(_finish.arg_names, op._preparation[3][1], strict=True))
    assert finish_args["BLOCK"] == expected_block

If the 480-key arithmetic at logprobs.py:141-147 were off by one, BLOCK would still be 512 and this test would still pass.

Rules. AGENTS.md:194-199: "Tests must exercise the affected behavior or contract; source-text checks and mocks that bypass the behavior cannot establish runtime correctness." AGENTS.md:302-307: "Report a skipped test as an unrun check."

Fair caveat. Every sibling tests/components/*_cuda.py (not opened) is gated identically, so this is repo-normal, and the PR does honestly report its hardware run (87 passed, 0 failed on Thor and Orin Nano). But this PR's headline guarantee is bit-exact tie ordering, and nothing automated protects it.

Impact. A future edit to _finish regresses silently; the merge is protected only by the author's two Jetsons.

Fix. Make the merge reproducible on CPU: the reference used by the CUDA tests (a stable descending argsort) already exists in the file as _reference_logprobs, so a NumPy/torch transcription of the 480-key fold could be checked against it for small vocabularies. Failing that, record in docs/TODO.txt that the four logprob kernels are hardware-verified only.

4.3 Minor — the CI-visible test couples to a private tuple this PR itself edits

tests/components/test_logprobs.py:67 (quoted above) zips _finish.arg_names against op._preparation[3][1]. _preparation is private (logprobs.py:176-186), emptied by prepare() (:203) and reordered by functional() (:214-218); this PR already edits the _finish entry at :182-185.

Impact. A future reordering of the prepared-operation tuple fails this test with a KeyError/ValueError that looks like a kernel regression.

Fix. Assert on a public expression instead — min(triton.next_power_of_2(triton.cdiv(vocab, 1024) * 32), _MERGE_BLOCK) == expected_block — or expose op.merge_block, which the constructor already computes at logprobs.py:164.

4.4 Minor — process: empty Discord: line, unmeasured checks not filed

The PR body's Discord: line has no value. AGENTS.md:144-153: "When the person provides no Discord username, the line states that explicitly: Discord: no username provided. Never omit the line." Second, the unmeasured items live only in the PR body, while AGENTS.md:57-58 requires: "Record unresolved defects, unrun checks, and pending measurements in docs/TODO.txt, not in design documents." A closely related entry already exists at docs/TODO.txt:175-178 ("Measure the serving cost of the 258-field completion_logprobs output … on an exported core").

Fix. Write Discord: no username provided, and add one TODO entry for the unmeasured _finish reduction at 32k–128k vocabularies and the unrun exported-core check (or fold it into the existing :175 entry).

4.5 Note on test coverage the PR does improve

tests/components/test_logprobs.py is the first direct test of _statistics/_normalization/_candidates/_finish; before it, no file exercised these kernels directly (tests/components/test_completion_outputs.py covers CompletionOutputs buffers and _merge, not the kernels). That is a real gain and should be credited — the finding above is about gating, not about test quality.


Open questions / not found

  1. Whether 4 warps hurts small/medium vocabularies. No measurement exists at any V below 262,144, and no width-1 _finish latency is reported. Only the author has the hardware.
  2. Worst-case serialization at V≈128k. Whether 8 serial 512-key sorts beat one 4,096-key sort at that tile count is unmeasured; the direction likely favors the PR (compare-exchange count drops ~3×) but this is an inference, not evidence.
  3. Stale Triton cache after upgrade (cf. #231's "undeclared programs" failure): no in-repo evidence either way on whether the specialization-key change surfaces to operators who upgrade in place.
  4. Multi-width provenance. Widths 1..6 come from outside this repo (in-repo paths are all width == 1, logprobs.py:156-157); the width-sharing benchmark needs scripts/benchmark_logprobs.py-style 3-D logits plus a Jetson, so it cannot be reproduced from the PR contents.
  5. Whether a doc update is a merge precondition here is a maintainer call; the repository states the requirement (AGENTS.md:232) but not the enforcement.