[vLLM IR] 2/N fused_add_rms_norm and maybe_inplace overload (#36823)

Signed-off-by: Luka Govedič <lgovedic@redhat.com>
Signed-off-by: Luka Govedič <ProExpertProg@users.noreply.github.com>
This commit is contained in:
Luka Govedič
2026-05-01 23:41:15 -04:00
committed by GitHub
parent 3e49479c4b
commit d58c42e19c
44 changed files with 2833 additions and 779 deletions
+1 -99
View File
@@ -647,58 +647,6 @@ def _rocm_aiter_gemm_a8w8_blockscale_fake(
return Y
def _rocm_aiter_rms_norm_impl(
x: torch.Tensor, weight: torch.Tensor, variance_epsilon: float
) -> torch.Tensor:
from aiter import rms_norm
if x.dim() > 2:
x_original_shape = x.shape
x = x.reshape(-1, x_original_shape[-1])
x = rms_norm(x, weight, variance_epsilon)
return x.reshape(x_original_shape)
return rms_norm(x, weight, variance_epsilon)
def _rocm_aiter_rms_norm_fake(
x: torch.Tensor, weight: torch.Tensor, variance_epsilon: float
) -> torch.Tensor:
return torch.empty_like(x)
def _rocm_aiter_rmsnorm2d_fwd_with_add_impl(
x: torch.Tensor,
residual: torch.Tensor,
weight: torch.Tensor,
variance_epsilon: float,
) -> tuple[torch.Tensor, torch.Tensor]:
from aiter import rmsnorm2d_fwd_with_add
residual_out = torch.empty_like(residual)
out = torch.empty_like(x)
rmsnorm2d_fwd_with_add(
out, # output
x, # input
residual, # residual input
residual_out, # residual output
weight,
variance_epsilon,
)
return out, residual_out
def _rocm_aiter_rmsnorm2d_fwd_with_add_fake(
x: torch.Tensor,
residual: torch.Tensor,
weight: torch.Tensor,
variance_epsilon: float,
) -> tuple[torch.Tensor, torch.Tensor]:
residual_out = torch.empty_like(residual)
out = torch.empty_like(x)
return out, residual_out
def _rocm_aiter_rmsnorm_fused_add_dynamic_quant_impl(
x: torch.Tensor,
residual: torch.Tensor,
@@ -1229,10 +1177,9 @@ class rocm_aiter_ops:
# Check if aiter is enabled before using operations
if rocm_aiter_ops.is_enabled():
result = rocm_aiter_ops.rms_norm(x, weight, epsilon)
result = rocm_aiter_ops.per_token_quant(x, FP8_DTYPE)
Operations:
- RMS normalization: rms_norm, rms_norm2d_with_add
- GEMM operations: gemm_a8w8, gemm_a8w8_blockscale
- Fused MoE: fused_moe, asm_moe_tkw1
- Routing: topk_softmax, biased_grouped_topk, grouped_topk
@@ -1244,7 +1191,6 @@ class rocm_aiter_ops:
# Check if the env variable is set
_AITER_ENABLED = envs.VLLM_ROCM_USE_AITER
_LINEAR_ENABLED = envs.VLLM_ROCM_USE_AITER_LINEAR
_RMSNORM_ENABLED = envs.VLLM_ROCM_USE_AITER_RMSNORM
_FMOE_ENABLED = envs.VLLM_ROCM_USE_AITER_MOE
_MLA_ENABLED = envs.VLLM_ROCM_USE_AITER_MLA
_MHA_ENABLED = envs.VLLM_ROCM_USE_AITER_MHA
@@ -1275,7 +1221,6 @@ class rocm_aiter_ops:
"""
cls._AITER_ENABLED = envs.VLLM_ROCM_USE_AITER
cls._LINEAR_ENABLED = envs.VLLM_ROCM_USE_AITER_LINEAR
cls._RMSNORM_ENABLED = envs.VLLM_ROCM_USE_AITER_RMSNORM
cls._FMOE_ENABLED = envs.VLLM_ROCM_USE_AITER_MOE
cls._MLA_ENABLED = envs.VLLM_ROCM_USE_AITER_MLA
cls._MHA_ENABLED = envs.VLLM_ROCM_USE_AITER_MHA
@@ -1367,11 +1312,6 @@ class rocm_aiter_ops:
def is_linear_fp8_enabled(cls) -> bool:
return cls.is_linear_enabled()
@classmethod
@if_aiter_supported
def is_rmsnorm_enabled(cls) -> bool:
return cls._AITER_ENABLED and cls._RMSNORM_ENABLED
@classmethod
@if_aiter_supported
def is_fused_moe_enabled(cls) -> bool:
@@ -1560,19 +1500,6 @@ class rocm_aiter_ops:
fake_impl=_rocm_aiter_gemm_a8w8_blockscale_fake,
)
direct_register_custom_op(
op_name="rocm_aiter_rms_norm",
op_func=_rocm_aiter_rms_norm_impl,
fake_impl=_rocm_aiter_rms_norm_fake,
)
direct_register_custom_op(
op_name="rocm_aiter_rmsnorm2d_fwd_with_add",
op_func=_rocm_aiter_rmsnorm2d_fwd_with_add_impl,
fake_impl=_rocm_aiter_rmsnorm2d_fwd_with_add_fake,
dispatch_key=current_platform.dispatch_key,
)
direct_register_custom_op(
op_name="rocm_aiter_rmsnorm_fused_dynamic_quant",
op_func=_rocm_aiter_rmsnorm_fused_dynamic_quant_impl,
@@ -1672,14 +1599,6 @@ class rocm_aiter_ops:
_OPS_REGISTERED = True
@staticmethod
def get_rmsnorm_fused_add_op() -> OpOverload:
return torch.ops.vllm.rocm_aiter_rmsnorm2d_fwd_with_add.default
@staticmethod
def get_rmsnorm_op() -> OpOverload:
return torch.ops.vllm.rocm_aiter_rms_norm.default
@staticmethod
def get_rmsnorm_fused_add_dynamic_quant_op() -> OpOverload:
return torch.ops.vllm.rocm_aiter_rmsnorm_fused_add_dynamic_quant.default
@@ -1724,23 +1643,6 @@ class rocm_aiter_ops:
def get_fused_mla_dual_rms_norm_op() -> OpOverload:
return torch.ops.vllm.fused_mla_dual_rms_norm.default
@staticmethod
def rms_norm(
x: torch.Tensor, weight: torch.Tensor, variance_epsilon: float
) -> torch.Tensor:
return torch.ops.vllm.rocm_aiter_rms_norm(x, weight, variance_epsilon)
@staticmethod
def rms_norm2d_with_add(
x: torch.Tensor,
residual: torch.Tensor,
weight: torch.Tensor,
variance_epsilon: float,
) -> tuple[torch.Tensor, torch.Tensor]:
return torch.ops.vllm.rocm_aiter_rmsnorm2d_fwd_with_add(
x, residual, weight, variance_epsilon
)
@staticmethod
def w8a8_gemm(
A: torch.Tensor,
-96
View File
@@ -1,96 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Small helper wrappers for external Oink Blackwell custom ops.
vLLM does not depend on the external Oink repository/package. When an external
plugin registers torch.library.custom_op entrypoints under the `oink::`
namespace (e.g. via vLLM's general_plugins mechanism) and
`VLLM_USE_OINK_OPS=1` is set, vLLM can route eligible calls to those ops.
This module provides:
- A single place to probe Oink op availability at module init time
(outside torch.compile tracing), and
- Thin wrappers around the torch.ops entrypoints for use in CUDA fast paths,
without introducing graph breaks.
Important:
Do not call the availability helpers in a compiled region. They may call
functions decorated with `torch._dynamo.disable` to safely check
conditions that should not be traced.
"""
from __future__ import annotations
from collections.abc import Callable
import torch
try:
from torch._dynamo import disable as _dynamo_disable # type: ignore[attr-defined]
except Exception: # pragma: no cover
def _dynamo_disable(fn: Callable): # type: ignore[misc]
return fn
def _has_oink_op(op_name: str) -> bool:
"""Check if a specific oink op is registered."""
return hasattr(torch.ops, "oink") and hasattr(torch.ops.oink, op_name)
@_dynamo_disable
def is_oink_available_for_device(device_index: int) -> bool:
"""Return True if Oink ops are registered and device is SM100+.
This function is intended to be called during module initialization
(e.g., in RMSNorm.__init__), not in the forward path.
External plugins are expected to gate registration on SM100+ and
VLLM_USE_OINK_OPS=1, so if the ops are present they should be usable.
"""
if not torch.cuda.is_available():
return False
try:
major, minor = torch.cuda.get_device_capability(device_index)
sm = 10 * major + minor
if sm < 100:
return False
except Exception:
return False
return _has_oink_op("rmsnorm")
def has_fused_add_rms_norm() -> bool:
"""Return True if the in-place fused op is registered."""
return _has_oink_op("fused_add_rms_norm")
def rmsnorm(x: torch.Tensor, weight: torch.Tensor, eps: float) -> torch.Tensor:
"""Call `torch.ops.oink.rmsnorm`.
This wrapper is safe to call in torch.compile regions.
"""
return torch.ops.oink.rmsnorm(x, weight, eps)
def fused_add_rms_norm_(
x: torch.Tensor,
residual: torch.Tensor,
weight: torch.Tensor,
eps: float,
) -> None:
"""Call `torch.ops.oink.fused_add_rms_norm` (mutates x and residual)."""
torch.ops.oink.fused_add_rms_norm(x, residual, weight, eps)
def fused_add_rms_norm(
x: torch.Tensor,
residual: torch.Tensor,
weight: torch.Tensor,
eps: float,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Convenience wrapper returning (x, residual) after in-place mutation."""
fused_add_rms_norm_(x, residual, weight, eps)
return x, residual
+19
View File
@@ -50,6 +50,7 @@ from .partition_rules import (
should_split,
)
from .passes.inductor_pass import InductorPass, pass_context
from .passes.ir.inplace_functionalization import VllmIRInplaceFunctionalizationPass
from .passes.pass_manager import PostGradPassManager
logger = init_logger(__name__)
@@ -926,6 +927,24 @@ class VllmBackend:
return standalone_compile_artifacts, sym_shape_indices_map, returns_tuple_map
def configure_post_pass(self) -> None:
# TODO proper PassManager?
pre_grad_pass_key = "pre_grad_custom_pass"
assert self.pass_key != pre_grad_pass_key
assert pre_grad_pass_key not in self.inductor_config
self.inductor_config[pre_grad_pass_key] = VllmIRInplaceFunctionalizationPass(
self.vllm_config
)
# Make sure pre_grad_custom_pass is not pickled
# as part of AOTAutograd built-in cache key
# TODO(luka) is there a cleaner way to do this
import torch._inductor.config as inductor_config
ignore = inductor_config._cache_config_ignore_prefix + [pre_grad_pass_key]
assert "_cache_config_ignore_prefix" not in self.inductor_config
self.inductor_config["_cache_config_ignore_prefix"] = ignore
# Configure the (nominally post-grad) pass manager
self.pass_manager.configure(self.vllm_config)
# Post-grad custom passes are run using the post_grad_custom_post_pass
@@ -40,7 +40,7 @@ from ..vllm_inductor_pass import (
VllmPatternMatcherPass,
VllmPatternReplacement,
)
from .matcher_utils import MatcherFusedAddRMSNorm, MatcherQuantFP8
from .matcher_utils import MatcherQuantFP8
FP8_DTYPE = current_platform.fp8_dtype()
@@ -356,10 +356,11 @@ class AllReduceFusedAddRMSNormPattern(BasePattern):
super().__init__(dtype, device)
self.epsilon = epsilon
self.allreduce_params = allreduce_params
self.rmsnorm_matcher = MatcherFusedAddRMSNorm(epsilon)
def get_inputs(self) -> list[torch.Tensor]:
input, residual, weight = self.rmsnorm_matcher.inputs()
input = self.empty(5, 16)
residual = self.empty(5, 16)
weight = self.empty(16)
# input goes through allreduce first, always 16-bit
return [residual, input.to(self.dtype), weight]
@@ -369,7 +370,9 @@ class AllReduceFusedAddRMSNormPattern(BasePattern):
residual: torch.Tensor, input: torch.Tensor, weight: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
allreduce_output = tensor_model_parallel_all_reduce(input)
rms, residual = self.rmsnorm_matcher(allreduce_output, weight, residual)
rms, residual = vllm.ir.ops.fused_add_rms_norm(
allreduce_output, residual, weight, self.epsilon
)
return rms, residual
def replacement(
@@ -503,11 +506,12 @@ class AllReduceFusedAddRMSNormStaticQuantFP8Pattern(BasePattern):
self.allreduce_params = allreduce_params
self.quant_dtype = torch.float8_e4m3fn
self.rmsnorm_matcher = MatcherFusedAddRMSNorm(epsilon)
self.quant_matcher = MatcherQuantFP8(kFp8StaticTensorSym)
def get_inputs(self) -> list[torch.Tensor]:
input, residual, weight = self.rmsnorm_matcher.inputs()
input = self.empty(5, 16)
residual = self.empty(5, 16)
weight = self.empty(16)
_, scale = self.quant_matcher.inputs()
# input goes through allreduce first, always 16-bit
@@ -521,7 +525,9 @@ class AllReduceFusedAddRMSNormStaticQuantFP8Pattern(BasePattern):
scale: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
allreduce_output = tensor_model_parallel_all_reduce(input)
rms, res = self.rmsnorm_matcher(allreduce_output, weight, residual)
rms, res = vllm.ir.ops.fused_add_rms_norm(
allreduce_output, residual, weight, self.epsilon
)
quant, _ = self.quant_matcher(rms, scale)
return quant, res
@@ -668,7 +674,6 @@ class AllReduceFusedAddRMSNormStaticQuantNVFP4Pattern(BasePattern):
super().__init__(dtype, device)
self.epsilon = epsilon
self.allreduce_params = allreduce_params
self.rmsnorm_matcher = MatcherFusedAddRMSNorm(epsilon)
def get_inputs(self) -> list[torch.Tensor]:
input = torch.empty([16, 16], device=self.device, dtype=self.dtype)
@@ -700,7 +705,9 @@ class AllReduceFusedAddRMSNormStaticQuantNVFP4Pattern(BasePattern):
input_global_scale: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
allreduce_output = tensor_model_parallel_all_reduce(input)
rms, residual = self.rmsnorm_matcher(allreduce_output, weight, residual)
rms, residual = vllm.ir.ops.fused_add_rms_norm(
allreduce_output, residual, weight, self.epsilon
)
quant_out_tuple = auto_functionalized(
STATIC_FP4_QUANT_OP,
input=rms,
@@ -955,15 +962,11 @@ class AiterAllreduceFusedAddRMSNormPattern(BasePattern, VllmPatternReplacement):
super().__init__(dtype, device)
self.epsilon = epsilon
self.dtype = dtype
self.rmsnorm_matcher = MatcherFusedAddRMSNorm(
epsilon, match_rocm_aiter=use_aiter_rmsnorm
)
self.FUSED_AR_RMSNORM_OP = rocm_aiter_ops.get_fused_allreduce_rmsnorm_op()
def get_inputs(self) -> list[torch.Tensor]:
input, residual, weight = self.rmsnorm_matcher.inputs()
return [residual, input.to(self.dtype), weight]
# input, residual, weight
return [self.empty(5, 16), self.empty(5, 16), self.empty(16)]
@property
def pattern(self):
@@ -971,8 +974,9 @@ class AiterAllreduceFusedAddRMSNormPattern(BasePattern, VllmPatternReplacement):
residual: torch.Tensor, input: torch.Tensor, weight: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
allreduce_output = tensor_model_parallel_all_reduce(input)
rms, residual = self.rmsnorm_matcher(allreduce_output, weight, residual)
rms, residual = vllm.ir.ops.fused_add_rms_norm(
allreduce_output, residual, weight, self.epsilon
)
return rms, residual
return _pattern
@@ -10,7 +10,6 @@ from torch._ops import OpOverload
from vllm._aiter_ops import rocm_aiter_ops
from vllm.config import get_current_vllm_config
from vllm.model_executor.layers.activation import SiluAndMul
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.quantization.input_quant_fp8 import QuantFP8
from vllm.model_executor.layers.quantization.utils.quant_utils import (
GroupShape,
@@ -159,72 +158,6 @@ class MatcherRotaryEmbedding(MatcherCustomOp):
return result
class MatcherFusedAddRMSNorm(MatcherCustomOp):
def __init__(
self,
epsilon: float,
enabled: bool | None = None,
match_rocm_aiter: bool = False,
) -> None:
if enabled is None:
enabled = RMSNorm.enabled()
super().__init__(enabled)
self.epsilon = epsilon
self.match_rocm_aiter = match_rocm_aiter
self._rmsnorm_op = RMS_ADD_OP
if match_rocm_aiter:
self._rmsnorm_op = rocm_aiter_ops.get_rmsnorm_fused_add_op()
def inputs(self) -> list[torch.Tensor]:
input = self.empty(5, 16) if self.enabled else self.empty_f32(5, 16)
weight = self.empty(16)
residual = self.empty(5, 16)
return [input, weight, residual]
def forward_rocm_aiter(
self,
input: torch.Tensor,
weight: torch.Tensor,
residual: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
return self._rmsnorm_op( # type: ignore[no-any-return]
x=input, residual=residual, weight=weight, variance_epsilon=self.epsilon
)
def forward_custom(
self,
input: torch.Tensor,
weight: torch.Tensor,
residual: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
if self.match_rocm_aiter:
return self.forward_rocm_aiter(input, weight, residual)
_, result, residual = auto_functionalized(
self._rmsnorm_op,
input=input,
residual=residual,
weight=weight,
epsilon=self.epsilon,
)
return result, residual
def forward_native(
self,
input: torch.Tensor,
weight: torch.Tensor,
residual: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
result: tuple[torch.Tensor, torch.Tensor] = RMSNorm.forward_static(
input, self.epsilon, input.size(-1), self.model_dtype, weight, residual
)
return result
class MatcherQuantFP8(MatcherCustomOp):
def __init__(
self,
@@ -29,7 +29,6 @@ from vllm.platforms import current_platform
from ..inductor_pass import enable_fake_mode
from ..vllm_inductor_pass import VllmInductorPass, VllmPatternMatcherPass
from .matcher_utils import (
MatcherFusedAddRMSNorm,
MatcherQuantFP8,
)
@@ -146,9 +145,6 @@ class RMSNormQuantPattern:
assert key in FUSED_OPS, f"unsupported fused rmsnorm+quant op for {key}"
self.FUSED_OP = FUSED_OPS[key]
if key.fused_add:
self.rmsnorm_matcher = MatcherFusedAddRMSNorm(epsilon)
self.quant_matcher = MatcherQuantFP8(
key.quant,
has_col_major_scales=has_col_major_scales,
@@ -231,7 +227,9 @@ class FusedAddRMSNormStaticQuantPattern(RMSNormQuantPattern):
residual: torch.Tensor,
scale: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
result_rms, residual = self.rmsnorm_matcher(input, weight, residual)
result_rms, residual = vllm.ir.ops.fused_add_rms_norm(
input, residual, weight, self.epsilon
)
result, _ = self.quant_matcher(result_rms, scale)
return result, residual
@@ -261,8 +259,9 @@ class FusedAddRMSNormStaticQuantPattern(RMSNormQuantPattern):
return at[1], at[2]
inputs = [
# input, weight, residual
*self.rmsnorm_matcher.inputs(),
empty_bf16(5, 16), # input
empty_bf16(16), # weight
empty_bf16(5, 16), # residual
self.quant_matcher.inputs()[1], # scale
]
@@ -311,7 +310,9 @@ class FusedAddRMSNormGroupQuantPattern(RMSNormQuantPattern):
residual: torch.Tensor,
scale: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
result_rms, residual = self.rmsnorm_matcher(input, weight, residual)
result_rms, residual = vllm.ir.ops.fused_add_rms_norm(
input, residual, weight, self.epsilon
)
result = torch.empty(
result_rms.shape,
device=result_rms.device,
@@ -366,12 +367,17 @@ class FusedAddRMSNormGroupQuantPattern(RMSNormQuantPattern):
# result, residual, scale
return at[1], at[3], at[2]
scale = self.quant_matcher.empty_f32(1, 1)
inputs = [
empty_bf16(5, 16), # input
empty_bf16(16), # weight
empty_bf16(5, 16), # residual
self.quant_matcher.empty_f32(1, 1), # scale
]
pm.register_replacement(
pattern,
replacement,
self.rmsnorm_matcher.inputs() + [scale],
inputs,
pm.fwd_only,
pm_pass,
extra_check=_rms_input_weight_dtype_match,
@@ -552,7 +558,9 @@ class FusedAddRMSNormDynamicQuantPattern(RMSNormQuantPattern):
def pattern(
input: torch.Tensor, weight: torch.Tensor, residual: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
result_rms, residual = self.rmsnorm_matcher(input, weight, residual)
result_rms, residual = vllm.ir.ops.fused_add_rms_norm(
input, residual, weight, self.epsilon
)
result, scale = self.quant_matcher(result_rms)
return result, residual, scale
@@ -580,10 +588,16 @@ class FusedAddRMSNormDynamicQuantPattern(RMSNormQuantPattern):
# result, residual, scale
return at[1], at[3], at[2]
inputs = [
empty_bf16(5, 16), # input
empty_bf16(16), # weight
empty_bf16(5, 16), # residual
]
pm.register_replacement(
pattern,
replacement,
self.rmsnorm_matcher.inputs(),
inputs,
pm.fwd_only,
pm_pass,
extra_check=_rms_input_weight_dtype_match,
@@ -29,7 +29,6 @@ from ..vllm_inductor_pass import (
VllmPatternReplacement,
)
from .matcher_utils import (
MatcherFusedAddRMSNorm,
MatcherQuantFP8,
MatcherSiluAndMul,
)
@@ -49,10 +48,6 @@ class AiterRMSNormQuantPattern:
self.quant_dtype = key.quant.dtype
self.device = torch.device("cuda")
if key.fused_add:
self.rmsnorm_matcher = MatcherFusedAddRMSNorm(
epsilon, match_rocm_aiter=True
)
self.quant_matcher = MatcherQuantFP8(
key.quant,
match_rocm_aiter=match_aiter_quant,
@@ -145,7 +140,9 @@ class AiterFusedAddRMSNormDynamicQuantPattern(AiterRMSNormQuantPattern):
weight: torch.Tensor,
residual: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
result_rms, residual_out = self.rmsnorm_matcher(input, weight, residual)
result_rms, residual_out = torch.ops.vllm_ir.fused_add_rms_norm(
input, residual, weight, self.epsilon
)
result, scale = self.quant_matcher(result_rms)
return result, residual_out, scale
@@ -163,10 +160,16 @@ class AiterFusedAddRMSNormDynamicQuantPattern(AiterRMSNormQuantPattern):
return result[0], result[1], result[2]
inputs = [
self.empty(5, 16), # input
self.empty(16), # weight
self.empty(5, 16), # residual
]
pm.register_replacement(
pattern,
replacement,
self.rmsnorm_matcher.inputs(),
inputs,
pm.fwd_only,
pm_pass,
)
@@ -258,7 +261,9 @@ class AiterFusedAddRMSFp8GroupQuantPattern(AiterRMSNormQuantPattern):
weight: torch.Tensor,
residual: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
result_rms, residual_out = self.rmsnorm_matcher(input, weight, residual)
result_rms, residual_out = torch.ops.vllm_ir.fused_add_rms_norm(
input, residual, weight, self.epsilon
)
result, scale = self.quant_matcher(result_rms)
return result, residual_out, scale
@@ -279,9 +284,13 @@ class AiterFusedAddRMSFp8GroupQuantPattern(AiterRMSNormQuantPattern):
# result, scale, residual
return at[0], at[1], at[2]
pm.register_replacement(
pattern, replacement, self.rmsnorm_matcher.inputs(), pm.fwd_only, pm_pass
)
inputs = [
self.empty(5, 16), # input
self.empty(16), # weight
self.empty(5, 16), # residual
]
pm.register_replacement(pattern, replacement, inputs, pm.fwd_only, pm_pass)
class RocmAiterRMSNormQuantFusionPass(VllmPatternMatcherPass):
@@ -420,12 +429,15 @@ class AddAiterRMSNormPadPattern:
self.epsilon = epsilon
self.hidden_size = hidden_size
self.x_pad_to_multiple = x_pad_to_multiple
self.rmsnorm_matcher = MatcherFusedAddRMSNorm(epsilon, match_rocm_aiter=True)
def get_inputs(self) -> list[torch.Tensor]:
input, weight, residual = self.rmsnorm_matcher.inputs()
router_weight = torch.empty([8, 16], dtype=weight.dtype, device=weight.device)
router_bias = torch.empty([8], dtype=weight.dtype, device=weight.device)
device = torch.device("cuda")
dtype = torch.bfloat16
input = torch.empty(5, 16, dtype=dtype, device=device)
weight = torch.empty(16, dtype=dtype, device=device)
residual = torch.empty(5, 16, dtype=dtype, device=device)
router_weight = torch.empty([8, 16], dtype=dtype, device=device)
router_bias = torch.empty([8], dtype=dtype, device=device)
return [input, weight, residual, router_weight, router_bias]
def register(self, pm_pass: PatternMatcherPass) -> None:
@@ -439,7 +451,9 @@ class AddAiterRMSNormPadPattern:
pad_size = self.x_pad_to_multiple - (
self.hidden_size % self.x_pad_to_multiple
)
result_rms, residual_out = self.rmsnorm_matcher(input, weight, residual)
result_rms, residual_out = torch.ops.vllm_ir.fused_add_rms_norm(
input, residual, weight, self.epsilon
)
router_logits = torch.ops.vllm.rocm_unquantized_gemm(
result_rms, router_weight, router_bias
)
@@ -23,7 +23,7 @@ from vllm.model_executor.layers.quantization.utils.quant_utils import (
from ..inductor_pass import enable_fake_mode
from ..utility.noop_elimination import NoOpEliminationPass
from ..vllm_inductor_pass import VllmInductorPass, VllmPatternMatcherPass
from .matcher_utils import MatcherFusedAddRMSNorm, MatcherQuantFP8
from .matcher_utils import MatcherQuantFP8
logger = init_logger(__name__)
@@ -174,7 +174,6 @@ class FirstAllReduceRMSNormPattern(_SequenceParallelPatternHelper):
class MiddleAllReduceRMSNormPattern(_SequenceParallelPatternHelper):
def __init__(self, epsilon: float, dtype: torch.dtype, device: str | None) -> None:
super().__init__(epsilon, dtype, device)
self.rmsnorm_matcher = MatcherFusedAddRMSNorm(epsilon)
def get_inputs(self) -> list[torch.Tensor]:
mm_1 = torch.empty([4, 4], device=self.device, dtype=self.dtype)
@@ -195,7 +194,9 @@ class MiddleAllReduceRMSNormPattern(_SequenceParallelPatternHelper):
rms_norm_weights: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
all_reduce = self._all_reduce(mm_1)
rmsnorm = self.rmsnorm_matcher(all_reduce, rms_norm_weights, residual)
rmsnorm = vllm.ir.ops.fused_add_rms_norm(
all_reduce, residual, rms_norm_weights, self.epsilon
)
return rmsnorm[0], rmsnorm[1]
def replacement(
@@ -208,7 +209,9 @@ class MiddleAllReduceRMSNormPattern(_SequenceParallelPatternHelper):
# once the seqpar pattern with the previous rmsnorm is replaced
reduce_scatter = self._reduce_scatter(mm_1)
residual = residual[0 : reduce_scatter.size(0), ...]
rmsnorm = self.rmsnorm_matcher(reduce_scatter, rms_norm_weights, residual)
rmsnorm = vllm.ir.ops.fused_add_rms_norm(
reduce_scatter, residual, rms_norm_weights, self.epsilon
)
all_gather = self._all_gather(rmsnorm[0])
# shape of residual changes but that's fine,
# next node is already slicing it, now becomes a noop
@@ -271,7 +274,6 @@ class FirstAllReduceRMSNormStaticFP8Pattern(_SequenceParallelPatternHelper):
class MiddleAllReduceRMSNormStaticFP8Pattern(_SequenceParallelPatternHelper):
def __init__(self, epsilon: float, dtype: torch.dtype, device: str | None) -> None:
super().__init__(epsilon, dtype, device)
self.rmsnorm_matcher = MatcherFusedAddRMSNorm(epsilon)
self.quant_matcher = MatcherQuantFP8(kFp8StaticTensorSym)
def get_inputs(self) -> list[torch.Tensor]:
@@ -290,8 +292,8 @@ class MiddleAllReduceRMSNormStaticFP8Pattern(_SequenceParallelPatternHelper):
scale: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
all_reduce = self._all_reduce(mm_1)
rms, residual_out = self.rmsnorm_matcher(
all_reduce, rms_norm_weights, residual
rms, residual_out = vllm.ir.ops.fused_add_rms_norm(
all_reduce, residual, rms_norm_weights, self.epsilon
)
quant, _ = self.quant_matcher(rms, scale)
return quant, residual_out
@@ -308,8 +310,8 @@ class MiddleAllReduceRMSNormStaticFP8Pattern(_SequenceParallelPatternHelper):
# once the seqpar pattern with the previous rmsnorm is replaced
reduce_scatter = self._reduce_scatter(mm_1)
residual = residual[0 : reduce_scatter.size(0), ...]
rms, residual_out = self.rmsnorm_matcher(
reduce_scatter, rms_norm_weights, residual
rms, residual_out = vllm.ir.ops.fused_add_rms_norm(
reduce_scatter, residual, rms_norm_weights, self.epsilon
)
quant, _ = self.quant_matcher(rms, scale)
all_gather = self._all_gather(quant)
+3
View File
@@ -30,6 +30,9 @@ class PassContext:
def __init__(self, compile_range: Range):
self.compile_range: Range = compile_range
# set of arg indices
self.donated_input_ids: set[int] = set()
def get_pass_context() -> PassContext:
"""Get the current pass context."""
@@ -0,0 +1,126 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import torch
from torch import fx
from torch._higher_order_ops.auto_functionalize import auto_functionalized
from torch._higher_order_ops.triton_kernel_wrap import TritonKernelWrapperFunctional
from torch._ops import HigherOrderOperator, OpOverload
from vllm.config import VllmConfig
from vllm.logger import init_logger
from ..fx_utils import is_func
from ..inductor_pass import get_pass_context
from ..vllm_inductor_pass import VllmInductorPass
logger = init_logger(__name__)
def user_writes_to_node(user: fx.Node, node: fx.Node) -> bool:
if user.op == "output":
return False
if is_func(user, auto_functionalized):
# While autofunc writes to the node,
# this is a follow-up use we're not interested in.
# It is also guaranteed to be the final use,
# as auto_functionalized returns the tensor back for follow-up use.
return False
elif user.op == "call_function" and isinstance(user.target, HigherOrderOperator):
# By default, be conservative, assume this could be a write
# (except functional HOPs)
return not isinstance(user.target, TritonKernelWrapperFunctional)
assert isinstance(user.target, OpOverload), (
f"{node=} {user=} {user.op=} {user.target=}"
)
schema = user.target._schema
assert len(user.args) <= len(schema.arguments)
for i, arg in enumerate(user.args):
# Only interested in writes to node
if arg is not node:
continue
# If not a write, next arg could be
if schema.arguments[i].is_write:
return True
# No writes found
return False
class UnsafeCloneEliminationPass(VllmInductorPass):
"""
This pass removes clone nodes that are no longer needed after vLLM IR lowering.
It uses donated_input_ids to eliminate clones of donated graph inputs, preserving
contents of non-donated graph inputs.
It is "unsafe" because it does not (yet) take aliasing into account. Solving
aliasing is an open problem, so this pass intends to support known vLLM cases
and not guarantee soundness on general graphs. In the future, this pass will likely
support basic forms of aliasing to handle simple views (e.g. qkv -> q,k,v).
"""
def __init__(self, vllm_config: VllmConfig) -> None:
super().__init__(vllm_config)
@VllmInductorPass.time_and_log
def __call__(self, graph: fx.Graph) -> None:
count = 0
node_to_idx = {node: i for i, node in enumerate(graph.nodes)}
pass_context = get_pass_context()
donated_input_ids = pass_context.donated_input_ids
logger.debug("Donated input ids: %s", donated_input_ids)
for node in graph.nodes:
if not is_func(node, torch.ops.aten.clone.default):
continue
original_node = node.args[0]
assert isinstance(original_node, fx.Node)
# Clone needs to be preserved if node is getting written to and
# the old value is used again.
# This could only happen if an inplace implementation was lowered.
# Then node (the clone) will have one write.
# TODO(luka) hopefully this can be removed once we lower functional graphs.
write_idxs = [
node_to_idx[u] for u in node.users if user_writes_to_node(u, node)
]
assert len(write_idxs) in (0, 1)
if write_idxs:
# Check if a user of original_node occurs after a write
write_idx = write_idxs[0]
if any(
node_to_idx[orig_user] > write_idx
for orig_user in original_node.users
):
logger.debug(
"Clone removal not possible, "
"original_node=%s used after mutation on node=%s",
original_node,
node,
)
continue
# Check if a node is a (non-donated) graph input
if (
original_node.op == "placeholder"
and node_to_idx[original_node] not in donated_input_ids
):
logger.debug(
"Graph input %s not donated, cannot eliminate its clone",
original_node,
)
continue
logger.debug(
"Node %s is a redundant clone node of %s, removing it",
node,
original_node,
)
node.replace_all_uses_with(original_node)
graph.erase_node(node)
count += 1
logger.debug("CloneCleanupPass removed %d clone nodes", count)
@@ -0,0 +1,101 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections import defaultdict
from torch import fx
from torch._inductor.pattern_matcher import (
PatternMatcherPass,
)
from vllm.config import VllmConfig
from vllm.logger import init_logger
from ..inductor_pass import get_pass_context
from ..vllm_inductor_pass import VllmInductorPass
from .lowering_pass import get_ir_op
from .utils import overload_or_default
logger = init_logger(__name__)
class VllmIRInplaceFunctionalizationPass(VllmInductorPass):
"""
This pass functionalizes maybe_inplace vLLM IR ops to the default overload.
The maybe_inplace overloads have the same signature as the default overload
so the pass simply replaces the called overload.
That makes the graph properly functional.
The pass also validates that activations passed to maybe_inplace have no later
uses in the graph: they are donated to the maybe_inplace op call,
and their contents are not defined afterward.
This pass operates pre-AOTAutograd,
so it must handle non-normalized and non-functional IR.
"""
def __init__(self, vllm_config: VllmConfig) -> None:
super().__init__(vllm_config)
self.patterns = PatternMatcherPass(self.pass_name)
self.functionalized_ops: dict[str, int] = defaultdict(lambda: 0)
@VllmInductorPass.time_and_log
def __call__(self, graph: fx.Graph) -> None:
# clear at the beginning instead of end, so that tests can inspect
self.functionalized_ops.clear()
assert graph.owning_module is not None
node_to_idx = {node: i for i, node in enumerate(graph.nodes)}
# Pass donated input via vLLM's pass context
pass_context = get_pass_context()
pass_context.donated_input_ids = set[int]()
for node in graph.nodes:
if (ir_op := get_ir_op(node)) is None:
continue
op_overload = overload_or_default(node.target)
overload_name = op_overload._overloadname
if overload_name != "maybe_inplace":
assert overload_name == "default", (
f"Found overload {overload_name} for op {ir_op.name}, "
f"expected maybe_inplace or default"
)
continue
# must have maybe_inplace overload and allow_inplace
assert ir_op.allow_inplace and hasattr(ir_op, "maybe_inplace")
# Check that activation inputs are not used after this op
for arg_idx in ir_op.activation_indices:
arg = node.args[arg_idx]
assert isinstance(arg, fx.Node), "Activation inputs must be fx.Node"
for user in arg.users:
if node_to_idx[user] > node_to_idx[node]:
raise ValueError(
f"Input {arg} to maybe_inplace node {node} "
f"is used again after the node. "
f"This is not allowed; activation inputs to maybe_inplace "
f"ops are donated to the op, meaning their memory may be "
f"recycled for outputs.\n\n"
f"To preserve the inputs, use the default overload or "
f"clone them manually beforehand."
)
if arg.op == "placeholder":
# Graph input that maybe_inplace might modify.
# Mark it so downstream passes know it's donated.
# TODO(luka) store in placeholder node meta once supported
pass_context.donated_input_ids.add(node_to_idx[arg])
# Same signature, just replace the overload that's called.
node.target = ir_op.torch_op
self.functionalized_ops[ir_op.name] += 1
count = sum(self.functionalized_ops.values())
ops = ",".join(self.functionalized_ops.keys())
logger.debug("Donated input IDs: %s", pass_context.donated_input_ids)
logger.debug(
"%s functionalized %d vLLM IR nodes for op(s) %s",
self.pass_name,
count,
ops,
)
+9 -35
View File
@@ -10,7 +10,6 @@ from torch._inductor.pattern_matcher import (
PatternMatcherPass,
register_graph_pattern,
)
from torch._ops import OpOverload, OpOverloadPacket
from vllm.config import VllmConfig
from vllm.ir.op import IrOp
@@ -18,41 +17,11 @@ from vllm.logger import init_logger
from vllm.logging_utils import lazy
from ..vllm_inductor_pass import VllmInductorPass
from .utils import get_ir_op
logger = init_logger(__name__)
def get_default_overload(op: OpOverload | OpOverloadPacket) -> OpOverload:
if isinstance(op, OpOverloadPacket):
return op.default
assert isinstance(op, OpOverload), "Expected an OpOverload or OpOverloadPacket"
return op
def get_ir_op(node: fx.Node) -> IrOp | None:
if node.op != "call_function":
return None
if not isinstance(node.target, (OpOverload, OpOverloadPacket)):
return None
op_overload = get_default_overload(node.target)
if op_overload.namespace != "vllm_ir":
return None
op_name = op_overload._opname
if op_name not in IrOp.registry:
logger.warning(
"Unknown vLLM IR op %s, there's likely an issue with torch registration, "
"or a torch custom op was registered in the vllm_ir namespace by mistake.",
op_name,
)
return None
ir_op = IrOp.registry[op_name]
return ir_op
class VllmIRLoweringPass(VllmInductorPass):
"""
This pass lowers vLLM IR ops to their implementations the priority list.
@@ -76,7 +45,7 @@ class VllmIRLoweringPass(VllmInductorPass):
assert len(match.nodes) == 1, "Expected single node match"
node = match.nodes[0]
ir_op = get_ir_op(node)
ir_op = get_ir_op(node) # TODO is node.target always an overload?
assert ir_op is not None, "Expected vLLM IR op"
assert not node.kwargs # I think there should never be kwargs here
@@ -86,13 +55,18 @@ class VllmIRLoweringPass(VllmInductorPass):
self.selected_impls[ir_op.name][node.name] = ir_op_impl.provider
# replace_by_example wants node args, not the fake tensors
# use func_impl_fn to properly handle in-place implementations
# TODO(luka): Use aot_export_module to get functionalized graph
# TODO(luka): Cache the fx_replacement to avoid re-tracing the same impl
# Defaults not present on node.args but required for replacement tracing
bound_args = ir_op._py_signature.bind(*node.args)
bound_args.apply_defaults()
match.replace_by_example(ir_op_impl.impl_fn, bound_args.args)
# It is not safe to run functional passes (like DCE) on the replacements
# as they might not be functional.
match.replace_by_example(
ir_op_impl.func_impl_fn, bound_args.args, run_functional_passes=False
)
@VllmInductorPass.time_and_log
def __call__(self, graph: fx.Graph) -> None:
@@ -136,7 +110,7 @@ class VllmIRLoweringPass(VllmInductorPass):
if failed_nodes or failed_ops:
logger.warning("Failed to lower vLLM IR ops: %s", ",".join(failed_ops))
logger.warning("Full node list: %s", failed_nodes)
logger.warning("Full node list: %s", ",".join(str(n) for n in failed_nodes))
def uuid(self) -> str:
"""
+40
View File
@@ -0,0 +1,40 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from torch import fx
from torch._ops import OpOverload, OpOverloadPacket
from vllm.ir.op import IrOp
from vllm.logger import init_logger
logger = init_logger(__name__)
def overload_or_default(op: OpOverload | OpOverloadPacket) -> OpOverload:
if isinstance(op, OpOverloadPacket):
return op.default
assert isinstance(op, OpOverload), "Expected an OpOverload or OpOverloadPacket"
return op
def get_ir_op(node: fx.Node) -> IrOp | None:
if node.op != "call_function":
return None
if not isinstance(node.target, (OpOverload, OpOverloadPacket)):
return None
op_overload = overload_or_default(node.target)
if op_overload.namespace != "vllm_ir":
return None
op_name = op_overload._opname
if op_name not in IrOp.registry:
logger.warning(
"Unknown vLLM IR op %s, there's likely an issue with torch registration, "
"or a torch custom op was registered in the vllm_ir namespace by mistake.",
op_name,
)
return None
ir_op = IrOp.registry[op_name]
return ir_op
+7 -1
View File
@@ -14,6 +14,7 @@ from vllm.logger import init_logger
from vllm.platforms import current_platform
from vllm.utils.system_utils import set_env_var
from .ir.clone_elimination import UnsafeCloneEliminationPass
from .ir.lowering_pass import VllmIRLoweringPass
from .vllm_inductor_pass import VllmInductorPass, VllmPatternMatcherPass
@@ -115,6 +116,8 @@ class PostGradPassManager(CustomGraphPass): # type: ignore[misc]
# DCE handles mutating ops correctly as well.
self.ir_lowering(graph)
VllmInductorPass.dump_prefix += 1
self.clone_elimination(graph)
VllmInductorPass.dump_prefix += 1
# clean up after lowering again
self.post_cleanup(graph)
@@ -149,11 +152,12 @@ class PostGradPassManager(CustomGraphPass): # type: ignore[misc]
self.passes += [MiniMaxQKNormPass(config)]
if self.pass_config.fuse_norm_quant:
self.passes += [RMSNormQuantFusionPass(config)]
if rocm_aiter_ops.is_enabled():
self.passes += [
RocmAiterRMSNormQuantFusionPass(config),
]
self.passes += [RMSNormQuantFusionPass(config)]
if self.pass_config.fuse_act_quant:
self.passes += [ActivationQuantFusionPass(config)]
if rocm_aiter_ops.is_enabled():
@@ -179,6 +183,7 @@ class PostGradPassManager(CustomGraphPass): # type: ignore[misc]
self.passes += [QKNormRoPEFusionPass(config)]
self.ir_lowering = VllmIRLoweringPass(config)
self.clone_elimination = UnsafeCloneEliminationPass(config)
self.post_cleanup = PostCleanupPass(config)
self.fix_functionalization = FixFunctionalizationPass(config)
@@ -200,6 +205,7 @@ class PostGradPassManager(CustomGraphPass): # type: ignore[misc]
passes.append(self.post_cleanup.uuid())
passes.append(self.ir_lowering.uuid())
passes.append(self.clone_elimination.uuid())
passes.append(self.post_cleanup.uuid())
passes.append(self.fix_functionalization.uuid())
+3
View File
@@ -31,6 +31,9 @@ class IrOpPriorityConfig:
rms_norm: list[str] = Field(default_factory=list)
"""Priority list for vllm.ir.ops.rms_norm"""
fused_add_rms_norm: list[str] = Field(default_factory=list)
"""Priority list for vllm.ir.ops.fused_add_rms_norm"""
def compute_hash(self) -> str:
"""
Produces a hash unique to the pass configuration.
+2 -5
View File
@@ -125,9 +125,7 @@ def enable_allreduce_rms_fusion(cfg: "VllmConfig") -> bool:
from vllm._aiter_ops import rocm_aiter_ops
return (
rocm_aiter_ops.is_enabled()
and rocm_aiter_ops.is_rmsnorm_enabled()
and cfg.parallel_config.tensor_parallel_size > 1
rocm_aiter_ops.is_enabled() and cfg.parallel_config.tensor_parallel_size > 1
)
return (
@@ -159,10 +157,9 @@ def enable_rope_kvcache_fusion(cfg: "VllmConfig") -> bool:
def enable_norm_pad_fusion(cfg: "VllmConfig") -> bool:
"""Enable if using AITER RMSNorm and hidden size is 2880 i.e. gpt-oss."""
from vllm._aiter_ops import rocm_aiter_ops
return (
rocm_aiter_ops.is_rmsnorm_enabled()
cfg.kernel_config.ir_op_priority.fused_add_rms_norm[0] == "aiter"
and cfg.model_config is not None
and cfg.model_config.get_hidden_size() == 2880
)
+3 -2
View File
@@ -143,7 +143,7 @@ if TYPE_CHECKING:
VLLM_DP_RANK_LOCAL: int = -1
VLLM_DP_SIZE: int = 1
VLLM_USE_STANDALONE_COMPILE: bool = True
VLLM_ENABLE_PREGRAD_PASSES: bool = False
VLLM_ENABLE_PREGRAD_PASSES: bool = True
VLLM_DP_MASTER_IP: str = ""
VLLM_DP_MASTER_PORT: int = 0
VLLM_RANDOMIZE_DP_DUMMY_INPUTS: bool = False
@@ -620,9 +620,10 @@ environment_variables: dict[str, Callable[[], Any]] = {
# The pre-grad passes get run even on cache-hit and negatively impact
# vllm cold compile times by O(1s)
# Can remove this after the following issue gets fixed
# TODO(luka): maybe_inplace requires this
# https://github.com/pytorch/pytorch/issues/174502
"VLLM_ENABLE_PREGRAD_PASSES": lambda: (
os.environ.get("VLLM_ENABLE_PREGRAD_PASSES", "0") == "1"
os.environ.get("VLLM_ENABLE_PREGRAD_PASSES", "1") == "1"
),
# Debug pattern matching inside custom passes.
# Should be set to the fx.Node name (e.g. 'getitem_34' or 'scaled_mm_3').
+147 -9
View File
@@ -4,7 +4,7 @@ import contextlib
import inspect
from collections.abc import Callable
from pathlib import Path
from typing import Any, ClassVar, overload
from typing import Any, ClassVar, Literal, overload
import torch
from torch.library import Library, infer_schema
@@ -46,35 +46,51 @@ def enable_torch_wrap(enable: bool = True):
_ENABLE_TORCH_WRAP = old
# 0-param decorator overload
# 0-param decorator overload (no inplace)
@overload
def register_op(f: Callable[..., Any]) -> "IrOp": ...
# parametrized decorator overload
# parametrized decorator with allow_inplace=False (default)
@overload
def register_op(
*,
name: str | None = None,
activations: list[str] | None = None,
allow_inplace: Literal[False] = False,
) -> Callable[[Callable[..., Any]], "IrOp"]: ...
# parametrized decorator with allow_inplace=True
@overload
def register_op(
*,
name: str | None = None,
activations: list[str] | None = None,
allow_inplace: Literal[True],
) -> Callable[[Callable[..., Any]], "IrOpInplace"]: ...
def register_op(
f: Callable | None = None,
*,
name: str | None = None,
activations: list[str] | None = None,
allow_inplace: bool = False,
) -> "IrOp | Callable[[Callable], IrOp]":
"""
Register a new vLLM IR op.
:param f: the native implementation of the op
:param name: the name of the op, defaults to the function name
:param activations: list of activation params, defaults to params starting with 'x'
:param allow_inplace: add a maybe_inplace overload that allows inplace impls
:return: the IrOp object if f is provided, otherwise a decorator
Example usage:
```python
@vllm.ir.register_op
def my_op(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
def my_add(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
return x + y
@@ -85,7 +101,10 @@ def register_op(
def decorator(_f: Callable):
op_name: str = _f.__name__ if name is None else name
assert op_name not in IrOp.registry
op = IrOp(op_name, _f)
if allow_inplace:
op: IrOp = IrOpInplace(op_name, _f, activations)
else:
op = IrOp(op_name, _f, activations)
IrOp.registry[op_name] = op
return op
@@ -100,8 +119,14 @@ class IrOp:
name: str
impls: dict[str, "IrOpImpl"]
allow_inplace: bool = False
def __init__(self, name: str, native_impl: Callable):
def __init__(
self,
name: str,
native_impl: Callable,
activations: list[str] | None = None,
):
self._py_signature = inspect.signature(native_impl)
if any(
p.kind == inspect.Parameter.KEYWORD_ONLY
@@ -112,8 +137,22 @@ class IrOp:
f"supported. That's because kwargs are not allowed during lowering."
)
# By convention, we consider parameters starting with 'x' as activations.
if activations is None:
activations = [
p.name
for p in self._py_signature.parameters.values()
if p.name.startswith("x")
]
self.name = name
self.impls: dict[str, IrOpImpl] = {}
self.activations = activations
self.activation_indices = [
i
for i, p in enumerate(self._py_signature.parameters.values())
if p.name in activations
]
self._priority_impls: list[IrOpImpl] = []
self._schema_str = infer_schema(native_impl, mutates_args=[])
self._input_generator: InputGenerator | None = None
@@ -121,7 +160,12 @@ class IrOp:
# native implementation
self.impls["native"] = IrOpImpl(
self, "native", native_impl, supported=True, supports_args=None
self,
"native",
native_impl,
# always supported
supported=True,
supports_args=None,
)
# By default, fake routes directly to native,
@@ -161,12 +205,14 @@ class IrOp:
*,
supported: bool = True,
supports_args: Callable[..., bool] | None = None,
inplace: bool = False,
):
"""
Register an implementation for this custom op.
:param provider: The name of the provider, must be unique.
:param supported: Static support check, use this to check platform support.
:param supports_args: Dynamic arg support check, used for types and shapes.
:param inplace: Does this op reuse activation input memory for outputs
:return: A decorator that registers the implementation.
The decorated function must have the same semantics and signature as
@@ -193,7 +239,7 @@ class IrOp:
)
def _register_impl(f: Callable):
impl = IrOpImpl(self, provider, f, supported, supports_args)
impl = IrOpImpl(self, provider, f, supported, supports_args, inplace)
self.impls[provider] = impl
if self.get_priority():
@@ -213,7 +259,10 @@ class IrOp:
__call__ routes straight here instead of going through torch op dispatching.
"""
impl = self.dispatch(*args, **kwargs)
return impl.impl_fn(*args, **kwargs)
# Default overload must be functional,
# use func_impl_fn to correctly handle inplace impls.
return impl.func_impl_fn(*args, **kwargs)
def apply_arg_defaults(self, args) -> tuple:
"""
@@ -314,6 +363,11 @@ class IrOp:
old_priority_impls = self._priority_impls
try:
self._priority_impls = filter_priority_impls(priority)
logger.debug(
"Priority for vllm.ir.%s set to %s",
self.name,
lazy(lambda: [p.provider for p in self._priority_impls]),
)
yield
finally:
self._priority_impls = old_priority_impls
@@ -354,6 +408,66 @@ class IrOp:
)
class IrOpInplace(IrOp):
"""IR op with inplace support via maybe_inplace."""
maybe_inplace: "IrOpInplaceOverload"
allow_inplace: bool = True
def __init__(
self,
name: str,
native_impl: Callable,
activations: list[str] | None = None,
):
super().__init__(name, native_impl, activations)
# Create the inplace overload
self.maybe_inplace = IrOpInplaceOverload(self)
class IrOpInplaceOverload:
def __init__(self, op: IrOp):
params, returns = op._schema_str.split(" -> ")
n_outputs = returns.count("Tensor")
assert returns.count("Tensor") == len(op.activations), (
"Inplace overload requires the same number of outputs as activations."
)
assert returns.count(",") == n_outputs - 1, (
"Inplace overload only supports Tensor outputs for now."
)
self.op = op
self.name = f"{op.name}.maybe_inplace"
self._schema_str = infer_schema(
op.impls["native"].impl_fn, mutates_args=op.activations
)
# torch registration
vllm_ir_lib.define(self.name + self._schema_str)
vllm_ir_lib.impl(
self.name, self._inner_call, dispatch_key="CompositeExplicitAutograd"
)
# fake goes to default overload for now
vllm_ir_lib._register_fake(self.name, self.op._fake_call)
assert hasattr(getattr(torch.ops.vllm_ir, self.op.name), "maybe_inplace")
self.torch_op = getattr(torch.ops.vllm_ir, self.op.name).maybe_inplace
def __call__(self, *args, **kwargs) -> Any:
if not _ENABLE_TORCH_WRAP:
return self._inner_call(*args, **kwargs)
return self.torch_op(*args, **kwargs)
def _inner_call(self, *args, **kwargs) -> Any:
# Calling the maybe_inplace overload means we can use inplace impls directly.
impl = self.op.dispatch(*args, **kwargs)
return impl.impl_fn(*args, **kwargs)
class IrOpImpl:
def __init__(
self,
@@ -362,6 +476,7 @@ class IrOpImpl:
impl_fn: Callable,
supported: bool,
supports_args: Callable[..., bool] | None,
inplace: bool = False,
):
assert provider not in op.impls, (
f"Implementation for provider {provider} already registered."
@@ -420,11 +535,18 @@ class IrOpImpl:
f"native default {op_p.default}'"
)
if inplace:
assert op.allow_inplace, (
f"Inplace implementation cannot be registered for op {op.name}"
f" that does not allow inplace."
)
self.op = op
self.provider = provider
self.impl_fn = impl_fn
self.supported = supported
self._supports_args = supports_args
self.inplace = inplace
@property
def supports_all_args(self) -> bool:
@@ -449,3 +571,19 @@ class IrOpImpl:
"""
sources = [Path(inspect.getfile(self.impl_fn))]
return hash_source(*sources)
def func_impl_fn(self, *args, **kwargs) -> Any:
"""
Copy any inputs in activations if this is an inplace impl,
to ensure functional semantics.
"""
if not self.inplace:
return self.impl_fn(*args, **kwargs)
# copy activations to ensure functional semantics
new_args = list(args)
for i in self.op.activation_indices:
assert isinstance(args[i], torch.Tensor)
new_args[i] = args[i].clone()
return self.impl_fn(*new_args, **kwargs)
+2 -2
View File
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from .layernorm import rms_norm
from .layernorm import fused_add_rms_norm, rms_norm
__all__ = ["rms_norm"]
__all__ = ["rms_norm", "fused_add_rms_norm"]
+37 -1
View File
@@ -27,10 +27,46 @@ def _rms_norm_input_generator(
) -> tuple:
x = torch.randn(num_tokens, hidden_size, dtype=dtype)
weight = torch.randn(hidden_size, dtype=dtype)
return (x, weight, epsilon)
return x, weight, epsilon
# Reductions in rms_norm accumulate rounding error at large shapes
# (e.g. 32768x16384), causing a few elements out of millions to exceed
# the default float16 tolerance.
rms_norm.override_tolerance(torch.float16, atol=1e-2, rtol=2e-3)
@register_op(allow_inplace=True)
def fused_add_rms_norm(
x: Tensor,
x_residual: Tensor,
weight: Tensor | None,
epsilon: float,
variance_size: int | None = None,
) -> tuple[Tensor, Tensor]:
"""Fused add and weighted root-mean-square layer normalization"""
orig_dtype = x.dtype
x = x.to(torch.float32)
x = x + x_residual.to(torch.float32)
x_residual = x.to(orig_dtype)
x_var = x if variance_size is None else x[..., :variance_size]
variance = x_var.pow(2).mean(dim=-1, keepdim=True)
x = x * torch.rsqrt(variance + epsilon)
if weight is not None:
x = x.to(weight.dtype) * weight
return x.to(orig_dtype), x_residual
# fused_add_rms_norm has similar rounding error accumulation as rms_norm
fused_add_rms_norm.override_tolerance(torch.float16, atol=1e-2, rtol=2e-3)
@fused_add_rms_norm.register_input_generator
def _fused_add_rms_norm_input_generator(
num_tokens: int, hidden_size: int, dtype: torch.dtype, epsilon: float = 1e-5
) -> tuple:
x = torch.randn(num_tokens, hidden_size, dtype=dtype)
x_residual = torch.randn(num_tokens, hidden_size, dtype=dtype)
weight = torch.randn(hidden_size, dtype=dtype)
return x, x_residual, weight, epsilon
+69
View File
@@ -75,3 +75,72 @@ def _rms_norm_fake(x: Tensor, weight: Tensor, variance_epsilon: float) -> Tensor
direct_register_aiter_op(
op_name="rms_norm", op_func=_rms_norm_impl, fake_impl=_rms_norm_fake
)
rms_add_no_var_16bit_only = (
lambda x, x_residual, weight, epsilon, variance_size=None: variance_size is None
and x.dtype in (torch.float16, torch.bfloat16)
and (weight is None or weight.dtype == x.dtype)
)
"""
AITER fused_add_rms_norm only supports 16-bit activations and no var_size override.
Requires weight dtype to match x dtype.
"""
@ir.ops.fused_add_rms_norm.register_impl(
"aiter", supports_args=rms_add_no_var_16bit_only, supported=AITER_SUPPORTED
)
def fused_add_rms_norm(
x: Tensor,
x_residual: Tensor,
weight: Tensor | None,
epsilon: float,
variance_size: int | None = None,
) -> tuple[Tensor, Tensor]:
assert variance_size is None
assert x.dtype in (torch.float16, torch.bfloat16)
if weight is None:
weight = torch.ones(x.shape[-1], device=x.device, dtype=x.dtype)
return torch.ops.vllm_aiter.fused_add_rms_norm(x, x_residual, weight, epsilon)
def _rocm_aiter_rmsnorm2d_fwd_with_add_impl(
x: torch.Tensor,
residual: torch.Tensor,
weight: torch.Tensor,
variance_epsilon: float,
) -> tuple[torch.Tensor, torch.Tensor]:
from aiter import rmsnorm2d_fwd_with_add
# TODO can out = x and residual_out = residual to save memory?
# Need to check if the kernel supports in-place residual output
# (if yes set mutates_args and inplace)
residual_out = torch.empty_like(residual)
out = torch.empty_like(x)
rmsnorm2d_fwd_with_add(
out, # output
x, # input
residual, # residual input
residual_out, # residual output
weight,
variance_epsilon,
)
return out, residual_out
def _rocm_aiter_rmsnorm2d_fwd_with_add_fake(
x: torch.Tensor,
residual: torch.Tensor,
weight: torch.Tensor,
variance_epsilon: float,
) -> tuple[torch.Tensor, torch.Tensor]:
residual_out = torch.empty_like(residual)
out = torch.empty_like(x)
return out, residual_out
direct_register_aiter_op(
op_name="fused_add_rms_norm",
op_func=_rocm_aiter_rmsnorm2d_fwd_with_add_impl,
fake_impl=_rocm_aiter_rmsnorm2d_fwd_with_add_fake,
)
+55 -5
View File
@@ -1,6 +1,16 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""This file registers Oink implementations for vLLM IR ops.
vLLM does not depend on the external Oink repository/package. When an external
plugin registers torch.library.custom_op entrypoints under the `oink::`
namespace (e.g. via vLLM's general_plugins mechanism), these ops will be marked
as supported. To dispatch to those ops, set kernel_config.ir_op_priority.<op> to oink.
Alternatively, `VLLM_USE_OINK_OPS=1` will add this to priority by default.
"""
import torch
from torch import Tensor
from vllm import ir
from vllm.platforms import current_platform
@@ -15,7 +25,7 @@ def has_oink_op(name: str) -> bool:
return OINK_AVAILABLE and hasattr(torch.ops.oink, name)
def _can_view_as_2d(x: torch.Tensor) -> bool:
def _can_view_as_2d(x: Tensor) -> bool:
"""Return True if x.view(-1, x.shape[-1]) is viewable (no copy)."""
if x.dim() < 2:
return False
@@ -32,7 +42,7 @@ def _can_view_as_2d(x: torch.Tensor) -> bool:
return True
def _is_oink_stride_compatible_2d(x_2d: torch.Tensor) -> bool:
def _is_oink_stride_compatible_2d(x_2d: Tensor) -> bool:
"""Return True if x_2d meets Oink's pointer-path stride constraints."""
if x_2d.dim() != 2:
return False
@@ -67,11 +77,51 @@ and no variance_size override.
"oink", supports_args=oink_rms_supported, supported=has_oink_op("rmsnorm")
)
def rms_norm(
x: torch.Tensor,
weight: torch.Tensor | None,
x: Tensor,
weight: Tensor | None,
epsilon: float,
variance_size: int | None = None,
) -> torch.Tensor:
) -> Tensor:
assert variance_size is None
x_2d = x.view(-1, x.shape[-1])
return torch.ops.oink.rmsnorm(x_2d, weight, epsilon).view_as(x)
oink_add_rms_supported = (
lambda x, x_residual, weight, epsilon, variance_size=None: variance_size is None
and weight is not None
and x.dim() >= 2
and x.dtype == weight.dtype
and weight.is_contiguous()
and _can_view_as_2d(x)
and _is_oink_stride_compatible_2d(x.view(-1, x.shape[-1]))
# residual must have 2d-compatible strides and match x shape/dtype
and x.dtype == x_residual.dtype
and x.shape == x_residual.shape
and _can_view_as_2d(x_residual)
and _is_oink_stride_compatible_2d(x_residual.view(-1, x_residual.shape[-1]))
)
"""
Oink fused_add_rms_norm has the same constraints as rms_norm,
and residual must be 2d-like with compatible strides.
"""
@ir.ops.fused_add_rms_norm.register_impl(
"oink",
supports_args=oink_add_rms_supported,
supported=has_oink_op("fused_add_rms_norm"),
inplace=True,
)
def fused_add_rms_norm(
x: Tensor,
x_residual: Tensor,
weight: Tensor | None,
epsilon: float,
variance_size: int | None = None,
) -> tuple[Tensor, Tensor]:
assert variance_size is None
x_2d = x.view(-1, x.shape[-1])
residual_2d = x_residual.view(-1, x_residual.shape[-1])
torch.ops.oink.fused_add_rms_norm(x_2d, residual_2d, weight, epsilon)
return x, x_residual
+30
View File
@@ -31,3 +31,33 @@ def rms_norm(
output = torch.empty(x.shape, device=x.device, dtype=x.dtype)
torch.ops._C.rms_norm(output, x, weight, epsilon)
return output
rms_add_no_var_size = (
lambda x, x_residual, weight, epsilon, variance_size=None: variance_size is None
and (weight is None or weight.dtype == x.dtype)
)
"""vLLM Kernel does not support variance_size parameter and requires
matching input/weight dtype."""
@ir.ops.fused_add_rms_norm.register_impl(
"vllm_c",
supports_args=rms_add_no_var_size,
supported=CUDA_ALIKE,
inplace=True,
)
def fused_add_rms_norm(
x: Tensor,
x_residual: Tensor,
weight: Tensor | None,
epsilon: float,
variance_size: int | None = None,
) -> tuple[Tensor, Tensor]:
if weight is None:
# Kernel requires weight tensor, pass ones
weight = torch.ones(x.shape[-1], device=x.device, dtype=x.dtype)
assert variance_size is None
torch.ops._C.fused_add_rms_norm(x, x_residual, weight, epsilon)
return x, x_residual
+28
View File
@@ -36,3 +36,31 @@ def rms_norm(
output = torch.empty(x.shape, device=x.device, dtype=x.dtype)
torch.ops._C.rms_norm(output, x, weight, epsilon)
return output
rms_add_no_var_size = (
lambda x, x_residual, weight, epsilon, variance_size=None: variance_size is None
and (weight is None or weight.dtype == x.dtype)
)
@ir.ops.fused_add_rms_norm.register_impl(
"xpu_kernels",
supports_args=rms_add_no_var_size,
supported=XPU_KERNELS_SUPPORTED,
inplace=True,
)
def fused_add_rms_norm(
x: Tensor,
x_residual: Tensor,
weight: Tensor | None,
epsilon: float,
variance_size: int | None = None,
) -> tuple[Tensor, Tensor]:
if weight is None:
# Kernel requires weight tensor, pass ones
weight = torch.ones(x.shape[-1], device=x.device, dtype=x.dtype)
assert variance_size is None
torch.ops._C.fused_add_rms_norm(x, x_residual, weight, epsilon)
return x, x_residual
+29 -252
View File
@@ -8,68 +8,15 @@ import torch.nn.functional as F
# Import kernels
import vllm.kernels # noqa: F401
from vllm import _oink_ops, envs, ir
from vllm._aiter_ops import rocm_aiter_ops
from vllm import envs, ir
from vllm.config import get_current_vllm_config
from vllm.logger import init_logger
from vllm.model_executor.custom_op import CustomOp
from vllm.model_executor.layers.batch_invariant import (
rms_norm_batch_invariant,
)
from vllm.platforms import current_platform
from vllm.model_executor.layers.batch_invariant import rms_norm_batch_invariant
logger = init_logger(__name__)
def _can_view_as_2d(x: torch.Tensor) -> bool:
"""Return True if x.view(-1, x.shape[-1]) is viewable (no copy)."""
if x.dim() < 2:
return False
if x.dim() == 2:
return True
# For a view(-1, N) to be valid, all leading dims must be contiguous with
# respect to each other (size-1 dims are ignored).
for dim in range(x.dim() - 1):
# Strides for size-1 dims are irrelevant and can be arbitrary.
if x.size(dim + 1) != 1 and x.stride(dim) != x.stride(dim + 1) * x.size(
dim + 1
):
return False
return True
def _is_oink_stride_compatible_2d(x_2d: torch.Tensor) -> bool:
"""Return True if x_2d meets Oink's pointer-path stride constraints."""
if x_2d.dim() != 2:
return False
if x_2d.stride(1) != 1:
return False
# Match Oink's vectorization constraint: stride(0) divisible by 256b.
if x_2d.dtype in (torch.float16, torch.bfloat16):
divby = 16
elif x_2d.dtype == torch.float32:
divby = 8
else:
return False
return (x_2d.stride(0) % divby) == 0
def fused_add_rms_norm(
x: torch.Tensor,
residual: torch.Tensor,
weight: torch.Tensor,
variance_epsilon: float,
) -> tuple[torch.Tensor, torch.Tensor]:
from vllm import _custom_ops as ops
ops.fused_add_rms_norm(
x,
residual,
weight,
variance_epsilon,
)
return x, residual
def poly_norm(
x: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor, variance_epsilon: float
) -> torch.Tensor:
@@ -86,18 +33,6 @@ def poly_norm(
return out
def dispatch_rocm_rmsnorm_func(dtype: torch.dtype, use_aiter: bool = False):
use_aiter = use_aiter and dtype in [
torch.float16,
torch.bfloat16,
]
if use_aiter:
return rocm_aiter_ops.rms_norm2d_with_add
else:
return fused_add_rms_norm
# --8<-- [start:rms_norm]
@CustomOp.register("rms_norm")
class RMSNorm(CustomOp):
@@ -130,105 +65,19 @@ class RMSNorm(CustomOp):
if self.has_weight:
self.weight = nn.Parameter(self.weight)
if current_platform.is_rocm():
aiter_rmsnorm_enabled = rocm_aiter_ops.is_rmsnorm_enabled()
self.rocm_norm_func_with_add = dispatch_rocm_rmsnorm_func(
dtype=weight_dtype, use_aiter=aiter_rmsnorm_enabled
)
# Optional: enable Oink Blackwell RMSNorm custom-op fast path on
# compatible CUDA devices (e.g., SM100) when the external Oink
# package is available. This is detected once at construction time
# to avoid per-call device queries in the hot path.
self._use_oink_fused_add_rmsnorm = False
if (
not current_platform.is_rocm()
and torch.cuda.is_available()
and bool(getattr(envs, "VLLM_USE_OINK_OPS", False))
):
# NOTE: vLLM disables custom ops by default when using Inductor.
# If this op is disabled, CustomOp will dispatch to forward_native,
# and the Oink path in forward_cuda will never run.
if getattr(self._forward_method, "__func__", None) is getattr(
self.forward_native, "__func__", None
):
try:
from vllm.config import get_cached_compilation_config
custom_ops = get_cached_compilation_config().custom_ops
except Exception:
custom_ops = ["<unknown>"]
logger.warning_once(
"VLLM_USE_OINK_OPS=1 but the `rms_norm` custom op is "
"disabled (CompilationConfig.custom_ops=%s). Enable it via "
"`compilation_config={'custom_ops': ['none', '+rms_norm']}` "
"(or `['all']`) to let vLLM call into torch.ops.oink.*.",
custom_ops,
)
# Custom op disabled => forward_cuda won't run. Avoid doing any
# external Oink initialization work in this case.
else:
try:
device_index = torch.accelerator.current_device_index()
if _oink_ops.is_oink_available_for_device(device_index):
self._use_oink_fused_add_rmsnorm = (
_oink_ops.has_fused_add_rms_norm()
)
except Exception as e:
# If anything goes wrong (no Oink install, CPU-only env, etc.),
# silently fall back to the built-in RMSNorm path.
logger.warning_once(
"VLLM_USE_OINK_OPS=1 but failed to initialize Oink "
"RMSNorm; falling back to vLLM RMSNorm. Error: %s",
e,
)
self._use_oink_fused_add_rmsnorm = False
@staticmethod
def forward_static(
x: torch.Tensor,
variance_epsilon: float,
hidden_size: int,
orig_dtype: torch.dtype,
weight: torch.Tensor | None = None,
residual: torch.Tensor | None = None,
variance_size_override: int | None = None,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
"""PyTorch-native implementation equivalent to forward()."""
x = x.to(torch.float32)
if residual is not None:
# residual promoted f16->f32 automatically,
# otherwise Inductor eliminates the casts to and from f16,
# increasing memory usage (and complicating pattern matching)
x = x + residual
residual = x.to(orig_dtype)
if x.shape[-1] != hidden_size:
raise ValueError(
f"Expected hidden_size to be {hidden_size}, but found: {x.shape[-1]}"
)
if variance_size_override is None:
x_var = x
else:
if hidden_size < variance_size_override:
raise ValueError(
"Expected hidden_size to be at least "
f"{variance_size_override}, but found: {hidden_size}"
)
x_var = x[:, :, :variance_size_override]
variance = x_var.pow(2).mean(dim=-1, keepdim=True)
x = x * torch.rsqrt(variance + variance_epsilon)
x = x.to(orig_dtype)
if weight is not None:
x = x * weight
if residual is None:
return x
else:
return x, residual
# Do not pass identity weight to native implementation (causes issue on TPU).
# Other implementations require weight to be passed even if all ones.
# Cheat and predict if native will be dispatched to:
# 1) if native is first in priority list
# 2) if variance_size_override is given (only supported by native impl)
# TODO(luka): address weight passing inconsistency:
# https://github.com/vllm-project/vllm/issues/39370
priority = get_current_vllm_config().kernel_config.ir_op_priority
var_override = self.variance_size_override is not None
native_rms_norm = priority.rms_norm[0] == "native" or var_override
native_add_rms_norm = priority.fused_add_rms_norm[0] == "native" or var_override
self.pass_weight = self.has_weight or not native_rms_norm
self.pass_weight_add = self.has_weight or not native_add_rms_norm
def forward_native(
self,
@@ -237,106 +86,34 @@ class RMSNorm(CustomOp):
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
"""PyTorch-native implementation equivalent to forward()."""
if residual is None:
# TODO(luka): address the weight=None passing issue more generally
return ir.ops.rms_norm(
x,
self.weight.data if self.has_weight else None,
self.weight.data if self.pass_weight else None,
self.variance_epsilon,
self.variance_size_override,
)
else:
return ir.ops.fused_add_rms_norm.maybe_inplace(
x,
residual,
self.weight.data if self.pass_weight_add else None,
self.variance_epsilon,
self.variance_size_override,
)
return self.forward_static(
x,
self.variance_epsilon,
self.hidden_size,
x.dtype,
self.weight.data if self.has_weight else None,
residual,
self.variance_size_override,
)
def forward_cuda(
self,
x: torch.Tensor,
residual: torch.Tensor | None = None,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
if residual is None and not envs.VLLM_BATCH_INVARIANT:
return ir.ops.rms_norm(
x, self.weight.data, self.variance_epsilon, self.variance_size_override
)
if self.variance_size_override is not None:
return self.forward_native(x, residual)
# Optional Oink SM100 fast path (fused residual-add + RMSNorm, in-place).
# This mirrors vLLM's fused_add_rms_norm semantics by mutating both
# `x` (normalized output) and `residual` (residual-out buffer).
if (
residual is not None
and getattr(self, "_use_oink_fused_add_rmsnorm", False)
and x.is_cuda
and residual.is_cuda
and x.shape == residual.shape
and x.dtype == residual.dtype
and x.dim() >= 2
and self.has_weight
and not envs.VLLM_BATCH_INVARIANT
and self.weight.data.dtype == x.dtype
and self.weight.data.is_contiguous()
envs.VLLM_BATCH_INVARIANT
and residual is None
and self.variance_size_override is None
):
orig_shape = x.shape
hidden_size = orig_shape[-1]
if _can_view_as_2d(x) and _can_view_as_2d(residual):
x_2d = x.view(-1, hidden_size)
res_2d = residual.view(-1, hidden_size)
# The Oink in-place pointer path supports the common vLLM
# layout where:
# - `x` may be strided/padded row-major (stride(1) == 1), and
# - `residual` is contiguous row-major ([M, N] with stride(0) == N).
# If these conditions are not met, fall back to vLLM's built-in
# fused kernel.
if (
_is_oink_stride_compatible_2d(x_2d)
and _is_oink_stride_compatible_2d(res_2d)
and res_2d.is_contiguous()
):
_oink_ops.fused_add_rms_norm_(
x_2d,
res_2d,
self.weight.data,
self.variance_epsilon,
)
return x, residual
if residual is not None:
return fused_add_rms_norm(
x, residual, self.weight.data, self.variance_epsilon
)
else:
assert envs.VLLM_BATCH_INVARIANT
return rms_norm_batch_invariant(x, self.weight.data, self.variance_epsilon)
def forward_hip(
self,
x: torch.Tensor,
residual: torch.Tensor | None = None,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
if residual is None and not envs.VLLM_BATCH_INVARIANT:
return ir.ops.rms_norm(
x, self.weight.data, self.variance_epsilon, self.variance_size_override
)
if self.variance_size_override is not None:
return self.forward_native(x, residual)
if residual is not None:
return self.rocm_norm_func_with_add(
x, residual, self.weight.data, self.variance_epsilon
)
else:
assert envs.VLLM_BATCH_INVARIANT
return rms_norm_batch_invariant(x, self.weight.data, self.variance_epsilon)
return self.forward_native(x, residual)
def forward_xpu(
self,
+3 -1
View File
@@ -578,7 +578,9 @@ class CudaPlatformBase(Platform):
if envs.VLLM_USE_OINK_OPS:
rms_norm = ["oink"] + default
return IrOpPriorityConfig.with_default(default, rms_norm=rms_norm)
return IrOpPriorityConfig.with_default(
default, rms_norm=rms_norm, fused_add_rms_norm=rms_norm
)
# NVML utils
+6 -16
View File
@@ -693,21 +693,11 @@ class RocmPlatform(Platform):
@classmethod
def apply_config_platform_defaults(cls, vllm_config: "VllmConfig") -> None:
from vllm._aiter_ops import rocm_aiter_ops
from vllm.config.compilation import CUDAGraphMode
compilation_config = vllm_config.compilation_config
is_eager_execution = compilation_config.cudagraph_mode == CUDAGraphMode.NONE
use_aiter_fused_moe = rocm_aiter_ops.is_fused_moe_enabled()
use_aiter_rms_norm = rocm_aiter_ops.is_rmsnorm_enabled()
use_aiter_fp8_linear = rocm_aiter_ops.is_linear_fp8_enabled()
use_aiter_fused_se = rocm_aiter_ops.is_fusion_moe_shared_experts_enabled()
# Aiter rms norm perform best when CUDA Graph capture is enabled.
if (
use_aiter_rms_norm
and not is_eager_execution
and "-rms_norm" not in compilation_config.custom_ops
):
compilation_config.custom_ops.append("+rms_norm")
if use_aiter_fp8_linear and "-quant_fp8" not in compilation_config.custom_ops:
compilation_config.custom_ops.append("+quant_fp8")
@@ -939,7 +929,7 @@ class RocmPlatform(Platform):
def get_default_ir_op_priority(
cls, vllm_config: "VllmConfig"
) -> "IrOpPriorityConfig":
from vllm.config.compilation import CompilationMode
from vllm.config.compilation import CompilationMode, CUDAGraphMode
from vllm.config.kernel import IrOpPriorityConfig
# Native used by default when compiling,
@@ -949,12 +939,10 @@ class RocmPlatform(Platform):
using_inductor = cc.backend == "inductor" and cc.mode != CompilationMode.NONE
default = ["native"] if using_inductor else ["vllm_c", "native"]
# This (mostly) preserves previous CustomOp behavior
# Necessary on ROCm because it's common that users
# enable rms_norm to use the aiter kernel.
# Aiter rms norm perform best when CUDA Graph capture is enabled.
# TODO(luka/TJ) remove env vars completely
if (
cc.is_custom_op_enabled("rms_norm")
cc.cudagraph_mode != CUDAGraphMode.NONE
and envs.VLLM_ROCM_USE_AITER
and envs.VLLM_ROCM_USE_AITER_RMSNORM
):
@@ -962,7 +950,9 @@ class RocmPlatform(Platform):
else:
rms_norm = default
return IrOpPriorityConfig.with_default(default, rms_norm=rms_norm)
return IrOpPriorityConfig.with_default(
default, rms_norm=rms_norm, fused_add_rms_norm=rms_norm
)
@classmethod
@with_amdsmi_context