Skip to content
Open
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
8 changes: 8 additions & 0 deletions docs/source/features/disagg-serving.md
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,14 @@ generation_servers:
A fleet worker fails fast if its coordinator is unreachable: on startup it probes the coordinator's `/cluster_info` with bounded retry (up to `--server_start_timeout` seconds) and exits with an error rather than coming up and returning `Cluster is not ready` for every request.
```

### Context server role

Launch context servers with `trtllm-serve serve ... --server_role context`; the
disaggregated MPI launch sets the role from each server's type. Python API
deployments set `TRTLLM_DISAGG_ROLE=context` before creating the model. A
context server never runs a generation step, so with the role it captures no
generation CUDA graphs at startup; prefill CUDA graphs are captured as configured.

### DeepSeek-V4.1 DSpark context KV

For ordinary native KV transfer, enable the same DSpark configuration on both
Expand Down
12 changes: 11 additions & 1 deletion docs/source/llm-api/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -224,11 +224,21 @@ engine skip the warmup-only pass:
- The switch is ignored, with a warning, for LoRA CUDA graphs, FlashInfer MXFP8 decode GEMMs that
need autotuning, `TLLM_CUDA_GRAPH_GEMM_TUNING=1` on a single rank, encoder-decoder models, DWDP
and pipeline parallelism, and when not every rank sets it. The KV cache estimation executor
always uses both passes, so the KV cache size does not depend on the switch.
always uses both passes, so the KV cache size does not depend on the switch; its graphs are
only measured, so its capture pass captures each shape without an eager warmup forward.
- With the switch, the final model engine's `gen_cuda_graph_capture_seconds` includes each shape's
eager warmup forward and, after a fallback, the discarded pass; `gen_cuda_graph_warmup_seconds`
then covers only a fallback's warmup-only pass.

### Capturing Generation CUDA Graphs Without the Capture Pass's Warmup Forwards (Prototype)

Setting `TLLM_CUDA_GRAPH_SKIP_CAPTURE_WARMUP=1` keeps both passes in the final model engine, but its
capture pass captures each shape without an eager warmup forward, as the KV cache estimation
executor's capture pass always does. The warmup-only pass has already run every shape, so shared
buffers have reached their largest size and first-use work such as kernel planning and tactic
tuning is done before the first capture. When `TLLM_CUDA_GRAPH_SKIP_WARMUP_PASS=1` captures in one
pass, this switch has no effect: each shape's eager warmup forward is then the only one it runs.

## Unified Cache for Compiled Artifacts

Set `TRTLLM_CACHE_DIR` before importing TensorRT-LLM to place its compiled
Expand Down
8 changes: 7 additions & 1 deletion tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,10 @@ class CUDAGraphRunner:
multiple graphs, keyed by batch shape and execution-path specializations.
"""
WARMUP_STEPS = 1
# Whether capture() captures without its eager warmup forwards outside a
# warmup-only pass: set by a caller that has just run every shape eagerly
# and only measures the graphs it captures.
skip_capture_warmup: bool = False
# CUDAGraphRunnerConfig.short_long_seq_len_threshold, when the config set one.
_configured_seq_len_threshold: Optional[int] = None
# The variants the decode graphs are keyed by besides their shape; set by
Expand Down Expand Up @@ -1332,7 +1336,9 @@ def run_warmup():
saved_kv_lens_cuda)
return result

for _ in range(self.WARMUP_STEPS):
warmup_steps = (0 if self.skip_capture_warmup
and not self.is_warmup_only else self.WARMUP_STEPS)
for _ in range(warmup_steps):
if self.is_warmup_only:
output = run_warmup()
else:
Expand Down
42 changes: 31 additions & 11 deletions tensorrt_llm/_torch/pyexecutor/engine/runners/decoder/graphs.py
Original file line number Diff line number Diff line change
Expand Up @@ -406,15 +406,22 @@ def preallocate_padding_dummies(self, resource_manager: ResourceManager) -> None
self.cuda_graph_runner.preallocate_padding_dummies(resource_manager)

def warmup_and_capture(
self, resource_manager: ResourceManager, *, allow_single_pass: bool = False
self,
resource_manager: ResourceManager,
*,
allow_single_pass: bool = False,
warm_up_before_capture: bool = True,
) -> None:
"""Warm up every graph shape, then capture them all.

Attention kernels can switch implementations at smaller batch sizes and
require a larger workspace, so the first pass grows the workspace to
its maximum size. The second pass runs the final per-shape warmup and
captures without resizing the workspace. ``allow_single_pass`` lets
``TLLM_CUDA_GRAPH_SKIP_WARMUP_PASS=1`` try one pass first.
``TLLM_CUDA_GRAPH_SKIP_WARMUP_PASS=1`` try one pass first. Without
``warm_up_before_capture`` the second pass captures each shape without
its eager warmup forward, which the first pass has just run: for graphs
that are only measured, never replayed by serving.
"""
with self.cuda_graph_runner.allow_capture():
if not (allow_single_pass and self._capture_in_one_pass(resource_manager)):
Expand All @@ -424,11 +431,15 @@ def warmup_and_capture(
finally:
self.cuda_graph_runner.is_warmup_only = False
self.reset_padding_dummies()
# Captured graphs keep the MoE communication timeouts that were
# current at capture, and serving replays them, so capture with the
# serving timeouts. The warmup-only pass above keeps the warmup ones.
with moe_comm_serving_timeouts():
self.run_cuda_graph_warmup(resource_manager)
self.cuda_graph_runner.skip_capture_warmup = not warm_up_before_capture
try:
# Captured graphs keep the MoE communication timeouts that were
# current at capture, and serving replays them, so capture with the
# serving timeouts. The warmup-only pass above keeps the warmup ones.
with moe_comm_serving_timeouts():
self.run_cuda_graph_warmup(resource_manager)
finally:
self.cuda_graph_runner.skip_capture_warmup = False
self._warm_inforward_split(resource_manager)

def _plans_inforward_splits(self, resource_manager: ResourceManager) -> bool:
Expand Down Expand Up @@ -556,6 +567,18 @@ def _single_pass_blocker(self) -> str | None:
return "the ranks cannot agree on it through this engine's communicator"
return None

def _serves_context_requests_only(self, kv_cache_manager: object) -> bool:
"""Whether this worker never runs a generation step: its cache was pruned for context
requests (``context_swa_layer_limit``), or it is a disaggregated context server.

The serving launcher publishes a disaggregated worker's role in ``TRTLLM_DISAGG_ROLE``
(``trtllm-serve --server_role``, and the disaggregated MPI launch per server type), and
every rank of the worker inherits it.
"""
if getattr(kv_cache_manager, "context_swa_layer_limit", None) is not None:
return True
return os.environ.get("TRTLLM_DISAGG_ROLE") == "context" and self._config.is_disagg

def _flashinfer_mxfp8_autotune_methods(self) -> list["MXFP8LinearMethod"]:
"""The FlashInfer MXFP8 decode GEMMs whose tactics the warmup-only pass tunes."""
from tensorrt_llm._torch.modules.linear import MXFP8LinearMethod
Expand Down Expand Up @@ -961,11 +984,8 @@ def run_cuda_graph_warmup(
kv_cache_manager = resource_manager.get_resource_manager(
ResourceManagerType.KV_CACHE_MANAGER
)
context_only = (
getattr(kv_cache_manager, "context_swa_layer_limit", None) is not None
)
# Context-only workers only use the separate prefill capture.
if not context_only:
if not self._serves_context_requests_only(kv_cache_manager):
from tensorrt_llm._torch.modules.linear import (
cuda_graph_gemm_tuning,
flashinfer_mxfp8_autotune,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,12 @@
from .metadata import DecoderMetadata


def _skip_capture_warmup_requested() -> bool:
"""Whether TLLM_CUDA_GRAPH_SKIP_CAPTURE_WARMUP=1 asks the final executor's capture pass to skip
each shape's eager warmup forward, as the KV-cache estimation executor's capture pass does."""
return os.environ.get("TLLM_CUDA_GRAPH_SKIP_CAPTURE_WARMUP", "0") == "1"


class AutotunerWarmupMode(Enum):
"""Batches the autotuner warmup tunes on."""

Expand Down Expand Up @@ -616,10 +622,15 @@ def _warmup_scheduled(
with self._warmup_timer.phase("lowm_mma_row_buckets"):
self._prewarm_lowm_mma_row_buckets()
with self._warmup_timer.phase("cuda_graph_capture"):
estimating = getattr(kv_cache_manager, "is_estimating_kv_cache", False)
# KV-cache estimation always uses both passes, so the KV-cache size ignores the switch.
# Its graphs are only measured, so its capture pass skips each shape's eager warmup
# forward: the warmup-only pass has just run it. TLLM_CUDA_GRAPH_SKIP_CAPTURE_WARMUP=1
# skips it in the final executor's capture pass too.
self._graphs.warmup_and_capture(
resource_manager,
allow_single_pass=not getattr(kv_cache_manager, "is_estimating_kv_cache", False),
allow_single_pass=not estimating,
warm_up_before_capture=not (estimating or _skip_capture_warmup_requested()),
)
log_mem_snapshot("warmup/after_cuda_graph_capture")
with self._warmup_timer.phase("prims_ts_dense_mla_prewarm"):
Expand Down
5 changes: 5 additions & 0 deletions tests/integration/defs/perf/test_perf_sanity.py
Original file line number Diff line number Diff line change
Expand Up @@ -2656,6 +2656,11 @@ def to_cmd(
"--config",
config_path,
]
if disagg_serving_type == "CTX":
# The context server's role, as a production launch passes it: the workers
# see TRTLLM_DISAGG_ROLE=context and skip what only a generation step uses,
# such as the generation CUDA graphs.
cmd += ["--server_role", "CONTEXT"]
return cmd

def to_env(self) -> Dict[str, str]:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,41 @@ def test_context_only_skips_decode_graphs_and_keeps_prefill_capture(warmup_only,
assert requests.create_cuda_graph_warmup_request(resources, 8, 0) is None


@pytest.mark.parametrize(
"is_disagg,role,skips_decode_graphs",
[
(True, "context", True),
(True, "generation", False),
(True, None, False),
(False, "context", False),
],
ids=["disagg_context", "disagg_generation", "disagg_without_role", "aggregated_context_role"],
)
def test_disagg_context_server_skips_decode_graphs(
monkeypatch, is_disagg, role, skips_decode_graphs
):
"""A disaggregated context server never runs a generation step: with its role it captures no
decode graphs on a cache that could serve them, and keeps the prefill capture."""
requests, _, resources = _warmup_fixture(False)
requests._config.prefill_cuda_graph_backend = PrefillCudaGraphBackend.PIECEWISE
requests._config.is_disagg = is_disagg
if role is None:
monkeypatch.delenv("TRTLLM_DISAGG_ROLE", raising=False)
else:
monkeypatch.setenv("TRTLLM_DISAGG_ROLE", role)
graphs = _cuda_graphs(requests, warmup_only=False)
with (
patch.object(graphs, "_capture_prefill_cuda_graphs") as prefill,
patch.object(graphs, "_capture_generation_cuda_graphs") as generation,
patch.object(graphs, "_capture_additional_cuda_graphs") as additional,
patch.object(graphs, "_flashinfer_mxfp8_autotune_methods", return_value=[]),
):
graphs.run_cuda_graph_warmup(resources)
assert generation.called is not skips_decode_graphs
assert additional.called is not skips_decode_graphs
prefill.assert_called_once_with(resources)


@pytest.mark.parametrize("context_only", [False, True])
@pytest.mark.parametrize(
"tokens,batch_size,expected",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,33 @@ def forward_fn(inputs):

torch.testing.assert_close(logits_cuda_graph, logits_eager)

@pytest.mark.parametrize("skip_capture_warmup", [False, True])
def test_capture_runs_its_warmup_forwards_unless_skipped(self, skip_capture_warmup):
"""capture() runs WARMUP_STEPS eager forwards before the captured one, and none with
skip_capture_warmup; the graph replays the same either way."""
batch_size = 1
runner = create_mock_cuda_graph_runner(batch_size, use_mrope=False)
runner.skip_capture_warmup = skip_capture_warmup
key = KeyType(batch_size=batch_size, draft_len=0)
num_tokens = runner._get_num_tokens_for_key(key)
attn_metadata = object()
capturing = []

def forward_fn(inputs):
capturing.append(torch.cuda.is_current_stream_capturing())
return inputs["input_ids"].clone() + inputs["position_ids"][...,].clone()

runner.capture(
key, forward_fn, self._make_inputs(attn_metadata, num_tokens, batch_size, value=5)
)
assert capturing == [False] * (0 if skip_capture_warmup else runner.WARMUP_STEPS) + [True]

logits_cuda_graph = runner.replay(
key, self._make_inputs(attn_metadata, num_tokens, batch_size, value=2)
)
logits_eager = forward_fn(self._make_inputs(attn_metadata, num_tokens, batch_size, value=2))
torch.testing.assert_close(logits_cuda_graph, logits_eager)


class TestEngineBuffersAsStaticInputs:
"""With static_input_ids / static_position_ids, the graphs' static inputs are views of the engine's own buffers:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TLLM_CUDA_GRAPH_SKIP_WARMUP_PASS=1 on a real model: same tokens, one capture pass, safe fallback."""
"""The decode CUDA graph capture switches on a real model: same tokens with fewer eager forwards.

TLLM_CUDA_GRAPH_SKIP_WARMUP_PASS=1 captures in one pass and falls back to two passes safely;
TLLM_CUDA_GRAPH_SKIP_CAPTURE_WARMUP=1 keeps both passes and drops the capture pass's eager forwards.
"""

import datetime
from collections.abc import Callable
Expand Down Expand Up @@ -69,9 +73,12 @@ class _Run:
capture_timeouts: list[set[tuple[bool, bool]]]


def _generate(skip_warmup_pass: bool, move_workspace: bool = False) -> _Run:
def _generate(
skip_warmup_pass: bool, move_workspace: bool = False, skip_capture_warmup: bool = False
) -> _Run:
"""Generate greedily; ``move_workspace`` regrows the shared workspace before the second
capture of the single pass, as a smaller shape needing more workspace would."""
capture of the single pass, as a smaller shape needing more workspace would;
``skip_capture_warmup`` sets TLLM_CUDA_GRAPH_SKIP_CAPTURE_WARMUP=1."""
passes: list[list[bool]] = []
capture_timeouts: list[set[tuple[bool, bool]]] = []
replayed: list[KeyType] = []
Expand Down Expand Up @@ -150,6 +157,10 @@ def fetch_prompts_together(
patch.setenv("TLLM_CUDA_GRAPH_SKIP_WARMUP_PASS", "1")
else:
patch.delenv("TLLM_CUDA_GRAPH_SKIP_WARMUP_PASS", raising=False)
if skip_capture_warmup:
patch.setenv("TLLM_CUDA_GRAPH_SKIP_CAPTURE_WARMUP", "1")
else:
patch.delenv("TLLM_CUDA_GRAPH_SKIP_CAPTURE_WARMUP", raising=False)
patch.setattr(moe_comm_timeout_guard, "_DEFAULT_GUARD", guard)
patch.setattr(DecoderCudaGraphs, "warmup_and_capture", record_executor)
patch.setattr(DecoderCudaGraphs, "run_cuda_graph_warmup", record_pass)
Expand Down Expand Up @@ -216,6 +227,12 @@ def two_pass_run() -> _Run:
run = _generate(skip_warmup_pass=False)
# The KV-cache estimation executor and the final one.
assert run.passes == [[True, False], [True, False]]
# The final executor's capture pass runs an eager forward, under the serving timeouts, before
# each capture; the KV-cache estimation executor's, whose graphs are only measured, does not.
assert run.capture_timeouts == [
{(False, True), (True, False)},
{(False, True), (False, False), (True, False)},
]
return run


Expand All @@ -232,6 +249,23 @@ def test_single_pass_capture_matches_two_passes(two_pass_run: _Run) -> None:
assert run.capture_timeouts[-1] == {(False, True), (True, False)}


@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA is required")
def test_capture_pass_without_warmup_forwards_matches_two_passes(two_pass_run: _Run) -> None:
"""The final executor keeps both passes but captures without the capture pass's eager
forwards, and generates the same tokens from the same graphs."""
run = _generate(skip_warmup_pass=False, skip_capture_warmup=True)
assert run.passes == [[True, False], [True, False]]
assert {key.batch_size for key in run.keys} == {1, 2, 4, 8}
assert run.keys == two_pass_run.keys
assert run.replayed == run.keys
Comment thread
chenfeiz0326 marked this conversation as resolved.
Resolved
_assert_same_generation(run, two_pass_run)
# Like the KV-cache estimation executor's, the final capture pass runs no eager forward.
assert run.capture_timeouts == [
{(False, True), (True, False)},
{(False, True), (True, False)},
]


@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA is required")
def test_single_pass_capture_falls_back_when_a_buffer_moves(two_pass_run: _Run) -> None:
"""A metadata tensor moved after an earlier capture sends the final executor back to two passes."""
Expand Down