Files
tokenspeed/test/runtime/test_logits_processor.py
zhuhaozhecool b5f15ab3fe perf(npu): accumulate packed row offsets in int32 (#3773)
## Summary

Use int32 throughout eager Prefill row-index construction. Each batch is
bounded by the scheduler's int32 token budget. Prefill indices select
the last packed row of each request. Mixed speculative batches also keep
the full range of decode verification rows in int32.

## Test Plan

- `pre-commit run --all-files`, the eight prefill output-layout tests,
and CPU checks of the production index construction passed. The CPU
cases included pure Prefill, mixed batches with and without speculation,
and the int32 budget boundary.
- Updated the device-backed logits-processor tests to exercise int32 row
indices for Prefill and mixed batches, with checks on the selected
logits.
- Prior Ascend 910B operator checks confirmed that the int32 scan used
AI Vector Core and that both advanced indexing and `index_select`
accepted int32 row indices. Accelerator serving coverage for the updated
PR is left to CI.

---------

Signed-off-by: zhuhaozhecool <zhuhaozhecool@163.com>
2026-11-24 23:52:44 +08:00

2341 lines
84 KiB
Python

"""Regression tests for logits processing helpers."""
from __future__ import annotations
import os
import sys
from dataclasses import replace
from types import SimpleNamespace
# CI Registration (parsed via AST, runtime no-op)
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from ci_system.ci_register import register_cuda_ci # noqa: E402
register_cuda_ci(est_time=90, suite="runtime-1gpu")
import pytest # noqa: E402
import torch # noqa: E402
import tokenspeed.runtime.distributed.comm_manager as comm_manager_module # noqa: E402
import tokenspeed.runtime.layers.logits_processor as logits_processor_module # noqa: E402
from tokenspeed.runtime.execution.context import InputLogprobRows # noqa: E402
from tokenspeed.runtime.execution.forward_batch_info import ForwardMode # noqa: E402
from tokenspeed.runtime.layers.logits_processor import ( # noqa: E402
DistArgmaxPrepared,
LogitsMetadata,
LogitsProcessor,
VocabParallelArgmax,
fused_softcap,
prepare_logits_communication,
)
from tokenspeed.runtime.layers.vocab_parallel_embedding import ( # noqa: E402
ParallelLMHead,
)
from tokenspeed.runtime.utils.env import global_server_args_dict # noqa: E402
@pytest.fixture(autouse=True)
def missing_cuda_capture_query(monkeypatch):
if not torch.cuda.is_available():
monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: False)
@pytest.fixture
def nvidia_logits(monkeypatch):
"""Exercise CUDA state handling without requiring a CUDA test host."""
platform = replace(logits_processor_module.current_platform(), vendor="nvidia")
monkeypatch.setattr(logits_processor_module, "current_platform", lambda: platform)
@pytest.mark.parametrize("do_argmax", [False, True])
def test_cpu_tp_logits_do_not_query_an_accelerator_capture(monkeypatch, do_argmax):
"""The prepared argmax and the lazy gather gate need no CUDA context."""
# A single-host group: the gather gate needs no fabric map.
monkeypatch.setitem(global_server_args_dict, "mapping", None)
from transformers import PretrainedConfig
def cuda_query():
raise RuntimeError("CPU-only torch has no CUDA capture API")
def collective(output, shard, group):
# Only the missing second process is substituted; the GEMM and gates run.
output.copy_(torch.cat((shard, shard), dim=0))
monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", cuda_query)
monkeypatch.setattr(logits_processor_module, "all_gather_single", collective)
processor = LogitsProcessor(
config=PretrainedConfig(vocab_size=8),
tp_rank=0,
tp_size=2,
tp_group=(0, 1),
do_argmax=do_argmax,
attn_tp_size=1,
dp_lm_head_tp=False,
)
hidden = torch.tensor([[1, 2], [-2, 1]], dtype=torch.bfloat16)
head = ParallelLMHead(
8,
2,
params_dtype=torch.bfloat16,
padding_size=1,
tp_rank=0,
tp_size=2,
tp_group=(0, 1),
)
with torch.no_grad():
head.weight.copy_(torch.tensor([[1, 0], [0, 1], [-1, 0], [0, -1]]))
processor.prepare_communication(head)
local = hidden @ head.weight.T
output = processor._get_logits(hidden, head, None, require_full_vocab=False)
expected = local if do_argmax else torch.cat((local, local), dim=-1)
torch.testing.assert_close(output, expected, rtol=0, atol=0)
def test_dist_argmax_ineligibility_uses_the_device_collective(monkeypatch, tmp_path):
"""A real Gloo vote needs no NCCL group when the fused kernel is unavailable."""
from transformers import PretrainedConfig
from tokenspeed.runtime.distributed.process_group_manager import ProcessGroupManager
if torch.distributed.is_initialized():
pytest.skip("needs its own isolated one-process Gloo world")
manager = ProcessGroupManager()
manager.init_emulated_rank_zero(
f"file://{tmp_path / 'rendezvous'}", "gloo", None, None
)
try:
manager.init_process_group((0, 1))
monkeypatch.setattr(logits_processor_module, "pg_manager", manager)
monkeypatch.setattr(
logits_processor_module, "dist_argmax_available", lambda: False
)
monkeypatch.setattr(LogitsProcessor, "_LOGITS_DIST_ARGMAX_STATES", {})
processor = LogitsProcessor(
config=PretrainedConfig(vocab_size=8192),
tp_rank=0,
tp_size=2,
tp_group=(0, 1),
attn_tp_size=1,
dp_lm_head_tp=False,
)
head = ParallelLMHead(
8192,
2,
params_dtype=torch.float32,
tp_rank=0,
tp_size=2,
tp_group=(0, 1),
)
assert (
processor.acquire_dist_argmax_state(
head, max_M=8, skip_ping_pong=False, dtype=torch.float32
)
is None
)
finally:
torch.distributed.destroy_process_group()
def test_logits_processor_only_uses_fused_lm_head_for_kimi(monkeypatch):
hidden_states = torch.tensor([[1.0, 2.0]], dtype=torch.float32)
lm_head = SimpleNamespace(weight=torch.eye(2, dtype=torch.float32))
metadata = LogitsMetadata(forward_mode=ForwardMode.DECODE, query_shard=None)
calls = {"fused": 0}
def fake_lm_head_matmul(hidden, weight):
calls["fused"] += 1
return torch.matmul(hidden.to(weight.dtype), weight.T)
monkeypatch.setattr(logits_processor_module, "_lm_head_matmul", fake_lm_head_matmul)
is_nvidia = logits_processor_module.current_platform().is_nvidia
monkeypatch.setattr(
logits_processor_module,
"current_platform",
lambda: SimpleNamespace(is_amd=False, is_nvidia=is_nvidia),
)
non_kimi = LogitsProcessor(
config=SimpleNamespace(model_type="test", vocab_size=2),
attn_tp_size=1,
dp_lm_head_tp=False,
)
non_kimi(
input_ids=None,
hidden_states=hidden_states,
lm_head=lm_head,
logits_metadata=metadata,
)
assert calls["fused"] == 0
kimi = LogitsProcessor(
config=SimpleNamespace(model_type="kimi_k2", vocab_size=2),
attn_tp_size=1,
dp_lm_head_tp=False,
)
kimi(
input_ids=None,
hidden_states=hidden_states,
lm_head=lm_head,
logits_metadata=metadata,
)
assert calls["fused"] == 1
def test_tp_logits_all_gather_handles_zero_rows(monkeypatch):
# A single-host group: the gather gate needs no fabric map.
monkeypatch.setitem(global_server_args_dict, "mapping", None)
processor = LogitsProcessor(
config=SimpleNamespace(model_type="test", vocab_size=6),
tp_rank=0,
tp_size=2,
tp_group=(0, 1),
attn_tp_size=1,
dp_lm_head_tp=False,
)
hidden_states = torch.empty((0, 2), dtype=torch.float32)
lm_head = SimpleNamespace(
weight=torch.ones((3, 2), dtype=torch.float32), num_embeddings_per_partition=3
)
metadata = LogitsMetadata(forward_mode=ForwardMode.DECODE, query_shard=None)
calls = {"all_gather": 0}
def fake_all_gather_single(output, input_, group):
calls["all_gather"] += 1
assert group == (0, 1)
assert tuple(output.shape) == (0, 3)
assert tuple(input_.shape) == (0, 3)
monkeypatch.setattr(
logits_processor_module,
"all_gather_single",
fake_all_gather_single,
)
output = processor(
input_ids=None,
hidden_states=hidden_states,
lm_head=lm_head,
logits_metadata=metadata,
)
assert calls["all_gather"] == 1
assert tuple(output.next_token_logits.shape) == (0, 6)
@pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16])
@pytest.mark.parametrize("cached", [False, True])
def test_tp_logits_gather_preserves_dtype(monkeypatch, nvidia_logits, dtype, cached):
processor = LogitsProcessor(
config=SimpleNamespace(model_type="test", vocab_size=16),
skip_all_gather=False,
do_argmax=False,
logit_scale=None,
tp_rank=0,
tp_size=2,
tp_group=(0, 1),
attn_tp_size=1,
dp_lm_head_tp=False,
)
# BF16 logits are one multicast word each, FP32 logits two; FP16 keeps the collective.
words = {torch.bfloat16: 1, torch.float32: 2}.get(dtype, 0)
state = SimpleNamespace(hidden_dim=32)
if cached:
processor._all_gather_state = state
calls = []
def initialize(lm_head, words_per_logit):
assert words and words_per_logit == words
calls.append("init")
return state
def multicast(received_state, logits, *, tp_hidden_dim, skip_entry_sync, safe):
assert received_state is state
assert logits.dtype == torch.bfloat16
assert tp_hidden_dim == 16 * words and skip_entry_sync and not safe
calls.append("multicast")
return torch.cat((logits, logits), dim=-1)
def collective(output, logits, group):
assert not words
assert output.dtype == logits.dtype == dtype
assert group == (0, 1)
calls.append("collective")
output.copy_(torch.cat((logits, logits), dim=0))
monkeypatch.setattr(processor, "_init_all_gather_state", initialize)
monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: False)
monkeypatch.setattr(logits_processor_module, "all_gather_inner", multicast)
monkeypatch.setattr(logits_processor_module, "all_gather_single", collective)
hidden = torch.tensor([[1.0, 1 / 512]], dtype=dtype)
weight = torch.zeros((8, 2), dtype=dtype)
weight[0, 0] = 1
weight[1] = 1
local = hidden @ weight.T
output = processor._get_logits(
hidden,
SimpleNamespace(weight=weight),
logits_metadata=None,
embedding_bias=None,
plan=None,
require_full_vocab=False,
)
assert output.dtype == dtype
torch.testing.assert_close(
output, torch.cat((local, local), dim=-1), rtol=0, atol=0
)
if words:
assert calls == (["multicast"] if cached else ["init", "multicast"])
else:
assert calls == ["collective"]
assert output.argmax(-1).item() == 1
@pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16])
def test_tp_logits_collective_gather_lays_rank_shards_side_by_side(monkeypatch, dtype):
"""Row r of the gathered logits holds every rank's vocab shard of row r, in
rank order, bit for bit (NaN payloads and signed zeros included)."""
tp, rows, shard = 3, 5, 8
processor = LogitsProcessor(
config=SimpleNamespace(model_type="test", vocab_size=tp * shard),
skip_all_gather=False,
do_argmax=False,
logit_scale=None,
tp_rank=0,
tp_size=tp,
tp_group=(0, 1, 2),
attn_tp_size=1,
dp_lm_head_tp=False,
)
processor._all_gather_state = None # no multicast gather: the collective path
words = torch.int16 if dtype.itemsize == 2 else torch.int32
bound = 2 ** (8 * dtype.itemsize - 1)
torch.manual_seed(0)
bits = torch.randint(-bound, bound, (tp, rows, shard), dtype=words)
def collective(output, logits, group):
assert tuple(output.shape) == (tp * rows, shard)
output.view(words).copy_(bits.reshape(tp * rows, shard))
monkeypatch.setattr(logits_processor_module, "all_gather_single", collective)
output = processor._get_logits(
torch.ones((rows, 2), dtype=dtype),
SimpleNamespace(weight=torch.ones((shard, 2), dtype=dtype)),
logits_metadata=None,
embedding_bias=None,
plan=None,
require_full_vocab=False,
)
assert output.dtype == dtype
assert torch.equal(
output.view(words), bits.transpose(0, 1).reshape(rows, tp * shard)
)
@pytest.mark.parametrize(
("initializer_name", "args"),
[
("_init_all_gather_state", (SimpleNamespace(), 1)),
("_init_dist_argmax_state", (SimpleNamespace(), torch.bfloat16)),
],
)
def test_force_deterministic_rsag_disables_logits_symm_mem(
monkeypatch, initializer_name, args
):
monkeypatch.setitem(global_server_args_dict, "force_deterministic_rsag", True)
monkeypatch.setattr(
logits_processor_module,
"create_state",
lambda *args, **kwargs: pytest.fail(
"symmetric-memory state must not initialize"
),
)
monkeypatch.setattr(
logits_processor_module,
"try_create_dist_argmax_state",
lambda *args, **kwargs: pytest.fail(
"symmetric-memory state must not initialize"
),
)
processor = LogitsProcessor(
config=SimpleNamespace(model_type="test", vocab_size=8),
tp_rank=0,
tp_size=2,
tp_group=(0, 1),
attn_tp_size=1,
dp_lm_head_tp=False,
)
assert getattr(processor, initializer_name)(*args) is None
def _set_fabric(monkeypatch, supported: bool) -> None:
import tokenspeed_kernel.ops.communication.fabric as fabric
# These tests model NVIDIA multicast regardless of the runner's platform.
monkeypatch.setattr(
logits_processor_module,
"current_platform",
lambda: SimpleNamespace(is_nvidia=True),
)
# The topology is what makes these groups host-spread; without it the tests
# would name a property their own setup never established.
monkeypatch.setitem(
global_server_args_dict, "mapping", SimpleNamespace(nprocs_per_node=4)
)
monkeypatch.setattr(torch.cuda, "device_count", lambda: 4)
monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: False)
monkeypatch.setattr(fabric, "group_has_fabric", lambda ranks: supported)
monkeypatch.setattr(LogitsProcessor, "_LOGITS_AG_STATES", {})
def test_tp_logits_custom_collectives_skip_host_spread_group_without_fabric(
monkeypatch,
):
_set_fabric(monkeypatch, False)
processor = LogitsProcessor(
config=SimpleNamespace(model_type="test", vocab_size=64),
tp_rank=0,
tp_size=8,
tp_group=tuple(range(8)),
attn_tp_size=1,
dp_lm_head_tp=False,
)
lm_head = SimpleNamespace(
weight=torch.ones((8, 2), dtype=torch.float32), num_embeddings_per_partition=8
)
monkeypatch.setattr(
logits_processor_module,
"create_state",
lambda **kwargs: pytest.fail("a group without fabric must not gather"),
)
# Distributed argmax is no longer topology-gated: cross-node groups probe
# for NVLS instead. This shard is below the kernel's vocab floor, so the
# kernel state is rejected before any collective work and the argmax
# falls back to the portable all-reduce of packed keys.
monkeypatch.setattr(
logits_processor_module,
"try_create_dist_argmax_state",
lambda **kwargs: pytest.fail(
"a shard below the vocab floor must not reach the constructor"
),
)
assert processor._init_all_gather_state(lm_head, 1) is None
assert isinstance(
processor._init_dist_argmax_state(lm_head, torch.float32), VocabParallelArgmax
)
def test_a_strided_tp_group_smaller_than_one_host_is_still_probed(monkeypatch):
"""Two ranks on two hosts is fewer ranks than one host holds.
Sizing the group against the local device count would admit it with no
probe, and a group the fabric cannot map hangs in the rendezvous.
"""
_set_fabric(monkeypatch, False)
processor = LogitsProcessor(
config=SimpleNamespace(model_type="test", vocab_size=64),
tp_rank=0,
tp_size=2,
tp_group=(0, 4),
attn_tp_size=1,
dp_lm_head_tp=False,
)
assert not processor._tp_group_multicast_reachable()
def test_a_peer_without_fabric_takes_the_whole_group_off_the_gather(monkeypatch):
"""The probe allocates on this device alone, so a lone no must carry.
One node with no IMEX channels answers no while its peers answer yes; the
yes-ranks would then block in a rendezvous the no-ranks never enter.
"""
_set_fabric(monkeypatch, True)
import tokenspeed_kernel.ops.communication.fabric as fabric
monkeypatch.setattr(
fabric,
"group_has_fabric",
lambda ranks: False,
)
processor = LogitsProcessor(
config=SimpleNamespace(model_type="test", vocab_size=64),
tp_rank=0,
tp_size=8,
tp_group=tuple(range(8)),
attn_tp_size=1,
dp_lm_head_tp=False,
)
assert not processor._tp_group_multicast_reachable()
def test_tp_logits_custom_collectives_serve_host_spread_group_with_fabric(monkeypatch):
"""An NVLink domain can span hosts, so fabric decides, not the host count."""
_set_fabric(monkeypatch, True)
processor = LogitsProcessor(
config=SimpleNamespace(model_type="test", vocab_size=64),
tp_rank=0,
tp_size=8,
tp_group=tuple(range(8)),
attn_tp_size=1,
dp_lm_head_tp=False,
)
lm_head = SimpleNamespace(
weight=torch.ones((8, 2), dtype=torch.float32), num_embeddings_per_partition=8
)
created = {}
def _create_state(**kwargs):
created.update(kwargs)
return "ag-state"
monkeypatch.setattr(logits_processor_module, "create_state", _create_state)
monkeypatch.setattr(
logits_processor_module.pg_manager,
"get_process_group",
lambda backend, group: "pg",
)
assert processor._init_all_gather_state(lm_head, 1) == "ag-state"
assert created["hidden_size"] == 64
# FP32 logits travel as two BF16 words each.
assert processor._init_all_gather_state(lm_head, 2) == "ag-state"
assert created["hidden_size"] == 128
def test_logits_gather_state_spans_the_vocab_of_a_transposed_quantized_head(
monkeypatch,
):
# An FP8 head keeps its weight as [hidden, vocab shard] after loading.
_set_fabric(monkeypatch, True)
processor = LogitsProcessor(
config=SimpleNamespace(model_type="test", vocab_size=64),
tp_rank=0,
tp_size=2,
tp_group=(0, 1),
attn_tp_size=1,
dp_lm_head_tp=False,
)
lm_head = SimpleNamespace(
weight=torch.ones((4, 32), dtype=torch.float8_e4m3fn),
num_embeddings_per_partition=32,
)
created = {}
def _create_state(**kwargs):
created.update(kwargs)
return "ag-state"
monkeypatch.setattr(logits_processor_module, "create_state", _create_state)
monkeypatch.setattr(
logits_processor_module.pg_manager,
"get_process_group",
lambda backend, group: "pg",
)
assert processor._init_all_gather_state(lm_head, 1) == "ag-state"
assert created["hidden_size"] == 64
def test_dist_argmax_probe_failure_falls_back_and_latches(monkeypatch):
"""A failed probe falls back to the portable argmax, latches its
verdict, and skips capture."""
monkeypatch.setitem(
global_server_args_dict,
"mapping",
SimpleNamespace(nprocs_per_node=4),
)
monkeypatch.setattr(logits_processor_module, "dist_argmax_available", lambda: True)
monkeypatch.setattr(
logits_processor_module,
"current_platform",
lambda: SimpleNamespace(is_nvidia=True),
)
capturing = {"on": True}
monkeypatch.setattr(
logits_processor_module,
"is_current_stream_capturing",
lambda device: capturing["on"],
)
monkeypatch.setattr(
logits_processor_module.pg_manager,
"get_process_group",
lambda *a, **k: object(),
)
monkeypatch.setattr(
logits_processor_module.torch.distributed,
"all_reduce",
lambda tensor, **k: None,
)
calls = []
def failing_create(**kwargs):
calls.append(1)
return None # the group has no NVLS multicast
monkeypatch.setattr(
logits_processor_module, "try_create_dist_argmax_state", failing_create
)
processor = LogitsProcessor(
config=SimpleNamespace(model_type="test", vocab_size=8192),
tp_rank=0,
tp_size=2,
tp_group=(0, 4),
attn_tp_size=1,
dp_lm_head_tp=False,
)
lm_head = SimpleNamespace(
weight=torch.ones((4096, 2), dtype=torch.float32),
num_embeddings_per_partition=4096,
)
# Inside capture: no collective work, and nothing may latch.
assert processor._init_dist_argmax_state(lm_head, torch.float32) is None
assert len(calls) == 0
capturing["on"] = False
# Without the kernel state, the argmax all-reduces packed keys instead.
assert isinstance(
processor._init_dist_argmax_state(lm_head, torch.float32), VocabParallelArgmax
)
# The verdict is cached: the constructor must not be retried.
assert isinstance(
processor._init_dist_argmax_state(lm_head, torch.float32), VocabParallelArgmax
)
assert len(calls) == 1
def test_dist_argmax_state_cache_separates_logits_dtypes(monkeypatch):
"""An FP32 corrected-logits user must not reuse a BF16 sampler state."""
monkeypatch.setattr(logits_processor_module, "dist_argmax_available", lambda: True)
monkeypatch.setattr(
logits_processor_module,
"current_platform",
lambda: SimpleNamespace(is_nvidia=True),
)
monkeypatch.setattr(
logits_processor_module.torch.cuda,
"is_current_stream_capturing",
lambda: False,
)
monkeypatch.setattr(
logits_processor_module.pg_manager,
"get_process_group",
lambda *a, **k: object(),
)
monkeypatch.setattr(
logits_processor_module.torch.distributed,
"all_reduce",
lambda tensor, **k: None,
)
created = []
def fake_create(**kwargs):
created.append(kwargs["dtype"])
return SimpleNamespace(dtype=kwargs["dtype"])
monkeypatch.setattr(
logits_processor_module, "try_create_dist_argmax_state", fake_create
)
monkeypatch.setattr(LogitsProcessor, "_LOGITS_DIST_ARGMAX_STATES", {})
processor = LogitsProcessor(
config=SimpleNamespace(model_type="test", vocab_size=8192),
tp_rank=0,
tp_size=2,
tp_group=(0, 1),
attn_tp_size=1,
dp_lm_head_tp=False,
)
lm_head = SimpleNamespace(
weight=torch.ones((4096, 2), dtype=torch.bfloat16),
num_embeddings_per_partition=4096,
)
bf16_state = processor.acquire_dist_argmax_state(
lm_head, max_M=8, skip_ping_pong=False, dtype=torch.bfloat16
)
fp32_state = processor.acquire_dist_argmax_state(
lm_head, max_M=8, skip_ping_pong=False, dtype=torch.float32
)
assert bf16_state.dtype == torch.bfloat16
assert fp32_state.dtype == torch.float32
assert created == [torch.bfloat16, torch.float32]
# Both verdicts are independently cached.
assert (
processor.acquire_dist_argmax_state(
lm_head, max_M=8, skip_ping_pong=False, dtype=torch.float32
)
is fp32_state
)
assert len(created) == 2
class _TransposedFp8Gemm:
"""Stands in for the FP8 LM head GEMM, which needs a GPU: the weight is
``[hidden, vocab shard]`` in FP8 and the logits come out in BF16."""
def apply(self, layer, hidden_states, bias):
return hidden_states.to(torch.bfloat16) @ layer.weight.to(torch.bfloat16)
def test_dist_argmax_state_serves_the_bf16_logits_of_a_transposed_quantized_head(
monkeypatch,
):
# An FP8 head keeps its weight as [hidden, vocab shard] after loading.
hidden, shard = 16, 4096
monkeypatch.setattr(logits_processor_module, "dist_argmax_available", lambda: True)
monkeypatch.setattr(
logits_processor_module,
"current_platform",
lambda: SimpleNamespace(is_nvidia=True),
)
monkeypatch.setattr(
logits_processor_module.torch.cuda,
"is_current_stream_capturing",
lambda: False,
)
monkeypatch.setattr(
logits_processor_module.pg_manager,
"get_process_group",
lambda *a, **k: object(),
)
monkeypatch.setattr(
logits_processor_module.torch.distributed,
"all_reduce",
lambda tensor, **k: None,
)
created = []
made = {}
def fake_create(**kwargs):
state = SimpleNamespace(dtype=kwargs["dtype"])
made[kwargs["dtype"]] = state
created.append(kwargs["dtype"])
return state
monkeypatch.setattr(
logits_processor_module, "try_create_dist_argmax_state", fake_create
)
for gather in ("create_state", "all_gather_single"):
monkeypatch.setattr(
logits_processor_module,
gather,
lambda *a, **k: pytest.fail("greedy rows must not gather the vocab"),
)
monkeypatch.setattr(LogitsProcessor, "_LOGITS_DIST_ARGMAX_STATES", {})
proc = LogitsProcessor(
config=SimpleNamespace(model_type="test", vocab_size=2 * shard),
tp_rank=0,
tp_size=2,
tp_group=(0, 1),
do_argmax=True,
attn_tp_size=1,
dp_lm_head_tp=False,
)
lm_head = SimpleNamespace(
weight=torch.ones((hidden, shard), dtype=torch.float8_e4m3fn),
num_embeddings_per_partition=shard,
quant_method=_TransposedFp8Gemm(),
)
md = LogitsMetadata(forward_mode=ForwardMode.DECODE, query_shard=None)
# Only the 4096-wide shard passes the vocab check that guards the state;
# startup prepares every supported logits dtype, outside any forward.
proc.prepare_communication(lm_head)
assert created == [torch.float16, torch.bfloat16, torch.float32]
created.clear()
logits = proc._get_logits(
torch.randn(3, hidden, dtype=torch.bfloat16),
lm_head,
md,
require_full_vocab=False,
)
# The forward selects the prepared state by logits dtype; it builds nothing.
assert created == []
assert logits.shape == (3, shard) # left sharded for the distributed argmax
reduced = []
def fake_reduce(state, shard_logits):
reduced.append(state)
return None, shard_logits.argmax(dim=-1)
monkeypatch.setattr(logits_processor_module, "distributed_argmax", fake_reduce)
proc._argmax(logits)
assert reduced == [made[torch.bfloat16]]
# Under graph capture the forward still only selects; a dtype switch picks
# that dtype's prepared state.
monkeypatch.setattr(
logits_processor_module.torch.cuda,
"is_current_stream_capturing",
lambda: True,
)
captured = proc._get_logits(
torch.randn(3, hidden, dtype=torch.bfloat16),
lm_head,
md,
require_full_vocab=False,
)
assert created == []
assert captured.shape == (3, shard)
proc._argmax(captured.float())
assert reduced[-1] is made[torch.float32]
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
def test_fused_softcap_handles_large_logits_without_nan():
cap = 30.0
logits = torch.tensor(
[[5000.0, 2000.0, 1500.0, 100.0, 0.0, -100.0, -1500.0, -5000.0]],
device="cuda",
dtype=torch.float32,
)
expected = cap * torch.tanh(logits / cap)
out = fused_softcap(logits.clone(), cap, 1.0)
torch.cuda.synchronize()
assert torch.isfinite(out).all()
torch.testing.assert_close(out, expected, rtol=1e-5, atol=2e-5)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
@pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16])
def test_fused_softcap_scale_rounds_like_an_in_place_multiply(dtype):
torch.manual_seed(0)
logits = (torch.randn(7, 4099, device="cuda") * 40).to(dtype)
scale, cap = 0.1767766952966369, 20.0
fused = fused_softcap(logits.clone(), cap, scale)
separate = fused_softcap(logits.clone().mul_(scale), cap, 1.0)
assert torch.equal(fused, separate)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
def test_scaled_softcapped_tp_logits_match_scaling_before_the_gather(
monkeypatch, nvidia_logits
):
"""The softcap kernel applies the logit scale after the vocab gather; the
result is bit for bit what scaling each rank's shard first gives."""
scale, cap = 0.1767766952966369, 20.0
def processor(softcap):
config = SimpleNamespace(
model_type="test", vocab_size=64, final_logit_softcapping=softcap
)
proc = LogitsProcessor(
attn_tp_size=2,
config=config,
skip_all_gather=False,
do_argmax=False,
logit_scale=scale,
tp_rank=0,
tp_size=2,
tp_group=(0, 1),
dp_lm_head_tp=False,
)
proc._all_gather_state = None # the collective gather path
return proc
def collective(output, logits, group):
output.copy_(torch.cat((logits, logits.flip(-1)), dim=0))
monkeypatch.setattr(logits_processor_module, "all_gather_single", collective)
torch.manual_seed(1)
hidden = torch.randn(5, 16, device="cuda", dtype=torch.bfloat16) * 4
head = SimpleNamespace(
weight=torch.randn(32, 16, device="cuda", dtype=torch.bfloat16)
)
def logits(proc):
return proc._get_logits(
hidden,
head,
logits_metadata=None,
embedding_bias=None,
plan=None,
require_full_vocab=False,
)
fused = logits(processor(cap))
expected = fused_softcap(logits(processor(None)), cap, 1.0)
assert torch.equal(fused, expected)
@pytest.mark.parametrize("sink_armed", [False, True])
def test_a_forward_whose_taps_went_to_the_sink_returns_no_capture(
nvidia_logits, sink_armed
):
"""With the drafter's sink attached, the drafter already has every tap:
the processor neither concatenates them nor stores a hidden capture."""
from tokenspeed.runtime.execution.context import ForwardContext
from tokenspeed.runtime.execution.forward_batch_info import CaptureHiddenMode
from tokenspeed.runtime.execution.output_layout import ForwardOutputLayout
processor = LogitsProcessor(
attn_tp_size=1,
config=SimpleNamespace(model_type="test", vocab_size=4),
skip_all_gather=True,
do_argmax=False,
logit_scale=None,
tp_rank=0,
tp_size=1,
tp_group=(0,),
dp_lm_head_tp=False,
)
ctx = ForwardContext(
attn_backend=None,
token_to_kv_pool=None,
bs=1,
num_extends=0,
output_layout=ForwardOutputLayout(0, 0, 1, 3),
input_num_tokens=3,
forward_mode=ForwardMode.DECODE,
capture_hidden_mode=CaptureHiddenMode.FULL,
target_capture_sink=object() if sink_armed else None,
)
hidden = torch.randn(3, 2)
taps = [torch.randn(3, 2), torch.randn(3, 2)]
output = processor(
None,
hidden,
SimpleNamespace(weight=torch.randn(4, 2)),
LogitsMetadata.from_forward_context(ctx),
taps,
)
assert output.next_token_logits.shape == (3, 4)
if sink_armed:
assert output.hidden_states is None
else:
assert torch.equal(output.hidden_states, torch.cat(taps, dim=-1))
def test_argmax_routes_sharded_to_kernel(monkeypatch):
"""Sharded logits (tp shards reconstruct vocab) hit the fused kernel."""
proc = LogitsProcessor(
config=SimpleNamespace(model_type="test", vocab_size=8),
tp_rank=0,
tp_size=2,
tp_group=(0, 1),
attn_tp_size=1,
dp_lm_head_tp=False,
)
proc._dist_argmax_state = DistArgmaxPrepared(
states={torch.float32: object()}, # prepared for the shard's dtype
fallback=VocabParallelArgmax((0, 1), 0),
)
recorded = {}
def fake_dist(state, logits):
recorded["called"] = True
return None, logits.argmax(dim=-1)
monkeypatch.setattr(logits_processor_module, "distributed_argmax", fake_dist)
shard = torch.randn(4, 4, dtype=torch.float32) # 4 * tp_size(2) == vocab_size(8)
ids = proc._argmax(shard)
assert recorded.get("called")
assert torch.equal(ids, shard.argmax(dim=-1))
def test_argmax_falls_back_without_state(monkeypatch):
"""No fused state (e.g. EAGLE3 draft vocab != target, or gate failed):
_argmax falls back to a plain argmax instead of routing to the kernel."""
proc = LogitsProcessor(
config=SimpleNamespace(model_type="test", vocab_size=100),
tp_rank=0,
tp_size=2,
tp_group=(0, 1),
attn_tp_size=1,
dp_lm_head_tp=False,
)
proc._dist_argmax_state = None # gate failed (draft vocab != target vocab)
monkeypatch.setattr(
logits_processor_module,
"distributed_argmax",
lambda *a, **k: pytest.fail("kernel must not run without a fused state"),
)
# Gathered draft logits are narrower than the target config.vocab_size.
draft = torch.randn(4, 32, dtype=torch.float32)
ids = proc._argmax(draft)
assert torch.equal(ids, draft.argmax(dim=-1))
def test_get_logits_skips_gather_when_dist_argmax_active(monkeypatch, nvidia_logits):
"""do_argmax + active state keeps logits sharded (no all-gather)."""
monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: False)
proc = LogitsProcessor(
config=SimpleNamespace(
model_type="test", vocab_size=8, final_logit_softcapping=None
),
tp_rank=0,
tp_size=2,
tp_group=(0, 1),
do_argmax=True,
attn_tp_size=1,
dp_lm_head_tp=False,
)
monkeypatch.setattr(
proc, "_init_dist_argmax_state", lambda lm_head, logits_dtype: object()
)
monkeypatch.setattr(
logits_processor_module,
"all_gather_inner",
lambda *a, **k: pytest.fail("gather must be skipped on the fused path"),
)
hidden = torch.randn(4, 2, dtype=torch.float32)
lm_head = SimpleNamespace(
weight=torch.randn(4, 2, dtype=torch.float32), num_embeddings_per_partition=4
) # 4*2 == 8
proc.prepare_communication(lm_head)
md = LogitsMetadata(forward_mode=ForwardMode.DECODE, query_shard=None)
out = proc._get_logits(hidden, lm_head, md, require_full_vocab=False)
assert out.shape == (4, 4) # local shard width retained, not gathered to 8
@pytest.mark.parametrize("mode", [ForwardMode.EXTEND, ForwardMode.DECODE])
@pytest.mark.parametrize("vetoed", [False, True])
def test_startup_prepares_shared_head_before_first_forward(monkeypatch, mode, vetoed):
monkeypatch.setitem(global_server_args_dict, "force_deterministic_rsag", vetoed)
capturing = {"active": False}
monkeypatch.setattr(
torch.cuda, "is_current_stream_capturing", lambda: capturing["active"]
)
processor = LogitsProcessor(
config=SimpleNamespace(model_type="test", vocab_size=8),
do_argmax=True,
tp_rank=0,
tp_size=2,
tp_group=(0, 1),
attn_tp_size=1,
dp_lm_head_tp=False,
)
language = torch.nn.Module()
language.lm_head = torch.nn.Linear(2, 4, bias=False)
language.lm_head.num_embeddings_per_partition = 4
language.logits_processor = processor
model = torch.nn.Module()
model.language_model = language
# A shared draft head/processor must reuse the prepared verdict.
draft = torch.nn.Module()
draft.lm_head = language.lm_head
draft.logits_processor = processor
prepare_logits_communication(model)
prepared = processor._dist_argmax_state
prepare_logits_communication(draft)
assert processor._dist_argmax_state is prepared
def gather(output, logits, group):
output.copy_(torch.cat((logits, logits), dim=0))
# The process group is unavailable in this CPU test; the LM-head and
# logits path are real. Capture now forbids late state construction.
monkeypatch.setattr(logits_processor_module, "all_gather_single", gather)
capturing["active"] = True
hidden = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
local = hidden @ language.lm_head.weight.T
logits = processor._get_logits(
hidden,
language.lm_head,
LogitsMetadata(forward_mode=mode, query_shard=None),
require_full_vocab=False,
)
expected = torch.cat((local, local), dim=-1) if vetoed else local
torch.testing.assert_close(logits, expected, rtol=0, atol=0)
def test_prepared_argmax_reuses_weight_updates_and_rebinds_padded_head(monkeypatch):
monkeypatch.setitem(global_server_args_dict, "force_deterministic_rsag", False)
# A single-host group: the gather gate needs no fabric map.
monkeypatch.setitem(global_server_args_dict, "mapping", None)
capturing = {"active": False}
monkeypatch.setattr(
logits_processor_module,
"is_current_stream_capturing",
lambda device: capturing["active"],
)
processor = LogitsProcessor(
config=SimpleNamespace(model_type="test", vocab_size=8),
do_argmax=True,
tp_rank=0,
tp_size=2,
tp_group=(0, 1),
attn_tp_size=1,
dp_lm_head_tp=False,
)
head = torch.nn.Linear(2, 4, bias=False)
head.num_embeddings_per_partition = 4
processor.prepare_communication(head)
state = processor._dist_argmax_state
with torch.no_grad():
head.weight.fill_(2)
processor.prepare_communication(head)
assert processor._dist_argmax_state is state
padded_head = torch.nn.Linear(2, 5, bias=False)
padded_head.num_embeddings_per_partition = 5
capturing["active"] = True
with pytest.raises(RuntimeError, match="before CUDA graph capture"):
processor.prepare_communication(padded_head)
assert processor._dist_argmax_state is state
capturing["active"] = False
processor.prepare_communication(padded_head)
monkeypatch.setattr(
logits_processor_module,
"all_gather_single",
lambda output, logits, group: output.copy_(torch.cat((logits, logits), dim=0)),
)
hidden = torch.tensor([[1.0, 2.0]])
local = hidden @ padded_head.weight.T
logits = processor._get_logits(
hidden,
padded_head,
LogitsMetadata(forward_mode=ForwardMode.EXTEND, query_shard=None),
require_full_vocab=False,
)
torch.testing.assert_close(
logits, torch.cat((local, local), dim=-1)[:, :8].float(), rtol=0, atol=0
)
def test_inactive_argmax_preserves_weightless_quantized_head():
class QuantMethod:
def apply(self, head, hidden, bias):
return hidden @ head.qweight.T
class Head(torch.nn.Module):
def __init__(self):
super().__init__()
self.quant_method = QuantMethod()
self.qweight = torch.nn.Parameter(torch.eye(2))
processor = LogitsProcessor(
config=SimpleNamespace(model_type="test", vocab_size=2),
attn_tp_size=1,
dp_lm_head_tp=False,
)
model = torch.nn.Module()
model.logits_processor = processor
model.lm_head = Head()
prepare_logits_communication(model)
hidden = torch.tensor([[1.0, 2.0]])
logits = processor._get_logits(
hidden,
model.lm_head,
LogitsMetadata(forward_mode=ForwardMode.EXTEND, query_shard=None),
require_full_vocab=False,
)
torch.testing.assert_close(logits, hidden, rtol=0, atol=0)
def test_require_full_vocab_logits_turns_the_fused_draft_argmax_off(monkeypatch):
"""A consumer that samples from the draft distribution asks for the
full-vocab gather explicitly; the draft model keeps constructing with
do_argmax=True and no global flag is consulted."""
proc = LogitsProcessor(
config=SimpleNamespace(
model_type="test", vocab_size=8, final_logit_softcapping=None
),
tp_rank=0,
tp_size=2,
tp_group=(0, 1),
do_argmax=True,
attn_tp_size=1,
dp_lm_head_tp=False,
)
assert proc.do_argmax
proc.require_full_vocab_logits()
assert not proc.do_argmax
monkeypatch.setattr(
proc,
"_init_dist_argmax_state",
lambda lm_head, logits_dtype: pytest.fail(
"the fused argmax gate must stay off"
),
)
monkeypatch.setattr(
proc, "_init_all_gather_state", lambda lm_head, words_per_logit: None
)
monkeypatch.setattr(
logits_processor_module, "all_gather_single", lambda out, inp, group: None
)
hidden = torch.randn(4, 2, dtype=torch.float32)
lm_head = SimpleNamespace(weight=torch.randn(4, 2, dtype=torch.float32))
md = LogitsMetadata(forward_mode=ForwardMode.DECODE, query_shard=None)
out = proc._get_logits(hidden, lm_head, md, require_full_vocab=True)
assert out.shape == (4, 8) # gathered to the full vocab
def test_capture_takes_the_plain_gather_and_leaves_the_gate_for_later(
monkeypatch, nvidia_logits
):
"""Forward never builds the distributed argmax; capture defers the gather gate.
The uninitialized sentinel is an ``object()`` and so passes
``is not None``: forward must refuse it instead of handing it to the
gather as if it were a state. Once ``prepare_communication`` has resolved
the argmax (None = prepared fallback), a capture takes the plain gather
and leaves the all-gather gate's sentinel for an eager call, since that
gate still rendezvouses lazily.
"""
proc = LogitsProcessor(
config=SimpleNamespace(
model_type="test", vocab_size=8, final_logit_softcapping=None
),
tp_rank=0,
tp_size=2,
tp_group=(0, 1),
do_argmax=True,
attn_tp_size=1,
dp_lm_head_tp=False,
)
monkeypatch.setattr(
logits_processor_module,
"all_gather_inner",
lambda *a, **k: pytest.fail("the sentinel must never reach the gather"),
)
hidden = torch.randn(4, 2, dtype=torch.bfloat16)
lm_head = SimpleNamespace(
weight=torch.randn(4, 2, dtype=torch.bfloat16), num_embeddings_per_partition=4
)
md = LogitsMetadata(forward_mode=ForwardMode.DECODE, query_shard=None)
with pytest.raises(RuntimeError, match="must be prepared before forwarding"):
proc._get_logits(hidden, lm_head, md, require_full_vocab=False)
# A prepared fallback gathers plainly inside a capture; both gates stay off.
monkeypatch.setattr(
proc, "_init_dist_argmax_state", lambda lm_head, logits_dtype: None
)
proc.prepare_communication(lm_head)
monkeypatch.setattr(
proc,
"_init_dist_argmax_state",
lambda lm_head, logits_dtype: pytest.fail(
"forward never re-runs the argmax gate"
),
)
monkeypatch.setattr(
proc,
"_init_all_gather_state",
lambda lm_head, words_per_logit: pytest.fail(
"the gate must not run inside a capture"
),
)
monkeypatch.setattr(
logits_processor_module, "is_current_stream_capturing", lambda device: True
)
monkeypatch.setattr(
logits_processor_module,
"all_gather_single",
lambda out, inp, group: None,
)
out = proc._get_logits(hidden, lm_head, md, require_full_vocab=False)
assert out.shape == (4, 8)
assert proc._all_gather_state is LogitsProcessor._LOGITS_AG_STATE_UNINITIALIZED
assert proc._dist_argmax_state is None
# A subsequent eager forward must still be able to initialize the states.
monkeypatch.setattr(
logits_processor_module, "is_current_stream_capturing", lambda device: False
)
monkeypatch.setattr(
proc,
"_init_all_gather_state",
lambda lm_head, words_per_logit: SimpleNamespace(hidden_dim=1 << 20),
)
monkeypatch.setattr(
logits_processor_module,
"all_gather_inner",
lambda state, logits, **kwargs: torch.cat((logits, logits), dim=-1),
)
eager = proc._get_logits(hidden, lm_head, md, require_full_vocab=False)
torch.testing.assert_close(eager, (hidden @ lm_head.weight.T).repeat(1, 2))
def test_get_logits_softcap_disables_fused_argmax(monkeypatch, nvidia_logits):
"""final_logit_softcapping must disable the fused early-return so the
softcap is applied to full-vocab logits (then a plain argmax runs)."""
monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: False)
proc = LogitsProcessor(
config=SimpleNamespace(
model_type="test", vocab_size=8, final_logit_softcapping=30.0
),
tp_rank=0,
tp_size=2,
tp_group=(0, 1),
do_argmax=True,
attn_tp_size=1,
dp_lm_head_tp=False,
)
# Fused state is otherwise eligible; softcap must still force the gather.
monkeypatch.setattr(
proc, "_init_dist_argmax_state", lambda lm_head, logits_dtype: object()
)
monkeypatch.setattr(
proc,
"_init_all_gather_state",
lambda lm_head, words_per_logit: SimpleNamespace(hidden_dim=1 << 20),
)
monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: False)
called = {}
def fake_ag(state, logits, **kw):
called["ag"] = True
return logits.repeat(1, proc.tp_size) # [bs, vocab/tp] -> [bs, vocab]
monkeypatch.setattr(logits_processor_module, "all_gather_inner", fake_ag)
monkeypatch.setattr(
logits_processor_module, "fused_softcap_generic", lambda *a, **k: None
)
hidden = torch.randn(4, 2, dtype=torch.bfloat16)
lm_head = SimpleNamespace(
weight=torch.randn(4, 2, dtype=torch.bfloat16), num_embeddings_per_partition=4
) # 4*2 == 8
proc.prepare_communication(lm_head)
md = LogitsMetadata(forward_mode=ForwardMode.DECODE, query_shard=None)
out = proc._get_logits(hidden, lm_head, md, require_full_vocab=False)
assert called.get("ag") # gathered (softcap on full vocab), not early-returned
assert out.shape == (4, 8)
if __name__ == "__main__":
raise SystemExit(pytest.main([__file__, "-v"]))
def _logprob_device() -> str:
return "cuda" if torch.cuda.is_available() else "cpu"
def _input_logprob_rows(
rows,
targets,
*,
num_input_rows,
chunk_tokens,
device,
rows_per_rank=None,
gathered_to_rows=None,
):
return InputLogprobRows(
rows=torch.tensor(rows, dtype=torch.int64, device=device),
targets=torch.tensor(targets, dtype=torch.int64, device=device),
slots=torch.zeros(
len(rows) if rows_per_rank is None else sum(rows_per_rank),
dtype=torch.int64,
device=device,
),
num_input_rows=num_input_rows,
chunk_tokens=chunk_tokens,
rows_per_rank=rows_per_rank,
gathered_to_rows=(
None
if gathered_to_rows is None
else torch.tensor(gathered_to_rows, dtype=torch.int64, device=device)
),
)
def test_gather_token_logprobs_widens_inside_the_kernel_bitwise():
"""The ``dtype=float32`` log-softmax (no fp32 copy of the logits) is the
same arithmetic as ``log_softmax(logits.float())``, bit for bit."""
from tokenspeed.runtime.sampling.utils import gather_token_logprobs_torch
torch.manual_seed(3)
for dtype in (torch.bfloat16, torch.float16, torch.float32):
logits = (torch.randn(7, 1000) * 8).to(dtype)
tokens = torch.randint(0, 1000, (7,))
got = gather_token_logprobs_torch(logits, tokens)
reference = (
torch.log_softmax(logits.float(), dim=-1)
.gather(-1, tokens.unsqueeze(-1))
.squeeze(-1)
)
assert got.dtype == torch.float32
assert torch.equal(got, reference), dtype
@pytest.mark.parametrize("chunk_tokens", [1, 2, 3, 64])
def test_input_logprobs_match_the_output_logprob_arithmetic(chunk_tokens):
"""Prompt logprobs are the sampler's fp32 ``log_softmax(...).gather`` on
the same ``_get_logits`` route, independent of the position chunk size,
and leave the sampled logits of the last row per request untouched."""
from tokenspeed.runtime.sampling.utils import gather_token_logprobs_torch
device = _logprob_device()
torch.manual_seed(0)
vocab = 6
# Two requests of 3 and 2 tokens; prompt logprobs for rows 1, 2 of the
# first and row 3 (position 0) of the second.
# Keep the four-term dot products exact so cuBLAS's batch-dependent
# reduction order cannot change the prompt or sampled logits. This tests
# logprob arithmetic and row selection, not GEMM batch invariance in auto.
hidden = torch.randint(-8, 9, (5, 4), device=device).float() / 8
weight = torch.randint(-8, 9, (vocab, 4), device=device).float() / 8
lm_head = SimpleNamespace(weight=weight)
rows, targets = [1, 2, 3], [5, 2, 3]
processor = LogitsProcessor(
config=SimpleNamespace(model_type="test", vocab_size=vocab),
attn_tp_size=1,
dp_lm_head_tp=False,
)
metadata = LogitsMetadata(
forward_mode=ForwardMode.EXTEND,
query_shard=None,
gather_ids=torch.tensor([2, 4], dtype=torch.int32, device=device),
input_logprob_rows=_input_logprob_rows(
rows, targets, num_input_rows=5, chunk_tokens=chunk_tokens, device=device
),
)
out = processor(
input_ids=None,
hidden_states=hidden,
lm_head=lm_head,
logits_metadata=metadata,
)
logits = hidden @ weight.T
torch.testing.assert_close(out.next_token_logits, logits[[2, 4]], rtol=0, atol=0)
expected = gather_token_logprobs_torch(
logits[rows], torch.tensor(targets, device=device)
)
assert out.input_token_logprobs.dtype == torch.float32
torch.testing.assert_close(out.input_token_logprobs, expected, rtol=0, atol=0)
def test_input_logprobs_are_gathered_from_prefill_rows_of_a_mixed_batch():
"""Decode rows sit behind the prefill rows; the plan only names prefill
positions, so the decode rows are never pushed through the gather."""
device = _logprob_device()
torch.manual_seed(1)
vocab = 8
hidden = torch.randn(6, 4, device=device) # 4 prefill rows + 2 decode rows
weight = torch.randn(vocab, 4, device=device)
processor = LogitsProcessor(
config=SimpleNamespace(model_type="test", vocab_size=vocab),
attn_tp_size=1,
dp_lm_head_tp=False,
)
seen = []
original = processor._get_logits
def spy(hidden_states, *args, **kwargs):
seen.append(hidden_states.shape[0])
return original(hidden_states, *args, **kwargs)
processor._get_logits = spy
metadata = LogitsMetadata(
forward_mode=ForwardMode.MIXED,
query_shard=None,
gather_ids=torch.tensor([3, 4, 5], dtype=torch.int32, device=device),
input_logprob_rows=_input_logprob_rows(
[0, 1, 2], [1, 2, 3], num_input_rows=6, chunk_tokens=2, device=device
),
)
out = processor(
input_ids=None,
hidden_states=hidden,
lm_head=SimpleNamespace(weight=weight),
logits_metadata=metadata,
)
# Two prompt chunks (2 + 1 rows) then the three sampled rows.
assert seen == [2, 1, 3]
logits = hidden @ weight.T
expected = torch.log_softmax(logits[:3].float(), dim=-1)[
torch.arange(3, device=device), torch.tensor([1, 2, 3], device=device)
]
torch.testing.assert_close(out.input_token_logprobs, expected, rtol=0, atol=0)
torch.testing.assert_close(out.next_token_logits, logits[[3, 4, 5]])
def test_input_logprobs_refuse_a_model_that_narrowed_its_logits_rows():
device = _logprob_device()
processor = LogitsProcessor(
config=SimpleNamespace(model_type="test", vocab_size=4),
attn_tp_size=1,
dp_lm_head_tp=False,
)
lm_head = SimpleNamespace(weight=torch.randn(4, 2, device=device))
rows = _input_logprob_rows(
[0, 1], [1, 2], num_input_rows=3, chunk_tokens=8, device=device
)
# A narrowing model hands over only its selected rows ...
with pytest.raises(ValueError, match="narrowed"):
processor(
input_ids=None,
hidden_states=torch.randn(1, 2, device=device),
lm_head=lm_head,
logits_metadata=LogitsMetadata(
forward_mode=ForwardMode.EXTEND,
query_shard=None,
gather_ids=torch.tensor([0], device=device),
logits_rows_selected=True,
input_logprob_rows=rows,
),
)
# ... and so does any forward whose activations do not cover every input row.
with pytest.raises(ValueError, match="narrowed"):
processor(
input_ids=None,
hidden_states=torch.randn(2, 2, device=device),
lm_head=lm_head,
logits_metadata=LogitsMetadata(
forward_mode=ForwardMode.EXTEND,
query_shard=None,
gather_ids=torch.tensor([1], device=device),
input_logprob_rows=rows,
),
)
# A cache-only chunk without logits rows cannot provide them either.
with pytest.raises(ValueError, match="selected logits rows"):
processor(
input_ids=None,
hidden_states=torch.empty(0, 2, device=device),
lm_head=lm_head,
logits_metadata=LogitsMetadata(
forward_mode=ForwardMode.EXTEND,
query_shard=None,
logits_rows_selected=True,
input_logprob_rows=rows,
),
)
def test_input_logprobs_bypass_the_sharded_argmax_shortcut(monkeypatch, nvidia_logits):
"""A ``do_argmax`` head keeps sampled logits TP-sharded for the fused
argmax; the prompt-logprob gather needs the whole vocabulary."""
proc = LogitsProcessor(
config=SimpleNamespace(
model_type="test", vocab_size=8, final_logit_softcapping=None
),
tp_rank=0,
tp_size=2,
tp_group=(0, 1),
do_argmax=True,
attn_tp_size=1,
dp_lm_head_tp=False,
)
monkeypatch.setattr(
proc, "_init_dist_argmax_state", lambda lm_head, logits_dtype: object()
)
monkeypatch.setattr(
proc, "_init_all_gather_state", lambda lm_head, words_per_logit: None
)
monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: False)
monkeypatch.setattr(
logits_processor_module,
"distributed_argmax",
lambda state, logits: (None, logits.argmax(dim=-1)),
)
gathered = []
def collective(output, logits, group):
gathered.append(logits.shape)
output.copy_(torch.cat((logits, logits), dim=0))
monkeypatch.setattr(logits_processor_module, "all_gather_single", collective)
hidden = torch.randn(3, 2, dtype=torch.float32)
lm_head = SimpleNamespace(
weight=torch.randn(4, 2, dtype=torch.float32), num_embeddings_per_partition=4
)
proc.prepare_communication(lm_head)
md = LogitsMetadata(
forward_mode=ForwardMode.EXTEND,
query_shard=None,
gather_ids=torch.tensor([2]),
input_logprob_rows=_input_logprob_rows(
[0, 1], [1, 6], num_input_rows=3, chunk_tokens=8, device="cpu"
),
)
out = proc(
input_ids=None, hidden_states=hidden, lm_head=lm_head, logits_metadata=md
)
# The prompt rows were gathered to the full vocab (target id 6 lives on the
# other shard); the sampled row kept the shortcut.
assert gathered == [(2, 4)]
assert out.input_token_logprobs.shape == (2,)
assert out.next_token_logits.shape == (1, 4)
def test_input_logprob_chunks_never_take_the_multicast_gather(
monkeypatch, nvidia_logits
):
"""The multicast all-gather hands back a view of the TP group's shared
buffer with no entry barrier; the next chunk's gather on a faster rank
would overwrite it under this rank's log-softmax. The chunk loop must go
through the NCCL collective into a private tensor, while the sampled rows
keep the multicast path."""
proc = LogitsProcessor(
config=SimpleNamespace(
model_type="test", vocab_size=8, final_logit_softcapping=None
),
tp_rank=0,
tp_size=2,
tp_group=(0, 1),
attn_tp_size=1,
dp_lm_head_tp=False,
)
multicast_state = SimpleNamespace(hidden_dim=1 << 20)
monkeypatch.setattr(
proc, "_init_all_gather_state", lambda lm_head, words_per_logit: multicast_state
)
monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: False)
multicast_rows: list[int] = []
collective_rows: list[int] = []
def multicast(state, logits, *, tp_hidden_dim, skip_entry_sync, safe):
assert state is multicast_state and skip_entry_sync and not safe
multicast_rows.append(logits.shape[0])
return torch.cat((logits, logits), dim=-1)
def collective(output, logits, group):
collective_rows.append(logits.shape[0])
output.copy_(torch.cat((logits, logits), dim=0))
monkeypatch.setattr(logits_processor_module, "all_gather_inner", multicast)
monkeypatch.setattr(logits_processor_module, "all_gather_single", collective)
# bf16 logits: the only dtype the multicast path accepts.
hidden = torch.randn(5, 2, dtype=torch.bfloat16)
lm_head = SimpleNamespace(weight=torch.randn(4, 2, dtype=torch.bfloat16))
md = LogitsMetadata(
forward_mode=ForwardMode.EXTEND,
query_shard=None,
gather_ids=torch.tensor([4]),
input_logprob_rows=_input_logprob_rows(
[0, 1, 2, 3], [1, 6, 2, 5], num_input_rows=5, chunk_tokens=3, device="cpu"
),
)
out = proc(
input_ids=None, hidden_states=hidden, lm_head=lm_head, logits_metadata=md
)
# Two prompt chunks (3 + 1 rows) through the collective; one sampled row
# through the multicast buffer.
assert collective_rows == [3, 1]
assert multicast_rows == [1]
assert out.input_token_logprobs.shape == (4,)
assert out.next_token_logits.shape == (1, 8)
# --------------------------------------------------------------------------
# Query context parallelism: the shard is a parameter of the row selection
# --------------------------------------------------------------------------
def _sharded_processor(monkeypatch, size: int, rank: int) -> LogitsProcessor:
"""A head sharded over ``size`` ranks whose vocab all-gather is faked as
the identity on a full-vocab head (each rank holds the whole head here);
the shard's row gathers are recorded by the test."""
proc = LogitsProcessor(
config=SimpleNamespace(
model_type="test", vocab_size=8, final_logit_softcapping=None
),
tp_rank=rank,
tp_size=size,
tp_group=tuple(range(size)),
attn_tp_size=1,
dp_lm_head_tp=False,
)
monkeypatch.setattr(
proc, "_init_all_gather_state", lambda lm_head, words_per_logit: None
)
monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: False)
def no_gather(hidden_states, lm_head, md, embedding_bias=None, plan=None, **kw):
return hidden_states.float() @ lm_head.weight.float().T
monkeypatch.setattr(proc, "_get_logits", no_gather)
return proc
def test_a_sharded_forward_gathers_the_planned_rows_then_the_sampled_rows(
monkeypatch,
):
"""Under a query shard the processor receives the shard's rows. The head
is vocab-sharded over the same group, so it first all-gathers the
planned prompt rows' activations with the per-rank counts and scores the
whole plan on every rank (one chunk schedule for the group), then gathers
the sampled rows (never ``hidden[gather_ids]``) and runs the LM head on
the batch's ``[bs, hidden]`` rows: prompt rows are scored before the
sampled rows leave the shard. A FULL capture stays the shard. Every rank,
one without planned rows included, joins both gathers."""
from tokenspeed.runtime.execution.forward_batch_info import CaptureHiddenMode
from tokenspeed.runtime.execution.query_shard import QueryShardPlan
# Rows 0..9, one per zigzag segment: rank 0 holds rows 0, 4, 5, rank 1
# rows 1, 6, rank 2 rows 2, 7, rank 3 rows 3, 8, 9. Sampled rows 3, 4, 9.
lengths = [4, 1, 5]
total = sum(lengths)
gather_ids = torch.cumsum(torch.tensor(lengths), 0) - 1
torch.manual_seed(0)
hidden = torch.randn(total, 2)
lm_head = SimpleNamespace(weight=torch.randn(8, 2))
# The plan: rows 0..2 of request 0, request 1's row and rows 5..7 of
# request 2; rank 3 holds none of them.
plan_rows = torch.tensor([0, 1, 2, 4, 5, 6, 7])
plan_targets = torch.tensor([3, 1, 7, 4, 2, 2, 5])
plans = [
QueryShardPlan.from_forward(
total_tokens=total, input_lengths=lengths, size=4, rank=rank, device="cpu"
)
for rank in range(4)
]
# What each collective returns: every rank's rows, rank by rank.
in_gather_order = {
"planned": torch.cat(
[p.local_row_ids[p.split_rows(plan_rows).local_ids] for p in plans]
),
"sampled": torch.cat([p.local_row_ids[p.local_sampled_index] for p in plans]),
}
assert in_gather_order["planned"].tolist() == [0, 4, 5, 1, 6, 2, 7]
assert in_gather_order["sampled"].tolist() == [4, 3, 9]
# The unsharded chunk loop (two rows per chunk, plan order): CPU GEMMs
# round by shape, so the reference runs the same chunks.
reference = torch.cat(
[
torch.log_softmax(
(hidden[plan_rows[i : i + 2]] @ lm_head.weight.T).float(), -1
)[torch.arange(len(plan_rows[i : i + 2])), plan_targets[i : i + 2]]
for i in range(0, len(plan_rows), 2)
]
)
gathers: list[tuple[int, str, list[int]]] = []
def fake_gather(kind):
def gather(tensor, group, counts):
assert group == (0, 1, 2, 3)
gathers.append((len(gathers), kind, list(counts)))
# Stand in for the collective: the rows every rank would
# contribute, rank by rank.
return hidden[in_gather_order[kind]]
return gather
# The planned-row gather (processor) and the sampled-row gather
# (comm_manager.gather_sampled_rows): both byte-preserving row gathers.
monkeypatch.setattr(
logits_processor_module, "token_all_gather_rows", fake_gather("planned")
)
monkeypatch.setattr(
comm_manager_module, "token_all_gather_rows", fake_gather("sampled")
)
for rank in range(4):
plan = QueryShardPlan.from_forward(
total_tokens=total, input_lengths=lengths, size=4, rank=rank, device="cpu"
)
proc = _sharded_processor(monkeypatch, 4, rank)
split = plan.split_rows(plan_rows)
assert split.rows_per_rank == (3, 2, 2, 0)
md = LogitsMetadata(
forward_mode=ForwardMode.EXTEND,
capture_hidden_mode=CaptureHiddenMode.FULL,
gather_ids=gather_ids,
query_shard=plan,
input_logprob_rows=InputLogprobRows(
rows=split.local_ids,
targets=plan_targets,
slots=torch.zeros(plan_rows.shape[0], dtype=torch.int64),
num_input_rows=plan.local_rows,
chunk_tokens=2,
rows_per_rank=split.rows_per_rank,
gathered_to_rows=split.to_rows_order,
),
)
shard = hidden[plan.local_row_ids]
out = proc(
input_ids=None, hidden_states=shard, lm_head=lm_head, logits_metadata=md
)
assert out.hidden_states is shard # FULL capture: the shard's own rows
# The planned rows leave before the sampled rows; rank 3 contributes
# no planned row and still joins.
assert [g[1] for g in gathers[2 * rank :]] == ["planned", "sampled"]
assert gathers[2 * rank][2] == [3, 2, 2, 0]
assert gathers[2 * rank + 1][2] == list(plan.sampled_rows_per_rank)
assert list(plan.sampled_rows_per_rank) == [1, 0, 0, 2]
# Every rank ends with the whole plan's logprobs and the batch's logits.
torch.testing.assert_close(out.input_token_logprobs, reference, rtol=0, atol=0)
torch.testing.assert_close(
out.next_token_logits,
(hidden[gather_ids] @ lm_head.weight.T).float(),
rtol=0,
atol=0,
)
@pytest.mark.parametrize("taps", [0, 1, 3])
def test_a_last_capture_under_a_shard_is_the_gathered_sampled_rows(monkeypatch, taps):
"""A LAST hidden capture under a query shard stores the batch's gathered
``[bs, hidden]`` rows, whole on every rank -- the aux taps' (Eagle3) when
the model has them, concatenated, else the final hidden's -- and each
tap costs one sampled-row gather only on a LAST capture: a FULL or NULL
capture never selects the taps, so the forward spends no collective on
them. ``taps=0`` is a model without taps."""
from tokenspeed.runtime.execution.forward_batch_info import CaptureHiddenMode
from tokenspeed.runtime.execution.query_shard import QueryShardPlan
# Rows 0..9, one per zigzag segment; sampled rows 3 and 9 on rank 3, 4 on
# rank 0.
lengths = [4, 1, 5]
total = sum(lengths)
gather_ids = torch.cumsum(torch.tensor(lengths), 0) - 1
torch.manual_seed(1)
hidden = torch.randn(total, 2)
aux = [torch.randn(total, 2) + 10 * (i + 1) for i in range(taps)]
lm_head = SimpleNamespace(weight=torch.randn(8, 2))
gathered: list[torch.Tensor] = []
current: dict[str, QueryShardPlan] = {}
def fake_gather(tensor, group, counts):
assert group == (0, 1, 2, 3) and list(counts) == [1, 0, 0, 2]
# The final rows are gathered first, then each tap in order; this
# rank contributes its sampled rows of that source, and the collective
# hands back every rank's, rank by rank (rows 4, 3, 9).
source = (hidden, *aux)[len(gathered)]
plan = current["plan"]
local = source[plan.local_row_ids][plan.local_sampled_index]
assert torch.equal(tensor, local)
gathered.append(tensor)
return source[torch.tensor([4, 3, 9])]
monkeypatch.setattr(comm_manager_module, "token_all_gather_rows", fake_gather)
modes = (CaptureHiddenMode.LAST, CaptureHiddenMode.FULL, CaptureHiddenMode.NULL)
for rank in range(4):
plan = QueryShardPlan.from_forward(
total_tokens=total, input_lengths=lengths, size=4, rank=rank, device="cpu"
)
current["plan"] = plan
shard = hidden[plan.local_row_ids]
aux_shard = [a[plan.local_row_ids] for a in aux] or None
for mode in modes:
gathered.clear()
proc = _sharded_processor(monkeypatch, 4, rank)
out = proc(
input_ids=None,
hidden_states=shard,
lm_head=lm_head,
logits_metadata=LogitsMetadata(
forward_mode=ForwardMode.EXTEND,
capture_hidden_mode=mode,
gather_ids=gather_ids,
query_shard=plan,
),
aux_hidden_states=aux_shard,
)
torch.testing.assert_close(
out.next_token_logits,
(hidden[gather_ids] @ lm_head.weight.T).float(),
rtol=0,
atol=0,
)
if mode is CaptureHiddenMode.LAST:
assert len(gathered) == 1 + taps
expected = (
torch.cat([a[gather_ids] for a in aux], dim=-1)
if taps
else hidden[gather_ids]
)
torch.testing.assert_close(out.hidden_states, expected, rtol=0, atol=0)
assert out.hidden_states.shape == (3, 2 * max(taps, 1))
else:
assert len(gathered) == 1 # the final hidden rows only
if mode is CaptureHiddenMode.FULL:
expected = torch.cat(aux_shard, dim=-1) if taps else shard
torch.testing.assert_close(
out.hidden_states, expected, rtol=0, atol=0
)
else:
assert out.hidden_states is None
def test_a_shard_refuses_pre_selected_rows_and_a_mismatched_head(monkeypatch):
"""A model that selected its rows before the processor has no prompt
activations left -- the refusal fires whether or not the forward is
sharded. And the shard's group must be the LM head's vocab-shard group."""
from tokenspeed.runtime.execution.query_shard import QueryShardPlan
plan = QueryShardPlan.from_forward(
total_tokens=4, input_lengths=[4], size=2, rank=0, device="cpu"
)
lm_head = SimpleNamespace(weight=torch.randn(8, 2))
rows = _input_logprob_rows(
[0, 1],
[1, 2],
num_input_rows=2,
chunk_tokens=8,
device="cpu",
rows_per_rank=(2, 1),
gathered_to_rows=[0, 1, 2],
)
proc = _sharded_processor(monkeypatch, 2, 0)
with pytest.raises(ValueError, match="narrowed"):
proc(
input_ids=None,
hidden_states=torch.randn(1, 2),
lm_head=lm_head,
logits_metadata=LogitsMetadata(
forward_mode=ForwardMode.EXTEND,
gather_ids=torch.tensor([3]),
logits_rows_selected=True,
query_shard=plan,
input_logprob_rows=rows,
),
)
# Rows staged for a shard reaching an unsharded forward, and vice versa.
with pytest.raises(ValueError, match="staged for"):
proc(
input_ids=None,
hidden_states=torch.randn(2, 2),
lm_head=lm_head,
logits_metadata=LogitsMetadata(
forward_mode=ForwardMode.EXTEND,
query_shard=None,
gather_ids=torch.tensor([1]),
input_logprob_rows=rows,
),
)
wide = LogitsProcessor(
config=SimpleNamespace(model_type="test", vocab_size=8),
tp_rank=0,
tp_size=4,
tp_group=(0, 1, 2, 3),
attn_tp_size=1,
dp_lm_head_tp=False,
)
with pytest.raises(ValueError, match="vocab-shard group"):
wide(
input_ids=None,
hidden_states=torch.randn(2, 2),
lm_head=lm_head,
logits_metadata=LogitsMetadata(
forward_mode=ForwardMode.EXTEND,
gather_ids=torch.tensor([3]),
query_shard=plan,
),
)
replicated = LogitsProcessor(
config=SimpleNamespace(model_type="test", vocab_size=8),
skip_all_gather=True,
tp_rank=0,
tp_size=2,
tp_group=(0, 1),
attn_tp_size=1,
dp_lm_head_tp=False,
)
with pytest.raises(ValueError, match="replicated LM head"):
replicated(
input_ids=None,
hidden_states=torch.randn(2, 2),
lm_head=lm_head,
logits_metadata=LogitsMetadata(
forward_mode=ForwardMode.EXTEND,
gather_ids=torch.tensor([3]),
query_shard=plan,
),
)
def test_rocm_keeps_the_portable_sharded_argmax(monkeypatch):
from transformers import PretrainedConfig
platform = replace(logits_processor_module.current_platform(), vendor="amd")
monkeypatch.setattr(logits_processor_module, "current_platform", lambda: platform)
monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: False)
monkeypatch.setattr(logits_processor_module, "kernel_mm", lambda x, w: x @ w.T)
def forbidden(*args, **kwargs):
pytest.fail("portable argmax must keep logits sharded without CUDA state")
monkeypatch.setattr(
logits_processor_module, "try_create_dist_argmax_state", forbidden
)
monkeypatch.setattr(logits_processor_module, "all_gather_single", forbidden)
processor = LogitsProcessor(
PretrainedConfig(vocab_size=8),
tp_rank=0,
tp_size=2,
tp_group=(0, 1),
do_argmax=True,
attn_tp_size=1,
dp_lm_head_tp=False,
)
hidden = torch.arange(8, dtype=torch.float32).reshape(4, 2)
head = torch.nn.Linear(2, 4, bias=False).requires_grad_(False)
head.num_embeddings_per_partition = 4
processor.prepare_communication(head)
actual = processor._get_logits(
hidden,
head,
LogitsMetadata(forward_mode=ForwardMode.DECODE, query_shard=None),
require_full_vocab=False,
)
torch.testing.assert_close(actual, hidden @ head.weight.T, rtol=0, atol=0)
@pytest.mark.parametrize("rows", [1, 512, 513])
@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float32])
def test_dp_head_vocab_gather_bounded_workspace(monkeypatch, rows, dtype):
from tokenspeed.runtime.utils.env import global_server_args_dict
monkeypatch.setitem(global_server_args_dict, "max_num_seqs", 128)
monkeypatch.setitem(global_server_args_dict, "speculative_algorithm", "MTP")
monkeypatch.setitem(global_server_args_dict, "speculative_num_draft_tokens", 4)
proc = LogitsProcessor(
config=SimpleNamespace(model_type="test", vocab_size=32),
tp_rank=0,
tp_size=8,
tp_group=tuple(range(8)),
attn_tp_size=2,
dp_lm_head_tp=True,
skip_all_gather=True,
)
# CPU tests replace only the GPU collectives; the processor owns sizing,
# dispatch, and the NCCL output's shard-to-vocabulary layout conversion.
words_per_logit = torch.finfo(dtype).bits // 16
state = SimpleNamespace(
max_token_num=proc._logits_ag_max_tokens, hidden_dim=32 * words_per_logit
)
assert state.max_token_num == 512
proc._all_gather_state = state
x = torch.arange(rows * 4, dtype=torch.float32).reshape(rows, 4).to(dtype)
expected = torch.cat([x + rank for rank in range(8)], dim=1)
def multicast(state, tensor, **kwargs):
assert tensor.shape[0] <= state.max_token_num
values = tensor.view(dtype)
return torch.cat([values + rank for rank in range(8)], dim=1).view(
torch.bfloat16
)
def nccl(output, tensor, group):
output.copy_(torch.cat([tensor + rank for rank in range(8)], dim=0))
monkeypatch.setattr(logits_processor_module, "all_gather_inner", multicast)
monkeypatch.setattr(logits_processor_module, "all_gather_single", nccl)
actual = proc._gather_vocab_logits(x, None, require_full_vocab=False)
torch.testing.assert_close(actual, expected)
@pytest.mark.parametrize("local_dp_rows", [None, slice(1, 3), slice(2, 2)])
def test_finish_logits_preserves_dp_rows(monkeypatch, local_dp_rows):
from transformers import PretrainedConfig
processor = LogitsProcessor(
PretrainedConfig(vocab_size=8),
tp_rank=0,
tp_size=2,
tp_group=(0, 1),
attn_tp_size=1,
dp_lm_head_tp=False,
)
head = ParallelLMHead(
8,
2,
params_dtype=torch.float32,
padding_size=1,
tp_rank=0,
tp_size=2,
tp_group=(0, 1),
)
logits = torch.arange(12, dtype=torch.float32).reshape(3, 4)
def collective(output, shard, group):
output.copy_(torch.cat((shard, shard + 100), dim=0))
monkeypatch.setattr(logits_processor_module, "all_gather_single", collective)
actual = processor._finish_logits(
logits,
head,
None,
None,
local_dp_rows=local_dp_rows,
require_full_vocab=True,
)
expected = torch.cat((logits, logits + 100), dim=1)
if local_dp_rows is not None:
expected = expected[local_dp_rows]
torch.testing.assert_close(actual, expected)
def test_sampled_vocab_fallback_finishes_all_rows(monkeypatch):
from transformers import PretrainedConfig
processor = LogitsProcessor(
PretrainedConfig(vocab_size=8),
tp_rank=0,
tp_size=2,
tp_group=(0, 1),
attn_tp_size=1,
dp_lm_head_tp=False,
)
head = ParallelLMHead(
8,
2,
params_dtype=torch.bfloat16,
padding_size=1,
tp_rank=0,
tp_size=2,
tp_group=(0, 1),
)
# A sampler that takes shards of any geometry; the processor asks it, not the kernels.
assert processor.keep_sampled_logits_vocab_sharded(
head, lambda dtype, columns, tp_size: True
)
def collective(output, shard, group):
output.copy_(torch.cat((shard, shard + 100), dim=0))
monkeypatch.setattr(logits_processor_module, "all_gather_single", collective)
logits = torch.arange(12, dtype=torch.float32).reshape(3, 4)
shard = processor.sampled_vocab_shard(logits, head)
actual = shard.gather_full(logits)
torch.testing.assert_close(actual, torch.cat((logits, logits + 100), dim=1))
@pytest.mark.parametrize("vocab", [8, 7, 5, 4])
def test_sampled_rows_stay_sharded_when_the_vocabulary_ends_in_the_last_shard(
vocab,
):
"""A head padded past the vocabulary keeps its sampled rows sharded while
the padding stays inside the last shard; the shard selects from its real
columns only, and the sampler is asked about the narrowest one."""
from transformers import PretrainedConfig
asked = []
def supports(dtype, columns, tp_size):
asked.append(columns)
return True
shards = []
for rank in (0, 1):
processor = LogitsProcessor(
PretrainedConfig(vocab_size=vocab),
tp_rank=rank,
tp_size=2,
tp_group=(0, 1),
attn_tp_size=1,
dp_lm_head_tp=False,
)
head = ParallelLMHead(
8,
2,
params_dtype=torch.bfloat16,
padding_size=1,
tp_rank=rank,
tp_size=2,
tp_group=(0, 1),
)
kept = processor.keep_sampled_logits_vocab_sharded(head, supports)
# The last shard would hold only padding.
assert kept == (vocab > 4)
if kept:
logits = torch.zeros(3, 4, dtype=torch.bfloat16)
shards.append(processor.sampled_vocab_shard(logits, head).columns)
if vocab > 4:
assert asked == [vocab - 4, vocab - 4]
assert shards == [4, vocab - 4]
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
@pytest.mark.parametrize("attn_tp,head_tp", [(2, 8), (2, 2), (4, 2), (1, 8)])
@pytest.mark.parametrize("rank", range(8))
@pytest.mark.parametrize(
"mode", ["greedy", "full", "empty", "padded", "limit", "softcap"]
)
def test_dp_head_argmax_and_local_head_input(monkeypatch, attn_tp, head_tp, rank, mode):
"""Real projections/argmax keys, with only the missing peers simulated."""
from transformers import PretrainedConfig
group = tuple(range(rank // head_tp * head_tp, (rank // head_tp + 1) * head_tp))
local_rank = group.index(rank)
vocab = 32 if mode != "padded" else 31
counts = [
0 if mode == "empty" else (2, 0, 3, 1)[r // attn_tp % 4] for r in range(8)
]
hidden = [
torch.arange(n * 4, device="cuda", dtype=torch.float32).reshape(n, 4) / 8
+ r // attn_tp
for r, n in enumerate(counts)
]
weights = (
torch.arange(128, device="cuda", dtype=torch.float32).reshape(32, 4) / 16 - 4
)
# Equal maxima in different vocabulary shards must select the lowest ID.
weights[0] = weights[-1]
if mode == "padded":
weights[-1] = 1000 # This padded token must never win.
processor = LogitsProcessor(
PretrainedConfig(
vocab_size=vocab, final_logit_softcapping=3.0 if mode == "softcap" else None
),
tp_rank=local_rank,
tp_size=head_tp,
tp_group=group,
attn_tp_size=attn_tp,
dp_lm_head_tp=True,
skip_all_gather=True,
do_argmax=True,
logit_scale=2.0,
)
head = ParallelLMHead(
vocab,
4,
params_dtype=torch.float32,
padding_size=32,
tp_rank=local_rank,
tp_size=head_tp,
tp_group=group,
)
head = head.to("cuda").requires_grad_(False)
width = 32 // head_tp
with torch.no_grad():
head.weight.copy_(weights[local_rank * width : (local_rank + 1) * width])
if mode == "full":
processor.require_full_vocab_logits()
if mode == "limit":
monkeypatch.setattr(processor, "_LOGITS_DIST_ARGMAX_MAX_TOKENS", 0)
processor.prepare_communication(head)
processor._all_gather_state = None # no multicast gather: the collective path
replicas = min(attn_tp, head_tp)
all_hidden = torch.cat([hidden[r] for r in group[::replicas]])
fast = mode in ("greedy", "empty") or (mode == "limit" and all_hidden.shape[0] == 0)
def reduce(tensor, ranks, op=torch.distributed.ReduceOp.SUM):
assert ranks == group
if tensor.dtype != torch.int64:
# Within one attention group no hidden-state collective is legal.
assert head_tp > attn_tp
expected = torch.zeros_like(all_hidden)
if local_rank % replicas == 0:
offset = sum(counts[r] for r in group[:local_rank:replicas])
expected[offset : offset + counts[rank]] = hidden[rank]
torch.testing.assert_close(tensor, expected)
return all_hidden.clone()
assert fast and op == torch.distributed.ReduceOp.MAX
keys = []
for i in range(head_tp):
peer_logits = (all_hidden @ weights[i * width : (i + 1) * width].T) * 2.0
out = torch.empty(all_hidden.shape[0], dtype=torch.int64, device="cuda")
logits_processor_module.vocab_parallel_argmax_keys(
peer_logits, vocab_offset=i * width, out=out
)
keys.append(out)
torch.testing.assert_close(tensor, keys[local_rank])
return torch.stack(keys).max(dim=0).values
def gather_rows(tensor, ranks, row_counts):
assert attn_tp == 1 and ranks == group
return all_hidden.clone()
comm_scale = 1.0 if mode == "softcap" else 2.0
def gather_vocab(output, tensor, ranks):
assert not fast and ranks == group
expected = all_hidden @ head.weight.T * comm_scale
torch.testing.assert_close(tensor, expected)
output.copy_(
torch.cat(
[all_hidden @ w.T * comm_scale for w in weights.split(width)], dim=0
)
)
def transpose(tensor, ranks, *, input_split_sizes):
assert not fast and attn_tp == 1 and ranks == group
return hidden[rank] @ weights.T * comm_scale
def gather_counts(tensor, ranks, dim):
assert head_tp > attn_tp and ranks == group
return tensor.new_tensor([counts[r] for r in group])
monkeypatch.setattr(logits_processor_module, "all_gather", gather_counts)
monkeypatch.setattr(logits_processor_module, "all_reduce", reduce)
monkeypatch.setattr(logits_processor_module, "token_all_gather", gather_rows)
monkeypatch.setattr(logits_processor_module, "all_gather_single", gather_vocab)
monkeypatch.setattr(logits_processor_module, "all_to_all_transpose", transpose)
metadata = LogitsMetadata(
forward_mode=ForwardMode.DECODE,
query_shard=None,
global_num_tokens=counts,
all_decode_or_idle=True,
logits_rows_selected=True,
)
result = processor(None, hidden[rank], head, metadata)
expected = (hidden[rank] @ weights[:vocab].T) * 2.0
if mode == "softcap":
expected = 3.0 * torch.tanh(expected / 3.0)
if mode == "full":
assert result.next_token_ids is None
else:
torch.testing.assert_close(result.next_token_ids, expected.argmax(dim=-1))
if not fast:
torch.testing.assert_close(result.next_token_logits, expected)
else:
torch.testing.assert_close(
result.next_token_logits, hidden[rank] @ head.weight.T * 2.0
)
@pytest.mark.parametrize("reduced", [True, False])
def test_packed_key_argmax_reduces_through_a_prepared_word_max(monkeypatch, reduced):
"""The packed keys take the group's word MAX where the backend prepared
one, and the all-reduce MAX otherwise."""
keys = torch.tensor([7, 3], dtype=torch.int64)
def fake_keys(logits, *, vocab_offset, out):
assert vocab_offset == 8
return out.copy_(keys)
def fake_word_max(words, group):
assert group == (0, 1)
if reduced:
words.add_(100) # the group's maximum, as another rank sent it
return reduced
def fake_all_reduce(tensor, group, op):
assert not reduced, "a prepared word MAX replaces the all-reduce"
assert group == (0, 1) and op == torch.distributed.ReduceOp.MAX
return tensor + 200
monkeypatch.setattr(
logits_processor_module, "vocab_parallel_argmax_keys", fake_keys
)
monkeypatch.setattr(
logits_processor_module,
"argmax_key_index",
lambda keys, *, out: out.copy_(keys),
)
monkeypatch.setattr(
logits_processor_module,
"get_global_backend",
lambda: SimpleNamespace(try_word_max=fake_word_max),
)
monkeypatch.setattr(logits_processor_module, "all_reduce", fake_all_reduce)
ids = VocabParallelArgmax((0, 1), 8)(torch.zeros((2, 4)))
assert ids.tolist() == ([107, 103] if reduced else [207, 203])