[9/N][warmup][DSv4] Migrate MHC TileLang kernels (#50178)
Signed-off-by: LopezCastroRoberto <rocastro@redhat.com> Signed-off-by: Roberto L. Castro <38211239+LopezCastroRoberto@users.noreply.github.com> Co-authored-by: Codex <codex@openai.com>
This commit is contained in:
co-authored by
Codex
parent
aed894c190
commit
e52be1a62d
@@ -1,211 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Warm up DeepSeek V4 mHC TileLang kernels before serving requests.
|
||||
|
||||
Ported from lucifer1004/vllm-jasl with the two env-var knobs removed
|
||||
(`VLLM_ENABLE_DEEPSEEK_V4_MHC_WARMUP`, `VLLM_DEEPSEEK_V4_MHC_WARMUP_TOKEN_SIZES`).
|
||||
Gating is intrinsic: non-DSv4 models and layers without hc_* attributes
|
||||
return early, so the warmup is a no-op except where it's needed.
|
||||
"""
|
||||
|
||||
import time
|
||||
from collections.abc import Iterable
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.tracing import instrument
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_AUTO_WARMUP_MAX_TOKENS = 16_384
|
||||
_DEFAULT_TOKEN_SIZE_CANDIDATES = (
|
||||
1,
|
||||
2,
|
||||
4,
|
||||
8,
|
||||
16,
|
||||
32,
|
||||
64,
|
||||
128,
|
||||
256,
|
||||
512,
|
||||
1024,
|
||||
2048,
|
||||
4096,
|
||||
8192,
|
||||
16_384,
|
||||
)
|
||||
|
||||
|
||||
def _normalize_token_sizes(
|
||||
token_sizes: Iterable[int],
|
||||
*,
|
||||
max_tokens: int,
|
||||
) -> list[int]:
|
||||
return sorted({size for size in token_sizes if 1 <= size <= max_tokens})
|
||||
|
||||
|
||||
def _select_mhc_warmup_token_sizes(
|
||||
*,
|
||||
max_tokens: int,
|
||||
cudagraph_capture_sizes: list[int],
|
||||
) -> list[int]:
|
||||
if max_tokens <= 0:
|
||||
return []
|
||||
|
||||
max_auto_tokens = min(max_tokens, _AUTO_WARMUP_MAX_TOKENS)
|
||||
candidates = list(_DEFAULT_TOKEN_SIZE_CANDIDATES)
|
||||
candidates.extend(cudagraph_capture_sizes)
|
||||
candidates.append(max_auto_tokens)
|
||||
return _normalize_token_sizes(candidates, max_tokens=max_auto_tokens)
|
||||
|
||||
|
||||
def _find_first_mhc_layer(model: torch.nn.Module) -> torch.nn.Module | None:
|
||||
for module in model.modules():
|
||||
if module.__class__.__name__ != "DeepseekV4DecoderLayer":
|
||||
continue
|
||||
if all(
|
||||
hasattr(module, attr)
|
||||
for attr in (
|
||||
"hc_pre",
|
||||
"hc_post",
|
||||
"hc_attn_fn",
|
||||
"hc_attn_scale",
|
||||
"hc_attn_base",
|
||||
"hc_ffn_fn",
|
||||
"hc_ffn_scale",
|
||||
"hc_ffn_base",
|
||||
)
|
||||
):
|
||||
return module
|
||||
return None
|
||||
|
||||
|
||||
def _find_deepseek_v4_model(model: torch.nn.Module) -> torch.nn.Module | None:
|
||||
for module in model.modules():
|
||||
if module.__class__.__name__ != "DeepseekV4Model":
|
||||
continue
|
||||
if all(
|
||||
hasattr(module, attr)
|
||||
for attr in ("hc_head_fn", "hc_head_scale", "hc_head_base")
|
||||
):
|
||||
return module
|
||||
return None
|
||||
|
||||
|
||||
def _warmup_layer_mhc(
|
||||
layer: torch.nn.Module,
|
||||
token_sizes: list[int],
|
||||
) -> None:
|
||||
max_tokens = max(token_sizes)
|
||||
hidden_size = int(layer.hidden_size)
|
||||
hc_mult = int(layer.hc_mult)
|
||||
device = layer.hc_attn_fn.device
|
||||
residual = torch.zeros(
|
||||
max_tokens,
|
||||
hc_mult,
|
||||
hidden_size,
|
||||
dtype=torch.bfloat16,
|
||||
device=device,
|
||||
)
|
||||
|
||||
for size in token_sizes:
|
||||
residual_slice = residual[:size]
|
||||
for fn, scale, base in (
|
||||
(layer.hc_attn_fn, layer.hc_attn_scale, layer.hc_attn_base),
|
||||
(layer.hc_ffn_fn, layer.hc_ffn_scale, layer.hc_ffn_base),
|
||||
):
|
||||
layer_input, post_mix, comb_mix = layer.hc_pre(
|
||||
residual_slice,
|
||||
fn,
|
||||
scale,
|
||||
base,
|
||||
)
|
||||
layer.hc_post(layer_input, residual_slice, post_mix, comb_mix)
|
||||
|
||||
|
||||
def _warmup_hc_head(
|
||||
model: torch.nn.Module,
|
||||
token_sizes: list[int],
|
||||
) -> None:
|
||||
# Upstream a8887c208 ("[DSV4] aiter mhc support (ROCm)") refactored
|
||||
# ``hc_head`` from a free function into the ``HCHeadOp`` CustomOp
|
||||
# instance attached to the model as ``hc_head_op``. We call through
|
||||
# that instance so the warmup exercises the same dispatched
|
||||
# implementation as the inference path.
|
||||
hc_head_op = getattr(model, "hc_head_op", None)
|
||||
if hc_head_op is None:
|
||||
return
|
||||
|
||||
max_tokens = max(token_sizes)
|
||||
hidden_size = int(model.config.hidden_size)
|
||||
hc_mult = int(model.hc_mult)
|
||||
device = model.hc_head_fn.device
|
||||
hidden_states = torch.zeros(
|
||||
max_tokens,
|
||||
hc_mult,
|
||||
hidden_size,
|
||||
dtype=torch.bfloat16,
|
||||
device=device,
|
||||
)
|
||||
|
||||
for size in token_sizes:
|
||||
hc_head_op(
|
||||
hidden_states[:size],
|
||||
model.hc_head_fn,
|
||||
model.hc_head_scale,
|
||||
model.hc_head_base,
|
||||
model.rms_norm_eps,
|
||||
model.hc_eps,
|
||||
)
|
||||
|
||||
|
||||
@instrument(span_name="DeepSeek V4 mHC warmup")
|
||||
def deepseek_v4_mhc_warmup(
|
||||
model: torch.nn.Module,
|
||||
*,
|
||||
max_tokens: int,
|
||||
cudagraph_capture_sizes: list[int] | None = None,
|
||||
) -> None:
|
||||
# Cheap model-type gate before walking ``model.modules()``. The class
|
||||
# walk below is O(num_layers) and shows up in startup time on very
|
||||
# large checkpoints; bail out for any model that is not DeepSeek V4.
|
||||
config = getattr(model, "config", None)
|
||||
model_type = getattr(config, "model_type", None) if config is not None else None
|
||||
if model_type is not None and model_type not in (
|
||||
"deepseek_v4",
|
||||
"deepseek_v41",
|
||||
):
|
||||
return
|
||||
|
||||
layer = _find_first_mhc_layer(model)
|
||||
if layer is None:
|
||||
return
|
||||
|
||||
device = layer.hc_attn_fn.device
|
||||
if device.type != "cuda":
|
||||
return
|
||||
|
||||
deepseek_model = _find_deepseek_v4_model(model)
|
||||
token_sizes = _select_mhc_warmup_token_sizes(
|
||||
max_tokens=max_tokens,
|
||||
cudagraph_capture_sizes=cudagraph_capture_sizes or [],
|
||||
)
|
||||
if not token_sizes:
|
||||
return
|
||||
|
||||
started = time.perf_counter()
|
||||
logger.info(
|
||||
"Warming up DeepSeek V4 mHC TileLang kernels for token sizes: %s",
|
||||
token_sizes,
|
||||
)
|
||||
with torch.inference_mode():
|
||||
_warmup_layer_mhc(layer, token_sizes)
|
||||
if deepseek_model is not None:
|
||||
_warmup_hc_head(deepseek_model, token_sizes)
|
||||
torch.accelerator.synchronize()
|
||||
logger.info(
|
||||
"DeepSeek V4 mHC TileLang warmup finished in %.2f seconds.",
|
||||
time.perf_counter() - started,
|
||||
)
|
||||
@@ -0,0 +1,172 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Compile-only helpers for TileLang JIT warmup."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from abc import abstractmethod
|
||||
from collections.abc import Callable, Iterator, Mapping, MutableMapping
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass, field
|
||||
from functools import wraps
|
||||
from typing import Any, ClassVar, Generic, TypeAlias, TypeVar, cast
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.model_executor.warmup.jit_warmup import VllmJitKernel
|
||||
|
||||
CompileKeyT = TypeVar("CompileKeyT")
|
||||
# (kernel_args, launch_args), optionally followed by keywords and a result.
|
||||
TileLangLaunchSpec: TypeAlias = (
|
||||
tuple[tuple[Any, ...], tuple[Any, ...]]
|
||||
| tuple[tuple[Any, ...], tuple[Any, ...], Mapping[str, Any] | None]
|
||||
| tuple[tuple[Any, ...], tuple[Any, ...], Mapping[str, Any] | None, Any]
|
||||
)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _quiet_tilelang_warmup_logs() -> Iterator[None]:
|
||||
loggers = [
|
||||
logging.getLogger("tilelang.cache.kernel_cache"),
|
||||
logging.getLogger("tilelang.jit.kernel"),
|
||||
]
|
||||
previous_levels = [logger.level for logger in loggers]
|
||||
try:
|
||||
for logger in loggers:
|
||||
logger.setLevel(logging.ERROR)
|
||||
yield
|
||||
finally:
|
||||
for logger, level in zip(loggers, previous_levels):
|
||||
logger.setLevel(level)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TileLangWarmupTensor:
|
||||
"""Minimal tensor-like object accepted by TileLang compile().
|
||||
|
||||
TileLang builds its cache key and TIR from tensor dtype, shape and stride.
|
||||
This object deliberately has no storage, so compile-only warmup does not
|
||||
allocate GPU memory and does not launch the kernel.
|
||||
"""
|
||||
|
||||
dtype: torch.dtype
|
||||
shape: tuple[int, ...] = (1,)
|
||||
strides: tuple[int, ...] | None = field(default=None)
|
||||
|
||||
def stride(self) -> tuple[int, ...]:
|
||||
if self.strides is not None:
|
||||
return self.strides
|
||||
|
||||
strides: list[int] = []
|
||||
stride = 1
|
||||
for size in reversed(self.shape):
|
||||
strides.append(stride)
|
||||
stride *= size
|
||||
return tuple(reversed(strides))
|
||||
|
||||
def new_empty(
|
||||
self,
|
||||
shape: tuple[int, ...],
|
||||
*,
|
||||
dtype: torch.dtype | None = None,
|
||||
device: Any = None,
|
||||
) -> TileLangWarmupTensor:
|
||||
return TileLangWarmupTensor(dtype or self.dtype, shape)
|
||||
|
||||
|
||||
def make_tilelang_warmup_tensor(
|
||||
dtype: torch.dtype,
|
||||
*shape: int,
|
||||
strides: tuple[int, ...] | None = None,
|
||||
) -> TileLangWarmupTensor:
|
||||
return TileLangWarmupTensor(dtype=dtype, shape=tuple(shape), strides=strides)
|
||||
|
||||
|
||||
def _tilelang_call_kwargs(kwargs: dict[str, Any]) -> dict[str, Any]:
|
||||
call_kwargs = dict(kwargs)
|
||||
tune_params = call_kwargs.pop("__tune_params", {})
|
||||
if isinstance(tune_params, dict):
|
||||
call_kwargs.update(tune_params)
|
||||
return call_kwargs
|
||||
|
||||
|
||||
def compile_tilelang(jit_impl: Any, *args: Any, **kwargs: Any) -> None:
|
||||
"""Compile one TileLang specialization and populate its call cache.
|
||||
|
||||
TileLang's ``compile()`` materializes the kernel without launching it.
|
||||
We also store the compiled kernel in ``_kernel_cache`` using the same
|
||||
parsed key as ``__call__`` so runtime does not report a cache miss for an
|
||||
already materialized specialization.
|
||||
"""
|
||||
|
||||
with _quiet_tilelang_warmup_logs():
|
||||
compiled = jit_impl.compile(*args, **kwargs)
|
||||
func = getattr(jit_impl, "func", None)
|
||||
parse_args = getattr(func, "parse_args", None)
|
||||
cache = getattr(jit_impl, "_kernel_cache", None)
|
||||
if not callable(parse_args) or not isinstance(cache, MutableMapping):
|
||||
return
|
||||
|
||||
key, _ = parse_args(*args, **_tilelang_call_kwargs(kwargs))
|
||||
cache[key] = compiled
|
||||
|
||||
|
||||
class VllmTileLangJitKernel(VllmJitKernel[CompileKeyT], Generic[CompileKeyT]):
|
||||
"""TileLang owner whose runtime launch specification is reused for warmup."""
|
||||
|
||||
kernel: ClassVar[Any]
|
||||
_warming_key: CompileKeyT | None = None
|
||||
|
||||
@abstractmethod
|
||||
def warmup_inputs(self, compile_key: CompileKeyT) -> dict[str, Any]:
|
||||
"""Return runtime-shaped inputs that reproduce one compile key."""
|
||||
raise NotImplementedError
|
||||
|
||||
def compile(self, compile_key: CompileKeyT) -> None:
|
||||
self._warming_key = compile_key
|
||||
try:
|
||||
cast(Callable[..., Any], self)(**self.warmup_inputs(compile_key))
|
||||
finally:
|
||||
self._warming_key = None
|
||||
|
||||
def launch(
|
||||
self,
|
||||
jit_impl: Any,
|
||||
args: tuple[Any, ...],
|
||||
kwargs: Mapping[str, Any] | None = None,
|
||||
) -> Any:
|
||||
call_kwargs = dict(kwargs or {})
|
||||
if self._warming_key is not None:
|
||||
return compile_tilelang(jit_impl, *args, **call_kwargs)
|
||||
return jit_impl(*args, **call_kwargs)
|
||||
|
||||
|
||||
def kernel_launcher(
|
||||
call_fn: Callable[..., TileLangLaunchSpec],
|
||||
) -> Callable[..., Any]:
|
||||
"""Launch TileLang from declarative kernel and runtime argument tuples."""
|
||||
|
||||
@wraps(call_fn)
|
||||
def wrapper(
|
||||
self: VllmTileLangJitKernel[Any],
|
||||
*args: Any,
|
||||
**kwargs: Any,
|
||||
) -> Any:
|
||||
launch_spec = call_fn(self, *args, **kwargs)
|
||||
kernel_args, launch_args = launch_spec[:2]
|
||||
if self._warming_key is not None and kernel_args not in (
|
||||
(),
|
||||
(self._warming_key,),
|
||||
):
|
||||
raise RuntimeError(
|
||||
"TileLang warmup inputs produced a different compile key: "
|
||||
f"expected {self._warming_key!r}, got kernel arguments "
|
||||
f"{kernel_args!r}"
|
||||
)
|
||||
launch_kwargs = launch_spec[2] if len(launch_spec) > 2 else None
|
||||
output = launch_spec[3] if len(launch_spec) > 3 else None
|
||||
result = self.launch(self.kernel(*kernel_args), launch_args, launch_kwargs)
|
||||
return output if len(launch_spec) > 3 else result
|
||||
|
||||
return wrapper
|
||||
@@ -17,9 +17,6 @@ from vllm.logger import init_logger
|
||||
from vllm.model_executor.warmup.b12x_warmup import b12x_warmup
|
||||
from vllm.model_executor.warmup.cutedsl_warmup import cutedsl_warmup
|
||||
from vllm.model_executor.warmup.deep_gemm_warmup import deep_gemm_warmup
|
||||
from vllm.model_executor.warmup.deepseek_v4_mhc_warmup import (
|
||||
deepseek_v4_mhc_warmup,
|
||||
)
|
||||
from vllm.model_executor.warmup.flashinfer_autotune_cache import (
|
||||
resolve_flashinfer_autotune_file,
|
||||
write_flashinfer_autotune_cache,
|
||||
@@ -197,15 +194,6 @@ def kernel_warmup(worker: "Worker", *, process_local_only: bool = False):
|
||||
compilation_config = worker.vllm_config.compilation_config
|
||||
cudagraph_capture_sizes = list(compilation_config.cudagraph_capture_sizes or [])
|
||||
|
||||
# DSv4 mHC TileLang kernels (hc_pre/hc_post/hc_head_op) run every decoder
|
||||
# layer per token; warm them across token sizes first so the first real
|
||||
# request doesn't pay JIT cost. No-op for non-DSv4 models (gated inside).
|
||||
deepseek_v4_mhc_warmup(
|
||||
worker.get_model(),
|
||||
max_tokens=worker.scheduler_config.max_num_batched_tokens,
|
||||
cudagraph_capture_sizes=cudagraph_capture_sizes,
|
||||
)
|
||||
|
||||
# Run next so input-prep kernels JIT against pristine runner state.
|
||||
if enable_jit_warmup:
|
||||
kimi_k3_triton_warmup(worker)
|
||||
|
||||
Reference in New Issue
Block a user