[Model] Decoder-side SWA bounded replay for DeepSeek-V4.1 (#58132)
Signed-off-by: Yifan Qiao <yifanqiao@inferact.ai> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5.1
parent
9af952c555
commit
4b2e1cfa7b
@@ -83,6 +83,7 @@ from vllm.models.deepseek_v4.nvidia.model import (
|
||||
prepare_mega_gate_routing_metadata,
|
||||
)
|
||||
from vllm.models.deepseek_v41.attention import DeepseekV4Attention
|
||||
from vllm.models.deepseek_v41.decoder_replay_layers import DecoderReplayLayers
|
||||
from vllm.models.deepseek_v41.nvidia.flash_mla_mega_attn import (
|
||||
DeepseekV4MegaAttnAttention,
|
||||
)
|
||||
@@ -741,6 +742,35 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
|
||||
if successor.engram is None:
|
||||
layer.ffn.defer_finalize()
|
||||
|
||||
# Decoder-side SWA bounded replay: in eager prefill steps the layers past
|
||||
# the last KV source run on each request's trailing window only
|
||||
# (decoder_replay_layers.py).
|
||||
self.decoder_replay_layers: DecoderReplayLayers | None = None
|
||||
self.decoder_replay_start = self.end_layer
|
||||
cut = max(config.kv_source_layer_ids)
|
||||
if (
|
||||
cut < self.end_layer - 1
|
||||
and self._decoder_replay_supported(vllm_config, cut)
|
||||
and self.layers[cut].attn.swa_cache_layer.bounded_replay
|
||||
):
|
||||
self.decoder_replay_start = cut + 1
|
||||
self.decoder_replay_layers = DecoderReplayLayers(
|
||||
config.sliding_window,
|
||||
self._run_replay_layers,
|
||||
[
|
||||
buf
|
||||
for buf in (self.topk_indices_buffer, self.candidate_block_buffer)
|
||||
if buf is not None
|
||||
],
|
||||
)
|
||||
logger.info_once(
|
||||
"Decoder SWA bounded replay: in eager prefill steps, layers "
|
||||
"%d-%d run on each request's last %d tokens only.",
|
||||
cut + 1,
|
||||
self.end_layer - 1,
|
||||
config.sliding_window,
|
||||
)
|
||||
|
||||
# The n-gram hash needs a slot-keyed rolling store of compressed ids
|
||||
# (chunked prefill / decode lookback); key it off the first local
|
||||
# layer's sliding-window KV cache. Only PP ranks owning an engram
|
||||
@@ -904,29 +934,28 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
|
||||
hidden_states = sp_shard(hidden_states)
|
||||
input_ids = sp_shard(input_ids)
|
||||
|
||||
mega_gate_metadata = None
|
||||
if self.use_mega_moe:
|
||||
mega_gate_metadata = prepare_mega_gate_routing_metadata(
|
||||
input_ids,
|
||||
has_hash_routing=False,
|
||||
image_sentinel_base_id=IMAGE_SENTINEL_BASE_ID
|
||||
if getattr(self.config, "vision_n_layers", 0) > 0
|
||||
else None,
|
||||
)
|
||||
|
||||
residual, post_mix, res_mix = None, None, None
|
||||
pre_mix: torch.Tensor | None = None
|
||||
if not get_pp_group().is_first_rank:
|
||||
assert intermediate_tensors is not None
|
||||
pre_mix = intermediate_tensors["pre_mix"]
|
||||
# Every layer's post runs inside the next layer's fused pre, so aux
|
||||
# hidden states are read back from there instead of recomputed.
|
||||
aux_hidden_by_layer: dict[int, torch.Tensor] = {}
|
||||
for idx, layer in enumerate(
|
||||
islice(self.layers, self.start_layer, self.end_layer),
|
||||
start=self.start_layer,
|
||||
):
|
||||
hidden_states, residual, post_mix, res_mix, pre_mix, previous_aux = layer(
|
||||
hidden_states, residual, post_mix, res_mix, pre_mix = self._run_layers(
|
||||
range(self.start_layer, self.decoder_replay_start),
|
||||
hidden_states,
|
||||
positions,
|
||||
input_ids,
|
||||
pre_mix,
|
||||
post_mix,
|
||||
res_mix,
|
||||
residual,
|
||||
aux_hidden_by_layer,
|
||||
engram_hashes,
|
||||
engram_mask,
|
||||
)
|
||||
late_aux: list[torch.Tensor] = []
|
||||
if self.decoder_replay_layers is not None:
|
||||
hidden_states, pre_mix, *late_aux = self.decoder_replay_layers(
|
||||
hidden_states,
|
||||
positions,
|
||||
input_ids,
|
||||
@@ -934,36 +963,22 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
|
||||
post_mix,
|
||||
res_mix,
|
||||
residual,
|
||||
engram_hashes,
|
||||
engram_mask,
|
||||
capture_previous_aux=idx in self.aux_hidden_state_layers,
|
||||
mega_gate_metadata=mega_gate_metadata,
|
||||
)
|
||||
if previous_aux is not None:
|
||||
# idx is the one-based id of the layer whose post this is.
|
||||
if self.use_sequence_parallel:
|
||||
previous_aux = sp_all_gather(previous_aux)[:full_num_tokens]
|
||||
aux_hidden_by_layer[idx] = previous_aux
|
||||
# Without a successor boundary, the last layer finalized its own MoE.
|
||||
assert isinstance(hidden_states, torch.Tensor)
|
||||
if layer is not None:
|
||||
# The last layer has no successor to fold its post into.
|
||||
if self.fuse_mhc_all_reduce:
|
||||
hidden_states = tensor_model_parallel_all_reduce(hidden_states)
|
||||
hidden_states = mhc_post_tilelang(
|
||||
hidden_states, residual, post_mix, res_mix
|
||||
else:
|
||||
hidden_states = self._collapse(
|
||||
hidden_states,
|
||||
residual,
|
||||
post_mix,
|
||||
res_mix,
|
||||
aux_hidden_by_layer,
|
||||
full_num_tokens,
|
||||
)
|
||||
if self.end_layer in self.aux_hidden_state_layers:
|
||||
final_aux = hidden_states.mean(dim=1)
|
||||
if self.use_sequence_parallel:
|
||||
final_aux = sp_all_gather(final_aux)[:full_num_tokens]
|
||||
aux_hidden_by_layer[self.end_layer] = final_aux
|
||||
|
||||
aux_hidden_states = [
|
||||
aux_hidden_by_layer[layer_id]
|
||||
for layer_id in self.aux_hidden_state_layers
|
||||
if layer_id in aux_hidden_by_layer
|
||||
]
|
||||
] + late_aux
|
||||
|
||||
if not get_pp_group().is_last_rank:
|
||||
return IntermediateTensors(
|
||||
@@ -992,6 +1007,169 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
|
||||
return hidden_states, aux_hidden_states
|
||||
return hidden_states
|
||||
|
||||
def _mega_gate_metadata(
|
||||
self, input_ids: torch.Tensor | None
|
||||
) -> MegaGateRoutingMetadata | None:
|
||||
if not self.use_mega_moe:
|
||||
return None
|
||||
assert input_ids is not None
|
||||
return prepare_mega_gate_routing_metadata(
|
||||
input_ids,
|
||||
has_hash_routing=False,
|
||||
image_sentinel_base_id=IMAGE_SENTINEL_BASE_ID
|
||||
if getattr(self.config, "vision_n_layers", 0) > 0
|
||||
else None,
|
||||
)
|
||||
|
||||
def _run_layers(
|
||||
self,
|
||||
layer_ids: range,
|
||||
hidden_states: torch.Tensor | MoEOutput,
|
||||
positions: torch.Tensor,
|
||||
input_ids: torch.Tensor | None,
|
||||
pre_mix: torch.Tensor | None,
|
||||
post_mix: torch.Tensor | None,
|
||||
res_mix: torch.Tensor | None,
|
||||
residual: torch.Tensor | None,
|
||||
aux_hidden_by_layer: dict[int, torch.Tensor],
|
||||
engram_hashes: torch.Tensor | None = None,
|
||||
engram_mask: torch.Tensor | None = None,
|
||||
) -> tuple[
|
||||
torch.Tensor | MoEOutput, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor
|
||||
]:
|
||||
# Every layer's post runs inside the next layer's fused pre, so aux
|
||||
# hidden states are read back from there instead of recomputed.
|
||||
full_num_tokens = positions.shape[0]
|
||||
mega_gate_metadata = self._mega_gate_metadata(input_ids)
|
||||
for idx in layer_ids:
|
||||
hidden_states, residual, post_mix, res_mix, pre_mix, previous_aux = (
|
||||
self.layers[idx](
|
||||
hidden_states,
|
||||
positions,
|
||||
input_ids,
|
||||
pre_mix,
|
||||
post_mix,
|
||||
res_mix,
|
||||
residual,
|
||||
engram_hashes,
|
||||
engram_mask,
|
||||
capture_previous_aux=idx in self.aux_hidden_state_layers,
|
||||
mega_gate_metadata=mega_gate_metadata,
|
||||
)
|
||||
)
|
||||
if previous_aux is not None:
|
||||
# idx is the one-based id of the layer whose post this is.
|
||||
if self.use_sequence_parallel:
|
||||
previous_aux = sp_all_gather(previous_aux)[:full_num_tokens]
|
||||
aux_hidden_by_layer[idx] = previous_aux
|
||||
assert residual is not None and post_mix is not None
|
||||
assert res_mix is not None and pre_mix is not None
|
||||
return hidden_states, residual, post_mix, res_mix, pre_mix
|
||||
|
||||
def _collapse(
|
||||
self,
|
||||
hidden_states: torch.Tensor | MoEOutput,
|
||||
residual: torch.Tensor,
|
||||
post_mix: torch.Tensor,
|
||||
res_mix: torch.Tensor,
|
||||
aux_hidden_by_layer: dict[int, torch.Tensor],
|
||||
full_num_tokens: int,
|
||||
) -> torch.Tensor:
|
||||
# Without a successor boundary, the last layer finalized its own MoE.
|
||||
assert isinstance(hidden_states, torch.Tensor)
|
||||
# The last layer has no successor to fold its post into.
|
||||
if self.fuse_mhc_all_reduce:
|
||||
hidden_states = tensor_model_parallel_all_reduce(hidden_states)
|
||||
hidden_states = mhc_post_tilelang(hidden_states, residual, post_mix, res_mix)
|
||||
if self.end_layer in self.aux_hidden_state_layers:
|
||||
final_aux = hidden_states.mean(dim=1)
|
||||
if self.use_sequence_parallel:
|
||||
final_aux = sp_all_gather(final_aux)[:full_num_tokens]
|
||||
aux_hidden_by_layer[self.end_layer] = final_aux
|
||||
return hidden_states
|
||||
|
||||
def _run_replay_layers(
|
||||
self,
|
||||
hidden_states: torch.Tensor | MoEOutput,
|
||||
positions: torch.Tensor,
|
||||
input_ids: torch.Tensor | None,
|
||||
pre_mix: torch.Tensor,
|
||||
post_mix: torch.Tensor,
|
||||
res_mix: torch.Tensor,
|
||||
residual: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, ...]:
|
||||
"""The layers past the last KV source, on whatever rows they are given;
|
||||
returns their output, the last FFN's pre-mix and the aux hidden states
|
||||
they capture."""
|
||||
aux_hidden_by_layer: dict[int, torch.Tensor] = {}
|
||||
hidden_states, residual, post_mix, res_mix, pre_mix = self._run_layers(
|
||||
range(self.decoder_replay_start, self.end_layer),
|
||||
hidden_states,
|
||||
positions,
|
||||
input_ids,
|
||||
pre_mix,
|
||||
post_mix,
|
||||
res_mix,
|
||||
residual,
|
||||
aux_hidden_by_layer,
|
||||
)
|
||||
hidden_states = self._collapse(
|
||||
hidden_states,
|
||||
residual,
|
||||
post_mix,
|
||||
res_mix,
|
||||
aux_hidden_by_layer,
|
||||
positions.shape[0],
|
||||
)
|
||||
return (
|
||||
hidden_states,
|
||||
pre_mix,
|
||||
*(
|
||||
aux_hidden_by_layer[layer_id]
|
||||
for layer_id in self.aux_hidden_state_layers
|
||||
if layer_id in aux_hidden_by_layer
|
||||
),
|
||||
)
|
||||
|
||||
def _decoder_replay_supported(self, vllm_config: VllmConfig, cut: int) -> bool:
|
||||
"""Whether this rank may trim the layers after ``cut``; warns when not."""
|
||||
parallel_config = vllm_config.parallel_config
|
||||
spec_config = vllm_config.speculative_config
|
||||
draft_config = spec_config.draft_model_config if spec_config else None
|
||||
draft_hf_config = getattr(draft_config, "hf_config", None)
|
||||
draft_window = getattr(draft_hf_config, "sliding_window", None)
|
||||
draft_layer_types = getattr(draft_hf_config, "layer_types", None) or ()
|
||||
window = self.config.sliding_window
|
||||
if self.start_layer > cut or self.end_layer < self.config.num_hidden_layers:
|
||||
reason = (
|
||||
"the pipeline stage holding the last KV source layer must also "
|
||||
"hold every layer after it"
|
||||
)
|
||||
elif (
|
||||
self.use_sequence_parallel
|
||||
or parallel_config.prefill_context_parallel_size > 1
|
||||
or parallel_config.use_ubatching
|
||||
):
|
||||
reason = (
|
||||
"the replay-layer batch shrinks per rank, which sequence and "
|
||||
"prefill-context parallelism and microbatching cannot follow"
|
||||
)
|
||||
elif any(i > cut for i in getattr(self.config, "engram_layer_ids", ())):
|
||||
reason = "an Engram layer sits after the last KV source layer"
|
||||
elif draft_config is not None and (
|
||||
draft_window is None
|
||||
or draft_window > window
|
||||
or any(t != "sliding_attention" for t in draft_layer_types)
|
||||
):
|
||||
reason = (
|
||||
f"the drafter (sliding window {draft_window}) reads hidden states "
|
||||
f"outside the target's {window}-token window"
|
||||
)
|
||||
else:
|
||||
return True
|
||||
logger.warning_once("Decoder SWA bounded replay is off: %s.", reason)
|
||||
return False
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
stacked_params_mapping = [
|
||||
# (param_name, shard_name, shard_id)
|
||||
@@ -1397,6 +1575,10 @@ class DeepseekV41LLMForCausalLM(
|
||||
engram_hash = self.model.engram_hash
|
||||
return engram_hash.lookback_depth if engram_hash is not None else 0
|
||||
|
||||
@property
|
||||
def decoder_replay_layers(self) -> DecoderReplayLayers | None:
|
||||
return self.model.decoder_replay_layers
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
|
||||
Reference in New Issue
Block a user