[Perf][Kernel][Quantization] Fuse ReLU2 with static FP8 activation quantization (#53793)
Signed-off-by: mgoin <mgoin64@gmail.com> Signed-off-by: ElizaWszola <ewszola@redhat.com> Signed-off-by: snordmann <snordmann@nvidia.com> Co-authored-by: mgoin <mgoin64@gmail.com> Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Co-authored-by: ElizaWszola <ewszola@redhat.com> Co-authored-by: OpenAI Codex <noreply@openai.com> Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
This commit is contained in:
co-authored by
mgoin
Claude Opus 4.8
ElizaWszola
OpenAI Codex
mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
parent
435c96f9db
commit
03dc26e639
@@ -5,21 +5,27 @@ Producer side of the QuantizedActivation contract for activation layers.
|
||||
|
||||
Given an activation module and the downstream linear it feeds, fuse the
|
||||
activation with that linear's input quantization into a single kernel when the
|
||||
linear advertises a consumable input_quant_key (see quant_activation.py).
|
||||
linear advertises a consumable input quantization key (see quant_activation.py).
|
||||
Falls back to the plain activation when nothing matches, so a model forward can
|
||||
always call maybe_fused_act_quant unconditionally.
|
||||
|
||||
This is the manual-fusion counterpart to ActivationQuantFusionPass: when fusion
|
||||
fires here the silu_and_mul pattern is already consumed, so the compiler pass
|
||||
finds nothing to rewrite and the two never double-fuse.
|
||||
fires here, the activation and quantization are already consumed, so a compiler
|
||||
pass cannot fuse the same boundary again.
|
||||
"""
|
||||
|
||||
from collections.abc import Callable
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.model_executor.layers.activation import SiluAndMul
|
||||
from vllm.model_executor.layers.fusion.quant_activation import QuantizedActivation
|
||||
from vllm.model_executor.layers.activation import ReLUSquaredActivation, SiluAndMul
|
||||
from vllm.model_executor.layers.fusion.quant_activation import (
|
||||
QuantizedActivation,
|
||||
get_input_quant_key,
|
||||
)
|
||||
from vllm.model_executor.layers.fusion.relu2_fp8_quant import (
|
||||
relu_squared_static_fp8_quant,
|
||||
)
|
||||
from vllm.model_executor.layers.linear import LinearBase
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import (
|
||||
QuantKey,
|
||||
@@ -139,12 +145,46 @@ def _silu_and_mul_nvfp4_dynamic(
|
||||
)
|
||||
|
||||
|
||||
# (activation module type, consumer input_quant_key) -> fused producer.
|
||||
# Mirrors ActivationQuantFusionPass.FUSED_OPS; add a row to migrate a scheme.
|
||||
# (activation module type, consumer input quantization key) -> fused producer.
|
||||
# Add a row for each supported manual producer.
|
||||
_FUSED_ACT_QUANT: dict[tuple[type, QuantKey], Callable] = {
|
||||
(SiluAndMul, kFp8StaticTensorSym): _silu_and_mul_fp8_static,
|
||||
}
|
||||
|
||||
|
||||
def _relu_squared_static_fp8_quant_supported(
|
||||
act_fn: torch.nn.Module,
|
||||
x: torch.Tensor,
|
||||
linear: LinearBase,
|
||||
) -> bool:
|
||||
"""Return whether the ReLU2 static-FP8 producer can consume this input."""
|
||||
scale = getattr(linear, "input_scale", None)
|
||||
return (
|
||||
isinstance(act_fn, ReLUSquaredActivation)
|
||||
and x.is_cuda
|
||||
and x.dtype == torch.bfloat16
|
||||
and x.is_contiguous()
|
||||
and isinstance(scale, torch.Tensor)
|
||||
and scale.dtype == torch.float32
|
||||
and scale.device == x.device
|
||||
and scale.numel() == 1
|
||||
)
|
||||
|
||||
|
||||
# Optional per-entry predicates preserve the unconditional fallback contract
|
||||
# for producers whose supported inputs are narrower than their registry key.
|
||||
_FUSED_ACT_QUANT_SUPPORT: dict[
|
||||
tuple[type, QuantKey], Callable[[torch.nn.Module, torch.Tensor, LinearBase], bool]
|
||||
] = {}
|
||||
|
||||
# This path is validated on SM90 and newer CUDA devices.
|
||||
if current_platform.is_cuda() and current_platform.has_device_capability(90):
|
||||
_RELU2_STATIC_FP8_KEY = (ReLUSquaredActivation, kFp8StaticTensorSym)
|
||||
_FUSED_ACT_QUANT[_RELU2_STATIC_FP8_KEY] = relu_squared_static_fp8_quant
|
||||
_FUSED_ACT_QUANT_SUPPORT[_RELU2_STATIC_FP8_KEY] = (
|
||||
_relu_squared_static_fp8_quant_supported
|
||||
)
|
||||
|
||||
# Add CUDA-specific entries for dynamic block quantization
|
||||
if current_platform.is_cuda_alike():
|
||||
_FUSED_ACT_QUANT[(SiluAndMul, kFp8Dynamic128Sym)] = _silu_and_mul_fp8_dynamic_128
|
||||
@@ -161,12 +201,14 @@ def maybe_fused_act_quant(
|
||||
) -> "torch.Tensor | QuantizedActivation":
|
||||
"""Apply act_fn, fusing the downstream linear's input quant when possible.
|
||||
|
||||
Returns a QuantizedActivation when a fused kernel matches
|
||||
(act_fn, linear.input_quant_key), else the plain activated tensor.
|
||||
Returns a QuantizedActivation when a fused kernel matches the activation and
|
||||
the consumer's effective input quantization key, else the plain activation.
|
||||
"""
|
||||
key = getattr(linear, "input_quant_key", None)
|
||||
key = get_input_quant_key(linear)
|
||||
if key is not None:
|
||||
producer = _FUSED_ACT_QUANT.get((type(act_fn), key))
|
||||
if producer is not None:
|
||||
registry_key = (type(act_fn), key)
|
||||
producer = _FUSED_ACT_QUANT.get(registry_key)
|
||||
support = _FUSED_ACT_QUANT_SUPPORT.get(registry_key)
|
||||
if producer is not None and (support is None or support(act_fn, x, linear)):
|
||||
return producer(x, linear)
|
||||
return act_fn(x)
|
||||
|
||||
@@ -5,7 +5,9 @@ A QuantizedActivation is a pre-quantized activation produced by a fused kernel
|
||||
and consumed directly by a linear layer, letting the layer skip its own input
|
||||
quantization. A linear advertises the key its kernel can consume via
|
||||
expose_input_quant_key; the kernel validates and reads the activation via
|
||||
as_quantized_activation.
|
||||
as_quantized_activation. Producers query the effective capability through
|
||||
get_input_quant_key, which hides the key when another consumer branch needs the
|
||||
original activation.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, replace
|
||||
@@ -46,12 +48,11 @@ class QuantizedActivation:
|
||||
|
||||
|
||||
def expose_input_quant_key(layer: torch.nn.Module, kernel) -> None:
|
||||
"""Advertise the kernel's pre-quantized input key on the layer, if any.
|
||||
"""Store the kernel's pre-quantized input key on the layer, if any.
|
||||
|
||||
This is the bridge from a kernel's input_quant_key() to the
|
||||
layer.input_quant_key attribute that fusion call sites read. The attribute
|
||||
is left unset when the kernel quantizes its own input, so non-supporting
|
||||
backends never receive a QuantizedActivation.
|
||||
This is the bridge from a kernel's input_quant_key() to the layer capability
|
||||
that fusion call sites read through get_input_quant_key. The raw key is left
|
||||
unset when the kernel quantizes its own input.
|
||||
|
||||
TODO(mgoin): Producers also need the consumer's quantization scales (e.g.
|
||||
static input scale, global scale). Expose those here as well so producers
|
||||
@@ -59,7 +60,14 @@ def expose_input_quant_key(layer: torch.nn.Module, kernel) -> None:
|
||||
"""
|
||||
key = kernel.input_quant_key()
|
||||
if key is not None:
|
||||
layer.input_quant_key = key
|
||||
layer._input_quant_key = key
|
||||
|
||||
|
||||
def get_input_quant_key(layer: torch.nn.Module) -> QuantKey | None:
|
||||
"""Return the pre-quantized input key the complete layer can consume."""
|
||||
if getattr(layer, "requires_unquantized_input", False):
|
||||
return None
|
||||
return getattr(layer, "_input_quant_key", None)
|
||||
|
||||
|
||||
def as_quantized_activation(
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.model_executor.layers.fusion.quant_activation import QuantizedActivation
|
||||
from vllm.model_executor.layers.linear import LinearBase
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import (
|
||||
get_fp8_min_max,
|
||||
kFp8StaticTensorSym,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
_FP8_MIN, _FP8_MAX = get_fp8_min_max()
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _relu_squared_static_fp8_quant_kernel(
|
||||
x_ptr,
|
||||
scale_ptr,
|
||||
output_ptr,
|
||||
num_elements,
|
||||
FP8_MIN: tl.constexpr,
|
||||
FP8_MAX: tl.constexpr,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
):
|
||||
offsets = tl.program_id(0) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
|
||||
mask = offsets < num_elements
|
||||
x = tl.load(x_ptr + offsets, mask=mask, other=0.0).to(tl.float32)
|
||||
input_is_nan = x != x
|
||||
relu = tl.maximum(x, 0.0)
|
||||
# Preserve the standalone ReLU2 kernel's BF16 output boundary.
|
||||
activated = (relu * relu).to(tl.bfloat16).to(tl.float32)
|
||||
# Match O2's Inductor-compiled QuantFP8 reciprocal-then-multiply.
|
||||
quantized = activated * (1.0 / tl.load(scale_ptr))
|
||||
quantized = tl.maximum(tl.minimum(quantized, FP8_MAX), FP8_MIN)
|
||||
# Match the O2 native chain by preserving NaN through the FP8 conversion.
|
||||
quantized = tl.where(input_is_nan, x, quantized)
|
||||
tl.store(output_ptr + offsets, quantized, mask=mask)
|
||||
|
||||
|
||||
def relu_squared_static_fp8_quant(
|
||||
x: torch.Tensor, linear: LinearBase
|
||||
) -> QuantizedActivation:
|
||||
"""BF16 ReLU2 followed by static per-tensor FP8 quantization."""
|
||||
assert x.dtype == torch.bfloat16
|
||||
assert x.is_contiguous()
|
||||
scale = linear.input_scale
|
||||
assert scale.dtype == torch.float32
|
||||
assert x.device == scale.device
|
||||
assert scale.numel() == 1
|
||||
|
||||
output = torch.empty_like(x, dtype=current_platform.fp8_dtype())
|
||||
if x.numel() != 0:
|
||||
block_size = min(triton.next_power_of_2(x.shape[-1]), 2048)
|
||||
num_warps = min(max(block_size // 256, 1), 4)
|
||||
grid = lambda meta: (triton.cdiv(x.numel(), meta["BLOCK_SIZE"]),)
|
||||
_relu_squared_static_fp8_quant_kernel[grid](
|
||||
x,
|
||||
scale,
|
||||
output,
|
||||
x.numel(),
|
||||
FP8_MIN=_FP8_MIN,
|
||||
FP8_MAX=_FP8_MAX,
|
||||
BLOCK_SIZE=block_size,
|
||||
num_warps=num_warps,
|
||||
)
|
||||
|
||||
return QuantizedActivation(
|
||||
data=output,
|
||||
scale=scale,
|
||||
orig_dtype=x.dtype,
|
||||
orig_shape=x.shape,
|
||||
quant_key=kFp8StaticTensorSym,
|
||||
)
|
||||
@@ -252,6 +252,8 @@ class LinearBase(PluggableLayer):
|
||||
disable_tp: If true, tensor parallelism will be disabled for this layer.
|
||||
"""
|
||||
|
||||
requires_unquantized_input = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
input_size: int,
|
||||
|
||||
Reference in New Issue
Block a user