[Perf][DSv4.1] Trim the last KV-source layer in decoder replay (#59894)
Signed-off-by: Canlin <canlinguosdu@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Juntian Liu <Juntianl777@gmail.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
Juntian Liu
parent
8cbd5d0300
commit
ad73a4740d
@@ -67,10 +67,8 @@ def _states(num_tokens: int):
|
||||
)
|
||||
|
||||
|
||||
def test_run_gathers_states_and_realigns_shared_indexer_buffers():
|
||||
topk = torch.arange(NUM_TOKENS * 4, device=DEVICE).view(NUM_TOKENS, 4).int()
|
||||
candidates = torch.arange(NUM_TOKENS * 3, device=DEVICE).view(NUM_TOKENS, 3).int()
|
||||
topk_before, candidates_before = topk.clone(), candidates.clone()
|
||||
def test_run_gathers_states():
|
||||
"""Every row's KV is written first; the layers then run on the replay rows."""
|
||||
seen = {}
|
||||
|
||||
def run_layers(hidden_states, positions, input_ids, pre_mix, post, res, residual):
|
||||
@@ -80,7 +78,8 @@ def test_run_gathers_states_and_realigns_shared_indexer_buffers():
|
||||
seen["is_padding"] = replay_context.is_padding
|
||||
return residual, pre_mix
|
||||
|
||||
layers = DecoderReplayLayers(WINDOW, run_layers, [topk, candidates], set())
|
||||
write_batch_kv = MagicMock()
|
||||
layers = DecoderReplayLayers(WINDOW, run_layers, write_batch_kv, set(), "swa")
|
||||
states = _states(NUM_TOKENS)
|
||||
hidden, residual = states[0], states[-1]
|
||||
full, sub = object(), object()
|
||||
@@ -90,11 +89,10 @@ def test_run_gathers_states_and_realigns_shared_indexer_buffers():
|
||||
outputs = layers(*states)
|
||||
assert get_forward_context() is context
|
||||
|
||||
write_batch_kv.assert_called_once_with(*states)
|
||||
rows = torch.tensor(REPLAY_ROWS, device=DEVICE)
|
||||
assert torch.equal(seen["hidden_states"], hidden[rows])
|
||||
assert seen["attn_metadata"] is sub and seen["is_padding"] is None
|
||||
assert torch.equal(topk[: len(REPLAY_ROWS)], topk_before[rows])
|
||||
assert torch.equal(candidates[: len(REPLAY_ROWS)], candidates_before[rows])
|
||||
assert len(outputs) == 2 and outputs[0].shape == residual.shape
|
||||
assert torch.equal(outputs[0][rows], residual[rows])
|
||||
assert outputs[0][1:173].abs().sum() == 0
|
||||
@@ -107,12 +105,14 @@ def test_no_replay_batch_runs_the_whole_batch():
|
||||
seen["attn_metadata"] = get_forward_context().attn_metadata
|
||||
return (hidden_states,)
|
||||
|
||||
layers = DecoderReplayLayers(WINDOW, run_layers, [], set())
|
||||
write_batch_kv = MagicMock()
|
||||
layers = DecoderReplayLayers(WINDOW, run_layers, write_batch_kv, set(), "swa")
|
||||
states = _states(NUM_TOKENS)
|
||||
full = object()
|
||||
with override_forward_context(_context(full)):
|
||||
(output,) = layers(*states)
|
||||
assert output is states[0] and seen["attn_metadata"] is full
|
||||
write_batch_kv.assert_not_called()
|
||||
|
||||
|
||||
def _graph_context(num_tokens):
|
||||
@@ -125,6 +125,25 @@ def _graph_context(num_tokens):
|
||||
)
|
||||
|
||||
|
||||
def test_piecewise_graphs_break_out_by_size():
|
||||
"""A PIECEWISE graph's KV write and break are fixed at capture, when no replay
|
||||
batch is set, so both follow the graph's size rather than the replay batch."""
|
||||
write_batch_kv = MagicMock()
|
||||
layers = DecoderReplayLayers(
|
||||
WINDOW, lambda *states: ("whole",), write_batch_kv, set(), "swa"
|
||||
)
|
||||
layers._run_in_graph_break = lambda *states: ("break",) # type: ignore[method-assign]
|
||||
states = _states(NUM_TOKENS)
|
||||
with override_forward_context(_graph_context(1024)):
|
||||
assert layers(*states) == ("whole",) # no threshold: no break
|
||||
layers.trim_threshold = 768
|
||||
assert layers(*states) == ("break",)
|
||||
_set_replay_batch(layers, REPLAY_ROWS, object())
|
||||
with override_forward_context(_graph_context(576)):
|
||||
assert not layers.uses_replay_batch() # a replay batch alone does not break out
|
||||
write_batch_kv.assert_called_once_with(*states)
|
||||
|
||||
|
||||
def test_replay_graph_matches_eager(monkeypatch):
|
||||
"""The replay graph of the next captured size pads and runs the rows."""
|
||||
monkeypatch.setattr(cudagraph_utils, "get_pp_group", MagicMock)
|
||||
@@ -142,7 +161,7 @@ def test_replay_graph_matches_eager(monkeypatch):
|
||||
def run_layers(hidden, positions, ids, pre, post, mix, residual):
|
||||
return residual + hidden[:, None] + positions[:, None, None], pre + ids[:, None]
|
||||
|
||||
layers = DecoderReplayLayers(4, run_layers, [], set())
|
||||
layers = DecoderReplayLayers(4, run_layers, MagicMock(), set(), "swa")
|
||||
manager = DecoderReplayCudaGraphManager(cfg, DEVICE, layers)
|
||||
|
||||
def prepare(desc):
|
||||
|
||||
@@ -11,6 +11,12 @@ import pytest
|
||||
import torch
|
||||
|
||||
from vllm.config import CUDAGraphMode
|
||||
from vllm.forward_context import (
|
||||
BatchDescriptor,
|
||||
ForwardContext,
|
||||
override_forward_context,
|
||||
)
|
||||
from vllm.models.deepseek_v41.decoder_replay_layers import DecoderReplayLayers
|
||||
from vllm.models.deepseek_v41.nvidia.model_state import DeepseekV41ModelState
|
||||
from vllm.v1.worker.gpu.cudagraph_utils import BatchExecutionDescriptor
|
||||
from vllm.v1.worker.gpu.input_batch import InputBatch, InputBuffers
|
||||
@@ -59,7 +65,7 @@ def state(monkeypatch):
|
||||
cfg.parallel_config.data_parallel_size = 1
|
||||
cfg.compilation_config.fast_moe_cold_start = False
|
||||
cfg.compilation_config.cudagraph_mode = CUDAGraphMode.NONE
|
||||
layers = SimpleNamespace(window=WINDOW, replay_batch=None, metadata_prefixes=set())
|
||||
layers = DecoderReplayLayers(WINDOW, MagicMock(), MagicMock(), set(), "swa_first")
|
||||
model = SimpleNamespace(token_lookback_depth=0, decoder_replay_layers=layers)
|
||||
builds: list = []
|
||||
|
||||
@@ -72,7 +78,7 @@ def state(monkeypatch):
|
||||
attn_metadata=object(),
|
||||
)
|
||||
builds.append(build)
|
||||
return {"swa": build.attn_metadata}
|
||||
return {"swa": build.attn_metadata, "swa_first": build.attn_metadata}
|
||||
|
||||
monkeypatch.setattr(DefaultModelState, "prepare_attn", prepare_attn)
|
||||
state = DeepseekV41ModelState(cfg, model, None, DEVICE)
|
||||
@@ -120,7 +126,8 @@ def _slot_mappings(num_tokens: int) -> torch.Tensor:
|
||||
|
||||
|
||||
def _prepare(state, batch, cg_mode):
|
||||
"""Runs prepare_attn; returns the replay batch and the replay build's inputs."""
|
||||
"""Runs prepare_attn; returns the replay batch and the replay build's inputs.
|
||||
The first replay layer's sliding-window build follows the replay build."""
|
||||
state.prepare_attn(
|
||||
batch,
|
||||
cg_mode,
|
||||
@@ -130,7 +137,7 @@ def _prepare(state, batch, cg_mode):
|
||||
GROUPS,
|
||||
)
|
||||
replay = state.decoder_replay_layers.replay_batch
|
||||
return (None, None) if replay is None else (replay, state.builds[-1])
|
||||
return (None, None) if replay is None else (replay, state.builds[-2])
|
||||
|
||||
|
||||
def test_replay_batch_keeps_each_request_window(state):
|
||||
@@ -151,8 +158,16 @@ def test_replay_batch_keeps_each_request_window(state):
|
||||
assert build.replay_start.tolist() == [0, 300 - WINDOW, 50]
|
||||
assert torch.equal(sub.positions, batch.positions[rows])
|
||||
assert torch.equal(build.slot_mappings, _slot_mappings(401)[:, rows])
|
||||
# The first replay layer keeps the encoder-side window starts: it wrote
|
||||
# every row's window KV.
|
||||
first = state.builds[-1]
|
||||
assert first.batch is sub and first.cg_mode == CUDAGraphMode.NONE
|
||||
assert first.replay_start.tolist() == [0, 0, 50]
|
||||
context = replay.forward_context
|
||||
assert context.attn_metadata == {"swa": build.attn_metadata}
|
||||
assert context.attn_metadata == {
|
||||
"swa": build.attn_metadata,
|
||||
"swa_first": first.attn_metadata,
|
||||
}
|
||||
assert torch.equal(context.slot_mapping["mla"], _slot_mappings(401)[1, rows])
|
||||
assert context.dp_metadata is None and context.is_padding is None
|
||||
|
||||
@@ -190,7 +205,8 @@ def test_replay_batch_keeps_adaptive_verification_query_bound(state):
|
||||
|
||||
def test_graph_steps_trim_only_piecewise_at_threshold(state):
|
||||
"""A CUDA graph keeps the layers on its whole batch, unless it is a PIECEWISE
|
||||
one at the trim threshold or above; an eager step trims a batch to its rows."""
|
||||
one at the trim threshold or above, as its capture decided; an eager step
|
||||
trims a batch to its rows."""
|
||||
batch = _input_batch(QUERY_LENS, SEQ_LENS, PREFILLING, num_tokens_after_padding=512)
|
||||
for cg_mode in (CUDAGraphMode.PIECEWISE, CUDAGraphMode.FULL):
|
||||
assert _prepare(state, batch, cg_mode) == (None, None)
|
||||
@@ -199,8 +215,21 @@ def test_graph_steps_trim_only_piecewise_at_threshold(state):
|
||||
assert replay.rows.tolist() == REPLAY_ROWS
|
||||
assert build.cg_mode == CUDAGraphMode.NONE
|
||||
assert build.batch.num_tokens_after_padding == len(REPLAY_ROWS)
|
||||
state._trim_threshold = 256
|
||||
replay, _ = _prepare(state, batch, CUDAGraphMode.PIECEWISE)
|
||||
layers = state.decoder_replay_layers
|
||||
graph = ForwardContext(
|
||||
no_compile_layers={},
|
||||
attn_metadata={},
|
||||
slot_mapping={},
|
||||
cudagraph_runtime_mode=CUDAGraphMode.PIECEWISE,
|
||||
batch_descriptor=BatchDescriptor(num_tokens=512),
|
||||
)
|
||||
for threshold in (513, 512):
|
||||
layers.trim_threshold = threshold
|
||||
replay, _ = _prepare(state, batch, CUDAGraphMode.PIECEWISE)
|
||||
with override_forward_context(graph): # the capture's decision
|
||||
assert (
|
||||
layers.uses_replay_batch() == (replay is not None) == (threshold == 512)
|
||||
)
|
||||
assert replay is not None and replay.rows.tolist() == REPLAY_ROWS
|
||||
assert _prepare(state, batch, CUDAGraphMode.FULL) == (None, None)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user