Repository navigation
perf(sampling): collapse per-row PreparedSampling loop to 1 row-independent FlashInfer launch - #684
Conversation
…endent FlashInfer launch Why this change is needed: PreparedSampling previously sampled each decode batch row in a Python loop calling sample_probabilities(probabilities[row:row+1], ...) followed by two single-element .copy_() operations per row to preserve request-independent Philox RNG state. Because FlashInfer's SamplingFromProbKernel previously mixed the thread-block index into curand_init, batching rows would have coupled a request's sampled token to its batch slot. At batch capacity 64, that loop emitted up to 192 sequential CUDA graph nodes (64 sampling launches plus 128 scalar copies) in every decode graph. What changed: - ignition/components/flashinfer_sampling.py: - Before: Exposed only sample_probabilities without row_independent_rng and had no out-tensor wrapper for sampling_from_probs_out. - After: Added row_independent_rng: bool = False to sample_probabilities and added sample_probabilities_out(..., row_independent_rng=False) backed by torch.ops.flashinfer.sampling_from_probs_out (requires local-inference-lab/flashinfer#208, which adds row_independent_rng to SamplingFromProbKernel and sampling_from_probs_out). - ignition/components/sampling.py: - Before: PreparedSampling.__call__ iterated over range(self._rows), launching one single-row sample_probabilities call and copying sampled_tokens[row:row+1] and sample_valid[row:row+1] per row. - After: Issues one batched sample_probabilities_out(probabilities, scratch["sampled_tokens"], scratch["sample_valid"], seed=scratch["packed_seed"], offset=scratch["packed_offset"], row_independent_rng=True) launch writing directly into the prepared scratch buffers. - Compatibility: No Helios wire format, Protobuf, CLI, or runtime ABI changes. Existing exported cores load and serve unchanged. Claimed benefit and result: - Measured on PreparedSampling at C=64, vocab=16384 inside torch.cuda.CUDAGraph(keep_graph=True): collapses the per-row sampling loop from 192 graph nodes to 1 batched sampling launch (23 total nodes for the complete PreparedSampling graph) while preserving bit-exact sampled tokens across batch slots. - Whole-model serving latency improvements are expected on newly exported cores and are not claimed from this standalone sampling graph measurement. Supporting evidence and limitations: - Single-GPU SM120 (RTX PRO 6000 Blackwell) verification against local-inference-lab/flashinfer#208: - PreparedSampling at C=64, vocab=16384 captured in torch.cuda.CUDAGraph(keep_graph=True): bit-exact token parity against single-row launches across 7 distinct slots (0, 1, 7, 15, 31, 48, 63), batched_valid.all() == True, 23 total CUDA graph nodes. - CPU component suite: - pytest tests/components/ -q: 185 passed, 55 skipped (GPU and qualification-feature tests skipped). - Unrun checks / limitations: tests/components/test_sampling_flashinfer.py could not run through GraphReplayWorker because flare_heliopause in the local .venv is built without the qualification Cargo feature; full-model export and multi-GPU serving benchmarks were not run. Dependency merge order: merge local-inference-lab/flashinfer#208 and update the pinned FlashInfer revision before merging this PR. Design-Signed-Off-By: Antigravity (Gemini); design-review=2e5b
|
A case file has been opened for 684. Future reviews will auto-run 90 minutes after code updates are pushed.
|
Autobot ReviewFull Review · Value Proposition · Case File Recommendation: Changes RequestedThe core change in
Walkthrough
Merge Risk: High · up to
|
…DSMEM cluster verify, router valid-token masking, and speculative token_limits (#132) Why this change is needed: Several b12x fast paths and metadata guards were stranded or omitted across flagship recipes in hyperflare-recipes: 1. hyperflare_recipes/components/moe.py hardcoded outer_scale == "token" on both route_output and integrated router lowering, blocking expert-outer NVFP4 A4, MXFP4 A8, and MXFP8 A8 experts from using unweighted route outputs and integrated routing. 2. Fused-addend PCIe/RoCE collective wrappers (has_addend=True, PreparedAllReduceAdd, PreparedAllReduceRMSNorm) were unused across most TP recipes (deepseek4, glm53, qwen38, kimi3, step5, mimo_v2), leaving separate residual or shared-expert additions beside plain PreparedAllReduce. 3. Six MoE routers (qwen38, glm53, kimi3, mimo_v2, step5, deepseek4) omitted num_valid_tokens, routing padded suffix rows across every layer, while gemma4 and glm53 speculative distribution heads omitted token_limits on PreparedSpeculativeDistributions. 4. Gemma 4 NVFP4 MoE ran a 6-launch Triton software-dequantization loop because b12x lacked GeGLU support; GLM-5.3 KDA verify and Qwen 3.8 GDN verify ran 3-launch paths with global scratch instead of b12x's 1-launch zero-scratch DSMEM cluster verify; and deepseek41/reference_speculation.py looped per-row over sample_probabilities. What changed: - Shared MoE and collective components (hyperflare_recipes/components/{moe.py,collectives.py,gated_delta.py,gdn_recovery.py}): - Before: PreparedRoutedExperts gated route_output and integrated router on outer_scale == "token"; PreparedChunkedAllReduce had no fused-addend interface; PreparedGDN used 3-launch Triton verification (PreparedRecoveredRecurrence + PreparedGatedRMSNorm) for speculative records; gdn_recovery.py imported speculative_decode_short_conv_kernel without unwrapping the b12x getter. - After: PreparedRoutedExperts delegates route_output eligibility to b12x fused_moe.supports_route_output(...) and gates integrated routing on router is not None and not self.prequantized_input. PreparedChunkedAllReduce accepts has_addend and forwards addend slices to each part. PreparedGDN declares and executes b12x plan_kda_fused_verify(..., decay_mode="scalar_gdn", round_normalized=True) via flare::gdn_record_fused in 1 zero-scratch launch while retaining PreparedGDNCommit and single-token in_place recovery; gdn_recovery.py unwraps speculative_decode_short_conv_kernel(). - Fused-addend collectives across TP recipes: - Wired has_addend=True / PreparedAllReduceAdd / PreparedAllReduceRMSNorm in deepseek4/decoder.py, glm53/{moe.py,decoder.py,mtp.py}, qwen38/{moe.py,decoder.py,mtp.py}, kimi3/decoder.py, step5/decoder.py (keeping FP32 MoE partial accumulation intact), and mimo_v2/{attention.py,decoder.py} (adding _FusedDecoderLayer when PreparedAllReduceRMSNorm.fits holds). Preserved Gemma 4's post-norm-before-residual topology and Inkling 2's PreparedResidualMix unchanged. - Router num_valid_tokens and speculative token_limits / batched sampling: - Threaded num_valid_tokens (metadata.live_counts[:1] or recurrent num_tokens) into MoE routers in qwen38/{moe.py,decoder.py}, glm53/{moe.py,decoder.py,stack.py,mtp.py}, kimi3/decoder.py, mimo_v2/decoder.py, step5/{decoder.py,mtp.py}, and deepseek4/decoder.py. - Passed token_limits=query_lengths[:b] to PreparedSpeculativeDistributions in gemma4/speculative.py and glm53/speculative.py. - Collapsed the per-row sampling loop in deepseek41/reference_speculation.py to 1 batched sample_probabilities_out(..., row_independent_rng=True) launch. - Gemma 4 NVFP4 MoE and GLM-5.3 KDA verify migrations: - gemma4/{weights.py,moe.py}: Before, always loaded NVFP4ExpertsWeight and ran the 6-launch Triton dequant loop. After, builds b12x fused_moe.PreparedExperts (MODELOPT_NVFP4, W13Layout.W31, ActivationMode.A4, nonlinearity="geglu", immutable_input_scales=True) when checkpoint input scales are present and runs PreparedRoutedExperts with padded suffix masking (ids=-1, weights=0.0), retaining the Triton path when input scales are absent. - glm53/{kda.py,speculative.py} and deletion of glm53/kda_recovery.py (-221 LOC): Before, ran 3-launch short_conv + CuTe/Triton verify + gated RMSNorm (and an SM103 Triton branch). After, prepares and runs b12x 1-launch zero-scratch plan_kda_fused_verify / _record_fused and removes the retired kda_recovery.py module. Claimed benefit and result: - Component-level verified effects on SM120: - GLM-5.3 PreparedGlmKDA runs 1-launch zero-scratch DSMEM cluster verify bit-identically to the 3-launch path inside compile_forward + CUDAGraph. - Qwen 3.8 PreparedGDN runs 1-launch zero-scratch scalar_gdn cluster verify inside compile_forward + CUDAGraph with compatible GDNRecords for PreparedGDNCommit. - Gemma 4 PreparedMoE runs hardware NVFP4 A4 GeGLU through b12x PreparedRoutedExperts with zeroed padded suffix rows. - Expected whole-model effects on newly exported cores: lower per-layer launch overhead and scratch usage on GLM-5.3, Qwen 3.8, and Gemma 4; elimination of padded-row routing and redundant residual/shared-expert additions on TP recipes; and tighter speculative top-p/top-k normalization bounds on Gemma 4 and GLM-5.3. End-to-end flare run serving benchmarks were not measured in this PR. Supporting evidence and limitations: - Dependencies and merge order: requires local-inference-lab/flashinfer#208 (row_independent_rng, supports_route_output, expert-outer has_valid_tokens + integrated routing, geglu MoE, scalar_gdn fused verify) and NVIDIA/hyperflare-inference#684 (sample_probabilities_out with row_independent_rng). Merge flashinfer#208 first, then hyperflare-inference#684, then this PR after updating pins. - Single-GPU SM120 (RTX PRO 6000 Blackwell) tests against flashinfer#208 and hyperflare-inference#684: - E2E GPU test (compile_forward + CUDAGraph) for GLM-5.3 PreparedGlmKDA (bit-identical to 3-launch across output, conv_state, recurrent_state, corrections, keys_and_gates), Qwen 3.8 PreparedGDN (fused_verify active, recurrent_state untouched), and Gemma 4 PreparedMoE (b12x GeGLU + padded suffix masking): all passed. - pytest tests/recipes/test_kimi3_kda_fused_verify_cuda.py tests/recipes/test_qwen38_gdn_recovery_cuda.py -k "test_fused_verify_matches_three_launches or test_single_token_rounds_advance_committed_state_in_place": 5 passed. - CPU tests: - pytest tests/components/test_gdn_functional.py tests/components/test_chunked_all_reduce.py tests/recipes/test_qwen38_moe.py: 25 passed, 3 skipped. - pytest tests/recipes/test_gemma4.py: 51 passed (9 template tests require FLARE_TEST_TEMPLATE_DIR and were not run). - py_compile across all 23 modified Python files: passed. - Unrun checks / limitations: Multi-GPU TP CUDA tests (FLARE_RUN_TP_CUDA_TESTS=1), full-checkpoint model exports, flare run serving benchmarks, and template tests requiring FLARE_TEST_TEMPLATE_DIR were not run on this host. Design-Signed-Off-By: Antigravity (Gemini); design-review=6fcc
…mple_probabilities kwarg Why this change is needed: pyproject.toml tracked flashinfer-python on branch = "main" without a commit pin, leaving CI and fresh environments exposed to moving upstream state even after local-inference-lab/flashinfer#208 merged. In addition, sample_probabilities in ignition/components/flashinfer_sampling.py carried an unused row_independent_rng parameter because all batched callers use sample_probabilities_out. What changed: - pyproject.toml: - Before: flashinfer-python = { git = "https://github.com/local-inference-lab/flashinfer.git", branch = "main" }. - After: Pinned flashinfer-python to rev = "5a8ceed80ccc58e11a4d49ccc910f52967699c09" (merge commit of local-inference-lab/flashinfer#208). - ignition/components/flashinfer_sampling.py: - Before: sample_probabilities accepted an unused keyword-only row_independent_rng=False parameter. - After: Restored sample_probabilities to its prior signature while keeping sample_probabilities_out(..., row_independent_rng=False). Claimed benefit and result: Guarantees that fresh environments and CI resolve the FlashInfer revision containing row_independent_rng on torch.ops.flashinfer.sampling_from_probs_out, and keeps the diff minimal by removing unused API surface. Supporting evidence and limitations: - Single-GPU SM120 verification of PreparedSampling across eager, compile_forward, and aot_forward (serialize + torch.compiler.load_compiled_function + CUDAGraph replay): - Cutoff ties & device parameter changes on vocab 154880 (GLM) and 248320 (Qwen) across eager, compile_forward, and aot_forward with zero allocations during graph replay: 6/6 passed. - RNG invariance across eager, compile_forward, and aot_forward, capacities (1, 2, 4, 64), slot rotations, and 3 (seed, counter) pairs: passed. - Functional PreparedSampling.functional() + run() under compile_forward and aot_forward: passed. - Fresh-process AOT deserialize (torch.compiler.load_compiled_function) + CUDAGraph replay at C=64: passed. - CPU tests: CUDA_VISIBLE_DEVICES="" pytest tests/preparation/test_packaging.py tests/preparation/test_core_boundary.py tests/components/ -q: 192 passed, 55 skipped. - Limitations / unrun checks: GraphReplayWorker execution of tests/components/test_sampling_flashinfer.py remains unrun locally because flare_heliopause in the local .venv lacks the qualification Cargo feature; full-model export and flare run serving benchmarks were not run. Design-Signed-Off-By: Antigravity (Gemini); design-review=2e5b
|
@flare-autobot Both blockers are addressed:
|
Why this change is needed
PreparedSampling(ignition/components/sampling.py) previously executed a per-row loop callingsample_probabilities(probabilities[row:row+1], ...)followed by two single-element.copy_()operations per row. That serialization existed because FlashInfer'sSamplingFromProbKernelmixed the thread-block indexbxintocurand_init, so launching all rows together would have made a request's sampled token depend on its batch slot rather than solely on(seed, offset). At batch capacityC=64, the loop added up to192sequential CUDA graph nodes (64kernel launches +128scalar copies) to every decode graph.What changed
pyproject.toml:flashinfer-pythontracked movingbranch = "main".flashinfer-pythontorev = "5a8ceed80ccc58e11a4d49ccc910f52967699c09"(the mergedlocal-inference-lab/flashinfer#208commit onmain, which addsrow_independent_rngtoSamplingFromProbKernel,SamplingFromProb, andtorch.ops.flashinfer.sampling_from_probs_out).ignition/components/flashinfer_sampling.py:sampling_from_probs_out.@torch.compiler.allow_in_graph def sample_probabilities_out(probabilities, samples, valid, seed, offset, *, row_independent_rng=False)callingtorch.ops.flashinfer.sampling_from_probs_out. Leftsample_probabilitiesunchanged.ignition/components/sampling.py:PreparedSampling._filter_scoresloopedfor row in range(self._rows), launching single-rowsample_probabilitiesand copyingsampled_tokens[row:row+1]andsample_valid[row:row+1]on every iteration.sample_probabilities_out(probabilities, scratch["sampled_tokens"], scratch["sample_valid"], seed=scratch["packed_seed"], offset=scratch["packed_offset"], row_independent_rng=True)call writing directly into the prepared scratch buffers for both captured (__call__) and functional (run) execution paths.Claimed benefit and result
C=64,vocab=16384): Replaces64single-row launches +128scalar copies (192nodes) with1parallel sampling launch (23total CUDA graph nodes for the entirePreparedSamplinggraph) while preserving bit-exact sampled tokens independent of batch slot index.flare runlatency was not measured in this PR.Supporting evidence and limitations
local-inference-lab/flashinfer#208is merged onmain(5a8ceed80ccc58e11a4d49ccc910f52967699c09) and pinned directly viarev = "5a8ceed80ccc58e11a4d49ccc910f52967699c09"inpyproject.toml.flashinfer@5a8ceed80ccc:PreparedSamplingcutoff-tie and device-parameter tests on bothvocab_size=154880(GLM) andvocab_size=248320(Qwen) acrosseager,compile_forward, andaot_forward(serialize->torch.compiler.load_compiled_function->CUDAGraphreplay with zero allocations during replay): 6/6 passed.eager,compile_forward, andaot_forward, batch capacities(1, 2, 4, 64), slot rotations, and 3(seed, counter)pairs ((17, 0),(2**64 - 79, 2**32 - 1),(2**63 + 19, 2**32 + 7)): passed (identical sampled token across all modes, capacities, and physical slots; exactrng_counterandgenerated_tokensupdates).PreparedSampling.functional(session=None)+run(logits)under bothcompile_forwardandaot_forward(serialize->load_compiled_function->CUDAGraphreplay): passed.torch.compiler.load_compiled_functionin a new Python subprocess aftersampler.prepare()) +CUDAGraphreplay atC=64,vocab_size=154880: passed.PreparedSamplingatC=64,vocab=16384captured intorch.cuda.CUDAGraph(keep_graph=True): bit-exact parity against single-row launches across 7 distinct slots (0, 1, 7, 15, 31, 48, 63),batched_valid.all() == True,23total graph nodes.CUDA_VISIBLE_DEVICES="" pytest tests/preparation/test_packaging.py tests/preparation/test_core_boundary.py tests/components/ -q: 192 passed, 55 skipped (GPU andqualification-feature tests skipped).tests/components/test_sampling_flashinfer.pywas not executed viaGraphReplayWorkerbecauseflare_heliopausein the local.venvlacks thequalificationCargo feature (itscompile_forward,aot_forward, cutoff-tie, and RNG-invariance assertions were executed directly viatorch.cuda.CUDAGraphabove). Full-model core export andflare runserving benchmarks were not run.Discord: lukealonso