"""Rollout-engine overrides for the pinned TRL 1.9.1 + vLLM 0.25.1 stack. TRL 1.9.1 builds the colocate rollout engine from a fixed ``LLM(...)`` kwarg list in ``trl/generation/vllm_generation.py`` and exposes **no** compilation or cuda-graph knob: ``GRPOConfig`` carries ``vllm_mode``, ``vllm_gpu_memory_utilization``, ``vllm_max_model_length``, ``vllm_tensor_parallel_size``, ``vllm_enable_sleep_mode``, ``vllm_model_impl`` and ``vllm_structured_outputs_regex``, and nothing for ``enforce_eager`` or ``compilation_config``. vLLM 0.25.1 has no ``VLLM_ENFORCE_EAGER`` environment escape hatch either (``vllm/envs.py``). On this pinned stack the only way to change the rollout engine's cuda-graph behaviour is therefore to inject the kwarg at TRL's ``LLM(...)`` call site. Why we inject it: vLLM V1 cuda-graph execution intermittently wedges mid-step during GRPO generation (GPU pinned at 100%, CPU idle, no traceback, SIGTERM ignored), roughly once per 600-900 optimizer steps, and clears on retry from the same checkpoint. Every ``py-spy`` frame collected across occurrences lands in cuda-graph execution of the Qwen3.5-VL Gated-DeltaNet text backbone (``vllm/compilation/cuda_graph.py`` ``execution_fn``, ``vllm/model_executor/models/qwen3_next.py`` ``Qwen3NextModel.forward``, the ``rearrange_mixed_qkv`` / ``qwen_gdn_attention_core`` GDN kernels) or in the stream ``synchronize`` that waits on it (``gpu_model_runner.get_output``). The hang is not output-driven: completions at the stalled steps are short (mean 8-12, max <=24 tokens) with ``clipped_ratio`` 0. ``cudagraph_mode="NONE"`` is preferred over ``enforce_eager=True``. Both remove graph capture and replay -- the implicated mechanism -- but ``enforce_eager`` *additionally* disables ``torch.compile``, giving up the Inductor-compiled kernels for the whole rollout. ``cudagraph_mode`` is an independent field from ``mode`` (``CompilationMode``) in vLLM 0.25.1's ``CompilationConfig``, so ``NONE`` keeps compilation and drops only the graph layer: the strictly smaller change, and the cheaper one for a rollout whose decode is only ~12 tokens deep (cuda-graphs mainly amortise launch overhead across many decode steps, so little is being given up here, while a stall costs the watchdog's 120-180s detection window plus a process restart and engine re-init). Consequences to keep in mind: * This does not go through ``vllm_config``, which is a frozen smoke-gate key (``smoke_gate.FROZEN_COMMON_KEYS``). The frozen common contract stays byte-identical, so this needs only a re-freeze at the new commit, not a re-smoke -- the same reasoning as the ``reload_weights`` skip in ``eafc6a5``. * Sampling is unchanged in intent (seed, prompt, sampling params, batch sizes are untouched), but disabling graph capture removes vLLM's padding of decode batches up to captured graph sizes, so reduction shapes can differ and completions are not guaranteed bit-identical to a cuda-graph run. Introduce it at an arm boundary rather than mid-arm when that matters. * Because the knob is not part of ``vllm_config``, the run manifest cannot distinguish the two settings; the applied state is logged at ``INFO`` into ``queue.log`` instead, and is pinned by ``code_commit`` for the default. Set ``EXPLICIT_VLLM_CUDAGRAPHS=1`` to restore upstream cuda-graph behaviour (accepting the hang risk), which is what an A/B measurement of the throughput cost or a confirmation of the root cause wants. This module deliberately imports no ``torch`` / ``trl`` / ``vllm`` so the policy stays unit-testable in the CPU test venv; ``aligned_grpo`` applies it. """ from __future__ import annotations import contextlib import importlib import logging from collections.abc import Iterator, Mapping from typing import Any logger = logging.getLogger(__name__) CUDAGRAPH_ENV_VAR = "EXPLICIT_VLLM_CUDAGRAPHS" TRL_VLLM_MODULE = "trl.generation.vllm_generation" _TRUTHY = frozenset({"1", "true", "yes", "on"}) # vLLM 0.25.1 ``CompilationConfig.cudagraph_mode``; ``"NONE"`` means no # cudagraph capture. Passed as a plain dict because ``LLM()`` accepts # ``int | dict | CompilationConfig`` and validates a string enum name via # ``CUDAGraphMode[value.upper()]`` -- so we need not import vllm here. _NO_CUDAGRAPH_COMPILATION_CONFIG: Mapping[str, Any] = {"cudagraph_mode": "NONE"} def cudagraphs_enabled(env: Mapping[str, str]) -> bool: """Whether the rollout engine should keep upstream cuda-graph behaviour. Defaults to ``False`` (graphs disabled): unattended long runs must not pay the deadlock retry tax. ``EXPLICIT_VLLM_CUDAGRAPHS`` opts back in. """ return (env.get(CUDAGRAPH_ENV_VAR) or "").strip().lower() in _TRUTHY def rollout_engine_kwargs(env: Mapping[str, str]) -> dict[str, Any]: """Extra ``LLM(...)`` kwargs for TRL's colocate rollout engine.""" if cudagraphs_enabled(env): return {} return {"compilation_config": dict(_NO_CUDAGRAPH_COMPILATION_CONFIG)} @contextlib.contextmanager def patched_rollout_engine(extra_kwargs: Mapping[str, Any]) -> Iterator[bool]: """Inject ``extra_kwargs`` into TRL's colocate ``LLM(...)`` construction. TRL imports ``LLM`` into its vLLM generation module at import time (guarded by ``is_vllm_available()``), so rebinding that module attribute for the duration of engine construction is enough to reach the single call site. Kwargs TRL passes explicitly always win, so this can only *add* settings that TRL leaves at their vLLM default. Yields whether the patch was installed, and always restores the original binding. A missing module or absent ``LLM`` (vLLM not installed, or TRL moved the call site) is a no-op with a warning rather than a hard failure: the engine still builds, just without the override. """ if not extra_kwargs: yield False return try: module = importlib.import_module(TRL_VLLM_MODULE) except ImportError: logger.warning( "Cannot import %s; vLLM rollout-engine override NOT applied.", TRL_VLLM_MODULE ) yield False return original = getattr(module, "LLM", None) if not callable(original): logger.warning( "%s exposes no callable LLM; vLLM rollout-engine override NOT applied.", TRL_VLLM_MODULE, ) yield False return def construct_llm(*args: Any, **kwargs: Any) -> Any: return original(*args, **{**extra_kwargs, **kwargs}) # setattr/getattr rather than attribute syntax: the binding only exists when # TRL imported vLLM, so it is not part of the module's static surface. setattr(module, "LLM", construct_llm) # noqa: B010 try: yield True finally: setattr(module, "LLM", original) # noqa: B010