[ROCm] Remove stale SDPA and skinny GEMM workarounds (#50907)

Signed-off-by: Andreas Karatzas <Andreas.Karatzas@amd.com>
Signed-off-by: Andreas Karatzas <akaratza@amd.com>
Co-authored-by: OpenAI Codex <codex@openai.com>
This commit is contained in:
Andreas Karatzas
2026-08-11 14:19:16 -04:00
committed by GitHub
co-authored by OpenAI Codex
parent 4f2f31b82e
commit 1ab2801dde
56 changed files with 500 additions and 558 deletions
+82
View File
@@ -1,12 +1,15 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import ctypes
import functools
import os
from collections.abc import Callable
import torch
from torch._ops import OpOverload
import vllm.envs as envs
from vllm.logger import init_logger
from vllm.platforms import current_platform
from vllm.utils.import_utils import PlaceholderModule
from vllm.utils.torch_utils import direct_register_custom_op
@@ -15,6 +18,8 @@ from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
rocm_aiter_sparse_attn_indexer_fake,
)
logger = init_logger(__name__)
try:
import pandas as pd
except ImportError:
@@ -49,6 +54,83 @@ def is_aiter_found() -> bool:
IS_AITER_FOUND = is_aiter_found()
class _DlInfo(ctypes.Structure):
_fields_ = [
("dli_fname", ctypes.c_char_p),
("dli_fbase", ctypes.c_void_p),
("dli_sname", ctypes.c_char_p),
("dli_saddr", ctypes.c_void_p),
]
_HIP_RUNTIME_HANDLE: ctypes.CDLL | None = None
def _find_torch_hip_runtime_path() -> str | None:
"""Find the HIP runtime already selected by PyTorch's extension graph."""
try:
torch_extension = ctypes.CDLL(torch._C.__file__)
hip_symbol = torch_extension.hipGetDeviceCount
dladdr = ctypes.CDLL(None).dladdr
dladdr.argtypes = [ctypes.c_void_p, ctypes.POINTER(_DlInfo)]
dladdr.restype = ctypes.c_int
info = _DlInfo()
if not dladdr(ctypes.cast(hip_symbol, ctypes.c_void_p), ctypes.byref(info)):
return None
except (AttributeError, OSError, TypeError, ctypes.ArgumentError):
return None
if info.dli_fname is None:
return None
runtime_path = os.fsdecode(info.dli_fname)
if "libamdhip64.so" not in os.path.basename(runtime_path):
return None
return runtime_path
def _promote_torch_hip_runtime() -> None:
"""Make PyTorch's HIP runtime symbols visible to AITER JIT extensions.
PyTorch loads its native extension with ``RTLD_LOCAL``. Some AITER JIT
extensions rely on HIP registration and launch symbols being available in
the process-global lookup scope. Reopening the exact runtime that provides
PyTorch's ``hipGetDeviceCount`` symbol promotes the existing DSO instead of
selecting or initializing a second HIP runtime.
"""
global _HIP_RUNTIME_HANDLE
if _HIP_RUNTIME_HANDLE is not None:
return
runtime_path = _find_torch_hip_runtime_path()
if runtime_path is None:
logger.warning_once(
"Could not locate PyTorch's HIP runtime; AITER JIT extensions may "
"fail to resolve HIP symbols."
)
return
try:
# Retain the handle for the process lifetime. Besides preventing a
# future dlclose, this documents that the RTLD_GLOBAL promotion is
# intentional and must outlive every lazily imported AITER extension.
_HIP_RUNTIME_HANDLE = ctypes.CDLL(runtime_path, mode=ctypes.RTLD_GLOBAL)
except OSError as err:
logger.warning_once(
"Could not promote PyTorch's HIP runtime at %s; AITER JIT "
"extensions may fail to resolve HIP symbols: %s",
runtime_path,
err,
)
def _maybe_promote_torch_hip_runtime() -> None:
if current_platform.is_rocm() and IS_AITER_FOUND:
_promote_torch_hip_runtime()
_maybe_promote_torch_hip_runtime()
def is_aiter_found_and_supported() -> bool:
"""Check if AITER library is available and platform supports it.
+12 -4
View File
@@ -134,12 +134,16 @@ def rocm_unquantized_gemm_impl(
GrpsShrB = min(N_p2 // 16, 4)
# Given the above, how many CUs would we need?
CuNeeded = rndup_cus * GrpsShrB
# candidate for atomic reduce count splitk?
# Deterministic reduction stores one float workspace value per K shard.
fits_wvsplitkrc = (
N_p2 * m * ((k + 512 - 1) // 512)
) <= 128 * 1024 * 12 # deterministic
fits_wvsplitkrc &= CuNeeded <= cu_count
skinny_operands_compatible = weight.is_contiguous() and (
bias is None or bias.is_contiguous()
)
use_skinny_reduce_counting = (
envs.VLLM_ROCM_USE_SKINNY_GEMM
and on_gfx950()
@@ -151,12 +155,13 @@ def rocm_unquantized_gemm_impl(
and k > 512
and m % 16 == 0
and fits_wvsplitkrc
and weight.is_contiguous()
and skinny_operands_compatible
)
)
if use_skinny_reduce_counting:
return ops.wvSplitKrc(x, weight, cu_count, bias)
x_view = x.reshape(-1, x.size(-1)).contiguous()
return ops.wvSplitKrc(x_view, weight, cu_count, bias)
# gfx1250's aiter gemm_a16w16 uses the gluon backend, which requires
# K % 256 == 0 (it walks K with fixed-size descriptors and won't pad a
@@ -174,10 +179,13 @@ def rocm_unquantized_gemm_impl(
# TODO GFX1250: Include once skinny GEMM is supported on gfx1250
and x.dtype in [torch.float16, torch.bfloat16]
and k % 8 == 0
and skinny_operands_compatible
)
if use_skinny:
x_view = x.reshape(-1, x.size(-1))
# The skinny kernels assume contiguous K elements. A shape-preserving
# reshape can retain a transposed activation's non-contiguous strides.
x_view = x.reshape(-1, x.size(-1)).contiguous()
if m > 8 and 0 < n <= 5:
cu_count = num_compute_units()
out = ops.wvSplitK(weight, x_view, cu_count, bias)
@@ -18,7 +18,7 @@
from collections import defaultdict
from collections.abc import Mapping, Sequence
from contextlib import ExitStack, contextmanager, nullcontext
from contextlib import ExitStack, contextmanager
from typing import TYPE_CHECKING, Any
import torch
@@ -53,7 +53,6 @@ from vllm.multimodal.processing import (
PromptUpdate,
TimingContext,
)
from vllm.platforms import current_platform
from vllm.sequence import IntermediateTensors
if TYPE_CHECKING:
@@ -727,15 +726,9 @@ class MultiModalMixin(SupportsMultiModal, SupportsMRoPE):
kwargs.pop("token_type_ids", None)
kwargs.pop("mm_token_type_ids", None)
context = nullcontext()
if current_platform.is_rocm():
context = torch.nn.attention.sdpa_kernel(
backends=[torch.nn.attention.SDPBackend.MATH]
)
with context:
audio_output = self.model.get_audio_features(
input_features, return_dict=True, **kwargs
)
audio_output = self.model.get_audio_features(
input_features, return_dict=True, **kwargs
)
audio_embeddings = audio_output.pooler_output
split_sizes = num_audio_tokens.flatten().tolist()
@@ -756,23 +749,7 @@ class MultiModalMixin(SupportsMultiModal, SupportsMRoPE):
num_image_patches = kwargs.pop("num_image_patches")
context = nullcontext()
if current_platform.is_rocm():
# ROCm: Force math SDP backend for vision encoder to avoid accuracy issues
# with flash_sdp and mem_efficient_sdp
# TODO: [ROCm] Fix accuracy issues with flash backend
logger.debug(
"ROCm platform detected. Forcing math SDP backend "
"for vision encoder. Currently ROCm platform has "
"accuracy issues with `flash_sdp` and"
"`mem_efficient_sdp` backends. See issue: "
"https://github.com/vllm-project/vllm/issues/30167"
)
context = torch.nn.attention.sdpa_kernel(
backends=[torch.nn.attention.SDPBackend.MATH]
)
with context:
vision_embeddings = self.model.get_image_features(pixel_values, **kwargs)
vision_embeddings = self.model.get_image_features(pixel_values, **kwargs)
# Transformers `v5`, `self.get_image_features` returns a tuple
# containing the features and optionally attentions/hidden_states
+1 -2
View File
@@ -619,8 +619,7 @@ def resolve_kv_cache_block_sizes(
``cache_config.prefix_match_unit`` override if set, else the GCD of
group block sizes; every group's block size must be divisible by it.
Returns the scheduler block size (i.e. disables finer hashing) if block
hashing is inactive or a mamba group's block size diverges from the
cache block size (mamba_cache_mode != "align").
hashing is inactive or a mamba group is not using cache mode "align".
"""
cache_config = vllm_config.cache_config
dcp = vllm_config.parallel_config.decode_context_parallel_size
+5 -3
View File
@@ -634,9 +634,11 @@ class SingleDirectionOffloadingHandler:
else torch.Event(enable_timing=True)
)
if self.gpu_to_cpu:
# wait for model computation to finish before offloading
stream.wait_stream(current_platform.current_stream())
# Stores must wait for the model to finish writing the KV they read.
# Loads must wait for pending writes (including zeroing) to their
# destination blocks; otherwise an earlier transfer can be overwritten
# by compute-stream work that was already queued when the load began.
stream.wait_stream(current_platform.current_stream())
if self._transfers:
last_transfer: Transfer = self._transfers[-1]
last_event = last_transfer.end_event
+27 -2
View File
@@ -6420,6 +6420,21 @@ class GPUModelRunner(
logits,
dummy_metadata,
)
# All-greedy is a separate Triton specialization from the
# mixed-sampling path above. Compile and exercise it before serving.
all_greedy_metadata = replace(
dummy_metadata,
temperature=None,
all_greedy=True,
all_random=False,
)
self.rejection_sampler(
dummy_spec_decode_metadata,
draft_probs,
logits,
all_greedy_metadata,
)
torch.accelerator.synchronize()
return sampler_output
def _dummy_pooler_run_task(
@@ -6615,16 +6630,26 @@ class GPUModelRunner(
@staticmethod
@contextmanager
def _freeze_gc():
gc_was_enabled = gc.isenabled()
gc.collect()
should_freeze = not envs.VLLM_ENABLE_CUDAGRAPH_GC
if should_freeze:
gc.freeze()
# A Triton kernel finalized during stream capture unloads its
# module and invalidates the captured graph.
gc.disable()
try:
yield
finally:
if should_freeze:
gc.unfreeze()
gc.collect()
try:
gc.unfreeze()
gc.collect()
finally:
if gc_was_enabled:
gc.enable()
else:
gc.disable()
def shutdown(self) -> None:
"""Release GPU tensors (model weights, KV caches, workspace) so that