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
- Major — the RNG contract is now stated wrong in three places. The
PreparedSamplingdocstring (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. - 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 neighbouringfilter_probabilities_outin the same file computes its PDL flag instead of hardcoding it (flashinfer_sampling.py:28-29). - Major — the declared merge prerequisite ("update the FlashInfer pin") has no artifact to update and no gate to enforce it:
pyproject.toml:47tracks the upstreammainbranch, there is nouv.lock, and CPU CI cannot exercise the changed path. - Major (charter #210) — no served-workload A/B evidence. The PR declines the
flare run/qualify.gpu_replaymeasurement thatdocs/performance-work.md:37-47anddocs/core-design.md:1276-1279prescribe, substituting an ad-hoc component node count. - 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. - 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)
- Dead/invalid rows cannot poison the batched call.
_sanitize_scoreswrites a dummy one-hot (sampling.py:304-312) and_normalize_probswrites 1.0 at token 0 when the mass is ≤ 0 (sampling.py:324-332), so every row — live, stale, duplicate, or sample-disabled — presents a finite distribution. The old loop also iterated allself._rowsregardless oflive_rows, so batching changes nothing about which rows are sampled._completeignores rows whose epoch/slot do not match (sampling.py:363-380). - No new synchronization hazard. Both paths use the caller's stream:
__call__runs_filter_scores(self.scratch_tensors)then the TP broadcast,_complete,logprobs(sampling.py:599-607); the functional path runs the same operations in order (sampling.py:609-641,:656-680). The broadcast stays strictly after sampling. - Platform parity: nothing in the diff is OS- or arch-conditional; no Windows/Unix split introduced. The only "parity" gap is evidence coverage (SM120 only, vs. charter targets SM103/SM120/SM121).
- Metric/observability span check: no rate/latency/admission metric is resampled by this diff. The only observable that moves is per-graph
node_count(helios/src/runtime_core/describe.rs:541 (not opened),785, surfaced byflare inspect), which drops — the intended effect, not a scope bug.
2. Unintended system-level consequences
No contention, memory, or failure-propagation hazard found — and the change is a net reduction.
- No lock/queue/HOL exposure:
PreparedSamplingis per-core, per-pass code with no mutex or waiter added; the diff removes 128.copy_()launches and 63 launches per decode graph, i.e. strictly less serialized host work on the hot path. - No memory amplification — the reverse: the out-variant writes into preallocated graph-private scratch (
scratch_layout,sampling.py:477-482), removing the per-row temporarysampled/validtensors the wrapper allocated. Steady-state allocation is not increased, keepingAGENTS.md:420-425satisfied. - Dynamic path not broken by uninitialized storage:
functional()/run()allocate local scratch withtorch.empty(sampling.py:610-614,:662-664), but the batched op overwrites all rows, so no uninitialized value is read — whereas the removed loop also covered all rows. - Smaller batches also benefit: the old cost was a fixed
3 × rowsnode term, so the relative win is largest at capacity 1–4, not a case where the optimization penalizes the uncontended path. Nothing here regresses partial-hit or single-row paths. - Benefit only materialises on re-export (pre-existing cores keep the old graph). The PR body says "on newly exported decode cores", which is accurate; a reader could still mistake it for a drop-in win, so it is worth stating explicitly as a rollout limitation.
- Blast radius of the upstream dependency is large but not silent-by-design: if FlashInfer
mainlackslocal-inference-lab/flashinfer#208, the failure is an op-lookup/AttributeErrorat capture (see 3.1) — the dangerous variant is the silent positional rebind in 1.1.
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)
- No
uv.lockexists in the tree —list_files *.lockreturns only Cargo lockfiles (eos,flare-cli,flare-winui/bridge,flare-winui/launcher,flare,heliopause,helios,selene-manager,selene). - CI cannot detect the violation:
.github/workflows/python-cpu.yml:25-33(not opened) runsuv sync --extra prepare --extra test(uv sync, not--locked) then.venv/bin/python -m pytest tests/ -qwithCUDA_VISIBLE_DEVICES: "". No workflow setsFLARE_RUN_CUDA_TESTS(repo-wide search: the variable appears only in tests/docs). Becausetorch.ops.flashinfer.sampling_from_probs_outis resolved at call time (flashinfer_sampling.py:45), import and the whole CPU suite pass whether or not upstream carries #208.
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)
- Placement: both edited modules are among the 12 sanctioned Helios-ABI interface modules (
AGENTS.md:388-396, enforced bytests/preparation/test_core_boundary.py(not opened)); using FlashInfer's sanctioned out-variant matchesAGENTS.md:404-409. - No new captured-graph operation family: no protobuf, manifest, graph-kind, recipe or CLI change, so the owner-approval rule for new op contracts (
AGENTS.md:376-381) is not triggered — and the author is that owner. Existing cores keep loading: the diff is two Python modules and cannot change an exported artifact. - No per-model special case, no new flag, no global default change in shared runtime layers;
row_independent_rngis opt-in at the call site.
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:
- The before/after description of
flashinfer_sampling.pymatchesmain: onmainthe module had onlysample_probabilities(norow_independent_rng) andverify_chain; the diff adds the kwarg andsample_probabilities_out, nothing else. - "No Helios runtime, Protobuf, core wire format, or CLI changes … existing prepared model cores continue to load and serve unchanged" — correct; the diff cannot affect exported artifacts. (The benefit, correctly, is scoped to "newly exported decode cores".)
- "185 passed, 55 skipped" and the unrun
GraphReplayWorkerpath are disclosed honestly, andpytest tests/components/ -qcannot be re-run from here.
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
- Whether
local-inference-lab/flashinfer#208is merged, and whether FlashInfermainexposessampling_from_probs_outwith the positional layout assumed atflashinfer_sampling.py:45-46— the schema is entirely out-of-tree. - The meaning of the
None/True/0/0literals in that call (workspace,deterministic,check_nan, PDL, stream) and whethervalidis mandatory in the out-variant. - Whether any recipe (living in the external
hyperflare_recipes) depends on per-row sampler launches, e.g. per-row streams/events around sampling. - 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:37namesqualify.gpu_replayas the required measurement tool whilequalifywas extracted from core Flare andtests/preparation/test_core_boundary.py(not opened) forbidsqualifyimports — a docs/reality gap worth raising with the same reviewers. - The author's own SM120 measurement is not reproducible in-tree; the
C=64node 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.