[Qwen4Exp] Restore torch.compile on the NVIDIA path; exact breakable pin; runtime graph-mode assertion

- torch.compile restored on the NVIDIA Qwen4Exp target and MTP so the
  production profile (VLLM_COMPILE + FULL_AND_PIECEWISE, breakable off) runs.
- The production pin requires VLLM_USE_BREAKABLE_CUDAGRAPH to be exactly "0".
- assert_resolved_cudagraph_modes() runs at the top of capture_model.
- CPU tests for the combined profile, the exact pin and the resolved modes.

Co-Authored-By: Hinata <hinata@idihore.id>
Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
2026-10-09 19:55:22 +07:00
co-authored by Hinata
parent 23349e43b2
commit 2e68aba2a7
8 changed files with 586 additions and 145 deletions
+33 -7
View File
@@ -10,6 +10,7 @@ import torch
from torch import nn
from transformers import Qwen4ExpConfig, Qwen4ExpTextConfig
from vllm.compilation.decorators import support_torch_compile
from vllm.config import VllmConfig
from vllm.distributed import get_pp_group
from vllm.logger import init_logger
@@ -78,7 +79,11 @@ from vllm.multimodal.inputs import MultiModalFeatureSpec
from vllm.sequence import IntermediateTensors
from vllm.tokenizers.registry import cached_tokenizer_from_config
from vllm.v1.attention.backends.registry import MambaAttentionBackendEnum
from vllm.v1.e2_guards import assert_graph_profile_is_executable, assert_ple_mode
from vllm.v1.e2_guards import (
assert_compiled_submodule,
assert_graph_profile_is_executable,
assert_ple_mode,
)
from vllm.v1.kv_cache_interface import MambaSpec
from ..common.mtp import make_mtp_hidden_buffer
@@ -472,6 +477,25 @@ class Qwen4ExpMixtureOfExperts(MixtureOfExperts):
moe.experts.update_expert_map()
# Compile-profile guard: torch.compile restored on the NVIDIA
# path, reverting #55272's removal. Every request-dependent region is a custom
# op listed in CompilationConfig._attention_ops (qsa_with_output,
# ple_short_conv, compute_ple_ngram_ids, ple_{start,finalize}_prefetch), so
# VLLM_COMPILE + FULL_AND_PIECEWISE is executable again with breakable capture
# off. query_start_loc / ngram_context are fixed-capacity since #55272
# (model_state.py); they stay marked dynamic as on v2.0.1 and only ever reach
# the opaque PLE ops.
@support_torch_compile(
dynamic_arg_dims={
"input_ids": 0,
"positions": -1,
"intermediate_tensors": 0,
"inputs_embeds": 0,
"query_start_loc": 0,
"ngram_context": 0,
"deepstack_input_embeds": 0,
}
)
class Qwen4ExpModel(nn.Module):
hf_to_vllm_mapper = Qwen3_5Model.hf_to_vllm_mapper | _EXTRA_WEIGHTS_MAPPER
@@ -760,12 +784,11 @@ class Qwen4ExpForCausalLM(
def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
super().__init__()
# V0.30.0 auto-enables breakable cudagraphs
# for this architecture when VLLM_USE_BREAKABLE_CUDAGRAPH is unset, and
# VLLM_COMPILE + a PIECEWISE mode dies at capture because #55272 left no
# compiled submodule. Fail here rather than let a reference-host run qualify an
# identity nobody chose. Qwen4ExpForConditionalGeneration constructs
# this class; Qwen4ExpMTP does not, and guards itself.
# Compile-profile guard: the only qualified profile on this tree is VLLM_COMPILE +
# FULL_AND_PIECEWISE with breakable capture off (the v2.0.1 identity).
# Fail at construction, before profiling or capture, on anything else.
# Qwen4ExpForConditionalGeneration constructs this class; Qwen4ExpMTP
# does not, and guards itself.
assert_graph_profile_is_executable(vllm_config, role="target")
assert_ple_mode(vllm_config, role="target")
config: Qwen4ExpTextConfig = vllm_config.model_config.hf_text_config
@@ -783,6 +806,9 @@ class Qwen4ExpForCausalLM(
self.model = Qwen4ExpModel(
vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model")
)
# has_compiled_submodule() at gpu/cudagraph_utils.py:605 is what capture
# actually tests; check the same property here.
assert_compiled_submodule(self.model, vllm_config, role="target")
# PP ownership: logits are computed on the
# last stage only; earlier stages carried an unused 0.59 GiB head.
if get_pp_group().is_last_rank:
+19 -1
View File
@@ -20,6 +20,7 @@ import torch
from torch import nn
from transformers import Qwen4ExpTextConfig
from vllm.compilation.decorators import support_torch_compile
from vllm.config import VllmConfig, replace, set_current_vllm_config
from vllm.distributed import get_pp_group
from vllm.model_executor.layers.fused_moe.utils import (
@@ -51,7 +52,11 @@ from vllm.model_executor.models.utils import (
maybe_prefix,
)
from vllm.sequence import IntermediateTensors
from vllm.v1.e2_guards import assert_graph_profile_is_executable, assert_ple_mode
from vllm.v1.e2_guards import (
assert_compiled_submodule,
assert_graph_profile_is_executable,
assert_ple_mode,
)
from .hyperconnection import GatedResidual, HyperConnectionConfig
from .low_latency_gemm import enable_qwen4_exp_low_latency_gemm
@@ -168,6 +173,18 @@ def _make_draft_vllm_config(
return draft_vllm_config
# Compile restored on the drafter too (reverts #55272 here), as
# on v2.0.1: both classes wrapped; the outer one compiles, the inner is
# inlined while Dynamo traces.
@support_torch_compile(
dynamic_arg_dims={
"input_ids": 0,
"positions": -1,
"intermediate_tensors": 0,
"inputs_embeds": 0,
"hidden_states": 0,
}
)
class Qwen4ExpMultiTokenPredictor(nn.Module):
hf_to_vllm_mapper = Qwen3_5Model.hf_to_vllm_mapper | _EXTRA_WEIGHTS_MAPPER
@@ -411,6 +428,7 @@ class Qwen4ExpMTP(
vllm_config=vllm_config,
prefix=maybe_prefix(prefix, "mtp"),
)
assert_compiled_submodule(self.model, vllm_config, role="draft")
if get_pp_group().is_last_rank:
if config.tie_word_embeddings:
+210 -5
View File
@@ -17,6 +17,7 @@ from vllm.model_executor.layers.quantization.base_config import (
QuantizationConfig,
)
from vllm.model_executor.models.utils import AutoWeightsLoader
from vllm.utils.torch_utils import direct_register_custom_op
from ..common.ngram_embedding import (
Qwen4ExpPLEDeviceEmbedding,
@@ -177,6 +178,15 @@ class Qwen4ExpPLEFileGatherEmbedding(Qwen4ExpPLEEmbedding):
self._host_rows[:num_tokens], non_blocking=True
)
@property
def prefetch_buffer(self) -> torch.Tensor:
"""Side-stream lookup destination (declared mutated by the start op)."""
return self._prefetch_buffer
def new_prefetch_output(self, num_tokens: int) -> torch.Tensor:
"""Graph-owned output storage for the finalize op."""
return self._prefetch_buffer.new_empty((num_tokens, self._output_dim))
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
"""Return the rows staged for this step."""
return self._staging[: hidden_states.shape[0]].flatten(-2)
@@ -296,10 +306,16 @@ class Qwen4ExpNGramEmbedding(nn.Module):
*,
data_parallel_rank: int,
prefix: str,
layer_name: str | None = None,
quant_config: QuantizationConfig | None = None,
params_dtype: torch.dtype | None = None,
) -> None:
super().__init__()
# Compile-profile guard: the owning Qwen4ExpPLELayer's static_forward_context key.
# When set, request-dependent work runs through the custom ops at the
# bottom of this file so VLLM_COMPILE never traces it (#55272 removed
# them together with @support_torch_compile). None = direct calls.
self.layer_name = layer_name
self.embedding_dim = embedding_dim
self.ngram_size = int(config.ngram_size)
self.heads_per_ngram = int(config.heads_per_ngram)
@@ -531,12 +547,43 @@ class Qwen4ExpNGramEmbedding(nn.Module):
ngram_context: torch.Tensor,
) -> torch.Tensor:
embedding = self.ngram_embedding
if embedding.supports_prefetch or isinstance(
embedding, Qwen4ExpPLEFileGatherEmbedding
):
if isinstance(embedding, Qwen4ExpPLEFileGatherEmbedding):
# Fork: this base's third backend stages rows in prepare_inputs,
# so it has no graph-owned lookup op.
return embedding(hidden_states)
ngram_ids = self.compute_ngram_ids(input_ids, query_start_loc, ngram_context)
return self.ngram_embedding(ngram_ids).flatten(-2)
if self.layer_name is None:
if embedding.supports_prefetch:
return embedding(hidden_states)
ngram_ids = self.compute_ngram_ids(
input_ids, query_start_loc, ngram_context
)
return self.ngram_embedding(ngram_ids).flatten(-2)
if embedding.supports_prefetch:
output = embedding.new_prefetch_output(hidden_states.shape[0])
torch.ops.vllm.qwen4_exp_ple_finalize_prefetch(output, self.layer_name)
return output
input_ids = input_ids.reshape(-1)
# Request-layout-dependent ID generation stays outside PIECEWISE graphs
# (a splitting op), as on v2.0.1; the op writes graph-owned storage.
ngram_ids = input_ids.new_empty(
(input_ids.numel(), self.ngram_heads), dtype=torch.long
)
torch.ops.vllm.qwen4_exp_compute_ple_ngram_ids(
input_ids,
query_start_loc,
ngram_context,
ngram_ids,
self.layer_name,
)
# The table lookup is opaque so Inductor never sees (or autotunes
# against) the full PLE table -- #55272's ~50 GB activation peak.
output = ngram_ids.new_empty(
(ngram_ids.shape[0], self.ngram_heads * self.head_dim),
dtype=embedding.weight.dtype,
)
torch.ops.vllm.qwen4_exp_ple_device_lookup(ngram_ids, output, self.layer_name)
return output
def start_prefetch(
self,
@@ -549,6 +596,32 @@ class Qwen4ExpNGramEmbedding(nn.Module):
embedding = self.ngram_embedding
if not embedding.supports_prefetch:
return
if self.layer_name is not None:
# Forks onto the prefetch side stream; the join is in the finalize
# op. Both are splitting ops, so neither end of the fork is ever
# inside a piecewise capture.
torch.ops.vllm.qwen4_exp_ple_start_prefetch(
hidden_states,
input_ids,
query_start_loc,
ngram_context,
embedding.prefetch_buffer,
self.layer_name,
)
return
self._start_prefetch_eager(
hidden_states, input_ids, query_start_loc, ngram_context
)
def _start_prefetch_eager(
self,
hidden_states: torch.Tensor,
input_ids: torch.Tensor,
query_start_loc: torch.Tensor,
ngram_context: torch.Tensor,
) -> None:
"""Compute IDs and launch the pinned lookup (runs outside compile)."""
embedding = self.ngram_embedding
ngram_ids = self.compute_ngram_ids(
input_ids,
query_start_loc,
@@ -646,6 +719,138 @@ def stage_checkpoint_rows(
module.ngram_embedding.stage_rows(num_tokens)
# --- compile support ------------------------------------------------
# The four ops below are the NVIDIA PLE's boundary with torch.compile. Each
# resolves its Qwen4ExpPLELayer through the forward context by name, as
# v2.0.1's qwen4_exp_compute_ple_ngram_ids did before #55272 removed it.
# Splitting ops (vllm/config/compilation.py ``_attention_ops``):
# qwen4_exp_compute_ple_ngram_ids, qwen4_exp_ple_start_prefetch,
# qwen4_exp_ple_finalize_prefetch.
# qwen4_exp_ple_device_lookup is opaque but NOT a split: a gather plus the ETP
# all-reduce is capturable; it only has to be hidden from Inductor.
def _ple_embedding_of(layer_name: str) -> Qwen4ExpNGramEmbedding:
layer = get_forward_context().no_compile_layers[layer_name]
embedding = getattr(layer, "ple_embedding", None)
if not isinstance(embedding, Qwen4ExpNGramEmbedding):
raise TypeError(f"{layer_name} does not own a Qwen4Exp PLE embedding")
if hasattr(type(embedding), "dequantize_pulled"):
# Fork (pull transport + compile profile): the pull transport's GPU placeholder owns no
# table and dispatches through PleOffloadLayer.forward; it must never
# reach these device/UVA ops (ple_layer.py builds it without a
# layer_name). Same marker ple_layer.py uses to select dequantisation.
raise TypeError(
f"{layer_name}: PLE pull transport module routed through an "
"upstream device/UVA PLE op"
)
return embedding
def qwen4_exp_compute_ple_ngram_ids(
input_ids: torch.Tensor,
query_start_loc: torch.Tensor,
ngram_context: torch.Tensor,
output: torch.Tensor,
layer_name: str,
) -> None:
"""Compute request-dependent PLE n-gram IDs outside piecewise graphs."""
_ple_embedding_of(layer_name).compute_ngram_ids(
input_ids, query_start_loc, ngram_context, output
)
def qwen4_exp_ple_device_lookup(
ngram_ids: torch.Tensor,
output: torch.Tensor,
layer_name: str,
) -> None:
"""Look up device-resident PLE rows; keeps the table out of Inductor."""
embedding = _ple_embedding_of(layer_name)
output.copy_(embedding.ngram_embedding(ngram_ids).flatten(-2))
def qwen4_exp_ple_start_prefetch(
hidden_states: torch.Tensor,
input_ids: torch.Tensor,
query_start_loc: torch.Tensor,
ngram_context: torch.Tensor,
prefetch_buffer: torch.Tensor,
layer_name: str,
) -> None:
"""Start the pinned-host (UVA) lookup on the side stream."""
embedding = _ple_embedding_of(layer_name)
owned = embedding.ngram_embedding.prefetch_buffer
if prefetch_buffer.data_ptr() != owned.data_ptr():
raise RuntimeError(f"{layer_name}: PLE prefetch buffer identity changed")
embedding._start_prefetch_eager(
hidden_states, input_ids, query_start_loc, ngram_context
)
def qwen4_exp_ple_finalize_prefetch(output: torch.Tensor, layer_name: str) -> None:
"""Join the side stream and write the pinned lookup into ``output``."""
pinned = _ple_embedding_of(layer_name).ngram_embedding
pinned._finalize_prefetch(pinned.prefetch_buffer, output)
def _compute_ple_ngram_ids_fake(
input_ids: torch.Tensor,
query_start_loc: torch.Tensor,
ngram_context: torch.Tensor,
output: torch.Tensor,
layer_name: str,
) -> None:
return None
def _ple_device_lookup_fake(
ngram_ids: torch.Tensor, output: torch.Tensor, layer_name: str
) -> None:
return None
def _ple_start_prefetch_fake(
hidden_states: torch.Tensor,
input_ids: torch.Tensor,
query_start_loc: torch.Tensor,
ngram_context: torch.Tensor,
prefetch_buffer: torch.Tensor,
layer_name: str,
) -> None:
return None
def _ple_finalize_prefetch_fake(output: torch.Tensor, layer_name: str) -> None:
return None
direct_register_custom_op(
op_name="qwen4_exp_compute_ple_ngram_ids",
op_func=qwen4_exp_compute_ple_ngram_ids,
mutates_args=["output"],
fake_impl=_compute_ple_ngram_ids_fake,
)
direct_register_custom_op(
op_name="qwen4_exp_ple_device_lookup",
op_func=qwen4_exp_ple_device_lookup,
mutates_args=["output"],
fake_impl=_ple_device_lookup_fake,
)
direct_register_custom_op(
op_name="qwen4_exp_ple_start_prefetch",
op_func=qwen4_exp_ple_start_prefetch,
mutates_args=["prefetch_buffer"],
fake_impl=_ple_start_prefetch_fake,
)
direct_register_custom_op(
op_name="qwen4_exp_ple_finalize_prefetch",
op_func=qwen4_exp_ple_finalize_prefetch,
mutates_args=["output"],
fake_impl=_ple_finalize_prefetch_fake,
)
__all__ = [
"Qwen4ExpNGramEmbedding",
]
+43 -3
View File
@@ -19,6 +19,7 @@ from vllm.model_executor.layers.mamba.mamba_utils import (
MambaStateShapeCalculator,
is_conv_state_dim_first,
)
from vllm.utils.torch_utils import direct_register_custom_op
from vllm.v1.attention.backends.registry import MambaAttentionBackendEnum
from vllm.v1.attention.backends.short_conv_attn import (
PleShortConvAttentionBackend,
@@ -95,6 +96,10 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
if envs.VLLM_E2_PLE_PULL_TRANSPORT:
# Fork: the E2 pull transport owns the table in a CPU-only
# offload process; upstream's device/UVA backends are never built.
# Pull transport with the compile-profile guard: no layer_name -- the pull module never routes
# through the n-gram custom ops. Its GPU placeholder dispatches
# through PleOffloadLayer.forward (the ple_offload_wait_copy op) and
# owns no table; the offload process calls forward_impl directly.
from .ple_pull import Qwen4ExpNGramEmbeddingPull
self.ple_embedding = Qwen4ExpNGramEmbeddingPull.build(
@@ -115,6 +120,7 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
vllm_config.scheduler_config.max_num_batched_tokens,
data_parallel_rank=vllm_config.parallel_config.data_parallel_rank,
prefix=f"{prefix}.ple_embedding",
layer_name=prefix,
quant_config=quant_config,
params_dtype=model_config.dtype,
)
@@ -161,11 +167,12 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
output_dtype: torch.dtype,
) -> torch.Tensor:
"""Dequantize PLE lookup output."""
return self.ple_embedding.ngram_embedding.dequantize(
dequantize_pulled = getattr(self.ple_embedding, "dequantize_pulled", None)
if dequantize_pulled is not None:
# Fork pull transport: no local table; FP8 scale kept here.
return dequantize_pulled(embeddings, output_dtype)
return self.ple_embedding.ngram_embedding.dequantize(
embeddings,
output_dtype,
)
@@ -450,11 +457,44 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
self.norm_key.eps,
)
# State routing depends on runtime request metadata and remains outside
# the graph; short convolution accumulates into gated_output.
self._short_conv(conv_input, gated_output, hidden_states)
# the graph; short convolution accumulates into gated_output. Compile-profile guard:
# a splitting op again (as on v2.0.1), so VLLM_COMPILE never traces it.
torch.ops.vllm.qwen4_exp_ple_short_conv(
conv_input, gated_output, hidden_states, self.prefix
)
return gated_output
def qwen4_exp_ple_short_conv(
inputs: torch.Tensor,
residual_output: torch.Tensor,
outer_residual: torch.Tensor,
layer_name: str,
) -> None:
"""PLE short convolution + state routing, outside piecewise graphs."""
layer = get_forward_context().no_compile_layers[layer_name]
if not isinstance(layer, Qwen4ExpPLELayer):
raise TypeError(f"{layer_name} is not a Qwen4Exp PLE layer")
layer._short_conv(inputs, residual_output, outer_residual)
def _qwen4_exp_ple_short_conv_fake(
inputs: torch.Tensor,
residual_output: torch.Tensor,
outer_residual: torch.Tensor,
layer_name: str,
) -> None:
return None
direct_register_custom_op(
op_name="qwen4_exp_ple_short_conv",
op_func=qwen4_exp_ple_short_conv,
mutates_args=["residual_output"],
fake_impl=_qwen4_exp_ple_short_conv_fake,
)
__all__ = [
"Qwen4ExpPLEGroupedNorm",
"Qwen4ExpPLELayer",