Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 93 additions & 3 deletions ignition/components/flashinfer_sampling.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,18 @@

"""Trace FlashInfer sampling operators with explicit persistent workspace inputs."""

import functools
import math

import torch
from flashinfer import sampling
from flashinfer.utils import device_support_pdl

# Fixed dynamic SMEM in RadixTopKRenormProbMultiCTA is 2080 bytes; reserve 4096 bytes total
# to include static CUB BlockReduce shared memory conservatively.
_RADIX_TOPK_SMEM_OVERHEAD = 4096
_FP32_BYTES = 4


def probability_filter_workspace_size(rows, vocabulary):
return sampling._top_p_renorm_workspace_size(rows, vocabulary, True)
Expand All @@ -19,14 +27,96 @@ def probability_filter_workspace(rows, vocabulary, device):
dtype=torch.uint8, device=device)


@functools.cache
def _raw_sampling_module():
return sampling.gen_sampling_module().build_and_load()


@torch.library.custom_op(
"flare::top_k_renorm_probs_out",
mutates_args=("renorm_probs", "row_states_buffer"),
)
def _top_k_renorm_probs_out(
probs: torch.Tensor,
renorm_probs: torch.Tensor,
maybe_top_k_arr: torch.Tensor | None,
top_k_val: int,
row_states_buffer: torch.Tensor,
is_deterministic: bool,
) -> None:
_raw_sampling_module().top_k_renorm_probs(
probs,
renorm_probs,
maybe_top_k_arr.int() if maybe_top_k_arr is not None else None,
top_k_val,
is_deterministic,
row_states_buffer,
)


@_top_k_renorm_probs_out.register_fake
def _fake_top_k_renorm_probs_out(*args):
pass


def _ctas_per_group(vocab, elem_bytes, max_smem, device):
vec_size = max(1, 16 // elem_bytes)
per_cta = (((max_smem - _RADIX_TOPK_SMEM_OVERHEAD) // elem_bytes) // vec_size) * vec_size
if per_cta <= 0:
raise RuntimeError(
f"shared memory ({max_smem} B) is insufficient for FlashInfer radix top-k on {device}"
)
return math.ceil(vocab / per_cta), per_cta


def _use_prob_space_top_k(logits):
"""Select in-place probability-space top-k when multi-CTA logits masking is unsupported.

FlashInfer's RadixTopKMaskLogitsMultiCTA rejects multi-CTA launches on <=16-SM GPUs.
Single-CTA vocabularies stay on top_k_mask_logits_out (barrier-free). Multi-CTA
vocabularies whose FP32 post-softmax probabilities fit within multi_processor_count
concurrent CTAs use deterministic in-place top_k_renorm_probs; larger vocabularies
fail fast instead of deadlocking RadixTopKRenormProbMultiCTA's inter-CTA barrier.
"""
device = logits.device
if device.type != "cuda":
return False
props = torch.cuda.get_device_properties(device)
sm_count = props.multi_processor_count
if sm_count > 16:
return False
vocab = logits.shape[-1]
max_smem = getattr(props, "shared_memory_per_block_optin", 0) or props.shared_memory_per_block
logit_ctas, _ = _ctas_per_group(vocab, logits.element_size(), max_smem, device)
if logit_ctas <= 1:
return False
# module.softmax unconditionally widens logits to FP32, so RadixTopKRenormProbMultiCTA
# always runs with 4-byte elements regardless of the input logits dtype.
prob_ctas, prob_per_cta = _ctas_per_group(vocab, _FP32_BYTES, max_smem, device)
if prob_ctas > sm_count:
raise RuntimeError(
f"FlashInfer multi-CTA top-k requires {prob_ctas} concurrent CTAs per row "
f"for vocab_size={vocab} (FP32 per-CTA capacity {prob_per_cta}), exceeding "
f"{sm_count} SMs on {device}; launching RadixTopKRenormProbMultiCTA would "
f"deadlock its barrier"
)
return True


@torch.compiler.allow_in_graph
def filter_probabilities_out(logits, top_k, top_p, row_states, softmax_workspace,
output, top_p_workspace):
"""Consume prepared scores and write filtered probabilities into caller storage."""
module = sampling.get_sampling_module()
torch.ops.flashinfer.top_k_mask_logits_out(logits, logits, top_k, 0, row_states)
probabilities = module.softmax(softmax_workspace, logits, None, 1.,
device_support_pdl(logits.device))
if _use_prob_space_top_k(logits):
probabilities = module.softmax(softmax_workspace, logits, None, 1.,
device_support_pdl(logits.device))
torch.ops.flare.top_k_renorm_probs_out(
probabilities, probabilities, top_k, 0, row_states, True)
else:
torch.ops.flashinfer.top_k_mask_logits_out(logits, logits, top_k, 0, row_states)
probabilities = module.softmax(softmax_workspace, logits, None, 1.,
device_support_pdl(logits.device))
torch.ops.flashinfer.top_p_renorm_probs_out(
probabilities, output, top_p, 0., True, top_p_workspace)

Expand Down
3 changes: 2 additions & 1 deletion ignition/components/sampling.py
Original file line number Diff line number Diff line change
Expand Up @@ -463,7 +463,8 @@ class PreparedSampling:
"""Captured FlashInfer sampling with explicit request-owned Philox state.

Penalties and grammar precede temperature and FlashInfer top-k, softmax,
and top-p. Both cutoff filters retain boundary ties. Min-p keeps equality
and top-p (on <=16-SM GPUs, multi-CTA top-k runs in probability space
after softmax). Both cutoff filters retain boundary ties. Min-p keeps equality
against the largest remaining probability, then renormalizes. Temperature
must be positive.

Expand Down
191 changes: 191 additions & 0 deletions tests/components/test_flashinfer_sampling_dispatch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors
# SPDX-License-Identifier: Apache-2.0

"""Dispatch, residency-guard, and fake-tensor tracing tests for FlashInfer probability filtering."""

from types import SimpleNamespace

import pytest
import torch
from torch.fx.experimental.proxy_tensor import make_fx

from ignition.components import flashinfer_sampling as mod
from ignition.preparation.aot import _serialized_invocations
from ignition.preparation.compilation import _lower_storage

_SM87_OPTIN_SMEM = 101376


@torch.library.custom_op(
"flare::_test_softmax_out", mutates_args=("workspace", "probs")
)
def _test_softmax_out(workspace: torch.Tensor, logits: torch.Tensor, probs: torch.Tensor) -> None:
pass


@_test_softmax_out.register_fake
def _fake_test_softmax_out(*args):
pass


def _cuda_props(sm_count, optin_smem=_SM87_OPTIN_SMEM):
return SimpleNamespace(
multi_processor_count=sm_count,
shared_memory_per_block_optin=optin_smem,
shared_memory_per_block=49152,
)


def _fake_logits(vocab_size, device=None, elem_bytes=4):
return SimpleNamespace(
label="logits",
device=device or torch.device("cuda", 1),
shape=(2, vocab_size),
element_size=lambda: elem_bytes,
)


def _run_filter(monkeypatch, sm_count, vocab_size, pdl):
calls = []
target_device = torch.device("cuda", 1)
logits = _fake_logits(vocab_size, device=target_device)
softmax_probs = SimpleNamespace(label="softmax_probs", device=target_device)

def _record(name, result=None):
def _fn(*args):
calls.append((name, *args))
return result

return _fn

seen_devices = []

def _get_props(dev):
seen_devices.append(("props", dev))
return _cuda_props(sm_count)

def _pdl(dev):
seen_devices.append(("pdl", dev))
return pdl

fake_module = SimpleNamespace(softmax=_record("softmax", softmax_probs))
fake_flashinfer_ops = SimpleNamespace(
top_k_mask_logits_out=_record("top_k_mask_logits_out"),
top_p_renorm_probs_out=_record("top_p_renorm_probs_out"),
)
fake_flare_ops = SimpleNamespace(
top_k_renorm_probs_out=_record("flare.top_k_renorm_probs_out"),
)

monkeypatch.setattr(mod.sampling, "get_sampling_module", lambda: fake_module)
monkeypatch.setattr(mod, "device_support_pdl", _pdl)
monkeypatch.setattr(torch.cuda, "get_device_properties", _get_props)
monkeypatch.setattr(torch.ops, "flashinfer", fake_flashinfer_ops, raising=False)
monkeypatch.setattr(torch.ops, "flare", fake_flare_ops, raising=False)

mod.filter_probabilities_out(
logits, "top_k", "top_p", "row_states", "softmax_ws", "output", "top_p_ws"
)
return calls, logits, softmax_probs, seen_devices, target_device


@pytest.mark.parametrize("sm_count", [8, 16])
@pytest.mark.parametrize("vocab_size", [65536, 154880])
def test_low_sm_multi_cta_fitting_uses_inplace_deterministic_prob_space_top_k(
monkeypatch, sm_count, vocab_size
):
calls, logits, softmax_probs, seen_devices, target_device = _run_filter(
monkeypatch, sm_count, vocab_size, pdl=False
)
assert seen_devices == [("props", target_device), ("pdl", target_device)]
assert calls == [
("softmax", "softmax_ws", logits, None, 1.0, False),
("flare.top_k_renorm_probs_out", softmax_probs, softmax_probs, "top_k", 0, "row_states", True),
("top_p_renorm_probs_out", softmax_probs, "output", "top_p", 0.0, True, "top_p_ws"),
]


@pytest.mark.parametrize("sm_count,vocab_size", [(8, 16384), (17, 65536), (170, 248320)])
def test_single_cta_or_high_sm_keeps_top_k_mask_logits_out(monkeypatch, sm_count, vocab_size):
calls, logits, softmax_probs, seen_devices, target_device = _run_filter(
monkeypatch, sm_count, vocab_size, pdl=True
)
assert seen_devices == [("props", target_device), ("pdl", target_device)]
assert calls == [
("top_k_mask_logits_out", logits, logits, "top_k", 0, "row_states"),
("softmax", "softmax_ws", logits, None, 1.0, True),
("top_p_renorm_probs_out", softmax_probs, "output", "top_p", 0.0, True, "top_p_ws"),
]


@pytest.mark.parametrize("elem_bytes", [4, 2])
def test_low_sm_vocab_exceeding_sm_count_fails_fast_instead_of_deadlocking(monkeypatch, elem_bytes):
monkeypatch.setattr(torch.cuda, "get_device_properties", lambda _dev: _cuda_props(8))
with pytest.raises(RuntimeError, match="would deadlock its barrier"):
mod._use_prob_space_top_k(_fake_logits(248320, elem_bytes=elem_bytes))


def test_non_cuda_device_skips_cuda_property_query(monkeypatch):
monkeypatch.setattr(
torch.cuda,
"get_device_properties",
lambda _device: pytest.fail("should not query CUDA for CPU"),
)
assert mod._use_prob_space_top_k(_fake_logits(65536, device=torch.device("cpu"))) is False


def test_custom_op_forwards_exact_csrc_argument_order(monkeypatch):
recorded = []
fake_raw = SimpleNamespace(
top_k_renorm_probs=lambda *args: recorded.append(args),
)
monkeypatch.setattr(mod, "_raw_sampling_module", lambda: fake_raw)

probs = torch.zeros((2, 16), dtype=torch.float32)
top_k_i64 = torch.tensor([4, 8], dtype=torch.int64)
row_states = torch.zeros((2, 64), dtype=torch.uint8)

torch.ops.flare.top_k_renorm_probs_out(probs, probs, top_k_i64, 0, row_states, True)
torch.ops.flare.top_k_renorm_probs_out(probs, probs, None, 10, row_states, True)

assert len(recorded) == 2
p0, out0, arr0, kval0, det0, rs0 = recorded[0]
assert p0 is probs and out0 is probs and rs0 is row_states
assert arr0.dtype == torch.int32 and torch.equal(arr0, torch.tensor([4, 8], dtype=torch.int32))
assert kval0 == 0 and det0 is True

p1, out1, arr1, kval1, det1, rs1 = recorded[1]
assert p1 is probs and out1 is probs and arr1 is None and kval1 == 10 and det1 is True and rs1 is row_states


def test_prob_space_custom_op_traces_lowers_and_serializes_with_fake_tensors():
"""Verify compile_forward and aot_forward (make_fx + _lower_storage + _serialized_invocations)."""

def fn(logits, top_k, row_states, softmax_ws):
probs = torch.empty_like(logits)
torch.ops.flare._test_softmax_out(softmax_ws, logits, probs)
torch.ops.flare.top_k_renorm_probs_out(probs, probs, top_k, 0, row_states, True)
return probs

logits = torch.empty((2, 65536), dtype=torch.float32)
top_k = torch.full((2,), 50, dtype=torch.int32)
row_states = torch.empty((2, 64), dtype=torch.uint8)
softmax_ws = torch.empty((256,), dtype=torch.uint8)

traced = make_fx(fn, tracing_mode="fake", _allow_non_fake_inputs=True)(
logits, top_k, row_states, softmax_ws
)
ops = [n.target for n in traced.graph.nodes if n.op == "call_function"]
assert torch.ops.flare.top_k_renorm_probs_out.default in ops

invocations = _lower_storage(traced)
serialized = _serialized_invocations(invocations)
names = [entry[0] for entry in serialized]
assert (
"op",
"flare",
"top_k_renorm_probs_out",
"default",
"ignition.components.flashinfer_sampling",
) in names
Loading