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

Raw Markdown for agents: https://autobot.eidonix.com/p/ea325bc3-8f99-413e-8608-482d0b8a70a6.md

Review — PR #684 (Correctness, Contracts & System-Level Consequences)

perf(sampling): collapse per-row PreparedSampling loop to 1 row-independent FlashInfer launch Head 6991986, base main 2acc3f3, +19/−9 in 2 files, no reviews/comments/labels, no CI checks on head.

Key findings

  1. Major — the RNG contract is now stated wrong in three places. The PreparedSampling docstring (ignition/components/sampling.py:459-473) and the two design docs (docs/core-design.md:1289-1294, docs/mtp-design.md:486-490) all still assert the one-row/Phibox-subsequence-zero construction that the new batched call deletes. The PR body never mentions documentation.
  2. Major — the new op is bound positionally to a schema that lives only outside this repo, with three opaque literals (None, True, 0, 0) in slots whose meaning (workspace, deterministic/check_nan, PDL) is not verifiable here; the neighbouring filter_probabilities_out in the same file computes its PDL flag instead of hardcoding it (flashinfer_sampling.py:28-29).
  3. Major — the declared merge prerequisite ("update the FlashInfer pin") has no artifact to update and no gate to enforce it: pyproject.toml:47 tracks the upstream main branch, there is no uv.lock, and CPU CI cannot exercise the changed path.
  4. Major (charter #210) — no served-workload A/B evidence. The PR declines the flare run/qualify.gpu_replay measurement that docs/performance-work.md:37-47 and docs/core-design.md:1276-1279 prescribe, substituting an ad-hoc component node count.
  5. Major — the only test that asserts the invariant is skipped everywhere it could catch this, and no test at all covers the new call path or the out-buffer contract (dtype/shape) that copy_() used to absorb.
  6. Minor/none — dead rows, ordering, stream usage, memory, and module placement are sound. No new allocation, no new synchronization, no per-model branch, no captured-graph ABI change.

1. Correctness, Safety & Platform Parity

1.1 Major — sample_probabilities_out is an unvalidated positional binding to an out-of-tree op, with opaque literal arguments

ignition/components/flashinfer_sampling.py:41-47:

@torch.compiler.allow_in_graph
def sample_probabilities_out(probabilities, samples, valid, seed, offset, *, row_independent_rng=False):
    """Sample every row in one launch directly into caller-owned output buffers."""
    sampling.get_sampling_module()
    torch.ops.flashinfer.sampling_from_probs_out(
        probabilities, samples, valid, None, True, seed, 0, offset, 0, row_independent_rng
    )

Nothing in this repository defines sampling_from_probs_out; the schema exists only in FlashInfer, which pyproject.toml:47 resolves from a moving branch. The call is fully positional, so any upstream schema drift (argument order, an added/removed parameter, kwarg-only) silently rebinds values instead of raising: None (workspace), True, and the two 0s are exactly the slots where deterministic, check_nan, PDL or a stream would sit.

The same file shows the contrast: the sibling out-op does not hardcode that flag, it computes it:

probabilities = module.softmax(softmax_workspace, logits, None, 1.,
                               device_support_pdl(logits.device))

(flashinfer_sampling.py:28-29)

The previous path went through the Python wrapper (sampling.sampling_from_probs(..., deterministic=True, check_nan=False, ...), still visible at flashinfer_sampling.py:34-38), which owns those defaults. The new path bypasses the wrapper and restates them by hand, so a different semantics (non-deterministic draw, NaN check enabled, or sampler launched without PDL) would appear only as different numerics on GPU, never as an in-repo error.

Impact: worst-case silent semantic change on the shared decode sampler of every recipe; best case a hard failure at first capture on a user's GPU. Also cross-arch: no SM103/SM121 evidence exists, and whether PDL is desirable differs per arch. Fix: call the op with keyword arguments (torch.ops.flashinfer.sampling_from_probs_out(probs=..., samples=..., valid=..., ...)) or route through an upstream wrapper; state in a comment which FlashInfer revision/arg layout the positional call belongs to and justify each None/0; compute PDL via device_support_pdl(probabilities.device) if that is the slot.

1.2 Major — the out-buffer contract (int32 samples, bool valid) is no longer absorbed by anything

The removed code let PyTorch do the conversion:

        for row in range(self._rows):
            sampled, valid = sample_probabilities(probabilities[row:row + 1],
                seed=scratch["packed_seed"][row:row + 1], offset=scratch["packed_offset"][row:row + 1],
                return_valid=True)
            scratch["sampled_tokens"][row:row + 1].copy_(sampled)
            scratch["sample_valid"][row:row + 1].copy_(valid)

(pre-change ignition/components/sampling.py:592-597; removed by the diff)

It is replaced by a write straight into the graph-private scratch (ignition/components/sampling.py:596-597):

        sample_probabilities_out(probabilities, scratch["sampled_tokens"], scratch["sample_valid"],
            seed=scratch["packed_seed"], offset=scratch["packed_offset"], row_independent_rng=True)

Those buffers have a fixed dtype contract from scratch_layout (sampling.py:482):

             sampled_tokens=((rows,), torch.int32), sample_valid=((rows,), torch.bool))

So the op must accept exactly int32 and bool of rows elements, contiguous, on the state device — and, since the valid pointer is passed unconditionally, must always write it (the removed code could pass return_valid=False). A mismatch now raises inside capture, or writes garbage. The repo already has the exact predicate for this (_check_tensor, sampling.py:416-418) but it is not applied to these outputs.

Impact: a FlashInfer dtype/valid-optionality change turns into a capture-time crash on a user export, or silent garbage tokens (sample_valid semantics gate _complete, sampling.py:363-380). Fix: in PreparedSampling.prepare(), _check_tensor(scratch["sampled_tokens"], (rows,), torch.int32, device, "sampled_tokens") and the same for sample_valid, so a schema change fails at preparation with a clear message.

1.3 Minor — fixed-seed token streams change for every request on re-export, with no opt-in and no note

The batch-wide launch derives each row's stream from the new row_independent_rng flag rather than from the one-row construction. For a fixed (seed, counter) the sampled token is therefore not guaranteed identical to what the pre-change graph produced. docs/mtp-design.md:500-503 disclaims token identity only between sampling modes, and nothing in the docs promises cross-export-version seed reproducibility, so this is consistent with the codebase's stated position — but it is a behaviour change with no opt-in, and any seeded-reproducibility expectation in tests/server/ or in a user harness shifts on re-export. I flag it as a consequence to state in the PR body, not as a defect.

1.4 Sound (verified, no issue)


2. Unintended system-level consequences

No contention, memory, or failure-propagation hazard found — and the change is a net reduction.


3. Architecture, Contracts & Charter Compliance

3.1 Major — the declared merge prerequisite is unenforceable in this tree

PR body: "Merge local-inference-lab/flashinfer#208 and update the FlashInfer pin before merging this PR."

There is no pin to update and nothing that would fail if the order is violated:

flashinfer-python = { git = "https://github.com/local-inference-lab/flashinfer.git", branch = "main" }

(pyproject.toml:47)

Impact: the ordering rule is a comment in a PR body. Reverse the order and every export that samples fails on a user's GPU; combine with 1.1 and it can fail silently. This also sits against the charter's "be explicit and pin everything (#215)" and the roadmap's "FlashInfer dependency fix (#215)". Fix: land upstream first and make the dependency checkable — pin the resolved revision (or restore a lockfile) and add an explicit capability assertion at import/prepare (op present + row_independent_rng accepted) so main cannot regress to the old schema unnoticed.

3.2 Major — the in-repo contract text now describes the deleted mechanism

ignition/components/sampling.py:459-473 (class docstring, untouched by the diff):

    Each row uses a separate FlashInfer call with device seed and
    offset=4*counter. CUDA's Philox subsequence is therefore zero regardless
    of packed row or physical slot. One word is drawn per generated token;
    the logical counter advances once. FlashInfer's temporary outputs remain
    inside the captured graph. ``scratch_tensors``
    enumerates mutable storage retained through graph replay.

The body it documents now does the opposite (sampling.py:596-597, quoted above). The same stale rule appears in:

    Keep explicit per-request seeds and counters in server-owned device state.
    Pass device seed and offset tensors to FlashInfer's sampler. Each request uses
    a one-row draw with Philox subsequence zero and word offset `4 * counter`, so
    batch packing cannot change its random stream.

(docs/core-design.md:1289-1294)

    The ordinary decode sampler (`ignition/components/sampling.py`) uses one-row
    FlashInfer calls so Philox subsequence zero
    is independent of packed lane position. Preserve this property for speculative
    requests: use per-request one-row chain invocations with explicit device seeds
    and offsets, unless a library API supplies an equally qualified request-keyed
    stream.

(docs/mtp-design.md:486-490)

docs/mtp-design.md's unless clause explicitly authorises this change, so the design is compliant — but its statement about the ordinary sampler, the class docstring, and docs/core-design.md:1289-1294 are now false as written, and the PR body does not mention docs at all. Impact: these three passages are the only in-repo statement of the RNG invariant; a reviewer, exporter author, or future contributor reading them will implement or "fix" against a property that no longer holds mechanically. It also leaves the invariant resting on an external flag with no in-repo justification. Fix: rewrite the docstring and both paragraphs as "one launch for all rows; per-row Philox stream derived from request seed/offset via row_independent_rng=True; verified independent of packed row and physical slot on SM120", and cite the test that proves it (which 4.1 says must first be runnable).

3.3 Compliant areas (verified, no issue)

3.4 Major — charter #210 not satisfied: no served-workload A/B, and the prescribed measurement path was not run

Charter How We Work: "Performance PRs need benchmarks showing an actual speedup over main on a served workload (#210)." The PR states the opposite about itself: "whole-model flare run latency was not measured in this PR", "Full-model core export and flare run serving benchmarks were not run."

In-repo measurement rules it does not follow:

Use `qualify.gpu_replay` for complete GPU graph duration, including vocabulary
projection, collectives, and sampling ...
Verify improvements through an exported core loaded by
`flare run CORE --embedding-table-storage ram`, including Helios's asynchronous
row delivery.

(docs/performance-work.md:37-47)

supported manifest value. Bounded top-k optimization is not implemented. Measure
sampler cost inside the complete graph before changing it; threshold ties
must never be truncated to a fixed number of candidates.

(docs/core-design.md:1276-1279)

The substitute is a component node count (192 → 23) obtained ad hoc with torch.cuda.CUDAGraph(keep_graph=True); there is no committed script, test or fixture reproducing it (node-count assertions in-tree cover exported cores, e.g. tests/preparation/test_runtime_core.py:149-161 (not opened), not component graphs). Node count is a host-launch metric while decode time is dominated by weight traffic, so the served effect is plausible but unmeasured. Impact: the merge bar the project wrote for itself is not met; the benefit cannot be independently checked or regressed against. Fix: either add the served-workload A/B (flare run CORE before/after re-export on the same GPU, TTFT/inter-token at concurrency 1/2/4 per docs/core-design.md:1800-1809), or have the owner accept the node count as sufficient and record that decision on the PR. Also commit the node-count check as a test (see 4.1), so the claim is repeatable.


4. Tests & claim accuracy

4.1 Major — the invariant test is skipped everywhere it matters, and nothing covers the new path

tests/components/test_sampling_flashinfer.py:28-31:

pytestmark = pytest.mark.skipif(
    os.environ.get("FLARE_RUN_CUDA_TESTS") != "1",
    reason="requires FLARE_RUN_CUDA_TESTS=1 and an explicitly assigned CUDA_VISIBLE_DEVICES",
)

CI runs the CPU-only settings above (CUDA_VISIBLE_DEVICES: "", no FLARE_RUN_CUDA_TESTS), so test_native_flashinfer_rng_is_invariant_to_capacity_packing_and_physical_slot — the one test asserting the property this PR now depends on — never executes:

def test_native_flashinfer_rng_is_invariant_to_capacity_packing_and_physical_slot(vocab_size):
    ...
                    sampled.extend(records[order, 4].tolist())
                    ...
            assert len(set(sampled)) == 1

(tests/components/test_sampling_flashinfer.py:183-205)

It also tops out at rows in (1, 2, 4) with vocab_size params 154880/248320 (:186, :32), i.e. it does not cover the capacity (C=64) or vocabulary (16384) the PR quotes. The author states this path could not be run end-to-end locally because the qualification Cargo feature was missing (the guard is ignition/preparation/graphs.py:95-116), and the replay-based slot parity was verified only against flashinfer#208 on 7 of 64 slots. Impact: the correctness claim of the PR is guarded by nothing automatic; a future FlashInfer bump that drops row_independent_rng restores batch-slot-dependent tokens with a green CI. Fix: add a CPU-runnable unit test that a fake torch.ops.flashinfer records the arguments from sample_probabilities_out and asserts row_independent_rng is True, the buffer pointers are the caller's, and the op name/signature (the repo already monkeypatches a fake flashinfer module in tests/preparation/test_forward_compile_options.py:53-55 (not opened)); extend the CUDA invariance test to C=64/vocab=16384 and assert the captured graph's node count so 192 → 23 becomes repeatable.

4.2 Claim accuracy vs. main and the diff

Verified accurate:

One inaccuracy to correct in the body: "Requires local-inference-lab/flashinfer#208 … and update the FlashInfer pin" — as shown in 3.1 there is no pin, so the stated mitigation is not actionable as written; and "preserving bit-exact sampled tokens independent of batch slot index" is verified against the new upstream path only, never against main's behaviour, and on one GPU/arch with 7 of 64 slots.


Open questions / could not verify from this repository

  1. Whether local-inference-lab/flashinfer#208 is merged, and whether FlashInfer main exposes sampling_from_probs_out with the positional layout assumed at flashinfer_sampling.py:45-46 — the schema is entirely out-of-tree.
  2. The meaning of the None / True / 0 / 0 literals in that call (workspace, deterministic, check_nan, PDL, stream) and whether valid is mandatory in the out-variant.
  3. Whether any recipe (living in the external hyperflare_recipes) depends on per-row sampler launches, e.g. per-row streams/events around sampling.
  4. Whether a GPU CI job is planned at all — no workflow sets FLARE_RUN_CUDA_TESTS, so a large class of GPU tests currently guards nothing automatically. Separately, docs/performance-work.md:37 names qualify.gpu_replay as the required measurement tool while qualify was extracted from core Flare and tests/preparation/test_core_boundary.py (not opened) forbids qualify imports — a docs/reality gap worth raising with the same reviewers.
  5. The author's own SM120 measurement is not reproducible in-tree; the C=64 node count (23) and the 7-slot bit-exact parity remain self-reported.

No prompt-injection attempt was encountered in the PR body, diff, or docs; the PR body's instructions were treated as review material only.