# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Fork startup guards that fail closed on a graph profile we never qualified. These run at model construction, on every rank, for the target model and for the MTP drafter, before profiling or capture. Compile-profile guard: this tree restores torch.compile on the NVIDIA Qwen4Exp path (reverting vLLM #55272) and removes Qwen4Exp from ``DEFAULT_BREAKABLE_CUDAGRAPH_ARCHITECTURES``. The ONE qualified profile is the v2.0.1 production identity: * ``VLLM_USE_BREAKABLE_CUDAGRAPH`` explicitly pinned to exactly ``0``, and resolved OFF; * ``CompilationMode.VLLM_COMPILE``; * ``CUDAGraphMode.FULL_AND_PIECEWISE``; * every Qwen4Exp request-dependent custom op in ``splitting_ops`` (:data:`REQUIRED_SPLITTING_OPS`); * a live ``@support_torch_compile`` submodule (:func:`assert_compiled_submodule`), which is the property ``vllm/v1/worker/gpu/cudagraph_utils.py:605`` actually tests at capture. Anything else -- eager, NONE + FULL, FULL_DECODE_ONLY, breakable PIECEWISE -- fails loud. ``VLLM_E2_ALLOW_BREAKABLE=1`` is the single, logged opt-out for deliberate non-production boots (debug, probes); a production launch must not set it. Timing limit: this runs AFTER ``VllmConfig.__post_init__`` resolved the profile. It stops the boot before profiling and capture; it cannot recover the originally requested profile if the config layer rewrote it. """ import os from vllm.logger import init_logger logger = init_logger(__name__) BREAKABLE_ENV = "VLLM_USE_BREAKABLE_CUDAGRAPH" #: Opt-out for every guard in this module. Recorded in the launch identity and #: PROHIBITED in production profiles; a production launch must not set it. ALLOW_BREAKABLE_ENV = "VLLM_E2_ALLOW_BREAKABLE" #: Optional expected resolved cudagraph mode, by name. When set, a mismatch is #: an error (in addition to the fixed requirement below). EXPECTED_MODE_ENV = "VLLM_E2_EXPECTED_CUDAGRAPH_MODE" #: The qualified profile (the compile-profile guard). REQUIRED_COMPILATION_MODE_NAME = "VLLM_COMPILE" REQUIRED_CUDAGRAPH_MODE_NAME = "FULL_AND_PIECEWISE" #: The only raw VLLM_USE_BREAKABLE_CUDAGRAPH value accepted as the production #: pin. Resolution semantics stay upstream's (_upstream_truth). PRODUCTION_BREAKABLE_PIN = "0" #: Custom ops that must stay graph breaks on the NVIDIA Qwen4Exp path. Each #: reads per-step request metadata (or forks/joins a side stream) and would be #: baked into a piecewise graph otherwise. REQUIRED_SPLITTING_OPS = ( "vllm::qwen4_exp_qsa_with_output", "vllm::qwen4_exp_ple_short_conv", "vllm::qwen4_exp_compute_ple_ngram_ids", "vllm::qwen4_exp_ple_start_prefetch", "vllm::qwen4_exp_ple_finalize_prefetch", "vllm::qwen_gdn_attention_core", "vllm::qwen_gdn_attention_core_fused_norm_packed", "vllm::ple_offload_wait_copy", ) #: Upstream v0.30.0 auto-enabled breakable cudagraphs for these; this tree #: does not (vllm/config/vllm.py). Kept to name the mechanism in messages. OUR_AUTO_BREAKABLE_ARCHITECTURES = frozenset( { "Qwen4ExpForCausalLM", "Qwen4ExpForConditionalGeneration", "Qwen4ExpMTP", } ) def _upstream_truth(raw: str | None) -> bool: """Upstream's exact semantics for the breakable switch. ``envs.py:937`` is ``os.environ.get(..., "0") == "1"``. Nothing else is on. """ return raw == "1" def breakable_resolved() -> bool: """Whether breakable cudagraphs are on, as the engine will see it. The raw environment and the (cached) envs accessor are two readings of one source; either saying "on" means on. No exception is swallowed. """ if _upstream_truth(os.environ.get(BREAKABLE_ENV)): return True import vllm.envs as envs return bool(envs.VLLM_USE_BREAKABLE_CUDAGRAPH) def _name(value) -> str: return getattr(value, "name", str(value)) def _profile(vllm_config) -> tuple[list[str], object, object, list[str] | None]: """Resolved (architectures, mode, cudagraph mode, splitting ops).""" model_config = getattr(vllm_config, "model_config", None) if model_config is None: raise RuntimeError("e2-guard: vllm_config has no model_config to check") compilation_config = getattr(vllm_config, "compilation_config", None) if compilation_config is None: raise RuntimeError("e2-guard: vllm_config has no compilation_config to check") architectures = list(getattr(model_config, "architectures", None) or []) return ( architectures, compilation_config.mode, compilation_config.cudagraph_mode, getattr(compilation_config, "splitting_ops", None), ) def _opted_out(role: str, detail: str) -> bool: if os.environ.get(ALLOW_BREAKABLE_ENV, "") != "1": return False logger.warning( "e2-guard[%s]: %s=1 -- guards disabled by request (%s). This boot is " "NOT a promotion-grade boot; a production launch must not set this flag.", role, ALLOW_BREAKABLE_ENV, detail, ) return True def assert_graph_profile_is_executable(vllm_config, *, role: str = "target") -> None: """Require the qualified profile: VLLM_COMPILE + FULL_AND_PIECEWISE. ``role`` is ``"target"`` or ``"draft"``; both are checked, because ``Qwen4ExpMTP`` builds ``Qwen4ExpMultiTokenPredictor`` rather than ``Qwen4ExpForCausalLM``, from a config rebuilt in ``mtp.py``. """ architectures, mode, cudagraph_mode, splitting_ops = _profile(vllm_config) detail = ( f"architectures={architectures} breakable={os.environ.get(BREAKABLE_ENV)} " f"compilation_mode={_name(mode)} cudagraph_mode={_name(cudagraph_mode)}" ) if _opted_out(role, detail): return # 1. The pin must be explicit, so a future upstream merge that re-adds us # to DEFAULT_BREAKABLE_CUDAGRAPH_ARCHITECTURES cannot flip it silently. raw_breakable = os.environ.get(BREAKABLE_ENV) if raw_breakable is None: raise RuntimeError( f"e2-guard[{role}]: {BREAKABLE_ENV} is not set. Pin it in the " f"launcher: export {BREAKABLE_ENV}=0, or set {ALLOW_BREAKABLE_ENV}=1 " "to take an unpinned boot on purpose." ) # 2. Breakable capture is not the qualified identity. if raw_breakable == "1" or breakable_resolved(): raise RuntimeError( f"e2-guard[{role}]: {BREAKABLE_ENV} resolved ON ({detail}). The " "qualified profile is breakable-off VLLM_COMPILE + " f"FULL_AND_PIECEWISE. Export {BREAKABLE_ENV}=0, or set " f"{ALLOW_BREAKABLE_ENV}=1 to take it deliberately." ) # 2b. The production pin is the exact string "0". # Upstream's accessor reads anything but "1" as off, so "2", "true", # "" or "00" would resolve off -- but a mistyped launcher value must # not be recorded as a qualified breakable-off profile. The logged # debug opt-out (VLLM_E2_ALLOW_BREAKABLE=1, handled above) is separate. if raw_breakable != PRODUCTION_BREAKABLE_PIN: raise RuntimeError( f"e2-guard[{role}]: {BREAKABLE_ENV}={raw_breakable!r} is not the " f"production pin; it must be exactly {PRODUCTION_BREAKABLE_PIN!r}. " "Upstream would read it as off, but the launch profile does not " f"say what was meant. Export {BREAKABLE_ENV}=0, or set " f"{ALLOW_BREAKABLE_ENV}=1 for a deliberate non-production boot." ) # 3. The profile itself: mode AND cudagraph mode, by name. if ( _name(mode) != REQUIRED_COMPILATION_MODE_NAME or _name(cudagraph_mode) != REQUIRED_CUDAGRAPH_MODE_NAME ): raise RuntimeError( f"e2-guard[{role}]: resolved compilation_mode={_name(mode)} " f"cudagraph_mode={_name(cudagraph_mode)}; the qualified profile is " f"compilation_mode={REQUIRED_COMPILATION_MODE_NAME} " f"cudagraph_mode={REQUIRED_CUDAGRAPH_MODE_NAME} (compile-profile guard). Check " "-O / --compilation-config / --enforce-eager / TORCH_COMPILE_DISABLE, " f"or set {ALLOW_BREAKABLE_ENV}=1 for a deliberate non-production boot." ) # 4. The graph breaks that make PIECEWISE correct on this model. if splitting_ops is None: raise RuntimeError( f"e2-guard[{role}]: compilation_config.splitting_ops is unresolved; " "cannot confirm the Qwen4Exp graph breaks." ) missing = [op for op in REQUIRED_SPLITTING_OPS if op not in splitting_ops] if missing: raise RuntimeError( f"e2-guard[{role}]: splitting_ops is missing {missing}. Each of " "these reads per-step request metadata (or forks/joins a side " "stream) and would be frozen into a piecewise CUDA graph." ) # 5. Optional exact pin of the resolved mode, for a launch profile. expected = os.environ.get(EXPECTED_MODE_ENV, "").strip() if expected and _name(cudagraph_mode) != expected: raise RuntimeError( f"e2-guard[{role}]: resolved cudagraph_mode={_name(cudagraph_mode)} " f"but {EXPECTED_MODE_ENV}={expected}. The launch profile and the " "engine disagree about the graph identity." ) logger.info( "e2-guard[%s]: architectures=%s breakable=OFF compilation_mode=%s " "cudagraph_mode=%s splitting_ops=+%d required. Recorded, not " "certified -- this checks startup state, not qualification.", role, architectures, _name(mode), _name(cudagraph_mode), len(REQUIRED_SPLITTING_OPS), ) def assert_compiled_submodule(module, vllm_config, *, role: str = "target") -> None: """Require a live ``@support_torch_compile`` wrapper on ``module``. This is the property ``has_compiled_submodule()`` checks before PIECEWISE capture (``gpu/cudagraph_utils.py:132``, ``:605``). Checking it at construction turns a mid-capture failure into a startup one. """ from vllm.compilation.wrapper import TorchCompileWithNoGuardsWrapper compiled = isinstance(module, TorchCompileWithNoGuardsWrapper) and not getattr( module, "do_not_compile", True ) if compiled: return detail = ( f"{type(module).__name__} is_wrapper=" f"{isinstance(module, TorchCompileWithNoGuardsWrapper)} " f"do_not_compile={getattr(module, 'do_not_compile', '')}" ) if _opted_out(role, detail): return raise RuntimeError( f"e2-guard[{role}]: {detail}: no live torch.compile wrapper, so " "PIECEWISE capture would raise at gpu/cudagraph_utils.py:605. The " "@support_torch_compile decorator (compile-profile guard) is missing or disabled." ) # -------------------------------------------------------------------------- # Resolved runtime graph modes. # -------------------------------------------------------------------------- #: Target architectures whose V2 capture is checked. The construction guard #: above lives in the NVIDIA Qwen4Exp model; this tree targets sm_86 only. QWEN4EXP_TARGET_ARCHITECTURES = frozenset( {"Qwen4ExpForCausalLM", "Qwen4ExpForConditionalGeneration"} ) #: What each V2 cudagraph manager may hold immediately before capture. #: The construction guard checks ``compilation_config.cudagraph_mode``; the #: V2 runner later calls ``resolve_cudagraph_mode_and_sizes`` (and, with #: adaptive verification, ``resolve_adaptive_cudagraph_mode``), which may #: downgrade to FULL_DECODE_ONLY / PIECEWISE / NONE or drop the piecewise half #: (attention CG support, spec-decode uniform batches, no compiled submodule). #: No such downgrade is allowed for the target. The drafter's managers are #: derived from the target's resolved mode by the speculator itself: #: * autoregressive / MTP (``AutoRegressiveSpeculator.init_cudagraph_manager``): #: prefill = the target's mode unchanged; decode = FULL_DECODE_ONLY #: ("PIECEWISE cudagraphs are not supported for draft decodes"); #: * multi-module MTP (``MultiModuleMTPSpeculator``): one manager, #: FULL_AND_PIECEWISE -> FULL_DECODE_ONLY by design. #: Those decode-specific modes are the only drafter deviations accepted. EXPECTED_RESOLVED_MODES = { "target": REQUIRED_CUDAGRAPH_MODE_NAME, "draft.prefill_cudagraph_manager": REQUIRED_CUDAGRAPH_MODE_NAME, "draft.decode_cudagraph_manager": "FULL_DECODE_ONLY", "draft.cudagraph_manager": "FULL_DECODE_ONLY", } _DRAFT_MANAGER_ATTRS = ( "prefill_cudagraph_manager", "decode_cudagraph_manager", "cudagraph_manager", ) def assert_resolved_cudagraph_modes( vllm_config, target_manager, speculator=None ) -> None: """Fail loud if the V2 runner is about to capture a downgraded mode. Called from ``GPUModelRunner.capture_model`` (``vllm/v1/worker/gpu``) before any capture, including the ``profile_only`` capture and the "nothing to capture" early return, so a resolver downgrade to NONE cannot skip it. Applies only to a Qwen4Exp target; any other model is untouched. ``VLLM_E2_ALLOW_BREAKABLE=1`` skips it, logged, like the other graph guards. """ model_config = getattr(vllm_config, "model_config", None) architectures = list(getattr(model_config, "architectures", None) or []) if not QWEN4EXP_TARGET_ARCHITECTURES & set(architectures): return observed: dict[str, str] = {} if target_manager is None: observed["target"] = "" else: observed["target"] = _name(getattr(target_manager, "cudagraph_mode", None)) if speculator is not None: found = False for attr in _DRAFT_MANAGER_ATTRS: if not hasattr(speculator, attr): continue found = True manager = getattr(speculator, attr) observed[f"draft.{attr}"] = ( "" if manager is None else _name(getattr(manager, "cudagraph_mode", None)) ) if not found: observed["draft"] = f"" detail = " ".join(f"{key}={value}" for key, value in observed.items()) if _opted_out("runtime", detail): return wrong = { key: value for key, value in observed.items() if EXPECTED_RESOLVED_MODES.get(key) != value } if wrong: expected = {key: EXPECTED_RESOLVED_MODES.get(key, "") for key in wrong} raise RuntimeError( f"e2-guard[runtime]: resolved cudagraph modes {wrong} differ from " f"the qualified profile {expected} ({detail}). The V2 runner's " "resolver downgraded the graph identity after the construction " "guard passed (attention CG support, spec-decode uniform batch, " "or no compiled submodule); see the resolver's warning above. Set " f"{ALLOW_BREAKABLE_ENV}=1 only for a deliberate non-production boot." ) logger.info( "e2-guard[runtime]: resolved cudagraph modes before capture: %s.", detail ) # -------------------------------------------------------------------------- # PLE transport: carry the pull transport, UVA disabled. # -------------------------------------------------------------------------- #: The fork's pull-transport switch (strict "0"/"1"; registered and hashed in #: vllm/envs.py). Renamed from the E2 base's VLLM_PLE_CPU_OFFLOAD. PULL_TRANSPORT_ENV = "VLLM_E2_PLE_PULL_TRANSPORT" #: Upstream v0.30.0's switch for the pinned-host UVA PLE backend. Same name as #: the E2 base's pull switch, opposite default (upstream: "1"). UPSTREAM_UVA_ENV = "VLLM_PLE_CPU_OFFLOAD" def pull_transport_enabled() -> bool: """Whether the fork's pull transport is on. Strict; raises on bad values. One source: the registered accessor ``envs.VLLM_E2_PLE_PULL_TRANSPORT``, whose parser (``envs._e2_strict_switch``) accepts exactly unset/"0"/"1". """ import vllm.envs as envs return bool(envs.VLLM_E2_PLE_PULL_TRANSPORT) def check_upstream_uva_env_against_pull() -> None: """Fail loud if the old name would turn upstream's UVA path on. With the pull transport on, ``VLLM_PLE_CPU_OFFLOAD`` may be unset (the fork then supplies ``cpu_offload=False`` as the Engram default) or exactly ``"0"``. ``"1"`` -- the E2-era spelling of "enable our offload" -- would enable upstream's pinned-host UVA backend beside ours: a double offload. Any other value is rejected rather than interpreted. With the pull transport off this function does nothing: the name is upstream's. """ if not pull_transport_enabled(): return raw = os.environ.get(UPSTREAM_UVA_ENV) if raw is None or raw == "0": return if raw == "1": raise RuntimeError( f"e2-guard: {PULL_TRANSPORT_ENV}=1 and {UPSTREAM_UVA_ENV}=1. On " f"vLLM v0.30.0 {UPSTREAM_UVA_ENV} is UPSTREAM's switch for the " "pinned-host UVA PLE backend (default on), not the E2 pull " "transport, so this launch asks for both transports at once. Unset " f"{UPSTREAM_UVA_ENV} or export {UPSTREAM_UVA_ENV}=0 " "(the pull transport replaces that switch)." ) raise ValueError( f"e2-guard: {PULL_TRANSPORT_ENV}=1 and {UPSTREAM_UVA_ENV}={raw!r}. " f'With the pull transport on, {UPSTREAM_UVA_ENV} must be unset or ' 'exactly "0"; any other value is refused rather than guessed.' ) def pull_transport_cpu_offload_default(upstream_default: bool) -> bool: """The Engram ``cpu_offload`` default, as this fork resolves it. Pull off: ``upstream_default`` unchanged (the tree behaves as upstream). Pull on: the old-name check above, then ``False`` -- upstream's UVA backend is never the default beside the pull transport. """ if not pull_transport_enabled(): return upstream_default check_upstream_uva_env_against_pull() return False def verify_engram_against_pull(engram_config) -> None: """Refuse an explicit ``cpu_offload=True`` while the pull transport is on. ``--engram-config '{"cpu_offload": true}'`` takes precedence over every default, so it is checked on the resolved object, not the environment. """ if not pull_transport_enabled(): return check_upstream_uva_env_against_pull() if engram_config is not None and bool(engram_config.cpu_offload): raise RuntimeError( f"e2-guard: {PULL_TRANSPORT_ENV}=1 but the resolved EngramConfig " "has cpu_offload=True (upstream's pinned-host UVA PLE backend). " "Both transports would own the PLE table. Drop cpu_offload from " "--engram-config (or set it false), or turn the pull transport off." ) #: Effective PLE modes, as the guard names them. PLE_MODE_PULL = "pull" # E2 pull transport (VLLM_E2_PLE_PULL_TRANSPORT=1) PLE_MODE_UVA = "uva" # upstream Qwen4ExpPLEPinnedHostEmbedding PLE_MODE_DEVICE = "device" # upstream Qwen4ExpPLEDeviceEmbedding PLE_MODE_NONE = "none" # no Engram config resolved (no PLE layers / not CUDA) def resolve_ple_mode(vllm_config) -> str: """The PLE transport this process will build, or an error if mixed. Reads the two inputs that decide it -- the pull switch (strict) and the RESOLVED ``engram_config.cpu_offload`` -- and nothing else. Mixed states raise; there is no fallback from one transport to another. """ pull = pull_transport_enabled() check_upstream_uva_env_against_pull() engram_config = getattr(vllm_config, "engram_config", None) cpu_offload = ( None if engram_config is None else bool(engram_config.cpu_offload) ) if pull: if cpu_offload: raise RuntimeError( f"e2-guard: {PULL_TRANSPORT_ENV}=1 with a resolved Engram " "cpu_offload=True: the pull transport and upstream's UVA " "backend would both own the PLE table." ) return PLE_MODE_PULL if cpu_offload is None: return PLE_MODE_NONE return PLE_MODE_UVA if cpu_offload else PLE_MODE_DEVICE def assert_ple_mode(vllm_config, *, role: str = "target") -> str: """Startup guard: resolve, assert and log the effective PLE mode. Runs beside ``assert_graph_profile_is_executable`` at model construction for ``role="target"`` and ``role="draft"`` (the MTP drafter carries the target's EngramConfig and the same process environment, so a mixed configuration fails there too). NOT disabled by VLLM_E2_ALLOW_BREAKABLE: that opt-out is about graph identity, not about owning the PLE table twice. """ mode = resolve_ple_mode(vllm_config) model_config = getattr(vllm_config, "model_config", None) text_config = getattr(model_config, "hf_text_config", None) ple_layer_ids = list(getattr(text_config, "ple_layer_ids", None) or []) engram_config = getattr(vllm_config, "engram_config", None) logger.info( "e2-guard[%s]: ple_mode=%s pull_transport=%d engram_cpu_offload=%s " "%s=%s ple_layer_ids=%s.", role, mode, 1 if mode == PLE_MODE_PULL else 0, None if engram_config is None else bool(engram_config.cpu_offload), UPSTREAM_UVA_ENV, os.environ.get(UPSTREAM_UVA_ENV, ""), ple_layer_ids, ) return mode #: Back-compatible name for the earlier call sites. assert_breakable_cudagraph_pinned = assert_graph_profile_is_executable