From dfd049e9ae4d0808ea76ef2cfe701173bd76550b Mon Sep 17 00:00:00 2001 From: LopezCastroRoberto Date: Tue, 21 Jul 2026 05:52:11 -0400 Subject: [PATCH 01/12] deprecate old cutedsl warmup and migrate inkling to new warmup contract Signed-off-by: LopezCastroRoberto --- vllm/config/kernel.py | 8 +- vllm/model_executor/warmup/cutedsl_warmup.py | 117 ---- .../warmup/fa4_cutedsl_warmup.py | 21 + vllm/model_executor/warmup/jit_warmup.py | 568 ++++++++++++++++++ vllm/model_executor/warmup/kernel_warmup.py | 9 +- vllm/models/inkling/nvidia/attention.py | 38 +- vllm/models/inkling/nvidia/ops/fa4_warmup.py | 387 ++++++++---- 7 files changed, 886 insertions(+), 262 deletions(-) delete mode 100644 vllm/model_executor/warmup/cutedsl_warmup.py create mode 100644 vllm/model_executor/warmup/fa4_cutedsl_warmup.py create mode 100644 vllm/model_executor/warmup/jit_warmup.py diff --git a/vllm/config/kernel.py b/vllm/config/kernel.py index f13562f59c0e..80080f59db04 100644 --- a/vllm/config/kernel.py +++ b/vllm/config/kernel.py @@ -175,8 +175,8 @@ class KernelConfig: enable_flashinfer_autotune: bool = None # type: ignore[assignment] """If True, run FlashInfer autotuning during kernel warmup.""" - enable_cutedsl_warmup: bool = True - """If True, run CuTeDSL compile warmup during kernel warmup.""" + enable_jit_warmup: bool = True + """If True, run JIT compile warmup during kernel warmup.""" enable_bf16x3_router_gemm: bool = False """If True, use the experimental SM100 BF16x3 CuteDSL router GEMM.""" @@ -249,7 +249,7 @@ def compute_hash(self) -> str: Any future fields that don't affect compilation should be excluded. """ ignored_factors = { - "enable_cutedsl_warmup", + "enable_jit_warmup", "enable_flashinfer_autotune", "ir_op_priority", # handled separately below } @@ -259,7 +259,7 @@ def compute_hash(self) -> str: @field_validator( "enable_flashinfer_autotune", - "enable_cutedsl_warmup", + "enable_jit_warmup", mode="wrap", ) @classmethod diff --git a/vllm/model_executor/warmup/cutedsl_warmup.py b/vllm/model_executor/warmup/cutedsl_warmup.py deleted file mode 100644 index 991eab22b8a8..000000000000 --- a/vllm/model_executor/warmup/cutedsl_warmup.py +++ /dev/null @@ -1,117 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""Run registered CuTeDSL warmup compile units.""" - -from __future__ import annotations - -import time -import weakref -from collections.abc import Callable, Hashable, Iterable -from dataclasses import dataclass - -import torch -from tqdm import tqdm - -from vllm.distributed import is_global_first_rank -from vllm.logger import init_logger -from vllm.platforms import current_platform -from vllm.tracing import instrument - -logger = init_logger(__name__) - -CuTeDSLCompileFn = Callable[[], None] - - -@dataclass(frozen=True) -class CuTeDSLCompileUnit: - name: str - key: Hashable - compile: CuTeDSLCompileFn - - -_CUTEDSL_WARMUP_PROVIDERS: weakref.WeakSet[object] = weakref.WeakSet() - - -def register_cutedsl_warmup_provider(provider: object) -> None: - """Register an object that can expose CuTeDSL warmup compile units.""" - _CUTEDSL_WARMUP_PROVIDERS.add(provider) - - -# Yield compile units from registered providers. -def _iter_cutedsl_warmup_compile_units() -> Iterable[CuTeDSLCompileUnit]: - for provider in tuple(_CUTEDSL_WARMUP_PROVIDERS): - get_units = getattr(provider, "get_cutedsl_warmup_compile_units", None) - if not callable(get_units): - continue - - compile_units = get_units() - if compile_units is None: - continue - for unit in compile_units: - if not isinstance(unit, CuTeDSLCompileUnit): - raise TypeError( - "get_cutedsl_warmup_compile_units must return " - "CuTeDSLCompileUnit objects" - ) - yield unit - - -# Drop duplicate compile units across providers. -def _collect_unique_compile_units( - compile_units: Iterable[CuTeDSLCompileUnit], -) -> list[CuTeDSLCompileUnit]: - seen: set[Hashable] = set() - unique_compile_units: list[CuTeDSLCompileUnit] = [] - - for unit in compile_units: - if unit.key in seen: - continue - - seen.add(unit.key) - unique_compile_units.append(unit) - - return unique_compile_units - - -# Execute compile units under inference mode. -def _compile_cutedsl_warmup_units( - compile_units: Iterable[CuTeDSLCompileUnit], -) -> int: - compiled = 0 - if is_global_first_rank(): - compile_units = tqdm(compile_units, desc="Compiling CuTeDSL kernels") - with torch.inference_mode(): - for unit in compile_units: - unit.compile() - compiled += 1 - torch.accelerator.synchronize() - return compiled - - -# Run all CuTeDSL warmup before serving. -@instrument(span_name="CuTeDSL warmup") -def cutedsl_warmup() -> None: - """Run CuTeDSL compile providers before serving.""" - if not current_platform.is_cuda(): - logger.info("Skipping CuTeDSL warmup on non-CUDA platform.") - return - - compile_units = _collect_unique_compile_units(_iter_cutedsl_warmup_compile_units()) - if not compile_units: - logger.info("Skipping CuTeDSL warmup because no compile units were requested.") - return - - unit_names = list(dict.fromkeys(unit.name for unit in compile_units)) - logger.info( - "Warming up CuTeDSL compile_units=%d names=%s.", - len(compile_units), - unit_names, - ) - - start_time = time.perf_counter() - compiled_count = _compile_cutedsl_warmup_units(compile_units) - logger.info( - "CuTeDSL warmup compiled %d units in %.2f s.", - compiled_count, - time.perf_counter() - start_time, - ) diff --git a/vllm/model_executor/warmup/fa4_cutedsl_warmup.py b/vllm/model_executor/warmup/fa4_cutedsl_warmup.py new file mode 100644 index 000000000000..777a01ababc2 --- /dev/null +++ b/vllm/model_executor/warmup/fa4_cutedsl_warmup.py @@ -0,0 +1,21 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Warm up FA4 CuTeDSL kernels owned by model modules.""" + +from __future__ import annotations + +from typing import Any, Protocol + +from torch import nn + + +class _FA4WarmupWorkerProtocol(Protocol): + def get_model(self) -> nn.Module: ... + + +def fa4_cutedsl_warmup(worker: _FA4WarmupWorkerProtocol) -> None: + seen_compile_keys: set[Any] = set() + for module in worker.get_model().modules(): + warmup_kernel = getattr(module, "fa4_rel_attention_kernel", None) + if warmup_kernel is not None: + warmup_kernel.warmup(seen_compile_keys=seen_compile_keys) diff --git a/vllm/model_executor/warmup/jit_warmup.py b/vllm/model_executor/warmup/jit_warmup.py new file mode 100644 index 000000000000..1a31abe44237 --- /dev/null +++ b/vllm/model_executor/warmup/jit_warmup.py @@ -0,0 +1,568 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Shared interfaces and tracing helpers for explicit JIT warmup keys.""" + +from __future__ import annotations + +import ast +import inspect +import itertools +import operator +import textwrap +from abc import ABC, abstractmethod +from collections.abc import Callable, Iterable, Mapping +from dataclasses import dataclass +from typing import Any, Generic, TypeVar + +__all__ = [ + "VllmJitKernel", + "WarmupIntRange", + "get_ast_full_name", + "get_function_source_node", + "zip_inputs", +] + + +CompileKeyT = TypeVar("CompileKeyT") + + +@dataclass(frozen=True) +class WarmupIntRange: + start: int + stop: int + step: int = 1 + + +WarmupValues = Any +CompileKeyDispatchFn = Callable[..., CompileKeyT] +WarmupPredicateFn = Callable[..., bool] + + +@dataclass(frozen=True) +class _WarmupInputRows: + """Warmup dispatch inputs expanded in lockstep.""" + + rows: tuple[Mapping[str, WarmupValues], ...] + + +def _expand_warmup_values(values: WarmupValues) -> tuple[Any, ...]: + if isinstance(values, WarmupIntRange): + return tuple(range(values.start, values.stop, values.step)) + if isinstance(values, (list, tuple)): + return tuple(values) + return (values,) + + +def zip_inputs(*rows: Mapping[str, WarmupValues]) -> _WarmupInputRows: + """Group row-wise dispatch inputs that should be expanded in lockstep.""" + if not rows: + raise ValueError("zip_inputs requires at least one dispatch input row") + if not all(isinstance(row, Mapping) for row in rows): + raise ValueError("zip_inputs rows must be mappings") + + first_names = frozenset(rows[0]) + if not first_names: + raise ValueError("zip_inputs rows require at least one dispatch input name") + if not all(isinstance(name, str) for name in first_names): + raise ValueError("zip_inputs dispatch input names must be strings") + + input_rows: list[Mapping[str, WarmupValues]] = [] + for row in rows: + names = frozenset(row) + if names != first_names: + raise ValueError("zip_inputs rows must use the same dispatch input names") + input_rows.append(dict(row)) + + return _WarmupInputRows(rows=tuple(input_rows)) + + +def _expand_warmup_value_grid( + values: Mapping[str, WarmupValues], + input_names: frozenset[str], +) -> tuple[dict[str, Any], ...]: + names = tuple(name for name in values if name in input_names) + if not names: + return ({},) + + expanded_values = tuple(_expand_warmup_values(values[name]) for name in names) + return tuple( + dict(zip(names, value_set)) for value_set in itertools.product(*expanded_values) + ) + + +def _expand_warmup_input_rows( + rows: tuple[Mapping[str, WarmupValues], ...], + input_names: frozenset[str], +) -> tuple[dict[str, Any], ...]: + active_names = tuple(name for name in rows[0] if name in input_names) + if not active_names: + return ({},) + + expanded_rows: list[dict[str, Any]] = [] + for row in rows: + expanded_rows.extend( + _expand_warmup_value_grid( + {name: row[name] for name in active_names}, input_names + ) + ) + return tuple(expanded_rows) + + +def _merge_warmup_kwargs(parts: Iterable[Mapping[str, Any]]) -> dict[str, Any]: + merged: dict[str, Any] = {} + for part in parts: + for name, value in part.items(): + if name in merged: + raise ValueError( + f"Warmup dispatch input '{name}' is specified more than once" + ) + merged[name] = value + return merged + + +@dataclass(frozen=True) +class _CompileKeyDispatchTrace: + local_exprs: tuple[tuple[str, ast.AST], ...] + field_exprs: tuple[tuple[str, ast.AST], ...] + globals: Mapping[str, Any] + input_names: frozenset[str] + defaults: Mapping[str, Any] + + def compile_key( + self, + compile_key_type: type[CompileKeyT], + kwargs: Mapping[str, Any], + ) -> CompileKeyT: + dispatch_values = {**self.defaults, **kwargs} + for name, expr in self.local_exprs: + dispatch_values[name] = _eval_dispatch_expr( + expr, dispatch_values, self.globals + ) + return compile_key_type( + **{ + field: _eval_dispatch_expr(expr, dispatch_values, self.globals) + for field, expr in self.field_exprs + } + ) + + +@dataclass(frozen=True) +class _WarmupPredicateTrace: + local_exprs: tuple[tuple[str, ast.AST], ...] + return_expr: ast.AST + globals: Mapping[str, Any] + input_names: frozenset[str] + defaults: Mapping[str, Any] + + def matches(self, kwargs: Mapping[str, Any]) -> bool: + dispatch_values = {**self.defaults, **kwargs} + for name, expr in self.local_exprs: + dispatch_values[name] = _eval_dispatch_expr( + expr, dispatch_values, self.globals + ) + return bool( + _eval_dispatch_expr(self.return_expr, dispatch_values, self.globals) + ) + + +_BIN_OPS: dict[type[ast.operator], Callable[[Any, Any], Any]] = { + ast.Add: operator.add, + ast.Sub: operator.sub, + ast.Mult: operator.mul, + ast.FloorDiv: operator.floordiv, + ast.Mod: operator.mod, + ast.Pow: operator.pow, +} +_CMP_OPS: dict[type[ast.cmpop], Callable[[Any, Any], bool]] = { + ast.Eq: operator.eq, + ast.NotEq: operator.ne, + ast.Lt: operator.lt, + ast.LtE: operator.le, + ast.Gt: operator.gt, + ast.GtE: operator.ge, +} + + +def _dispatch_expr_source(node: ast.AST) -> str: + try: + return ast.unparse(node) + except Exception: + return ast.dump(node) + + +def _dispatch_expr_error(node: ast.AST, reason: str) -> ValueError: + return ValueError( + f"{reason}: {_dispatch_expr_source(node)}. " + "Supported dispatch expressions are names, constants, attributes, " + "tuple/list literals, conditional expressions, comparisons, boolean " + "operators, unary not/minus, arithmetic, and calls without **kwargs." + ) + + +class _DispatchExprEvaluator(ast.NodeVisitor): + def __init__( + self, + values: Mapping[str, Any], + globals_: Mapping[str, Any], + ) -> None: + self.values = values + self.globals = globals_ + + def eval(self, node: ast.AST) -> Any: + return self.visit(node) + + def generic_visit(self, node: ast.AST) -> Any: + raise _dispatch_expr_error(node, "Unsupported dispatch expression") + + def visit_Name(self, node: ast.Name) -> Any: + if node.id in self.values: + return self.values[node.id] + if node.id in self.globals: + return self.globals[node.id] + raise _dispatch_expr_error(node, f"Unknown dispatch name '{node.id}'") + + def visit_Constant(self, node: ast.Constant) -> Any: + return node.value + + def visit_IfExp(self, node: ast.IfExp) -> Any: + return self.visit(node.body if self.visit(node.test) else node.orelse) + + def visit_Tuple(self, node: ast.Tuple) -> tuple[Any, ...]: + return tuple(self.visit(elt) for elt in node.elts) + + def visit_List(self, node: ast.List) -> list[Any]: + return [self.visit(elt) for elt in node.elts] + + def visit_BoolOp(self, node: ast.BoolOp) -> Any: + if isinstance(node.op, ast.And): + result = None + for value in node.values: + result = self.visit(value) + if not result: + return result + return result + if isinstance(node.op, ast.Or): + result = None + for value in node.values: + result = self.visit(value) + if result: + return result + return result + raise _dispatch_expr_error(node, "Unsupported dispatch boolean operator") + + def visit_Compare(self, node: ast.Compare) -> bool: + left = self.visit(node.left) + for op_node, comparator in zip(node.ops, node.comparators): + right = self.visit(comparator) + op = _CMP_OPS.get(type(op_node)) + if op is None: + raise _dispatch_expr_error( + node, "Unsupported dispatch comparison operator" + ) + if not op(left, right): + return False + left = right + return True + + def visit_UnaryOp(self, node: ast.UnaryOp) -> Any: + operand = self.visit(node.operand) + if isinstance(node.op, ast.Not): + return not operand + if isinstance(node.op, ast.USub): + return -operand + raise _dispatch_expr_error(node, "Unsupported dispatch unary operator") + + def visit_BinOp(self, node: ast.BinOp) -> Any: + op = _BIN_OPS.get(type(node.op)) + if op is None: + raise _dispatch_expr_error(node, "Unsupported dispatch binary operator") + return op(self.visit(node.left), self.visit(node.right)) + + def visit_Call(self, node: ast.Call) -> Any: + for keyword in node.keywords: + if keyword.arg is None: + raise _dispatch_expr_error( + node, "Dispatch helper calls cannot use **kwargs" + ) + + args = [self.visit(arg) for arg in node.args] + fn = self.visit(node.func) + call_kwargs: dict[str, Any] = {} + for keyword in node.keywords: + assert keyword.arg is not None + call_kwargs[keyword.arg] = self.visit(keyword.value) + return fn(*args, **call_kwargs) + + def visit_Attribute(self, node: ast.Attribute) -> Any: + return getattr(self.visit(node.value), node.attr) + + +def get_ast_full_name(node: ast.AST) -> str | None: + if isinstance(node, ast.Name): + return node.id + if isinstance(node, ast.Attribute): + parent = get_ast_full_name(node.value) + if parent is not None: + return f"{parent}.{node.attr}" + return None + + +def get_function_source_node(fn: Callable[..., Any]) -> ast.FunctionDef: + source_fn = getattr(fn, "fn", fn) + source = textwrap.dedent(inspect.getsource(source_fn)) + tree = ast.parse(source) + function_defs = [node for node in tree.body if isinstance(node, ast.FunctionDef)] + if len(function_defs) != 1: + name = getattr(source_fn, "__name__", type(source_fn).__name__) + raise ValueError(f"Expected one function in {name}, found {len(function_defs)}") + return function_defs[0] + + +def _eval_dispatch_expr( + node: ast.AST, + kwargs: Mapping[str, Any], + globals_: Mapping[str, Any], +) -> Any: + return _DispatchExprEvaluator(kwargs, globals_).eval(node) + + +def _collect_input_names( + node: ast.AST, + candidate_names: set[str], + local_names: set[str] | None = None, +) -> set[str]: + if local_names is None: + local_names = set() + return { + child.id + for child in ast.walk(node) + if ( + isinstance(child, ast.Name) + and child.id in candidate_names + and child.id not in local_names + ) + } + + +def _collect_expression_body( + fn: Callable[..., Any], + function_def: ast.FunctionDef, +) -> tuple[list[tuple[str, ast.AST]], ast.AST]: + local_exprs: list[tuple[str, ast.AST]] = [] + for statement in function_def.body: + if ( + isinstance(statement, ast.Expr) + and isinstance(statement.value, ast.Constant) + and isinstance(statement.value.value, str) + ): + continue + + if isinstance(statement, ast.Assign): + if len(statement.targets) != 1 or not isinstance( + statement.targets[0], ast.Name + ): + raise _dispatch_expr_error( + statement, "Dispatch assignments must target one local name" + ) + local_exprs.append((statement.targets[0].id, statement.value)) + continue + + if isinstance(statement, ast.AnnAssign): + if statement.value is None: + raise _dispatch_expr_error( + statement, "Dispatch annotations must assign a value" + ) + if not isinstance(statement.target, ast.Name): + raise _dispatch_expr_error( + statement, "Dispatch assignments must target one local name" + ) + local_exprs.append((statement.target.id, statement.value)) + continue + + if isinstance(statement, ast.Return) and statement.value is not None: + return local_exprs, statement.value + + if isinstance(statement, ast.Return): + raise _dispatch_expr_error( + statement, "Traced warmup helper must return an expression" + ) + + raise _dispatch_expr_error( + statement, + "Traced warmup helper may only contain local assignments before return", + ) + + raise ValueError(f"Expected {fn.__name__} to return an expression") + + +def _collect_dispatch_body( + fn: CompileKeyDispatchFn[Any], + function_def: ast.FunctionDef, +) -> tuple[list[tuple[str, ast.AST]], ast.Call]: + local_exprs, return_expr = _collect_expression_body(fn, function_def) + if not isinstance(return_expr, ast.Call): + raise _dispatch_expr_error( + return_expr, + "Dispatch must return one CompileKey(...) call", + ) + return local_exprs, return_expr + + +def _function_defaults(fn: Callable[..., Any]) -> dict[str, Any]: + signature = inspect.signature(fn) + defaults = { + name: parameter.default + for name, parameter in signature.parameters.items() + if parameter.default is not inspect.Parameter.empty + } + bound_self = getattr(fn, "__self__", None) + if bound_self is not None: + defaults["self"] = bound_self + return defaults + + +def _function_candidate_names(fn: Callable[..., Any]) -> set[str]: + return set(inspect.signature(fn).parameters) + + +def _trace_compile_key_dispatch( + fn: CompileKeyDispatchFn[Any], +) -> _CompileKeyDispatchTrace: + source_fn = getattr(fn, "__func__", fn) + globals_ = source_fn.__globals__ + function_def = get_function_source_node(fn) + + local_exprs, return_call = _collect_dispatch_body(fn, function_def) + + field_exprs: list[tuple[str, ast.AST]] = [] + defaults = _function_defaults(fn) + candidate_names = _function_candidate_names(fn) + input_names: set[str] = set() + local_names = {name for name, _ in local_exprs} + for _, expr in local_exprs: + input_names.update(_collect_input_names(expr, candidate_names)) + for keyword in return_call.keywords: + if keyword.arg is None: + raise ValueError(f"{fn.__name__} cannot use **kwargs in CompileKey") + field_exprs.append((keyword.arg, keyword.value)) + input_names.update( + _collect_input_names(keyword.value, candidate_names, local_names) + ) + + return _CompileKeyDispatchTrace( + tuple(local_exprs), + tuple(field_exprs), + globals_, + frozenset(input_names), + defaults, + ) + + +def _trace_warmup_predicate( + fn: WarmupPredicateFn, +) -> _WarmupPredicateTrace: + source_fn = getattr(fn, "__func__", fn) + globals_ = source_fn.__globals__ + function_def = get_function_source_node(fn) + + local_exprs, return_expr = _collect_expression_body(fn, function_def) + defaults = _function_defaults(fn) + candidate_names = _function_candidate_names(fn) + input_names: set[str] = set() + local_names = {name for name, _ in local_exprs} + for _, expr in local_exprs: + input_names.update(_collect_input_names(expr, candidate_names)) + input_names.update(_collect_input_names(return_expr, candidate_names, local_names)) + + return _WarmupPredicateTrace( + tuple(local_exprs), + return_expr, + globals_, + frozenset(input_names), + defaults, + ) + + +class VllmJitKernel(Generic[CompileKeyT], ABC): + """Kernel wrapper that owns dispatch, warmup keys, and compilation.""" + + CompileKey: type[CompileKeyT] + + def __init__(self) -> None: + self.compile_key_dispatch_trace = _trace_compile_key_dispatch(self.dispatch) + + def compile_key(self, kwargs: Mapping[str, Any]) -> CompileKeyT: + return self.compile_key_dispatch_trace.compile_key(self.CompileKey, kwargs) + + def _trace_dispatch( + self, dispatch: CompileKeyDispatchFn[CompileKeyT] + ) -> Callable[..., list[CompileKeyT]]: + compile_key_dispatch_trace = _trace_compile_key_dispatch(dispatch) + + def traced( + *input_groups: _WarmupInputRows, + _when: WarmupPredicateFn | None = None, + **kwargs: WarmupValues, + ) -> list[CompileKeyT]: + for group in input_groups: + if not isinstance(group, _WarmupInputRows): + raise TypeError( + "_trace_dispatch positional arguments must be " + "zip_inputs(...) groups" + ) + predicate_trace = ( + _trace_warmup_predicate(_when) if _when is not None else None + ) + input_names = compile_key_dispatch_trace.input_names + if predicate_trace is not None: + input_names = input_names | predicate_trace.input_names + expanded_input_groups = tuple( + _expand_warmup_input_rows(group.rows, input_names) + for group in input_groups + ) + expanded_kwargs = _expand_warmup_value_grid(kwargs, input_names) + dispatch_value_groups = (*expanded_input_groups, expanded_kwargs) + return list( + dict.fromkeys( + compile_key_dispatch_trace.compile_key( + self.CompileKey, dispatch_values + ) + for dispatch_value_group in itertools.product( + *dispatch_value_groups + ) + for dispatch_values in (_merge_warmup_kwargs(dispatch_value_group),) + if predicate_trace is None + or predicate_trace.matches(dispatch_values) + ) + ) + + return traced + + @abstractmethod + def dispatch(self, **kwargs: Any) -> CompileKeyT: + """Build one compile key from one concrete dispatch point.""" + raise NotImplementedError + + @abstractmethod + def get_warmup_keys(self, *args: Any, **kwargs: Any) -> list[CompileKeyT]: + """Return compile keys that should be warmed for this kernel.""" + raise NotImplementedError + + @abstractmethod + def compile(self, compile_key: CompileKeyT) -> None: + """Compile one warmup key.""" + raise NotImplementedError + + def warmup( + self, + *args: Any, + seen_compile_keys: set[CompileKeyT] | None = None, + **kwargs: Any, + ) -> None: + """Compile this kernel's warmup keys.""" + for compile_key in self.get_warmup_keys(*args, **kwargs): + if seen_compile_keys is not None: + if compile_key in seen_compile_keys: + continue + seen_compile_keys.add(compile_key) + self.compile(compile_key) diff --git a/vllm/model_executor/warmup/kernel_warmup.py b/vllm/model_executor/warmup/kernel_warmup.py index d4b9a735d2cd..b5b9a87ffbc6 100644 --- a/vllm/model_executor/warmup/kernel_warmup.py +++ b/vllm/model_executor/warmup/kernel_warmup.py @@ -12,7 +12,6 @@ import vllm.envs as envs from vllm.logger import init_logger -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, @@ -155,8 +154,12 @@ def _is_flashinfer_backend(backend): create_mixed_batch=True, ) - if worker.vllm_config.kernel_config.enable_cutedsl_warmup: - cutedsl_warmup() + if worker.vllm_config.kernel_config.enable_jit_warmup: + from vllm.model_executor.warmup.fa4_cutedsl_warmup import ( + fa4_cutedsl_warmup, + ) + + fa4_cutedsl_warmup(worker) def _flashinfer_autotune_skip_ops(runner: "GPUModelRunner") -> set[str] | None: diff --git a/vllm/models/inkling/nvidia/attention.py b/vllm/models/inkling/nvidia/attention.py index fc617b89ad6a..4f1f133adf94 100644 --- a/vllm/models/inkling/nvidia/attention.py +++ b/vllm/models/inkling/nvidia/attention.py @@ -37,9 +37,8 @@ from .ops.fa4_rel_attention import ( bucket_max_seqlen_q, inkling_fa4_num_splits, - inkling_fa4_rel_attention, ) -from .ops.fa4_warmup import InklingFA4WarmupConfig, register_fa4_warmup +from .ops.fa4_warmup import InklingFA4RelAttentionKernel from .ops.qkvr_prep import fused_qkvr_prep from .sconv_swa_attn import _K, _V, InklingConvState, InklingSconvMetadata from .short_conv import InklingShortConv @@ -174,24 +173,21 @@ def __init__( raise ValueError(f"Duplicate layer name: {prefix}") compilation_config.static_forward_context[prefix] = self self.kv_cache = torch.tensor([]) # replaced by bind_kv_cache - - register_fa4_warmup( - InklingFA4WarmupConfig( - num_heads=self.num_heads, - num_kv_heads=self.num_kv_heads, - head_dim=self.head_dim, - rel_extent=self.rel_extent, - window_size=self.window_size, - is_local=self.is_local, - max_kv_len=self._max_kv_len, - dtype=vllm_config.model_config.dtype, - kv_dtype=self.kv_cache_torch_dtype, - block_size=vllm_config.cache_config.block_size, - max_num_reqs=vllm_config.scheduler_config.max_num_seqs, - max_num_batched_tokens=( - vllm_config.scheduler_config.max_num_batched_tokens - ), - ) + self.fa4_rel_attention_kernel = InklingFA4RelAttentionKernel( + num_heads=self.num_heads, + num_kv_heads=self.num_kv_heads, + head_dim=self.head_dim, + rel_extent=self.rel_extent, + window_size=self.window_size, + is_local=self.is_local, + max_kv_len=self._max_kv_len, + dtype=vllm_config.model_config.dtype, + kv_dtype=self.kv_cache_torch_dtype, + block_size=vllm_config.cache_config.block_size, + max_num_reqs=vllm_config.scheduler_config.max_num_seqs, + max_num_batched_tokens=( + vllm_config.scheduler_config.max_num_batched_tokens + ), ) def get_attn_backend(self) -> type[AttentionBackend]: @@ -309,7 +305,7 @@ def _attention( num_kv_heads=self.num_kv_heads, max_kv_len=self._max_kv_len, ) - inkling_fa4_rel_attention( + self.fa4_rel_attention_kernel( q[:nt], key_cache, value_cache, diff --git a/vllm/models/inkling/nvidia/ops/fa4_warmup.py b/vllm/models/inkling/nvidia/ops/fa4_warmup.py index ff8cdb029362..2aa67818d9f0 100644 --- a/vllm/models/inkling/nvidia/ops/fa4_warmup.py +++ b/vllm/models/inkling/nvidia/ops/fa4_warmup.py @@ -4,15 +4,13 @@ from __future__ import annotations -from collections.abc import Iterator from dataclasses import dataclass -from functools import partial import torch -from vllm.model_executor.warmup.cutedsl_warmup import ( - CuTeDSLCompileUnit, - register_cutedsl_warmup_provider, +from vllm.model_executor.warmup.jit_warmup import ( + VllmJitKernel, + WarmupIntRange, ) from .fa4_rel_attention import ( @@ -22,133 +20,288 @@ ) -@dataclass(frozen=True) -class InklingFA4WarmupConfig: - num_heads: int - num_kv_heads: int - head_dim: int - rel_extent: int - window_size: tuple[int, int] - is_local: bool - max_kv_len: int - dtype: torch.dtype - kv_dtype: torch.dtype - block_size: int - max_num_reqs: int - max_num_batched_tokens: int - - -def _num_warps_bucket(num_reqs: int) -> int: - num_warps = min((num_reqs + 30) // 31, 32) - return 1 << (num_warps - 1).bit_length() - - -def _compile(config: InklingFA4WarmupConfig, max_seqlen_q: int, num_reqs: int) -> None: +def _compile_fa4_rel_attention_from_specs( + *, + q_shape: tuple[int, ...], + key_cache_shape: tuple[int, ...], + value_cache_shape: tuple[int, ...], + block_table_shape: tuple[int, ...], + cache_seqlens_shape: tuple[int, ...], + cu_seqlens_q_shape: tuple[int, ...], + rel_logits_shape: tuple[int, ...], + q_dtype: torch.dtype, + kv_dtype: torch.dtype, + max_seqlen_q: int, + softmax_scale: float, + causal: bool, + window_size: tuple[int, int], + num_splits: int, +) -> None: + """Compile TML FA4 via fake tensors without launching a kernel.""" from torch._subclasses.fake_tensor import FakeTensorMode - num_splits = inkling_fa4_num_splits( - is_local=config.is_local, - batch_size=num_reqs, - max_query_len=max_seqlen_q, - num_heads=config.num_heads, - num_kv_heads=config.num_kv_heads, - max_kv_len=config.max_kv_len, - ) + from vllm.third_party.tml_fa4 import flash_attn_varlen_func + + cute_window = (None, None) if window_size == (-1, -1) else window_size + # FakeTensorMode carries shape, dtype, stride, and device metadata into TML + # FA4 so the JIT can build the specialization without allocating real inputs + # or running the kernel body. This is not a dummy runtime launch. with FakeTensorMode(): device = torch.accelerator.current_accelerator() - total_q = max_seqlen_q + num_reqs - 1 - q = torch.empty( - total_q, - config.num_heads, - config.head_dim, - dtype=config.dtype, - device=device, - ) - kv = torch.empty( - 1, - 2, - config.block_size, - config.num_kv_heads, - config.head_dim, - dtype=config.kv_dtype, - device=device, - ) - key_cache, value_cache = kv.unbind(1) - inkling_fa4_rel_attention( - q, - key_cache, - value_cache, - block_table=torch.empty(num_reqs, 1, dtype=torch.int32, device=device), - cache_seqlens=torch.empty(num_reqs, dtype=torch.int32, device=device), - cu_seqlens_q=torch.empty(num_reqs + 1, dtype=torch.int32, device=device), + q = torch.empty(q_shape, dtype=q_dtype, device=device) + key_cache = torch.empty(key_cache_shape, dtype=kv_dtype, device=device) + value_cache = torch.empty(value_cache_shape, dtype=kv_dtype, device=device) + rel_logits = torch.empty(rel_logits_shape, dtype=q_dtype, device=device) + flash_attn_varlen_func( + q=q, + k=key_cache, + v=value_cache, + cu_seqlens_q=torch.empty( + cu_seqlens_q_shape, + dtype=torch.int32, + device=device, + ), + seqused_k=torch.empty( + cache_seqlens_shape, + dtype=torch.int32, + device=device, + ), max_seqlen_q=max_seqlen_q, - softmax_scale=1.0 / config.head_dim, - causal=True, - window_size=config.window_size, - rel_extent=config.rel_extent, - rel_logits=torch.empty( - total_q, - config.num_heads, - config.rel_extent, - dtype=config.dtype, + page_table=torch.empty( + block_table_shape, + dtype=torch.int32, device=device, ), + softmax_scale=softmax_scale, + causal=causal, + window_size=cute_window, num_splits=num_splits, + return_lse=False, out=torch.empty_like(q), + rel_bias=rel_logits.contiguous(), ) -def _iter_compile_units( - config: InklingFA4WarmupConfig, -) -> Iterator[CuTeDSLCompileUnit]: - max_bucket = bucket_max_seqlen_q(config.max_num_batched_tokens) - max_seqlen_q = 1 - while max_seqlen_q <= max_bucket: - min_query_len = max_seqlen_q // 2 + 1 - max_num_reqs = min( - config.max_num_reqs, - config.max_num_batched_tokens - min_query_len + 1, +def _num_warps_bucket(num_reqs: int) -> int: + num_warps = min((num_reqs + 30) // 31, 32) + return 1 << (num_warps - 1).bit_length() + + +def _materialized_num_reqs( + num_splits: int, + num_warps_bucket: int | None, + large_num_reqs: bool, +) -> int: + if num_splits == 1 or num_warps_bucket is None: + return 1025 if large_num_reqs else 1 + + min_num_warps = 1 if num_warps_bucket == 1 else num_warps_bucket // 2 + 1 + min_num_reqs = (min_num_warps - 1) * 31 + 1 + return max(min_num_reqs, 1025 if large_num_reqs else 1) + + +class InklingFA4RelAttentionKernel( + VllmJitKernel["InklingFA4RelAttentionKernel.CompileKey"] +): + def __init__( + self, + *, + num_heads: int, + num_kv_heads: int, + head_dim: int, + rel_extent: int, + window_size: tuple[int, int], + is_local: bool, + max_kv_len: int, + dtype: torch.dtype, + kv_dtype: torch.dtype, + block_size: int, + max_num_reqs: int, + max_num_batched_tokens: int, + ) -> None: + self.num_heads = num_heads + self.num_kv_heads = num_kv_heads + self.head_dim = head_dim + self.rel_extent = rel_extent + self.window_size = window_size + self.is_local = is_local + self.max_kv_len = max_kv_len + self.dtype = dtype + self.kv_dtype = kv_dtype + self.block_size = block_size + self.max_num_reqs = max_num_reqs + self.max_num_batched_tokens = max_num_batched_tokens + super().__init__() + + @dataclass(frozen=True) + class CompileKey: + num_heads: int + num_kv_heads: int + head_dim: int + rel_extent: int + dtype: torch.dtype + kv_dtype: torch.dtype + block_size: int + window_size: tuple[int, int] + max_seqlen_q: int + num_splits: int + num_warps_bucket: int | None + large_num_reqs: bool + + def dispatch( # type: ignore[override] + self, + *, + query_len: int, + num_reqs: int, + ) -> CompileKey: + max_seqlen_q = bucket_max_seqlen_q(query_len) + num_splits = inkling_fa4_num_splits( + is_local=self.is_local, + batch_size=num_reqs, + max_query_len=max_seqlen_q, + num_heads=self.num_heads, + num_kv_heads=self.num_kv_heads, + max_kv_len=self.max_kv_len, ) - seen: set[tuple[int, int, int | None, bool]] = set() - for num_reqs in range(1, max_num_reqs + 1): - num_splits = inkling_fa4_num_splits( - is_local=config.is_local, - batch_size=num_reqs, - max_query_len=max_seqlen_q, - num_heads=config.num_heads, - num_kv_heads=config.num_kv_heads, - max_kv_len=config.max_kv_len, - ) - key = ( - max_seqlen_q, - num_splits, - _num_warps_bucket(num_reqs) if num_splits > 1 else None, - num_reqs > 1024, - ) - if key in seen: - continue - seen.add(key) - yield CuTeDSLCompileUnit( - name="inkling_fa4", - key=("inkling_fa4", config, key), - compile=partial(_compile, config, max_seqlen_q, num_reqs), - ) - max_seqlen_q *= 2 - - -class _WarmupProvider: - def __init__(self) -> None: - self.configs: set[InklingFA4WarmupConfig] = set() - - def get_cutedsl_warmup_compile_units(self) -> tuple[CuTeDSLCompileUnit, ...]: - return tuple( - unit for config in self.configs for unit in _iter_compile_units(config) + return self.CompileKey( + num_heads=self.num_heads, + num_kv_heads=self.num_kv_heads, + head_dim=self.head_dim, + rel_extent=self.rel_extent, + dtype=self.dtype, + kv_dtype=self.kv_dtype, + block_size=self.block_size, + window_size=self.window_size, + max_seqlen_q=max_seqlen_q, + num_splits=num_splits, + num_warps_bucket=(_num_warps_bucket(num_reqs) if num_splits > 1 else None), + large_num_reqs=num_reqs > 1024, ) + def _is_valid_warmup_dispatch( + self, + *, + query_len: int, + num_reqs: int, + ) -> bool: + max_seqlen_q = bucket_max_seqlen_q(query_len) + min_query_len = 1 if max_seqlen_q == 1 else max_seqlen_q // 2 + 1 + return min_query_len + num_reqs <= self.max_num_batched_tokens + 1 + + def get_warmup_keys(self) -> list[CompileKey]: + if self.max_num_reqs <= 0 or self.max_num_batched_tokens <= 0: + return [] + + return self._trace_dispatch(self.dispatch)( + query_len=WarmupIntRange(1, self.max_num_batched_tokens + 1), + num_reqs=WarmupIntRange(1, self.max_num_reqs + 1), + _when=self._is_valid_warmup_dispatch, + ) -_PROVIDER = _WarmupProvider() + def compile(self, compile_key: CompileKey) -> None: + num_reqs = _materialized_num_reqs( + compile_key.num_splits, + compile_key.num_warps_bucket, + compile_key.large_num_reqs, + ) + total_q = compile_key.max_seqlen_q + num_reqs - 1 + _compile_fa4_rel_attention_from_specs( + q_shape=(total_q, compile_key.num_heads, compile_key.head_dim), + key_cache_shape=( + 1, + compile_key.block_size, + compile_key.num_kv_heads, + compile_key.head_dim, + ), + value_cache_shape=( + 1, + compile_key.block_size, + compile_key.num_kv_heads, + compile_key.head_dim, + ), + block_table_shape=(num_reqs, 1), + cache_seqlens_shape=(num_reqs,), + cu_seqlens_q_shape=(num_reqs + 1,), + rel_logits_shape=( + total_q, + compile_key.num_heads, + compile_key.rel_extent, + ), + q_dtype=compile_key.dtype, + kv_dtype=compile_key.kv_dtype, + max_seqlen_q=compile_key.max_seqlen_q, + softmax_scale=compile_key.head_dim**-1, + causal=True, + window_size=compile_key.window_size, + num_splits=compile_key.num_splits, + ) + @staticmethod + def kernel( + q: torch.Tensor, + key_cache: torch.Tensor, + value_cache: torch.Tensor, + *, + block_table: torch.Tensor, + cache_seqlens: torch.Tensor, + cu_seqlens_q: torch.Tensor, + max_seqlen_q: int, + softmax_scale: float, + causal: bool, + window_size: tuple[int, int], + rel_extent: int, + rel_logits: torch.Tensor, + num_splits: int = 32, + out: torch.Tensor | None = None, + ) -> torch.Tensor: + return inkling_fa4_rel_attention( + q, + key_cache, + value_cache, + block_table=block_table, + cache_seqlens=cache_seqlens, + cu_seqlens_q=cu_seqlens_q, + max_seqlen_q=max_seqlen_q, + softmax_scale=softmax_scale, + causal=causal, + window_size=window_size, + rel_extent=rel_extent, + rel_logits=rel_logits, + num_splits=num_splits, + out=out, + ) -def register_fa4_warmup(config: InklingFA4WarmupConfig) -> None: - _PROVIDER.configs.add(config) - register_cutedsl_warmup_provider(_PROVIDER) + def __call__( + self, + q: torch.Tensor, + key_cache: torch.Tensor, + value_cache: torch.Tensor, + *, + block_table: torch.Tensor, + cache_seqlens: torch.Tensor, + cu_seqlens_q: torch.Tensor, + max_seqlen_q: int, + softmax_scale: float, + causal: bool, + window_size: tuple[int, int], + rel_extent: int, + rel_logits: torch.Tensor, + num_splits: int = 32, + out: torch.Tensor | None = None, + ) -> torch.Tensor: + return self.kernel( + q, + key_cache, + value_cache, + block_table=block_table, + cache_seqlens=cache_seqlens, + cu_seqlens_q=cu_seqlens_q, + max_seqlen_q=max_seqlen_q, + softmax_scale=softmax_scale, + causal=causal, + window_size=window_size, + rel_extent=rel_extent, + rel_logits=rel_logits, + num_splits=num_splits, + out=out, + ) From 6e997e31a11e88a29dd6f9087f40ea3dcc9cef83 Mon Sep 17 00:00:00 2001 From: LopezCastroRoberto Date: Tue, 21 Jul 2026 07:19:57 -0400 Subject: [PATCH 02/12] update Signed-off-by: LopezCastroRoberto --- .../warmup/fa4_cutedsl_warmup.py | 18 ++- vllm/models/inkling/nvidia/attention.py | 20 +-- vllm/models/inkling/nvidia/ops/fa4_warmup.py | 136 ++++++++++++------ 3 files changed, 103 insertions(+), 71 deletions(-) diff --git a/vllm/model_executor/warmup/fa4_cutedsl_warmup.py b/vllm/model_executor/warmup/fa4_cutedsl_warmup.py index 433be4f3df53..21511db64d84 100644 --- a/vllm/model_executor/warmup/fa4_cutedsl_warmup.py +++ b/vllm/model_executor/warmup/fa4_cutedsl_warmup.py @@ -4,7 +4,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING from vllm.v1.attention.backends.mla.prefill import get_mla_prefill_backend @@ -31,11 +31,17 @@ def _warm_fa4_mla_prefill(worker: Worker) -> None: def _warm_inkling_fa4_rel_attention(worker: Worker) -> None: - seen_compile_keys: set[Any] = set() - for module in worker.get_model().modules(): - warmup_kernel = getattr(module, "fa4_rel_attention_kernel", None) - if warmup_kernel is not None: - warmup_kernel.warmup(seen_compile_keys=seen_compile_keys) + from vllm.models.inkling.configs import InklingModelConfig + from vllm.models.inkling.nvidia.ops.fa4_warmup import ( + INKLING_FA4_REL_ATTENTION_KERNEL, + ) + + vllm_config = worker.vllm_config + hf_config = vllm_config.model_config.hf_config + if not isinstance(hf_config, InklingModelConfig): + return + + INKLING_FA4_REL_ATTENTION_KERNEL.warmup(vllm_config) def fa4_cutedsl_warmup(worker: Worker) -> None: diff --git a/vllm/models/inkling/nvidia/attention.py b/vllm/models/inkling/nvidia/attention.py index 4f1f133adf94..6aa363e8161e 100644 --- a/vllm/models/inkling/nvidia/attention.py +++ b/vllm/models/inkling/nvidia/attention.py @@ -38,7 +38,7 @@ bucket_max_seqlen_q, inkling_fa4_num_splits, ) -from .ops.fa4_warmup import InklingFA4RelAttentionKernel +from .ops.fa4_warmup import INKLING_FA4_REL_ATTENTION_KERNEL from .ops.qkvr_prep import fused_qkvr_prep from .sconv_swa_attn import _K, _V, InklingConvState, InklingSconvMetadata from .short_conv import InklingShortConv @@ -173,22 +173,6 @@ def __init__( raise ValueError(f"Duplicate layer name: {prefix}") compilation_config.static_forward_context[prefix] = self self.kv_cache = torch.tensor([]) # replaced by bind_kv_cache - self.fa4_rel_attention_kernel = InklingFA4RelAttentionKernel( - num_heads=self.num_heads, - num_kv_heads=self.num_kv_heads, - head_dim=self.head_dim, - rel_extent=self.rel_extent, - window_size=self.window_size, - is_local=self.is_local, - max_kv_len=self._max_kv_len, - dtype=vllm_config.model_config.dtype, - kv_dtype=self.kv_cache_torch_dtype, - block_size=vllm_config.cache_config.block_size, - max_num_reqs=vllm_config.scheduler_config.max_num_seqs, - max_num_batched_tokens=( - vllm_config.scheduler_config.max_num_batched_tokens - ), - ) def get_attn_backend(self) -> type[AttentionBackend]: return FlashAttentionBackend @@ -305,7 +289,7 @@ def _attention( num_kv_heads=self.num_kv_heads, max_kv_len=self._max_kv_len, ) - self.fa4_rel_attention_kernel( + INKLING_FA4_REL_ATTENTION_KERNEL( q[:nt], key_cache, value_cache, diff --git a/vllm/models/inkling/nvidia/ops/fa4_warmup.py b/vllm/models/inkling/nvidia/ops/fa4_warmup.py index 2aa67818d9f0..4d3b6244edaf 100644 --- a/vllm/models/inkling/nvidia/ops/fa4_warmup.py +++ b/vllm/models/inkling/nvidia/ops/fa4_warmup.py @@ -8,10 +8,14 @@ import torch +from vllm.config import VllmConfig +from vllm.distributed import get_tensor_model_parallel_world_size from vllm.model_executor.warmup.jit_warmup import ( VllmJitKernel, WarmupIntRange, + zip_inputs, ) +from vllm.utils.torch_utils import kv_cache_dtype_str_to_dtype from .fa4_rel_attention import ( bucket_max_seqlen_q, @@ -103,38 +107,9 @@ def _materialized_num_reqs( class InklingFA4RelAttentionKernel( VllmJitKernel["InklingFA4RelAttentionKernel.CompileKey"] ): - def __init__( - self, - *, - num_heads: int, - num_kv_heads: int, - head_dim: int, - rel_extent: int, - window_size: tuple[int, int], - is_local: bool, - max_kv_len: int, - dtype: torch.dtype, - kv_dtype: torch.dtype, - block_size: int, - max_num_reqs: int, - max_num_batched_tokens: int, - ) -> None: - self.num_heads = num_heads - self.num_kv_heads = num_kv_heads - self.head_dim = head_dim - self.rel_extent = rel_extent - self.window_size = window_size - self.is_local = is_local - self.max_kv_len = max_kv_len - self.dtype = dtype - self.kv_dtype = kv_dtype - self.block_size = block_size - self.max_num_reqs = max_num_reqs - self.max_num_batched_tokens = max_num_batched_tokens - super().__init__() - @dataclass(frozen=True) class CompileKey: + is_local: bool num_heads: int num_kv_heads: int head_dim: int @@ -151,27 +126,38 @@ class CompileKey: def dispatch( # type: ignore[override] self, *, + is_local: bool, + num_heads: int, + num_kv_heads: int, + head_dim: int, + rel_extent: int, + dtype: torch.dtype, + kv_dtype: torch.dtype, + block_size: int, + window_size: tuple[int, int], + max_kv_len: int, query_len: int, num_reqs: int, ) -> CompileKey: max_seqlen_q = bucket_max_seqlen_q(query_len) num_splits = inkling_fa4_num_splits( - is_local=self.is_local, + is_local=is_local, batch_size=num_reqs, max_query_len=max_seqlen_q, - num_heads=self.num_heads, - num_kv_heads=self.num_kv_heads, - max_kv_len=self.max_kv_len, + num_heads=num_heads, + num_kv_heads=num_kv_heads, + max_kv_len=max_kv_len, ) return self.CompileKey( - num_heads=self.num_heads, - num_kv_heads=self.num_kv_heads, - head_dim=self.head_dim, - rel_extent=self.rel_extent, - dtype=self.dtype, - kv_dtype=self.kv_dtype, - block_size=self.block_size, - window_size=self.window_size, + is_local=is_local, + num_heads=num_heads, + num_kv_heads=num_kv_heads, + head_dim=head_dim, + rel_extent=rel_extent, + dtype=dtype, + kv_dtype=kv_dtype, + block_size=block_size, + window_size=window_size, max_seqlen_q=max_seqlen_q, num_splits=num_splits, num_warps_bucket=(_num_warps_bucket(num_reqs) if num_splits > 1 else None), @@ -183,18 +169,71 @@ def _is_valid_warmup_dispatch( *, query_len: int, num_reqs: int, + max_num_batched_tokens: int, ) -> bool: max_seqlen_q = bucket_max_seqlen_q(query_len) min_query_len = 1 if max_seqlen_q == 1 else max_seqlen_q // 2 + 1 - return min_query_len + num_reqs <= self.max_num_batched_tokens + 1 + return min_query_len + num_reqs <= max_num_batched_tokens + 1 - def get_warmup_keys(self) -> list[CompileKey]: - if self.max_num_reqs <= 0 or self.max_num_batched_tokens <= 0: + def get_warmup_keys(self, vllm_config: VllmConfig) -> list[CompileKey]: + max_num_reqs = vllm_config.scheduler_config.max_num_seqs + max_num_batched_tokens = vllm_config.scheduler_config.max_num_batched_tokens + if max_num_reqs <= 0 or max_num_batched_tokens <= 0: return [] + config = vllm_config.model_config.hf_config + tp_size = get_tensor_model_parallel_world_size() + dtype = vllm_config.model_config.dtype + kv_dtype = kv_cache_dtype_str_to_dtype( + vllm_config.cache_config.cache_dtype, + vllm_config.model_config, + ) + block_size = vllm_config.cache_config.block_size + local_extent = config.sliding_window_size + + global_num_kv_heads = config.num_key_value_heads + local_num_kv_heads = config.swa_num_key_value_heads + assert config.num_attention_heads % tp_size == 0 + assert config.swa_num_attention_heads % tp_size == 0 + if global_num_kv_heads >= tp_size: + assert global_num_kv_heads % tp_size == 0 + else: + assert tp_size % global_num_kv_heads == 0 + if local_num_kv_heads >= tp_size: + assert local_num_kv_heads % tp_size == 0 + else: + assert tp_size % local_num_kv_heads == 0 + return self._trace_dispatch(self.dispatch)( - query_len=WarmupIntRange(1, self.max_num_batched_tokens + 1), - num_reqs=WarmupIntRange(1, self.max_num_reqs + 1), + zip_inputs( + dict( + is_local=False, + num_heads=config.num_attention_heads // tp_size, + num_kv_heads=max(1, global_num_kv_heads // tp_size), + head_dim=config.head_dim, + rel_extent=config.rel_extent, + dtype=dtype, + kv_dtype=kv_dtype, + block_size=block_size, + window_size=[(-1, -1)], + max_kv_len=vllm_config.model_config.max_model_len, + ), + dict( + is_local=True, + num_heads=config.swa_num_attention_heads // tp_size, + num_kv_heads=max(1, local_num_kv_heads // tp_size), + head_dim=config.swa_head_dim, + rel_extent=local_extent, + dtype=dtype, + kv_dtype=kv_dtype, + block_size=block_size, + window_size=[(local_extent - 1, 0)], + max_kv_len=local_extent, + ), + ), + query_len=WarmupIntRange(1, max_num_batched_tokens + 1), + num_reqs=WarmupIntRange(1, max_num_reqs + 1), + max_num_batched_tokens=max_num_batched_tokens, _when=self._is_valid_warmup_dispatch, ) @@ -305,3 +344,6 @@ def __call__( num_splits=num_splits, out=out, ) + + +INKLING_FA4_REL_ATTENTION_KERNEL = InklingFA4RelAttentionKernel() From 03f5dc0ebe83f58fd5be1aeea0fa18febdd79c43 Mon Sep 17 00:00:00 2001 From: LopezCastroRoberto Date: Tue, 21 Jul 2026 07:31:55 -0400 Subject: [PATCH 03/12] update Signed-off-by: LopezCastroRoberto --- tests/models/inkling/test_fa4_warmup.py | 100 +++++++++++++++++++----- 1 file changed, 79 insertions(+), 21 deletions(-) diff --git a/tests/models/inkling/test_fa4_warmup.py b/tests/models/inkling/test_fa4_warmup.py index e4a0b7b92db4..fe40abe5110b 100644 --- a/tests/models/inkling/test_fa4_warmup.py +++ b/tests/models/inkling/test_fa4_warmup.py @@ -1,30 +1,45 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project +from types import SimpleNamespace + import torch +from vllm.models.inkling.nvidia.ops import fa4_warmup from vllm.models.inkling.nvidia.ops.fa4_rel_attention import ( bucket_max_seqlen_q, + inkling_fa4_num_splits, ) from vllm.models.inkling.nvidia.ops.fa4_warmup import ( InklingFA4RelAttentionKernel, + _num_warps_bucket, ) -def _make_kernel() -> InklingFA4RelAttentionKernel: - return InklingFA4RelAttentionKernel( - num_heads=16, - num_kv_heads=2, - head_dim=128, - rel_extent=1024, - window_size=(-1, -1), - is_local=False, - max_kv_len=65536, - dtype=torch.bfloat16, - kv_dtype=torch.bfloat16, - block_size=16, - max_num_reqs=64, - max_num_batched_tokens=192, +def _vllm_config_from_reference_config(config: SimpleNamespace) -> SimpleNamespace: + return SimpleNamespace( + model_config=SimpleNamespace( + hf_config=SimpleNamespace( + num_attention_heads=config.num_heads, + num_key_value_heads=config.num_kv_heads, + head_dim=config.head_dim, + rel_extent=config.rel_extent, + swa_num_attention_heads=config.num_heads, + swa_num_key_value_heads=config.num_kv_heads, + swa_head_dim=config.head_dim, + sliding_window_size=config.rel_extent, + ), + max_model_len=config.max_kv_len, + dtype=config.dtype, + ), + cache_config=SimpleNamespace( + cache_dtype="auto", + block_size=config.block_size, + ), + scheduler_config=SimpleNamespace( + max_num_seqs=config.max_num_reqs, + max_num_batched_tokens=config.max_num_batched_tokens, + ), ) @@ -42,15 +57,58 @@ def test_bucket_max_seqlen_q(): ] -def test_warmup_enumerates_every_runtime_compile_class(): - kernel = _make_kernel() - warmed_keys = set(kernel.get_warmup_keys()) +def test_warmup_enumerates_every_runtime_compile_class(monkeypatch): + monkeypatch.setattr( + fa4_warmup, + "get_tensor_model_parallel_world_size", + lambda: 1, + ) + config = SimpleNamespace( + num_heads=16, + num_kv_heads=2, + head_dim=128, + rel_extent=1024, + window_size=(-1, -1), + is_local=False, + max_kv_len=65536, + dtype=torch.bfloat16, + kv_dtype=torch.bfloat16, + block_size=16, + max_num_reqs=64, + max_num_batched_tokens=192, + ) + vllm_config = _vllm_config_from_reference_config(config) + kernel = InklingFA4RelAttentionKernel() + warmed_keys = { + ( + key.max_seqlen_q, + key.num_splits, + key.num_warps_bucket, + key.large_num_reqs, + ) + for key in kernel.get_warmup_keys(vllm_config) + if key.is_local == config.is_local + } - for query_len in range(1, kernel.max_num_batched_tokens + 1): + for query_len in range(1, config.max_num_batched_tokens + 1): + max_seqlen_q = bucket_max_seqlen_q(query_len) max_num_reqs = min( - kernel.max_num_reqs, - kernel.max_num_batched_tokens - query_len + 1, + config.max_num_reqs, + config.max_num_batched_tokens - query_len + 1, ) for num_reqs in range(1, max_num_reqs + 1): - runtime_key = kernel.dispatch(query_len=query_len, num_reqs=num_reqs) + num_splits = inkling_fa4_num_splits( + is_local=config.is_local, + batch_size=num_reqs, + max_query_len=max_seqlen_q, + num_heads=config.num_heads, + num_kv_heads=config.num_kv_heads, + max_kv_len=config.max_kv_len, + ) + runtime_key = ( + max_seqlen_q, + num_splits, + _num_warps_bucket(num_reqs) if num_splits > 1 else None, + num_reqs > 1024, + ) assert runtime_key in warmed_keys From 1f7430f6045f0aac1857281c3214a3741b807622 Mon Sep 17 00:00:00 2001 From: LopezCastroRoberto Date: Tue, 21 Jul 2026 07:50:33 -0400 Subject: [PATCH 04/12] update Signed-off-by: LopezCastroRoberto --- tests/model_executor/test_jit_warmup.py | 32 ++++++++++++++++++ vllm/model_executor/warmup/jit_warmup.py | 34 ++++++-------------- vllm/models/inkling/nvidia/ops/fa4_warmup.py | 4 +-- 3 files changed, 43 insertions(+), 27 deletions(-) diff --git a/tests/model_executor/test_jit_warmup.py b/tests/model_executor/test_jit_warmup.py index da6b21091b97..b2cc3ef2d244 100644 --- a/tests/model_executor/test_jit_warmup.py +++ b/tests/model_executor/test_jit_warmup.py @@ -143,6 +143,38 @@ def test_trace_dispatch_combines_zipped_rows_with_independent_values() -> None: ] +def test_trace_dispatch_filters_with_traced_predicate() -> None: + class PredicateKernel(ToyKernel): + def _is_valid_warmup_dispatch( + self, + *, + tokens: int, + lanes: int, + max_work: int, + ) -> bool: + block_size = _next_power_of_2(tokens) + return block_size * lanes <= max_work + + def get_warmup_keys( + self, max_tokens: int, cfg: Any + ) -> list[ToyKernel.CompileKey]: + return self._trace_dispatch(self.dispatch)( + tokens=WarmupIntRange(1, max_tokens + 1), + lanes=(1, 2), + cfg=cfg, + max_work=4, + _when=self._is_valid_warmup_dispatch, + ) + + assert PredicateKernel().get_warmup_keys(5, _config()) == [ + ToyKernel.CompileKey(1, 1, 1, ("base", "default", -1, 1, 1), True), + ToyKernel.CompileKey(1, 2, 1, ("base", "default", -1, 1, 1), True), + ToyKernel.CompileKey(2, 2, 1, ("base", "default", -2, 2, 4), True), + ToyKernel.CompileKey(2, 4, 1, ("base", "default", -2, 2, 4), True), + ToyKernel.CompileKey(4, 4, 1, ("base", "default", -4, 1, 16), True), + ] + + def test_zip_inputs_validates_input_rows() -> None: with pytest.raises(ValueError, match="requires at least one"): zip_inputs() diff --git a/vllm/model_executor/warmup/jit_warmup.py b/vllm/model_executor/warmup/jit_warmup.py index 1a31abe44237..c9352a98fa4d 100644 --- a/vllm/model_executor/warmup/jit_warmup.py +++ b/vllm/model_executor/warmup/jit_warmup.py @@ -94,18 +94,14 @@ def _expand_warmup_input_rows( rows: tuple[Mapping[str, WarmupValues], ...], input_names: frozenset[str], ) -> tuple[dict[str, Any], ...]: - active_names = tuple(name for name in rows[0] if name in input_names) + active_names = frozenset(name for name in rows[0] if name in input_names) if not active_names: return ({},) - expanded_rows: list[dict[str, Any]] = [] - for row in rows: - expanded_rows.extend( - _expand_warmup_value_grid( - {name: row[name] for name in active_names}, input_names - ) - ) - return tuple(expanded_rows) + return tuple( + {name: value for name, value in row.items() if name in active_names} + for row in rows + ) def _merge_warmup_kwargs(parts: Iterable[Mapping[str, Any]]) -> dict[str, Any]: @@ -279,17 +275,14 @@ def visit_BinOp(self, node: ast.BinOp) -> Any: return op(self.visit(node.left), self.visit(node.right)) def visit_Call(self, node: ast.Call) -> Any: + args = [self.visit(arg) for arg in node.args] + fn = self.visit(node.func) + call_kwargs: dict[str, Any] = {} for keyword in node.keywords: if keyword.arg is None: raise _dispatch_expr_error( node, "Dispatch helper calls cannot use **kwargs" ) - - args = [self.visit(arg) for arg in node.args] - fn = self.visit(node.func) - call_kwargs: dict[str, Any] = {} - for keyword in node.keywords: - assert keyword.arg is not None call_kwargs[keyword.arg] = self.visit(keyword.value) return fn(*args, **call_kwargs) @@ -553,16 +546,7 @@ def compile(self, compile_key: CompileKeyT) -> None: """Compile one warmup key.""" raise NotImplementedError - def warmup( - self, - *args: Any, - seen_compile_keys: set[CompileKeyT] | None = None, - **kwargs: Any, - ) -> None: + def warmup(self, *args: Any, **kwargs: Any) -> None: """Compile this kernel's warmup keys.""" for compile_key in self.get_warmup_keys(*args, **kwargs): - if seen_compile_keys is not None: - if compile_key in seen_compile_keys: - continue - seen_compile_keys.add(compile_key) self.compile(compile_key) diff --git a/vllm/models/inkling/nvidia/ops/fa4_warmup.py b/vllm/models/inkling/nvidia/ops/fa4_warmup.py index 4d3b6244edaf..f2f7cf768ddd 100644 --- a/vllm/models/inkling/nvidia/ops/fa4_warmup.py +++ b/vllm/models/inkling/nvidia/ops/fa4_warmup.py @@ -215,7 +215,7 @@ def get_warmup_keys(self, vllm_config: VllmConfig) -> list[CompileKey]: dtype=dtype, kv_dtype=kv_dtype, block_size=block_size, - window_size=[(-1, -1)], + window_size=(-1, -1), max_kv_len=vllm_config.model_config.max_model_len, ), dict( @@ -227,7 +227,7 @@ def get_warmup_keys(self, vllm_config: VllmConfig) -> list[CompileKey]: dtype=dtype, kv_dtype=kv_dtype, block_size=block_size, - window_size=[(local_extent - 1, 0)], + window_size=(local_extent - 1, 0), max_kv_len=local_extent, ), ), From 8d71b1e87c0fffde7e3bab11d11e5efe63e3ac62 Mon Sep 17 00:00:00 2001 From: LopezCastroRoberto Date: Tue, 21 Jul 2026 07:54:54 -0400 Subject: [PATCH 05/12] update Signed-off-by: LopezCastroRoberto --- vllm/model_executor/warmup/jit_warmup.py | 32 +++++++++++++++--------- 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/vllm/model_executor/warmup/jit_warmup.py b/vllm/model_executor/warmup/jit_warmup.py index c9352a98fa4d..88b06b580582 100644 --- a/vllm/model_executor/warmup/jit_warmup.py +++ b/vllm/model_executor/warmup/jit_warmup.py @@ -36,6 +36,18 @@ class WarmupIntRange: WarmupValues = Any CompileKeyDispatchFn = Callable[..., CompileKeyT] WarmupPredicateFn = Callable[..., bool] +LocalExprs = tuple[tuple[str, ast.AST], ...] + + +def _eval_local_exprs( + local_exprs: LocalExprs, + values: Mapping[str, Any], + globals_: Mapping[str, Any], +) -> dict[str, Any]: + evaluated_values = dict(values) + for name, expr in local_exprs: + evaluated_values[name] = _eval_dispatch_expr(expr, evaluated_values, globals_) + return evaluated_values @dataclass(frozen=True) @@ -118,7 +130,7 @@ def _merge_warmup_kwargs(parts: Iterable[Mapping[str, Any]]) -> dict[str, Any]: @dataclass(frozen=True) class _CompileKeyDispatchTrace: - local_exprs: tuple[tuple[str, ast.AST], ...] + local_exprs: LocalExprs field_exprs: tuple[tuple[str, ast.AST], ...] globals: Mapping[str, Any] input_names: frozenset[str] @@ -129,11 +141,9 @@ def compile_key( compile_key_type: type[CompileKeyT], kwargs: Mapping[str, Any], ) -> CompileKeyT: - dispatch_values = {**self.defaults, **kwargs} - for name, expr in self.local_exprs: - dispatch_values[name] = _eval_dispatch_expr( - expr, dispatch_values, self.globals - ) + dispatch_values = _eval_local_exprs( + self.local_exprs, {**self.defaults, **kwargs}, self.globals + ) return compile_key_type( **{ field: _eval_dispatch_expr(expr, dispatch_values, self.globals) @@ -144,18 +154,16 @@ def compile_key( @dataclass(frozen=True) class _WarmupPredicateTrace: - local_exprs: tuple[tuple[str, ast.AST], ...] + local_exprs: LocalExprs return_expr: ast.AST globals: Mapping[str, Any] input_names: frozenset[str] defaults: Mapping[str, Any] def matches(self, kwargs: Mapping[str, Any]) -> bool: - dispatch_values = {**self.defaults, **kwargs} - for name, expr in self.local_exprs: - dispatch_values[name] = _eval_dispatch_expr( - expr, dispatch_values, self.globals - ) + dispatch_values = _eval_local_exprs( + self.local_exprs, {**self.defaults, **kwargs}, self.globals + ) return bool( _eval_dispatch_expr(self.return_expr, dispatch_values, self.globals) ) From d076256ec796efa2e829aa1de40253610ed57914 Mon Sep 17 00:00:00 2001 From: LopezCastroRoberto Date: Tue, 21 Jul 2026 08:01:38 -0400 Subject: [PATCH 06/12] update Signed-off-by: LopezCastroRoberto --- vllm/model_executor/warmup/jit_warmup.py | 55 +++++++++++------------- 1 file changed, 26 insertions(+), 29 deletions(-) diff --git a/vllm/model_executor/warmup/jit_warmup.py b/vllm/model_executor/warmup/jit_warmup.py index 88b06b580582..5b3f400cf68d 100644 --- a/vllm/model_executor/warmup/jit_warmup.py +++ b/vllm/model_executor/warmup/jit_warmup.py @@ -36,11 +36,11 @@ class WarmupIntRange: WarmupValues = Any CompileKeyDispatchFn = Callable[..., CompileKeyT] WarmupPredicateFn = Callable[..., bool] -LocalExprs = tuple[tuple[str, ast.AST], ...] +_LocalExprs = tuple[tuple[str, ast.AST], ...] def _eval_local_exprs( - local_exprs: LocalExprs, + local_exprs: _LocalExprs, values: Mapping[str, Any], globals_: Mapping[str, Any], ) -> dict[str, Any]: @@ -130,7 +130,7 @@ def _merge_warmup_kwargs(parts: Iterable[Mapping[str, Any]]) -> dict[str, Any]: @dataclass(frozen=True) class _CompileKeyDispatchTrace: - local_exprs: LocalExprs + local_exprs: _LocalExprs field_exprs: tuple[tuple[str, ast.AST], ...] globals: Mapping[str, Any] input_names: frozenset[str] @@ -154,7 +154,7 @@ def compile_key( @dataclass(frozen=True) class _WarmupPredicateTrace: - local_exprs: LocalExprs + local_exprs: _LocalExprs return_expr: ast.AST globals: Mapping[str, Any] input_names: frozenset[str] @@ -363,7 +363,8 @@ def _collect_expression_body( statement.targets[0], ast.Name ): raise _dispatch_expr_error( - statement, "Dispatch assignments must target one local name" + statement, + "Traced warmup helper assignments must target one local name", ) local_exprs.append((statement.targets[0].id, statement.value)) continue @@ -371,11 +372,12 @@ def _collect_expression_body( if isinstance(statement, ast.AnnAssign): if statement.value is None: raise _dispatch_expr_error( - statement, "Dispatch annotations must assign a value" + statement, "Traced warmup helper annotations must assign a value" ) if not isinstance(statement.target, ast.Name): raise _dispatch_expr_error( - statement, "Dispatch assignments must target one local name" + statement, + "Traced warmup helper assignments must target one local name", ) local_exprs.append((statement.target.id, statement.value)) continue @@ -409,7 +411,9 @@ def _collect_dispatch_body( return local_exprs, return_expr -def _function_defaults(fn: Callable[..., Any]) -> dict[str, Any]: +def _function_trace_inputs( + fn: Callable[..., Any], +) -> tuple[dict[str, Any], set[str]]: signature = inspect.signature(fn) defaults = { name: parameter.default @@ -419,11 +423,7 @@ def _function_defaults(fn: Callable[..., Any]) -> dict[str, Any]: bound_self = getattr(fn, "__self__", None) if bound_self is not None: defaults["self"] = bound_self - return defaults - - -def _function_candidate_names(fn: Callable[..., Any]) -> set[str]: - return set(inspect.signature(fn).parameters) + return defaults, set(signature.parameters) def _trace_compile_key_dispatch( @@ -436,8 +436,7 @@ def _trace_compile_key_dispatch( local_exprs, return_call = _collect_dispatch_body(fn, function_def) field_exprs: list[tuple[str, ast.AST]] = [] - defaults = _function_defaults(fn) - candidate_names = _function_candidate_names(fn) + defaults, candidate_names = _function_trace_inputs(fn) input_names: set[str] = set() local_names = {name for name, _ in local_exprs} for _, expr in local_exprs: @@ -467,8 +466,7 @@ def _trace_warmup_predicate( function_def = get_function_source_node(fn) local_exprs, return_expr = _collect_expression_body(fn, function_def) - defaults = _function_defaults(fn) - candidate_names = _function_candidate_names(fn) + defaults, candidate_names = _function_trace_inputs(fn) input_names: set[str] = set() local_names = {name for name, _ in local_exprs} for _, expr in local_exprs: @@ -523,19 +521,18 @@ def traced( ) expanded_kwargs = _expand_warmup_value_grid(kwargs, input_names) dispatch_value_groups = (*expanded_input_groups, expanded_kwargs) - return list( - dict.fromkeys( - compile_key_dispatch_trace.compile_key( - self.CompileKey, dispatch_values - ) - for dispatch_value_group in itertools.product( - *dispatch_value_groups - ) - for dispatch_values in (_merge_warmup_kwargs(dispatch_value_group),) - if predicate_trace is None - or predicate_trace.matches(dispatch_values) + compile_keys: dict[CompileKeyT, None] = {} + for dispatch_value_group in itertools.product(*dispatch_value_groups): + dispatch_values = _merge_warmup_kwargs(dispatch_value_group) + if predicate_trace is not None and not predicate_trace.matches( + dispatch_values + ): + continue + compile_key = compile_key_dispatch_trace.compile_key( + self.CompileKey, dispatch_values ) - ) + compile_keys[compile_key] = None + return list(compile_keys) return traced From 5abd5b35c3794478f6fcf291f1580da28108ef7d Mon Sep 17 00:00:00 2001 From: LopezCastroRoberto Date: Tue, 21 Jul 2026 09:31:46 -0400 Subject: [PATCH 07/12] update Signed-off-by: LopezCastroRoberto --- vllm/model_executor/warmup/fa4_cutedsl_warmup.py | 4 ++-- vllm/models/inkling/nvidia/ops/fa4_warmup.py | 5 ++++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/vllm/model_executor/warmup/fa4_cutedsl_warmup.py b/vllm/model_executor/warmup/fa4_cutedsl_warmup.py index 21511db64d84..6bc2083a1d86 100644 --- a/vllm/model_executor/warmup/fa4_cutedsl_warmup.py +++ b/vllm/model_executor/warmup/fa4_cutedsl_warmup.py @@ -31,14 +31,14 @@ def _warm_fa4_mla_prefill(worker: Worker) -> None: def _warm_inkling_fa4_rel_attention(worker: Worker) -> None: - from vllm.models.inkling.configs import InklingModelConfig + from vllm.models.inkling.configs import InklingMMConfig, InklingModelConfig from vllm.models.inkling.nvidia.ops.fa4_warmup import ( INKLING_FA4_REL_ATTENTION_KERNEL, ) vllm_config = worker.vllm_config hf_config = vllm_config.model_config.hf_config - if not isinstance(hf_config, InklingModelConfig): + if not isinstance(hf_config, (InklingMMConfig, InklingModelConfig)): return INKLING_FA4_REL_ATTENTION_KERNEL.warmup(vllm_config) diff --git a/vllm/models/inkling/nvidia/ops/fa4_warmup.py b/vllm/models/inkling/nvidia/ops/fa4_warmup.py index f2f7cf768ddd..3f4d2e072d83 100644 --- a/vllm/models/inkling/nvidia/ops/fa4_warmup.py +++ b/vllm/models/inkling/nvidia/ops/fa4_warmup.py @@ -181,7 +181,10 @@ def get_warmup_keys(self, vllm_config: VllmConfig) -> list[CompileKey]: if max_num_reqs <= 0 or max_num_batched_tokens <= 0: return [] - config = vllm_config.model_config.hf_config + hf_config = vllm_config.model_config.hf_config + get_text_config = getattr(hf_config, "get_text_config", None) + config = get_text_config() if callable(get_text_config) else hf_config + tp_size = get_tensor_model_parallel_world_size() dtype = vllm_config.model_config.dtype kv_dtype = kv_cache_dtype_str_to_dtype( From 031b07b84ff9b27ed2e3511017d07a231e791487 Mon Sep 17 00:00:00 2001 From: LopezCastroRoberto Date: Tue, 21 Jul 2026 09:33:29 -0400 Subject: [PATCH 08/12] update Signed-off-by: LopezCastroRoberto --- tests/models/inkling/test_fa4_warmup.py | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/tests/models/inkling/test_fa4_warmup.py b/tests/models/inkling/test_fa4_warmup.py index fe40abe5110b..bedfb786e419 100644 --- a/tests/models/inkling/test_fa4_warmup.py +++ b/tests/models/inkling/test_fa4_warmup.py @@ -5,6 +5,7 @@ import torch +from vllm.models.inkling.configs import InklingMMConfig, InklingModelConfig from vllm.models.inkling.nvidia.ops import fa4_warmup from vllm.models.inkling.nvidia.ops.fa4_rel_attention import ( bucket_max_seqlen_q, @@ -19,15 +20,17 @@ def _vllm_config_from_reference_config(config: SimpleNamespace) -> SimpleNamespace: return SimpleNamespace( model_config=SimpleNamespace( - hf_config=SimpleNamespace( - num_attention_heads=config.num_heads, - num_key_value_heads=config.num_kv_heads, - head_dim=config.head_dim, - rel_extent=config.rel_extent, - swa_num_attention_heads=config.num_heads, - swa_num_key_value_heads=config.num_kv_heads, - swa_head_dim=config.head_dim, - sliding_window_size=config.rel_extent, + hf_config=InklingMMConfig( + text_config=InklingModelConfig( + num_attention_heads=config.num_heads, + num_key_value_heads=config.num_kv_heads, + head_dim=config.head_dim, + rel_extent=config.rel_extent, + swa_num_attention_heads=config.num_heads, + swa_num_key_value_heads=config.num_kv_heads, + swa_head_dim=config.head_dim, + sliding_window_size=config.rel_extent, + ) ), max_model_len=config.max_kv_len, dtype=config.dtype, From 2ee9e6a8ddf50676dda5c9bb4149c68d0039691a Mon Sep 17 00:00:00 2001 From: LopezCastroRoberto Date: Tue, 21 Jul 2026 11:00:30 -0400 Subject: [PATCH 09/12] fa4 mla cleanup Signed-off-by: LopezCastroRoberto --- .../backends/mla/prefill/flash_attn.py | 105 ++++++++++-------- 1 file changed, 59 insertions(+), 46 deletions(-) diff --git a/vllm/v1/attention/backends/mla/prefill/flash_attn.py b/vllm/v1/attention/backends/mla/prefill/flash_attn.py index c5fdbaebc023..4083f89e1adb 100644 --- a/vllm/v1/attention/backends/mla/prefill/flash_attn.py +++ b/vllm/v1/attention/backends/mla/prefill/flash_attn.py @@ -13,7 +13,7 @@ from vllm.model_executor.layers.quantization.utils.quant_utils import ( kFp8StaticTensorSym, ) -from vllm.model_executor.warmup.jit_warmup import VllmJitKernel +from vllm.model_executor.warmup.jit_warmup import VllmJitKernel, zip_inputs from vllm.platforms import current_platform from vllm.v1.attention.backends.fa_utils import ( compile_flash_attn_varlen_func_from_specs, @@ -54,12 +54,6 @@ FA4_MLA_PREFILL_LSE_OPTIONS = (False, True) -@dataclass(frozen=True) -class _FA4MLAPrefillShapeProbe: - max_seqlen_q: int - max_seqlen_k: int - - class FA4MLAPrefillKernel(VllmJitKernel["FA4MLAPrefillKernel.CompileKey"]): """FA4 MLA prefill compile-key wrapper used by generic JIT warmup.""" @@ -96,7 +90,8 @@ def dispatch( # type: ignore[override] dtype: torch.dtype, num_heads: int, mla_dims: "MLADims", - shape_probe: _FA4MLAPrefillShapeProbe, + max_seqlen_q: int, + max_seqlen_k: int, requires_v_padding: bool, causal: bool, fa_version: int, @@ -106,17 +101,17 @@ def dispatch( # type: ignore[override] ) -> CompileKey: return self.CompileKey( q_shape=( - batch_size * shape_probe.max_seqlen_q, + batch_size * max_seqlen_q, num_heads, mla_dims.qk_nope_head_dim + mla_dims.qk_rope_head_dim, ), k_shape=( - batch_size * shape_probe.max_seqlen_k, + batch_size * max_seqlen_k, num_heads, mla_dims.qk_nope_head_dim + mla_dims.qk_rope_head_dim, ), v_shape=( - batch_size * shape_probe.max_seqlen_k, + batch_size * max_seqlen_k, num_heads, ( mla_dims.qk_nope_head_dim + mla_dims.qk_rope_head_dim @@ -125,8 +120,8 @@ def dispatch( # type: ignore[override] ), ), q_dtype=dtype, - max_seqlen_q=shape_probe.max_seqlen_q, - max_seqlen_k=shape_probe.max_seqlen_k, + max_seqlen_q=max_seqlen_q, + max_seqlen_k=max_seqlen_k, softmax_scale=(mla_dims.qk_nope_head_dim + mla_dims.qk_rope_head_dim) ** -0.5, causal=causal, @@ -147,6 +142,28 @@ def dispatch( # type: ignore[override] num_splits=num_splits, ) + def _is_valid_warmup_shape_probe( + self, + *, + max_seqlen_k: int, + num_splits: int, + is_sm90: bool, + qk_head_dim: int, + effective_v_head_dim: int, + ) -> bool: + long_k = FA4_MLA_PREFILL_LONG_K_BLOCKS * FA4_MLA_PREFILL_K_TILE + very_long_k = FA4_MLA_PREFILL_VERY_LONG_K_BLOCKS * FA4_MLA_PREFILL_K_TILE + return ( + max_seqlen_k < long_k + or (num_splits != 1 and max_seqlen_k == long_k) + or ( + num_splits != 1 + and max_seqlen_k == very_long_k + and not is_sm90 + and qk_head_dim != effective_v_head_dim + ) + ) + def get_warmup_keys(self, vllm_config: "VllmConfig") -> list[CompileKey]: from vllm.model_executor.layers.attention.mla_attention import ( get_mla_dims, @@ -182,51 +199,47 @@ def get_warmup_keys(self, vllm_config: "VllmConfig") -> list[CompileKey]: effective_v_head_dim = ( qk_head_dim if requires_v_padding else mla_dims.v_head_dim ) - shape_probes = [ - _FA4MLAPrefillShapeProbe(1, FA4_MLA_PREFILL_K_TILE), - _FA4MLAPrefillShapeProbe( - FA4_MLA_PREFILL_Q_TILE + 1, - 4 * FA4_MLA_PREFILL_K_TILE, + shape_probes = ( + dict(max_seqlen_q=1, max_seqlen_k=FA4_MLA_PREFILL_K_TILE), + dict( + max_seqlen_q=FA4_MLA_PREFILL_Q_TILE + 1, + max_seqlen_k=4 * FA4_MLA_PREFILL_K_TILE, ), - ] - if num_splits != 1: - shape_probes.extend( - ( - _FA4MLAPrefillShapeProbe( - 1, - FA4_MLA_PREFILL_LONG_K_BLOCKS * FA4_MLA_PREFILL_K_TILE, - ), - _FA4MLAPrefillShapeProbe( - FA4_MLA_PREFILL_Q_TILE + 1, - FA4_MLA_PREFILL_LONG_K_BLOCKS * FA4_MLA_PREFILL_K_TILE, - ), - ) - ) - if not is_sm90 and qk_head_dim != effective_v_head_dim: - shape_probes.extend( - ( - _FA4MLAPrefillShapeProbe( - 1, - FA4_MLA_PREFILL_VERY_LONG_K_BLOCKS * FA4_MLA_PREFILL_K_TILE, - ), - _FA4MLAPrefillShapeProbe( - FA4_MLA_PREFILL_Q_TILE + 1, - FA4_MLA_PREFILL_VERY_LONG_K_BLOCKS * FA4_MLA_PREFILL_K_TILE, - ), - ) - ) + dict( + max_seqlen_q=1, + max_seqlen_k=FA4_MLA_PREFILL_LONG_K_BLOCKS * FA4_MLA_PREFILL_K_TILE, + ), + dict( + max_seqlen_q=FA4_MLA_PREFILL_Q_TILE + 1, + max_seqlen_k=FA4_MLA_PREFILL_LONG_K_BLOCKS * FA4_MLA_PREFILL_K_TILE, + ), + dict( + max_seqlen_q=1, + max_seqlen_k=FA4_MLA_PREFILL_VERY_LONG_K_BLOCKS + * FA4_MLA_PREFILL_K_TILE, + ), + dict( + max_seqlen_q=FA4_MLA_PREFILL_Q_TILE + 1, + max_seqlen_k=FA4_MLA_PREFILL_VERY_LONG_K_BLOCKS + * FA4_MLA_PREFILL_K_TILE, + ), + ) return self._trace_dispatch(self.dispatch)( + zip_inputs(*shape_probes), batch_size=FA4_MLA_PREFILL_COMPILE_BATCH_SIZE, dtype=dtype, num_heads=num_heads, mla_dims=mla_dims, - shape_probe=shape_probes, requires_v_padding=requires_v_padding, + is_sm90=is_sm90, + qk_head_dim=qk_head_dim, + effective_v_head_dim=effective_v_head_dim, causal=FA4_MLA_PREFILL_CAUSAL_OPTIONS, return_lse=FA4_MLA_PREFILL_LSE_OPTIONS, num_splits=num_splits, fa_version=fa_version, + _when=self._is_valid_warmup_shape_probe, ) @staticmethod From aa05ae9f0f3fd90a1d226ee14961fa6781f376ef Mon Sep 17 00:00:00 2001 From: LopezCastroRoberto Date: Wed, 29 Jul 2026 09:05:56 -0400 Subject: [PATCH 10/12] cleanup and fix conflicts with upstream Signed-off-by: LopezCastroRoberto --- tests/model_executor/test_jit_warmup.py | 33 ++ .../models/inkling/test_fa4_rel_attention.py | 8 +- tests/models/inkling/test_fa4_warmup.py | 83 ++-- vllm/config/kernel.py | 8 + vllm/model_executor/warmup/cutedsl_warmup.py | 128 ++++++ .../warmup/fa4_cutedsl_warmup.py | 2 +- vllm/model_executor/warmup/jit_warmup.py | 56 ++- vllm/model_executor/warmup/kernel_warmup.py | 1 + vllm/models/inkling/nvidia/attention.py | 2 +- vllm/models/inkling/nvidia/ops/__init__.py | 6 +- .../inkling/nvidia/ops/fa4_rel_attention.py | 402 +++++++++++++++--- vllm/models/inkling/nvidia/ops/fa4_warmup.py | 352 --------------- .../backends/mla/prefill/flash_attn.py | 29 +- 13 files changed, 623 insertions(+), 487 deletions(-) create mode 100644 vllm/model_executor/warmup/cutedsl_warmup.py delete mode 100644 vllm/models/inkling/nvidia/ops/fa4_warmup.py diff --git a/tests/model_executor/test_jit_warmup.py b/tests/model_executor/test_jit_warmup.py index b2cc3ef2d244..f93de50a3d30 100644 --- a/tests/model_executor/test_jit_warmup.py +++ b/tests/model_executor/test_jit_warmup.py @@ -105,6 +105,39 @@ def test_trace_dispatch_expands_ranges_dedupes_and_ignores_unused_inputs() -> No ] +def test_warmup_range_uses_custom_advancement() -> None: + keys = ToyKernel()._trace_dispatch(ToyKernel().dispatch)( + tokens=WarmupIntRange( + 1, + 10, + advance=lambda value: _next_power_of_2(value) + 1, + ), + cfg=_config(), + ) + + assert [key.block_size for key in keys] == [1, 2, 4, 8, 16] + + +def test_warmup_range_validates_custom_advancement() -> None: + trace_dispatch = ToyKernel()._trace_dispatch(ToyKernel().dispatch) + + with pytest.raises(ValueError, match="both step and advance"): + trace_dispatch( + tokens=WarmupIntRange( + 1, + 10, + step=2, + advance=lambda value: value + 1, + ), + cfg=_config(), + ) + with pytest.raises(ValueError, match="must return a greater value"): + trace_dispatch( + tokens=WarmupIntRange(1, 10, advance=lambda value: value), + cfg=_config(), + ) + + def test_compile_key_uses_defaults_locals_attributes_and_expressions() -> None: cfg = _config(bias=3, disabled=True, name="cfg", vectorized=True) diff --git a/tests/models/inkling/test_fa4_rel_attention.py b/tests/models/inkling/test_fa4_rel_attention.py index 1a11ac220c87..bdd1fbf944e3 100644 --- a/tests/models/inkling/test_fa4_rel_attention.py +++ b/tests/models/inkling/test_fa4_rel_attention.py @@ -2,8 +2,8 @@ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Correctness test for the Inkling FA4 relative-attention score-mod kernel. -Checks ``inkling_fa4_rel_attention`` against a pure-PyTorch reference that -implements the relative bias exactly as documented in the Inkling architecture +Checks ``INKLING_FA4_REL_ATTENTION_KERNEL`` against a pure-PyTorch reference +that implements the relative bias exactly as documented in the Inkling architecture guide:: logit(i, j, h) = (1 / head_dim) * dot(q[i, h], k[j, h]) + rel_bias(i, j, h) @@ -23,9 +23,9 @@ compute_log_scaling_tau, ) from vllm.models.inkling.nvidia.ops.fa4_rel_attention import ( + INKLING_FA4_REL_ATTENTION_KERNEL, _use_sheared_bias, inkling_fa4_num_splits, - inkling_fa4_rel_attention, ) from vllm.platforms import current_platform from vllm.platforms.interface import DeviceCapability @@ -279,7 +279,7 @@ def _run_case(seq_lens, num_heads, num_kv_heads, rel_extent, window_left, seed=0 num_kv_heads=num_kv_heads, max_kv_len=max(kv_lens), ) - out = inkling_fa4_rel_attention( + out = INKLING_FA4_REL_ATTENTION_KERNEL( q, key_cache, value_cache, diff --git a/tests/models/inkling/test_fa4_warmup.py b/tests/models/inkling/test_fa4_warmup.py index bedfb786e419..33997633a178 100644 --- a/tests/models/inkling/test_fa4_warmup.py +++ b/tests/models/inkling/test_fa4_warmup.py @@ -5,15 +5,13 @@ import torch +import vllm.models.inkling.nvidia.ops.fa4_rel_attention as fa4_rel_attention from vllm.models.inkling.configs import InklingMMConfig, InklingModelConfig -from vllm.models.inkling.nvidia.ops import fa4_warmup from vllm.models.inkling.nvidia.ops.fa4_rel_attention import ( - bucket_max_seqlen_q, - inkling_fa4_num_splits, -) -from vllm.models.inkling.nvidia.ops.fa4_warmup import ( InklingFA4RelAttentionKernel, _num_warps_bucket, + bucket_max_seqlen_q, + inkling_fa4_num_splits, ) @@ -62,7 +60,7 @@ def test_bucket_max_seqlen_q(): def test_warmup_enumerates_every_runtime_compile_class(monkeypatch): monkeypatch.setattr( - fa4_warmup, + fa4_rel_attention, "get_tensor_model_parallel_world_size", lambda: 1, ) @@ -82,36 +80,47 @@ def test_warmup_enumerates_every_runtime_compile_class(monkeypatch): ) vllm_config = _vllm_config_from_reference_config(config) kernel = InklingFA4RelAttentionKernel() - warmed_keys = { - ( - key.max_seqlen_q, - key.num_splits, - key.num_warps_bucket, - key.large_num_reqs, - ) - for key in kernel.get_warmup_keys(vllm_config) - if key.is_local == config.is_local - } + warmed_keys = set(kernel.get_warmup_keys(vllm_config)) + expected_keys: set[InklingFA4RelAttentionKernel.CompileKey] = set() - for query_len in range(1, config.max_num_batched_tokens + 1): - max_seqlen_q = bucket_max_seqlen_q(query_len) - max_num_reqs = min( - config.max_num_reqs, - config.max_num_batched_tokens - query_len + 1, - ) - for num_reqs in range(1, max_num_reqs + 1): - num_splits = inkling_fa4_num_splits( - is_local=config.is_local, - batch_size=num_reqs, - max_query_len=max_seqlen_q, - num_heads=config.num_heads, - num_kv_heads=config.num_kv_heads, - max_kv_len=config.max_kv_len, + for is_local in (False, True): + max_kv_len = config.rel_extent if is_local else config.max_kv_len + window_size = (config.rel_extent - 1, 0) if is_local else (-1, -1) + for query_len in range(1, config.max_num_batched_tokens + 1): + max_seqlen_q = bucket_max_seqlen_q(query_len) + max_num_reqs = min( + config.max_num_reqs, + config.max_num_batched_tokens - query_len + 1, ) - runtime_key = ( - max_seqlen_q, - num_splits, - _num_warps_bucket(num_reqs) if num_splits > 1 else None, - num_reqs > 1024, - ) - assert runtime_key in warmed_keys + for num_reqs in range(1, max_num_reqs + 1): + num_splits = inkling_fa4_num_splits( + is_local=is_local, + batch_size=num_reqs, + max_query_len=max_seqlen_q, + num_heads=config.num_heads, + num_kv_heads=config.num_kv_heads, + max_kv_len=max_kv_len, + ) + expected_keys.add( + InklingFA4RelAttentionKernel.CompileKey( + is_local=is_local, + num_heads=config.num_heads, + num_kv_heads=config.num_kv_heads, + head_dim=config.head_dim, + rel_extent=config.rel_extent, + dtype=config.dtype, + kv_dtype=config.kv_dtype, + block_size=config.block_size, + window_size=window_size, + max_seqlen_q=max_seqlen_q, + num_splits=num_splits, + num_warps_bucket=( + _num_warps_bucket(num_reqs) + if num_splits > 1 + else None + ), + large_num_reqs=num_reqs > 1024, + ) + ) + + assert warmed_keys == expected_keys diff --git a/vllm/config/kernel.py b/vllm/config/kernel.py index 09593cac6fd3..6e369e1ad0e0 100644 --- a/vllm/config/kernel.py +++ b/vllm/config/kernel.py @@ -176,6 +176,12 @@ class KernelConfig: enable_flashinfer_autotune: bool = None # type: ignore[assignment] """If True, run FlashInfer autotuning during kernel warmup.""" + """Deprecated: run legacy CuTeDSL warmup providers.""" + # TODO(roberto): Remove after registered CuTeDSL warmups are migrated + # to the shared JIT warmup infrastructure. + # https://github.com/vllm-project/vllm/pull/47451 + enable_cutedsl_warmup: bool = True + enable_jit_warmup: bool = True """If True, run JIT compile warmup during kernel warmup.""" @@ -252,6 +258,7 @@ def compute_hash(self) -> str: Any future fields that don't affect compilation should be excluded. """ ignored_factors = { + "enable_cutedsl_warmup", "enable_jit_warmup", "enable_flashinfer_autotune", "ir_op_priority", # handled separately below @@ -262,6 +269,7 @@ def compute_hash(self) -> str: @field_validator( "enable_flashinfer_autotune", + "enable_cutedsl_warmup", "enable_jit_warmup", mode="wrap", ) diff --git a/vllm/model_executor/warmup/cutedsl_warmup.py b/vllm/model_executor/warmup/cutedsl_warmup.py new file mode 100644 index 000000000000..59838dba0eba --- /dev/null +++ b/vllm/model_executor/warmup/cutedsl_warmup.py @@ -0,0 +1,128 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Deprecated compatibility registry for legacy CuTeDSL warmups.""" + +# TODO(roberto): Remove this compatibility registry after registered CuTeDSL +# warmups are migrated to the shared JIT warmup infrastructure. +# https://github.com/vllm-project/vllm/pull/47451 + +from __future__ import annotations + +import time +import weakref +from collections.abc import Callable, Hashable, Iterable +from dataclasses import dataclass + +import torch +from tqdm import tqdm + +from vllm.distributed import is_global_first_rank +from vllm.logger import init_logger +from vllm.platforms import current_platform +from vllm.tracing import instrument + +logger = init_logger(__name__) + +CuTeDSLCompileFn = Callable[[], None] + + +@dataclass(frozen=True) +class CuTeDSLCompileUnit: + name: str + key: Hashable + compile: CuTeDSLCompileFn + + +_CUTEDSL_WARMUP_PROVIDERS: weakref.WeakSet[object] = weakref.WeakSet() + + +def register_cutedsl_warmup_provider(provider: object) -> None: + """Register an object that can expose CuTeDSL warmup compile units.""" + _CUTEDSL_WARMUP_PROVIDERS.add(provider) + + +# Yield compile units from registered providers. +def _iter_cutedsl_warmup_compile_units() -> Iterable[CuTeDSLCompileUnit]: + for provider in tuple(_CUTEDSL_WARMUP_PROVIDERS): + get_units = getattr(provider, "get_cutedsl_warmup_compile_units", None) + if not callable(get_units): + continue + + compile_units = get_units() + if compile_units is None: + continue + for unit in compile_units: + if not isinstance(unit, CuTeDSLCompileUnit): + raise TypeError( + "get_cutedsl_warmup_compile_units must return " + "CuTeDSLCompileUnit objects" + ) + yield unit + + +# Drop duplicate compile units across providers. +def _collect_unique_compile_units( + compile_units: Iterable[CuTeDSLCompileUnit], +) -> list[CuTeDSLCompileUnit]: + seen: set[Hashable] = set() + unique_compile_units: list[CuTeDSLCompileUnit] = [] + + for unit in compile_units: + if unit.key in seen: + continue + + seen.add(unit.key) + unique_compile_units.append(unit) + + return unique_compile_units + + +# Execute compile units under inference mode. +def _compile_cutedsl_warmup_units( + compile_units: Iterable[CuTeDSLCompileUnit], +) -> int: + compiled = 0 + if is_global_first_rank(): + compile_units = tqdm(compile_units, desc="Compiling CuTeDSL kernels") + with torch.inference_mode(): + for unit in compile_units: + unit.compile() + compiled += 1 + torch.accelerator.synchronize() + return compiled + + +# Run all CuTeDSL warmup before serving. +@instrument(span_name="CuTeDSL warmup") +def cutedsl_warmup() -> None: + """Run CuTeDSL compile providers before serving.""" + if not current_platform.is_cuda(): + logger.info("Skipping CuTeDSL warmup on non-CUDA platform.") + return + + compile_units = _collect_unique_compile_units(_iter_cutedsl_warmup_compile_units()) + if not compile_units: + logger.info("Skipping CuTeDSL warmup because no compile units were requested.") + return + + if is_global_first_rank(): + logger.warning( + "The legacy CuTeDSL warmup registry is deprecated and will be removed. " + "Migrate providers to the shared JIT warmup contract: " + "https://github.com/vllm-project/vllm/issues/49349" + ) + + unit_names = list(dict.fromkeys(unit.name for unit in compile_units)) + logger.info( + "Warming up CuTeDSL compile_units=%d names=%s.", + len(compile_units), + unit_names, + ) + + start_time = time.perf_counter() + compiled_count = _compile_cutedsl_warmup_units(compile_units) + logger.info( + "CuTeDSL warmup compiled %d units in %.2f s.", + compiled_count, + time.perf_counter() - start_time, + ) diff --git a/vllm/model_executor/warmup/fa4_cutedsl_warmup.py b/vllm/model_executor/warmup/fa4_cutedsl_warmup.py index abed6ecb034f..5470da50341f 100644 --- a/vllm/model_executor/warmup/fa4_cutedsl_warmup.py +++ b/vllm/model_executor/warmup/fa4_cutedsl_warmup.py @@ -36,7 +36,7 @@ def _warm_fa4_mla_prefill(worker: Worker) -> None: def _warm_inkling_fa4_rel_attention(worker: Worker) -> None: from vllm.models.inkling.configs import InklingMMConfig, InklingModelConfig - from vllm.models.inkling.nvidia.ops.fa4_warmup import ( + from vllm.models.inkling.nvidia.ops.fa4_rel_attention import ( INKLING_FA4_REL_ATTENTION_KERNEL, ) diff --git a/vllm/model_executor/warmup/jit_warmup.py b/vllm/model_executor/warmup/jit_warmup.py index 5b3f400cf68d..36b7e66f6d86 100644 --- a/vllm/model_executor/warmup/jit_warmup.py +++ b/vllm/model_executor/warmup/jit_warmup.py @@ -28,9 +28,12 @@ @dataclass(frozen=True) class WarmupIntRange: + """Expand integers with range semantics or a custom monotonic progression.""" + start: int stop: int step: int = 1 + advance: Callable[[int], int] | None = None WarmupValues = Any @@ -59,7 +62,22 @@ class _WarmupInputRows: def _expand_warmup_values(values: WarmupValues) -> tuple[Any, ...]: if isinstance(values, WarmupIntRange): - return tuple(range(values.start, values.stop, values.step)) + if values.advance is None: + return tuple(range(values.start, values.stop, values.step)) + if values.step != 1: + raise ValueError("WarmupIntRange cannot set both step and advance") + + expanded: list[int] = [] + value = values.start + while value < values.stop: + expanded.append(value) + next_value = values.advance(value) + if next_value <= value: + raise ValueError( + "WarmupIntRange.advance must return a greater value" + ) + value = next_value + return tuple(expanded) if isinstance(values, (list, tuple)): return tuple(values) return (values,) @@ -88,17 +106,14 @@ def zip_inputs(*rows: Mapping[str, WarmupValues]) -> _WarmupInputRows: return _WarmupInputRows(rows=tuple(input_rows)) -def _expand_warmup_value_grid( +def _expand_warmup_value_axes( values: Mapping[str, WarmupValues], input_names: frozenset[str], -) -> tuple[dict[str, Any], ...]: - names = tuple(name for name in values if name in input_names) - if not names: - return ({},) - - expanded_values = tuple(_expand_warmup_values(values[name]) for name in names) +) -> tuple[tuple[str, tuple[Any, ...]], ...]: return tuple( - dict(zip(names, value_set)) for value_set in itertools.product(*expanded_values) + (name, _expand_warmup_values(value)) + for name, value in values.items() + if name in input_names ) @@ -519,11 +534,26 @@ def traced( _expand_warmup_input_rows(group.rows, input_names) for group in input_groups ) - expanded_kwargs = _expand_warmup_value_grid(kwargs, input_names) - dispatch_value_groups = (*expanded_input_groups, expanded_kwargs) + expanded_kwarg_axes = _expand_warmup_value_axes(kwargs, input_names) + dispatch_value_axes = ( + *expanded_input_groups, + *(values for _, values in expanded_kwarg_axes), + ) + input_group_count = len(expanded_input_groups) + kwarg_names = tuple(name for name, _ in expanded_kwarg_axes) compile_keys: dict[CompileKeyT, None] = {} - for dispatch_value_group in itertools.product(*dispatch_value_groups): - dispatch_values = _merge_warmup_kwargs(dispatch_value_group) + for dispatch_value_set in itertools.product(*dispatch_value_axes): + dispatch_values = _merge_warmup_kwargs( + ( + *dispatch_value_set[:input_group_count], + dict( + zip( + kwarg_names, + dispatch_value_set[input_group_count:], + ) + ), + ) + ) if predicate_trace is not None and not predicate_trace.matches( dispatch_values ): diff --git a/vllm/model_executor/warmup/kernel_warmup.py b/vllm/model_executor/warmup/kernel_warmup.py index a3cf16b70743..afe47f39ced0 100644 --- a/vllm/model_executor/warmup/kernel_warmup.py +++ b/vllm/model_executor/warmup/kernel_warmup.py @@ -12,6 +12,7 @@ import vllm.envs as envs from vllm.logger import init_logger +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, diff --git a/vllm/models/inkling/nvidia/attention.py b/vllm/models/inkling/nvidia/attention.py index 6aa363e8161e..b18fa81f7eff 100644 --- a/vllm/models/inkling/nvidia/attention.py +++ b/vllm/models/inkling/nvidia/attention.py @@ -35,10 +35,10 @@ from ..configs import InklingModelConfig from .layernorm import InklingRMSNorm from .ops.fa4_rel_attention import ( + INKLING_FA4_REL_ATTENTION_KERNEL, bucket_max_seqlen_q, inkling_fa4_num_splits, ) -from .ops.fa4_warmup import INKLING_FA4_REL_ATTENTION_KERNEL from .ops.qkvr_prep import fused_qkvr_prep from .sconv_swa_attn import _K, _V, InklingConvState, InklingSconvMetadata from .short_conv import InklingShortConv diff --git a/vllm/models/inkling/nvidia/ops/__init__.py b/vllm/models/inkling/nvidia/ops/__init__.py index 2d364fc6149a..bb7f066ddbd1 100644 --- a/vllm/models/inkling/nvidia/ops/__init__.py +++ b/vllm/models/inkling/nvidia/ops/__init__.py @@ -15,11 +15,13 @@ _LAZY_EXPORTS = { "silu_and_mul_triton": "silu_and_mul", "sink_silu_mul_epilogue": "silu_and_mul", - "inkling_fa4_rel_attention": "fa4_rel_attention", + "INKLING_FA4_REL_ATTENTION_KERNEL": "fa4_rel_attention", } if TYPE_CHECKING: - from .fa4_rel_attention import inkling_fa4_rel_attention # noqa: F401 + from .fa4_rel_attention import ( # noqa: F401 + INKLING_FA4_REL_ATTENTION_KERNEL, + ) from .silu_and_mul import ( # noqa: F401 silu_and_mul_triton, sink_silu_mul_epilogue, diff --git a/vllm/models/inkling/nvidia/ops/fa4_rel_attention.py b/vllm/models/inkling/nvidia/ops/fa4_rel_attention.py index 883545e3f2da..ce10d4fbbbf5 100644 --- a/vllm/models/inkling/nvidia/ops/fa4_rel_attention.py +++ b/vllm/models/inkling/nvidia/ops/fa4_rel_attention.py @@ -3,12 +3,23 @@ from __future__ import annotations from collections.abc import Callable +from dataclasses import dataclass from functools import cache -from typing import Any +from typing import TYPE_CHECKING, Any import torch +from vllm.distributed import get_tensor_model_parallel_world_size +from vllm.model_executor.warmup.jit_warmup import ( + VllmJitKernel, + WarmupIntRange, + zip_inputs, +) from vllm.platforms import current_platform +from vllm.utils.torch_utils import kv_cache_dtype_str_to_dtype + +if TYPE_CHECKING: + from vllm.config import VllmConfig def bucket_max_seqlen_q(max_seqlen_q: int) -> int: @@ -98,73 +109,330 @@ def inkling_fa4_num_splits( ) -def inkling_fa4_rel_attention( - q: torch.Tensor, - key_cache: torch.Tensor, - value_cache: torch.Tensor, - *, - block_table: torch.Tensor, - cache_seqlens: torch.Tensor, - cu_seqlens_q: torch.Tensor, - max_seqlen_q: int, - softmax_scale: float, - causal: bool, - window_size: tuple[int, int], - rel_extent: int, - rel_logits: torch.Tensor, - num_splits: int = 32, - out: torch.Tensor | None = None, -) -> torch.Tensor: - """Paged varlen FA4 over the bound K/V cache with the Inkling relative bias. - - ``q`` is ``(num_tokens, num_heads, head_dim)``; ``key_cache`` / ``value_cache`` - are the paged caches ``(num_blocks, block_size, num_kv_heads, head_dim)``; - ``block_table`` is the per-request page table and ``cache_seqlens`` the - per-request KV lengths (``seqused_k``). ``rel_logits`` is - ``(num_tokens, num_heads, rel_extent)``. - - Hopper uses standard FA4's score-mod gather. Blackwell uses tml-fa4's - sheared relative-bias layout. - """ - # cute uses (None, None) to mean "no window". - cute_window = (None, None) if window_size == (-1, -1) else window_size - - rel_logits = rel_logits.contiguous() - flash_attn_varlen_func: Callable[..., Any] - if _use_sheared_bias(): - from vllm.third_party.tml_fa4 import ( - flash_attn_varlen_func as tml_flash_attn_varlen_func, +def _num_warps_bucket(num_reqs: int) -> int: + num_warps = min((num_reqs + 30) // 31, 32) + return 1 << (num_warps - 1).bit_length() + + +class InklingFA4RelAttentionKernel( + VllmJitKernel["InklingFA4RelAttentionKernel.CompileKey"] +): + @dataclass(frozen=True) + class CompileKey: + is_local: bool + num_heads: int + num_kv_heads: int + head_dim: int + rel_extent: int + dtype: torch.dtype + kv_dtype: torch.dtype + block_size: int + window_size: tuple[int, int] + max_seqlen_q: int + num_splits: int + num_warps_bucket: int | None + large_num_reqs: bool + + @staticmethod + def kernel( + q: torch.Tensor, + key_cache: torch.Tensor, + value_cache: torch.Tensor, + *, + block_table: torch.Tensor, + cache_seqlens: torch.Tensor, + cu_seqlens_q: torch.Tensor, + max_seqlen_q: int, + softmax_scale: float, + causal: bool, + window_size: tuple[int, int], + rel_extent: int, + rel_logits: torch.Tensor, + num_splits: int = 32, + out: torch.Tensor | None = None, + ) -> torch.Tensor: + """Paged varlen FA4 over the bound K/V cache with the Inkling relative bias. + + ``q`` is ``(num_tokens, num_heads, head_dim)``; ``key_cache`` / ``value_cache`` + are the paged caches ``(num_blocks, block_size, num_kv_heads, head_dim)``; + ``block_table`` is the per-request page table and ``cache_seqlens`` the + per-request KV lengths (``seqused_k``). ``rel_logits`` is + ``(num_tokens, num_heads, rel_extent)``. + + Hopper uses standard FA4's score-mod gather. Blackwell uses tml-fa4's + sheared relative-bias layout. + """ + # cute uses (None, None) to mean "no window". + cute_window = (None, None) if window_size == (-1, -1) else window_size + + rel_logits = rel_logits.contiguous() + flash_attn_varlen_func: Callable[..., Any] + if _use_sheared_bias(): + from vllm.third_party.tml_fa4 import ( + flash_attn_varlen_func as tml_flash_attn_varlen_func, + ) + + flash_attn_varlen_func = tml_flash_attn_varlen_func + bias_kwargs: dict[str, Any] = {"rel_bias": rel_logits} + else: + from vllm.vllm_flash_attn.cute import ( + flash_attn_varlen_func as cute_flash_attn_varlen_func, + ) + + flash_attn_varlen_func = cute_flash_attn_varlen_func + bias_kwargs = { + "score_mod": _get_score_mod(rel_extent), + "aux_tensors": [rel_logits], + } + + ret = flash_attn_varlen_func( + q=q, + k=key_cache, + v=value_cache, + cu_seqlens_q=cu_seqlens_q, + seqused_k=cache_seqlens, + max_seqlen_q=max_seqlen_q, + page_table=block_table, + softmax_scale=softmax_scale, + causal=causal, + window_size=cute_window, + num_splits=num_splits, + return_lse=False, + out=out, + **bias_kwargs, ) + if isinstance(ret, tuple): + return ret[0] + return ret - flash_attn_varlen_func = tml_flash_attn_varlen_func - bias_kwargs: dict[str, Any] = {"rel_bias": rel_logits} - else: - from vllm.vllm_flash_attn.cute import ( - flash_attn_varlen_func as cute_flash_attn_varlen_func, + def dispatch( # type: ignore[override] + self, + *, + is_local: bool, + num_heads: int, + num_kv_heads: int, + head_dim: int, + rel_extent: int, + dtype: torch.dtype, + kv_dtype: torch.dtype, + block_size: int, + window_size: tuple[int, int], + max_kv_len: int, + query_len: int, + num_reqs: int, + ) -> CompileKey: + max_seqlen_q = bucket_max_seqlen_q(query_len) + num_splits = inkling_fa4_num_splits( + is_local=is_local, + batch_size=num_reqs, + max_query_len=max_seqlen_q, + num_heads=num_heads, + num_kv_heads=num_kv_heads, + max_kv_len=max_kv_len, + ) + return self.CompileKey( + is_local=is_local, + num_heads=num_heads, + num_kv_heads=num_kv_heads, + head_dim=head_dim, + rel_extent=rel_extent, + dtype=dtype, + kv_dtype=kv_dtype, + block_size=block_size, + window_size=window_size, + max_seqlen_q=max_seqlen_q, + num_splits=num_splits, + num_warps_bucket=( + _num_warps_bucket(num_reqs) if num_splits > 1 else None + ), + large_num_reqs=num_reqs > 1024, ) - flash_attn_varlen_func = cute_flash_attn_varlen_func - bias_kwargs = { - "score_mod": _get_score_mod(rel_extent), - "aux_tensors": [rel_logits], - } - - ret = flash_attn_varlen_func( - q=q, - k=key_cache, - v=value_cache, - cu_seqlens_q=cu_seqlens_q, - seqused_k=cache_seqlens, - max_seqlen_q=max_seqlen_q, - page_table=block_table, - softmax_scale=softmax_scale, - causal=causal, - window_size=cute_window, - num_splits=num_splits, - return_lse=False, - out=out, - **bias_kwargs, - ) - if isinstance(ret, tuple): - return ret[0] - return ret + def _is_valid_warmup_dispatch( + self, + *, + query_len: int, + num_reqs: int, + max_num_batched_tokens: int, + ) -> bool: + return query_len + num_reqs <= max_num_batched_tokens + 1 + + def get_warmup_keys(self, vllm_config: VllmConfig) -> list[CompileKey]: + max_num_reqs = vllm_config.scheduler_config.max_num_seqs + max_num_batched_tokens = vllm_config.scheduler_config.max_num_batched_tokens + if max_num_reqs <= 0 or max_num_batched_tokens <= 0: + return [] + + hf_config = vllm_config.model_config.hf_config + get_text_config = getattr(hf_config, "get_text_config", None) + config = get_text_config() if callable(get_text_config) else hf_config + + tp_size = get_tensor_model_parallel_world_size() + dtype = vllm_config.model_config.dtype + kv_dtype = kv_cache_dtype_str_to_dtype( + vllm_config.cache_config.cache_dtype, + vllm_config.model_config, + ) + block_size = vllm_config.cache_config.block_size + local_extent = config.sliding_window_size + + global_num_kv_heads = config.num_key_value_heads + local_num_kv_heads = config.swa_num_key_value_heads + assert config.num_attention_heads % tp_size == 0 + assert config.swa_num_attention_heads % tp_size == 0 + if global_num_kv_heads >= tp_size: + assert global_num_kv_heads % tp_size == 0 + else: + assert tp_size % global_num_kv_heads == 0 + if local_num_kv_heads >= tp_size: + assert local_num_kv_heads % tp_size == 0 + else: + assert tp_size % local_num_kv_heads == 0 + + return self._trace_dispatch(self.dispatch)( + zip_inputs( + dict( + is_local=False, + num_heads=config.num_attention_heads // tp_size, + num_kv_heads=max(1, global_num_kv_heads // tp_size), + head_dim=config.head_dim, + rel_extent=config.rel_extent, + dtype=dtype, + kv_dtype=kv_dtype, + block_size=block_size, + window_size=(-1, -1), + max_kv_len=vllm_config.model_config.max_model_len, + ), + dict( + is_local=True, + num_heads=config.swa_num_attention_heads // tp_size, + num_kv_heads=max(1, local_num_kv_heads // tp_size), + head_dim=config.swa_head_dim, + rel_extent=local_extent, + dtype=dtype, + kv_dtype=kv_dtype, + block_size=block_size, + window_size=(local_extent - 1, 0), + max_kv_len=local_extent, + ), + ), + query_len=WarmupIntRange( + 1, + max_num_batched_tokens + 1, + advance=lambda value: bucket_max_seqlen_q(value) + 1, + ), + num_reqs=WarmupIntRange(1, max_num_reqs + 1), + max_num_batched_tokens=max_num_batched_tokens, + _when=self._is_valid_warmup_dispatch, + ) + + def compile(self, compile_key: CompileKey) -> None: + from torch._subclasses.fake_tensor import FakeTensorMode + + if compile_key.num_splits == 1 or compile_key.num_warps_bucket is None: + num_reqs = 1025 if compile_key.large_num_reqs else 1 + else: + min_num_warps = ( + 1 + if compile_key.num_warps_bucket == 1 + else compile_key.num_warps_bucket // 2 + 1 + ) + min_num_reqs = (min_num_warps - 1) * 31 + 1 + num_reqs = max( + min_num_reqs, + 1025 if compile_key.large_num_reqs else 1, + ) + + with FakeTensorMode(): + device = torch.accelerator.current_accelerator() + total_q = compile_key.max_seqlen_q + num_reqs - 1 + q = torch.empty( + total_q, + compile_key.num_heads, + compile_key.head_dim, + dtype=compile_key.dtype, + device=device, + ) + kv = torch.empty( + 1, + 2, + compile_key.block_size, + compile_key.num_kv_heads, + compile_key.head_dim, + dtype=compile_key.kv_dtype, + device=device, + ) + key_cache, value_cache = kv.unbind(1) + self.kernel( + q, + key_cache, + value_cache, + block_table=torch.empty( + num_reqs, + 1, + dtype=torch.int32, + device=device, + ), + cache_seqlens=torch.empty( + num_reqs, + dtype=torch.int32, + device=device, + ), + cu_seqlens_q=torch.empty( + num_reqs + 1, + dtype=torch.int32, + device=device, + ), + max_seqlen_q=compile_key.max_seqlen_q, + softmax_scale=compile_key.head_dim**-1, + causal=True, + window_size=compile_key.window_size, + rel_extent=compile_key.rel_extent, + rel_logits=torch.empty( + total_q, + compile_key.num_heads, + compile_key.rel_extent, + dtype=compile_key.dtype, + device=device, + ), + num_splits=compile_key.num_splits, + out=torch.empty_like(q), + ) + + def __call__( + self, + q: torch.Tensor, + key_cache: torch.Tensor, + value_cache: torch.Tensor, + *, + block_table: torch.Tensor, + cache_seqlens: torch.Tensor, + cu_seqlens_q: torch.Tensor, + max_seqlen_q: int, + softmax_scale: float, + causal: bool, + window_size: tuple[int, int], + rel_extent: int, + rel_logits: torch.Tensor, + num_splits: int = 32, + out: torch.Tensor | None = None, + ) -> torch.Tensor: + return self.kernel( + q, + key_cache, + value_cache, + block_table=block_table, + cache_seqlens=cache_seqlens, + cu_seqlens_q=cu_seqlens_q, + max_seqlen_q=max_seqlen_q, + softmax_scale=softmax_scale, + causal=causal, + window_size=window_size, + rel_extent=rel_extent, + rel_logits=rel_logits, + num_splits=num_splits, + out=out, + ) + + +INKLING_FA4_REL_ATTENTION_KERNEL = InklingFA4RelAttentionKernel() diff --git a/vllm/models/inkling/nvidia/ops/fa4_warmup.py b/vllm/models/inkling/nvidia/ops/fa4_warmup.py deleted file mode 100644 index 3f4d2e072d83..000000000000 --- a/vllm/models/inkling/nvidia/ops/fa4_warmup.py +++ /dev/null @@ -1,352 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""Startup compilation of the FA4 kernels used by Inkling.""" - -from __future__ import annotations - -from dataclasses import dataclass - -import torch - -from vllm.config import VllmConfig -from vllm.distributed import get_tensor_model_parallel_world_size -from vllm.model_executor.warmup.jit_warmup import ( - VllmJitKernel, - WarmupIntRange, - zip_inputs, -) -from vllm.utils.torch_utils import kv_cache_dtype_str_to_dtype - -from .fa4_rel_attention import ( - bucket_max_seqlen_q, - inkling_fa4_num_splits, - inkling_fa4_rel_attention, -) - - -def _compile_fa4_rel_attention_from_specs( - *, - q_shape: tuple[int, ...], - key_cache_shape: tuple[int, ...], - value_cache_shape: tuple[int, ...], - block_table_shape: tuple[int, ...], - cache_seqlens_shape: tuple[int, ...], - cu_seqlens_q_shape: tuple[int, ...], - rel_logits_shape: tuple[int, ...], - q_dtype: torch.dtype, - kv_dtype: torch.dtype, - max_seqlen_q: int, - softmax_scale: float, - causal: bool, - window_size: tuple[int, int], - num_splits: int, -) -> None: - """Compile TML FA4 via fake tensors without launching a kernel.""" - from torch._subclasses.fake_tensor import FakeTensorMode - - from vllm.third_party.tml_fa4 import flash_attn_varlen_func - - cute_window = (None, None) if window_size == (-1, -1) else window_size - # FakeTensorMode carries shape, dtype, stride, and device metadata into TML - # FA4 so the JIT can build the specialization without allocating real inputs - # or running the kernel body. This is not a dummy runtime launch. - with FakeTensorMode(): - device = torch.accelerator.current_accelerator() - q = torch.empty(q_shape, dtype=q_dtype, device=device) - key_cache = torch.empty(key_cache_shape, dtype=kv_dtype, device=device) - value_cache = torch.empty(value_cache_shape, dtype=kv_dtype, device=device) - rel_logits = torch.empty(rel_logits_shape, dtype=q_dtype, device=device) - flash_attn_varlen_func( - q=q, - k=key_cache, - v=value_cache, - cu_seqlens_q=torch.empty( - cu_seqlens_q_shape, - dtype=torch.int32, - device=device, - ), - seqused_k=torch.empty( - cache_seqlens_shape, - dtype=torch.int32, - device=device, - ), - max_seqlen_q=max_seqlen_q, - page_table=torch.empty( - block_table_shape, - dtype=torch.int32, - device=device, - ), - softmax_scale=softmax_scale, - causal=causal, - window_size=cute_window, - num_splits=num_splits, - return_lse=False, - out=torch.empty_like(q), - rel_bias=rel_logits.contiguous(), - ) - - -def _num_warps_bucket(num_reqs: int) -> int: - num_warps = min((num_reqs + 30) // 31, 32) - return 1 << (num_warps - 1).bit_length() - - -def _materialized_num_reqs( - num_splits: int, - num_warps_bucket: int | None, - large_num_reqs: bool, -) -> int: - if num_splits == 1 or num_warps_bucket is None: - return 1025 if large_num_reqs else 1 - - min_num_warps = 1 if num_warps_bucket == 1 else num_warps_bucket // 2 + 1 - min_num_reqs = (min_num_warps - 1) * 31 + 1 - return max(min_num_reqs, 1025 if large_num_reqs else 1) - - -class InklingFA4RelAttentionKernel( - VllmJitKernel["InklingFA4RelAttentionKernel.CompileKey"] -): - @dataclass(frozen=True) - class CompileKey: - is_local: bool - num_heads: int - num_kv_heads: int - head_dim: int - rel_extent: int - dtype: torch.dtype - kv_dtype: torch.dtype - block_size: int - window_size: tuple[int, int] - max_seqlen_q: int - num_splits: int - num_warps_bucket: int | None - large_num_reqs: bool - - def dispatch( # type: ignore[override] - self, - *, - is_local: bool, - num_heads: int, - num_kv_heads: int, - head_dim: int, - rel_extent: int, - dtype: torch.dtype, - kv_dtype: torch.dtype, - block_size: int, - window_size: tuple[int, int], - max_kv_len: int, - query_len: int, - num_reqs: int, - ) -> CompileKey: - max_seqlen_q = bucket_max_seqlen_q(query_len) - num_splits = inkling_fa4_num_splits( - is_local=is_local, - batch_size=num_reqs, - max_query_len=max_seqlen_q, - num_heads=num_heads, - num_kv_heads=num_kv_heads, - max_kv_len=max_kv_len, - ) - return self.CompileKey( - is_local=is_local, - num_heads=num_heads, - num_kv_heads=num_kv_heads, - head_dim=head_dim, - rel_extent=rel_extent, - dtype=dtype, - kv_dtype=kv_dtype, - block_size=block_size, - window_size=window_size, - max_seqlen_q=max_seqlen_q, - num_splits=num_splits, - num_warps_bucket=(_num_warps_bucket(num_reqs) if num_splits > 1 else None), - large_num_reqs=num_reqs > 1024, - ) - - def _is_valid_warmup_dispatch( - self, - *, - query_len: int, - num_reqs: int, - max_num_batched_tokens: int, - ) -> bool: - max_seqlen_q = bucket_max_seqlen_q(query_len) - min_query_len = 1 if max_seqlen_q == 1 else max_seqlen_q // 2 + 1 - return min_query_len + num_reqs <= max_num_batched_tokens + 1 - - def get_warmup_keys(self, vllm_config: VllmConfig) -> list[CompileKey]: - max_num_reqs = vllm_config.scheduler_config.max_num_seqs - max_num_batched_tokens = vllm_config.scheduler_config.max_num_batched_tokens - if max_num_reqs <= 0 or max_num_batched_tokens <= 0: - return [] - - hf_config = vllm_config.model_config.hf_config - get_text_config = getattr(hf_config, "get_text_config", None) - config = get_text_config() if callable(get_text_config) else hf_config - - tp_size = get_tensor_model_parallel_world_size() - dtype = vllm_config.model_config.dtype - kv_dtype = kv_cache_dtype_str_to_dtype( - vllm_config.cache_config.cache_dtype, - vllm_config.model_config, - ) - block_size = vllm_config.cache_config.block_size - local_extent = config.sliding_window_size - - global_num_kv_heads = config.num_key_value_heads - local_num_kv_heads = config.swa_num_key_value_heads - assert config.num_attention_heads % tp_size == 0 - assert config.swa_num_attention_heads % tp_size == 0 - if global_num_kv_heads >= tp_size: - assert global_num_kv_heads % tp_size == 0 - else: - assert tp_size % global_num_kv_heads == 0 - if local_num_kv_heads >= tp_size: - assert local_num_kv_heads % tp_size == 0 - else: - assert tp_size % local_num_kv_heads == 0 - - return self._trace_dispatch(self.dispatch)( - zip_inputs( - dict( - is_local=False, - num_heads=config.num_attention_heads // tp_size, - num_kv_heads=max(1, global_num_kv_heads // tp_size), - head_dim=config.head_dim, - rel_extent=config.rel_extent, - dtype=dtype, - kv_dtype=kv_dtype, - block_size=block_size, - window_size=(-1, -1), - max_kv_len=vllm_config.model_config.max_model_len, - ), - dict( - is_local=True, - num_heads=config.swa_num_attention_heads // tp_size, - num_kv_heads=max(1, local_num_kv_heads // tp_size), - head_dim=config.swa_head_dim, - rel_extent=local_extent, - dtype=dtype, - kv_dtype=kv_dtype, - block_size=block_size, - window_size=(local_extent - 1, 0), - max_kv_len=local_extent, - ), - ), - query_len=WarmupIntRange(1, max_num_batched_tokens + 1), - num_reqs=WarmupIntRange(1, max_num_reqs + 1), - max_num_batched_tokens=max_num_batched_tokens, - _when=self._is_valid_warmup_dispatch, - ) - - def compile(self, compile_key: CompileKey) -> None: - num_reqs = _materialized_num_reqs( - compile_key.num_splits, - compile_key.num_warps_bucket, - compile_key.large_num_reqs, - ) - total_q = compile_key.max_seqlen_q + num_reqs - 1 - _compile_fa4_rel_attention_from_specs( - q_shape=(total_q, compile_key.num_heads, compile_key.head_dim), - key_cache_shape=( - 1, - compile_key.block_size, - compile_key.num_kv_heads, - compile_key.head_dim, - ), - value_cache_shape=( - 1, - compile_key.block_size, - compile_key.num_kv_heads, - compile_key.head_dim, - ), - block_table_shape=(num_reqs, 1), - cache_seqlens_shape=(num_reqs,), - cu_seqlens_q_shape=(num_reqs + 1,), - rel_logits_shape=( - total_q, - compile_key.num_heads, - compile_key.rel_extent, - ), - q_dtype=compile_key.dtype, - kv_dtype=compile_key.kv_dtype, - max_seqlen_q=compile_key.max_seqlen_q, - softmax_scale=compile_key.head_dim**-1, - causal=True, - window_size=compile_key.window_size, - num_splits=compile_key.num_splits, - ) - - @staticmethod - def kernel( - q: torch.Tensor, - key_cache: torch.Tensor, - value_cache: torch.Tensor, - *, - block_table: torch.Tensor, - cache_seqlens: torch.Tensor, - cu_seqlens_q: torch.Tensor, - max_seqlen_q: int, - softmax_scale: float, - causal: bool, - window_size: tuple[int, int], - rel_extent: int, - rel_logits: torch.Tensor, - num_splits: int = 32, - out: torch.Tensor | None = None, - ) -> torch.Tensor: - return inkling_fa4_rel_attention( - q, - key_cache, - value_cache, - block_table=block_table, - cache_seqlens=cache_seqlens, - cu_seqlens_q=cu_seqlens_q, - max_seqlen_q=max_seqlen_q, - softmax_scale=softmax_scale, - causal=causal, - window_size=window_size, - rel_extent=rel_extent, - rel_logits=rel_logits, - num_splits=num_splits, - out=out, - ) - - def __call__( - self, - q: torch.Tensor, - key_cache: torch.Tensor, - value_cache: torch.Tensor, - *, - block_table: torch.Tensor, - cache_seqlens: torch.Tensor, - cu_seqlens_q: torch.Tensor, - max_seqlen_q: int, - softmax_scale: float, - causal: bool, - window_size: tuple[int, int], - rel_extent: int, - rel_logits: torch.Tensor, - num_splits: int = 32, - out: torch.Tensor | None = None, - ) -> torch.Tensor: - return self.kernel( - q, - key_cache, - value_cache, - block_table=block_table, - cache_seqlens=cache_seqlens, - cu_seqlens_q=cu_seqlens_q, - max_seqlen_q=max_seqlen_q, - softmax_scale=softmax_scale, - causal=causal, - window_size=window_size, - rel_extent=rel_extent, - rel_logits=rel_logits, - num_splits=num_splits, - out=out, - ) - - -INKLING_FA4_REL_ATTENTION_KERNEL = InklingFA4RelAttentionKernel() diff --git a/vllm/v1/attention/backends/mla/prefill/flash_attn.py b/vllm/v1/attention/backends/mla/prefill/flash_attn.py index 881c5073bc06..dd31e1d2a11d 100644 --- a/vllm/v1/attention/backends/mla/prefill/flash_attn.py +++ b/vllm/v1/attention/backends/mla/prefill/flash_attn.py @@ -83,6 +83,16 @@ class CompileKey: return_softmax_lse: bool = False num_splits: int = 0 + @staticmethod + def kernel( + *args: Any, + runtime_kernel: Callable[..., Any] | None = None, + **kwargs: Any, + ) -> Any: + kernel = flash_attn_varlen_func if runtime_kernel is None else runtime_kernel + assert kernel is not None + return kernel(*args, **kwargs) + def dispatch( # type: ignore[override] self, *, @@ -242,11 +252,6 @@ def get_warmup_keys(self, vllm_config: "VllmConfig") -> list[CompileKey]: _when=self._is_valid_warmup_shape_probe, ) - @staticmethod - def kernel(*args: Any, **kwargs: Any) -> Any: - assert flash_attn_varlen_func is not None - return flash_attn_varlen_func(*args, **kwargs) - def compile(self, compile_key: CompileKey) -> None: assert compile_flash_attn_varlen_func_from_specs is not None window_size = ( @@ -281,11 +286,13 @@ def __call__( runtime_kernel: Callable[..., Any] | None = None, **kwargs: Any, ) -> Any: - kernel = self.kernel if runtime_kernel is None else runtime_kernel - return kernel(q=q, k=k, v=v, **kwargs) - - -FA4_MLA_PREFILL_KERNEL = FA4MLAPrefillKernel() + return self.kernel( + q=q, + k=k, + v=v, + runtime_kernel=runtime_kernel, + **kwargs, + ) class FlashAttnPrefillBackend(MLAPrefillBackend): @@ -476,3 +483,5 @@ def run_prefill_context_chunk( causal=False, # Context is unmasked return_softmax_lse=True, ) + +FA4_MLA_PREFILL_KERNEL = FA4MLAPrefillKernel() From 17448de6057889be31d3a908d0912351e0fe7b01 Mon Sep 17 00:00:00 2001 From: LopezCastroRoberto Date: Wed, 29 Jul 2026 09:19:31 -0400 Subject: [PATCH 11/12] fix pre-commit Signed-off-by: LopezCastroRoberto --- tests/models/inkling/test_fa4_warmup.py | 4 +--- vllm/config/kernel.py | 2 +- vllm/model_executor/warmup/jit_warmup.py | 4 +--- vllm/models/inkling/nvidia/ops/fa4_rel_attention.py | 4 +--- vllm/v1/attention/backends/mla/prefill/flash_attn.py | 1 + 5 files changed, 5 insertions(+), 10 deletions(-) diff --git a/tests/models/inkling/test_fa4_warmup.py b/tests/models/inkling/test_fa4_warmup.py index 33997633a178..8b7a65471535 100644 --- a/tests/models/inkling/test_fa4_warmup.py +++ b/tests/models/inkling/test_fa4_warmup.py @@ -115,9 +115,7 @@ def test_warmup_enumerates_every_runtime_compile_class(monkeypatch): max_seqlen_q=max_seqlen_q, num_splits=num_splits, num_warps_bucket=( - _num_warps_bucket(num_reqs) - if num_splits > 1 - else None + _num_warps_bucket(num_reqs) if num_splits > 1 else None ), large_num_reqs=num_reqs > 1024, ) diff --git a/vllm/config/kernel.py b/vllm/config/kernel.py index 6e369e1ad0e0..74e959f33ab9 100644 --- a/vllm/config/kernel.py +++ b/vllm/config/kernel.py @@ -176,11 +176,11 @@ class KernelConfig: enable_flashinfer_autotune: bool = None # type: ignore[assignment] """If True, run FlashInfer autotuning during kernel warmup.""" - """Deprecated: run legacy CuTeDSL warmup providers.""" # TODO(roberto): Remove after registered CuTeDSL warmups are migrated # to the shared JIT warmup infrastructure. # https://github.com/vllm-project/vllm/pull/47451 enable_cutedsl_warmup: bool = True + """Deprecated: run legacy CuTeDSL warmup providers.""" enable_jit_warmup: bool = True """If True, run JIT compile warmup during kernel warmup.""" diff --git a/vllm/model_executor/warmup/jit_warmup.py b/vllm/model_executor/warmup/jit_warmup.py index 36b7e66f6d86..4ef0c70f02e5 100644 --- a/vllm/model_executor/warmup/jit_warmup.py +++ b/vllm/model_executor/warmup/jit_warmup.py @@ -73,9 +73,7 @@ def _expand_warmup_values(values: WarmupValues) -> tuple[Any, ...]: expanded.append(value) next_value = values.advance(value) if next_value <= value: - raise ValueError( - "WarmupIntRange.advance must return a greater value" - ) + raise ValueError("WarmupIntRange.advance must return a greater value") value = next_value return tuple(expanded) if isinstance(values, (list, tuple)): diff --git a/vllm/models/inkling/nvidia/ops/fa4_rel_attention.py b/vllm/models/inkling/nvidia/ops/fa4_rel_attention.py index ce10d4fbbbf5..4385786135ae 100644 --- a/vllm/models/inkling/nvidia/ops/fa4_rel_attention.py +++ b/vllm/models/inkling/nvidia/ops/fa4_rel_attention.py @@ -242,9 +242,7 @@ def dispatch( # type: ignore[override] window_size=window_size, max_seqlen_q=max_seqlen_q, num_splits=num_splits, - num_warps_bucket=( - _num_warps_bucket(num_reqs) if num_splits > 1 else None - ), + num_warps_bucket=(_num_warps_bucket(num_reqs) if num_splits > 1 else None), large_num_reqs=num_reqs > 1024, ) diff --git a/vllm/v1/attention/backends/mla/prefill/flash_attn.py b/vllm/v1/attention/backends/mla/prefill/flash_attn.py index dd31e1d2a11d..4d01a121f113 100644 --- a/vllm/v1/attention/backends/mla/prefill/flash_attn.py +++ b/vllm/v1/attention/backends/mla/prefill/flash_attn.py @@ -484,4 +484,5 @@ def run_prefill_context_chunk( return_softmax_lse=True, ) + FA4_MLA_PREFILL_KERNEL = FA4MLAPrefillKernel() From 299a79fe01ed57723cb2812d9711f430a838fa9c Mon Sep 17 00:00:00 2001 From: LopezCastroRoberto Date: Wed, 29 Jul 2026 11:09:32 -0400 Subject: [PATCH 12/12] address review comments Signed-off-by: LopezCastroRoberto --- vllm/model_executor/warmup/cutedsl_warmup.py | 7 ---- vllm/model_executor/warmup/jit_warmup.py | 40 +++++++------------- 2 files changed, 13 insertions(+), 34 deletions(-) diff --git a/vllm/model_executor/warmup/cutedsl_warmup.py b/vllm/model_executor/warmup/cutedsl_warmup.py index 59838dba0eba..f2324f70d5c6 100644 --- a/vllm/model_executor/warmup/cutedsl_warmup.py +++ b/vllm/model_executor/warmup/cutedsl_warmup.py @@ -105,13 +105,6 @@ def cutedsl_warmup() -> None: logger.info("Skipping CuTeDSL warmup because no compile units were requested.") return - if is_global_first_rank(): - logger.warning( - "The legacy CuTeDSL warmup registry is deprecated and will be removed. " - "Migrate providers to the shared JIT warmup contract: " - "https://github.com/vllm-project/vllm/issues/49349" - ) - unit_names = list(dict.fromkeys(unit.name for unit in compile_units)) logger.info( "Warming up CuTeDSL compile_units=%d names=%s.", diff --git a/vllm/model_executor/warmup/jit_warmup.py b/vllm/model_executor/warmup/jit_warmup.py index 4ef0c70f02e5..d8c51409502e 100644 --- a/vllm/model_executor/warmup/jit_warmup.py +++ b/vllm/model_executor/warmup/jit_warmup.py @@ -104,17 +104,6 @@ def zip_inputs(*rows: Mapping[str, WarmupValues]) -> _WarmupInputRows: return _WarmupInputRows(rows=tuple(input_rows)) -def _expand_warmup_value_axes( - values: Mapping[str, WarmupValues], - input_names: frozenset[str], -) -> tuple[tuple[str, tuple[Any, ...]], ...]: - return tuple( - (name, _expand_warmup_values(value)) - for name, value in values.items() - if name in input_names - ) - - def _expand_warmup_input_rows( rows: tuple[Mapping[str, WarmupValues], ...], input_names: frozenset[str], @@ -411,19 +400,6 @@ def _collect_expression_body( raise ValueError(f"Expected {fn.__name__} to return an expression") -def _collect_dispatch_body( - fn: CompileKeyDispatchFn[Any], - function_def: ast.FunctionDef, -) -> tuple[list[tuple[str, ast.AST]], ast.Call]: - local_exprs, return_expr = _collect_expression_body(fn, function_def) - if not isinstance(return_expr, ast.Call): - raise _dispatch_expr_error( - return_expr, - "Dispatch must return one CompileKey(...) call", - ) - return local_exprs, return_expr - - def _function_trace_inputs( fn: Callable[..., Any], ) -> tuple[dict[str, Any], set[str]]: @@ -446,7 +422,12 @@ def _trace_compile_key_dispatch( globals_ = source_fn.__globals__ function_def = get_function_source_node(fn) - local_exprs, return_call = _collect_dispatch_body(fn, function_def) + local_exprs, return_expr = _collect_expression_body(fn, function_def) + if not isinstance(return_expr, ast.Call): + raise _dispatch_expr_error( + return_expr, + "Dispatch must return one CompileKey(...) call", + ) field_exprs: list[tuple[str, ast.AST]] = [] defaults, candidate_names = _function_trace_inputs(fn) @@ -454,7 +435,7 @@ def _trace_compile_key_dispatch( local_names = {name for name, _ in local_exprs} for _, expr in local_exprs: input_names.update(_collect_input_names(expr, candidate_names)) - for keyword in return_call.keywords: + for keyword in return_expr.keywords: if keyword.arg is None: raise ValueError(f"{fn.__name__} cannot use **kwargs in CompileKey") field_exprs.append((keyword.arg, keyword.value)) @@ -532,7 +513,12 @@ def traced( _expand_warmup_input_rows(group.rows, input_names) for group in input_groups ) - expanded_kwarg_axes = _expand_warmup_value_axes(kwargs, input_names) + # Expand independent keyword inputs into cartesian-product axes. + expanded_kwarg_axes = tuple( + (name, _expand_warmup_values(value)) + for name, value in kwargs.items() + if name in input_names + ) dispatch_value_axes = ( *expanded_input_groups, *(values for _, values in expanded_kwarg_axes),