Skip to content

Commit 5993735

Browse files
committed
Add a native RDNA2 kernel for the mHC pre-block projection
The projection is very wide and very short -- K spans the widened residual while N is a couple of dozen mixing coefficients -- and rocBLAS picks a 64x64x8 macro tile for it, landing at 1.1 TFLOP/s. It is not bandwidth-bound: a loads-only kernel over the same operand runs seven times faster, and an fp16 dot over the same shape is exactly 1.9x an fp32 one, which is the packed-FMA ratio, so what binds is fp32 issue rate. This kernel gives one wave several rows of x and keeps the accumulators in registers across every K chunk the workgroup walks, so there is a single wave reduction at the end rather than one per chunk, and it stages fn in LDS for reuse across the waves. Lanes take consecutive k: striding several k per lane instead puts every lane on a multiple of eight and collapses the 32 LDS banks onto four, which costs more than everything else here. Folding the widening in as well -- exact, since fp16 and bf16 both convert to fp32 losslessly -- drops the fp32 copy of the residual the two-pass path had to write and read back. The pre-block runs 2.3x faster at a 512-token chunk and 1.6x at one token, worth 4.5% of TPOT end to end.
1 parent 58a8b71 commit 5993735

7 files changed

Lines changed: 467 additions & 11 deletions

File tree

CMakeLists.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1461,7 +1461,8 @@ if(VLLM_GPU_LANG STREQUAL "HIP")
14611461
list(APPEND VLLM_ROCM_EXT_SRC
14621462
"csrc/rocm/q_gemm_rdna2.cu"
14631463
"csrc/rocm/moe_q_gemm_rdna2.cu"
1464-
"csrc/rocm/skinny_gemms_rdna2.cu")
1464+
"csrc/rocm/skinny_gemms_rdna2.cu"
1465+
"csrc/rocm/mhc_proj_rdna2.cu")
14651466
endif()
14661467

14671468
set(VLLM_ROCM_HAS_GFX1100 OFF)

csrc/rocm/mhc_proj_rdna2.cu

Lines changed: 251 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,251 @@
1+
// SPDX-License-Identifier: Apache-2.0
2+
// SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3+
//
4+
// RDNA2 (gfx1030) mHC pre-block projection: mixes[T,N] = x[T,K] @ fn[N,K]^T in
5+
// fp32, plus the per-row sum of squares of x, from a fp16/bf16 residual.
6+
//
7+
// The shape is very wide and very short -- K spans the widened residual
8+
// (hc_mult * hidden_size) while N is 2*hc_mult + hc_mult^2 mixing coefficients,
9+
// 24 for hc_mult=4. rocBLAS picks a 64x64x8 macro tile for it and lands at ~1.1
10+
// TFLOP/s; the op is limited by fp32 FMA issue and LDS traffic, not bandwidth
11+
// (a loads-only kernel over the same operand runs 7x faster), so the wins here
12+
// come from occupancy and from reusing each staged fn value.
13+
//
14+
// Structure: one wave owns TPW rows of x; a workgroup walks one K chunk with
15+
// fn[:, chunk] staged in LDS and reused by every wave. Accumulators stay in
16+
// registers for the whole chunk, so there is one wave reduction at the end
17+
// rather than one per K step. Lanes take CONSECUTIVE k, which keeps the global
18+
// loads coalesced and -- with an odd LDS row stride -- puts the 32 lanes on 32
19+
// distinct LDS banks; striding several k per lane instead collapses them onto a
20+
// multiple of 8 and costs an 8-way conflict.
21+
//
22+
// The widening is exact, so folding it in here drops the fp32 copy of the
23+
// residual that the two-pass path had to materialise and read back.
24+
#include <torch/all.h>
25+
#include <c10/cuda/CUDAGuard.h>
26+
#include <ATen/cuda/CUDAContext.h>
27+
28+
#include <hip/hip_runtime.h>
29+
#include <hip/hip_fp16.h>
30+
#include <hip/hip_bf16.h>
31+
32+
#if defined(__HIPCC__) && defined(__gfx1030__)
33+
#define __HIP__RDNA2__
34+
#endif
35+
36+
namespace vllm {
37+
namespace mhc_rdna2 {
38+
39+
static constexpr int WAVE = 32;
40+
static constexpr int LDS_BYTES = 64 * 1024;
41+
// LDS row stride in floats. Odd, so consecutive lanes (consecutive k) map to
42+
// consecutive banks; an even stride would alias lanes onto shared banks.
43+
static constexpr int PAD_EXTRA = 1;
44+
45+
#if defined(__HIP__RDNA2__) || !defined(__HIP_DEVICE_COMPILE__)
46+
47+
template <typename T>
48+
__device__ __forceinline__ float to_f32(T v);
49+
template <>
50+
__device__ __forceinline__ float to_f32<__half>(__half v) {
51+
return __half2float(v);
52+
}
53+
template <>
54+
__device__ __forceinline__ float to_f32<__hip_bfloat16>(__hip_bfloat16 v) {
55+
return __bfloat162float(v);
56+
}
57+
58+
template <typename T, int NOUT, int KC, int WAVES, int TPW>
59+
__global__ __launch_bounds__(WAVES* WAVE) void mhc_proj_kernel(
60+
const T* __restrict__ x, // [T, K]
61+
const float* __restrict__ fn, // [NOUT, K]
62+
float* __restrict__ partial, // [nchunk, T, NOUT]
63+
float* __restrict__ sqr_partial, // [nchunk, T]
64+
const int num_tokens, const int K) {
65+
constexpr int PAD = NOUT + PAD_EXTRA;
66+
static_assert(KC * PAD * sizeof(float) <= LDS_BYTES,
67+
"mhc_proj_rdna2: staged fn chunk exceeds the RDNA2 LDS budget; "
68+
"lower KC for this NOUT");
69+
__shared__ float fs[KC * PAD];
70+
71+
const int wave = threadIdx.x / WAVE;
72+
const int lane = threadIdx.x % WAVE;
73+
const int kchunk = blockIdx.x;
74+
const int tbase = blockIdx.y * (WAVES * TPW) + wave * TPW;
75+
76+
const int k0 = kchunk * KC;
77+
const int kc = min(KC, K - k0);
78+
79+
// Stage fn[:, k0:k0+kc] as [kc][NOUT]; every wave in the block reuses it.
80+
for (int i = threadIdx.x; i < kc * NOUT; i += WAVES * WAVE) {
81+
const int kk = i / NOUT;
82+
const int n = i - kk * NOUT;
83+
fs[kk * PAD + n] = fn[(long)n * K + k0 + kk];
84+
}
85+
__syncthreads();
86+
87+
float acc[TPW][NOUT];
88+
float sq[TPW];
89+
#pragma unroll
90+
for (int i = 0; i < TPW; i++) {
91+
#pragma unroll
92+
for (int n = 0; n < NOUT; n++) acc[i][n] = 0.f;
93+
sq[i] = 0.f;
94+
}
95+
96+
const int ntok = min(TPW, num_tokens - tbase);
97+
if (ntok > 0) {
98+
// k outer, tokens inner: each staged fn value feeds TPW FMAs.
99+
for (int k = lane; k < kc; k += WAVE) {
100+
float v[TPW];
101+
#pragma unroll
102+
for (int i = 0; i < TPW; i++) {
103+
v[i] = (i < ntok) ? to_f32<T>(x[(long)(tbase + i) * K + k0 + k]) : 0.f;
104+
sq[i] += v[i] * v[i];
105+
}
106+
const float* f = &fs[k * PAD];
107+
#pragma unroll
108+
for (int n = 0; n < NOUT; n++) {
109+
const float fv = f[n];
110+
#pragma unroll
111+
for (int i = 0; i < TPW; i++) acc[i][n] = fmaf(v[i], fv, acc[i][n]);
112+
}
113+
}
114+
}
115+
116+
#pragma unroll
117+
for (int i = 0; i < TPW; i++) {
118+
if (i >= ntok) break;
119+
const int t = tbase + i;
120+
#pragma unroll
121+
for (int n = 0; n < NOUT; n++) {
122+
float a = acc[i][n];
123+
#pragma unroll
124+
for (int m = WAVE / 2; m >= 1; m >>= 1) a += __shfl_xor(a, m, WAVE);
125+
if (lane == 0) partial[((long)kchunk * num_tokens + t) * NOUT + n] = a;
126+
}
127+
float s = sq[i];
128+
#pragma unroll
129+
for (int m = WAVE / 2; m >= 1; m >>= 1) s += __shfl_xor(s, m, WAVE);
130+
if (lane == 0) sqr_partial[(long)kchunk * num_tokens + t] = s;
131+
}
132+
}
133+
134+
// Sum the per-chunk partials. Kept as its own pass so the reduction order is
135+
// fixed by chunk index rather than by whichever workgroup finishes first.
136+
template <int NOUT>
137+
__global__ void mhc_reduce_kernel(const float* __restrict__ partial,
138+
const float* __restrict__ sqr_partial,
139+
float* __restrict__ mixes,
140+
float* __restrict__ sqrsum,
141+
const int num_tokens, const int nchunk) {
142+
const int t = blockIdx.x;
143+
if (t >= num_tokens) return;
144+
if (threadIdx.x < NOUT) {
145+
float a = 0.f;
146+
for (int c = 0; c < nchunk; c++)
147+
a += partial[((long)c * num_tokens + t) * NOUT + threadIdx.x];
148+
mixes[(long)t * NOUT + threadIdx.x] = a;
149+
} else if (threadIdx.x == NOUT) {
150+
float s = 0.f;
151+
for (int c = 0; c < nchunk; c++) s += sqr_partial[(long)c * num_tokens + t];
152+
sqrsum[t] = s;
153+
}
154+
}
155+
156+
#else // non-RDNA2 device pass: empty stubs for symbol parity.
157+
158+
template <typename T, int NOUT, int KC, int WAVES, int TPW>
159+
__global__ void mhc_proj_kernel(const T*, const float*, float*, float*,
160+
const int, const int) {}
161+
template <int NOUT>
162+
__global__ void mhc_reduce_kernel(const float*, const float*, float*, float*,
163+
const int, const int) {}
164+
165+
#endif // __HIP__RDNA2__ || !__HIP_DEVICE_COMPILE__
166+
167+
} // namespace mhc_rdna2
168+
} // namespace vllm
169+
170+
// Requirements (caller-checked): x is 2-D fp16 or bf16 [T, K], fn is fp32
171+
// [NOUT, K] with NOUT one of the instantiated widths, K % 8 == 0. Returns
172+
// (mixes [T, NOUT] fp32, sqrsum [T] fp32).
173+
std::tuple<torch::Tensor, torch::Tensor> mhc_proj_rdna2(
174+
const at::Tensor& x, const at::Tensor& fn) {
175+
TORCH_CHECK(x.dim() == 2 && fn.dim() == 2, "mhc_proj_rdna2 expects 2-D x/fn");
176+
TORCH_CHECK(x.dtype() == torch::kFloat16 || x.dtype() == torch::kBFloat16,
177+
"mhc_proj_rdna2 supports fp16 and bf16 x only");
178+
TORCH_CHECK(fn.dtype() == torch::kFloat32, "mhc_proj_rdna2 needs fp32 fn");
179+
TORCH_CHECK(x.size(1) == fn.size(1), "mhc_proj_rdna2 K mismatch");
180+
TORCH_CHECK(x.stride(1) == 1 && fn.stride(1) == 1,
181+
"mhc_proj_rdna2 needs K-contiguous x and fn");
182+
TORCH_CHECK(x.stride(0) == x.size(1) && fn.stride(0) == fn.size(1),
183+
"mhc_proj_rdna2 needs packed rows");
184+
185+
const int num_tokens = x.size(0);
186+
const int K = x.size(1);
187+
const int nout = fn.size(0);
188+
TORCH_CHECK(K % 8 == 0, "mhc_proj_rdna2 requires K % 8 == 0");
189+
190+
auto f32 = torch::TensorOptions().dtype(torch::kFloat32).device(x.device());
191+
auto mixes = torch::empty({num_tokens, nout}, f32);
192+
auto sqrsum = torch::empty({num_tokens}, f32);
193+
if (num_tokens == 0) return {mixes, sqrsum};
194+
195+
const at::cuda::OptionalCUDAGuard device_guard(device_of(x));
196+
const cudaStream_t stream = at::cuda::getCurrentCUDAStream();
197+
198+
// Small batches do not fill a wide workgroup, so they take one row per wave
199+
// and fewer waves; wide batches amortise the fn staging over more waves.
200+
const bool wide = num_tokens >= 32;
201+
202+
#define VLLM_MHC_LAUNCH(T, NOUT, KC, WAVES, TPW) \
203+
do { \
204+
const int nchunk = (K + (KC) - 1) / (KC); \
205+
auto partial = torch::empty({nchunk, num_tokens, nout}, f32); \
206+
auto sqr_partial = torch::empty({nchunk, num_tokens}, f32); \
207+
const dim3 grid(nchunk, \
208+
(num_tokens + (WAVES) * (TPW) - 1) / ((WAVES) * (TPW))); \
209+
vllm::mhc_rdna2::mhc_proj_kernel<T, NOUT, KC, WAVES, TPW> \
210+
<<<grid, (WAVES) * vllm::mhc_rdna2::WAVE, 0, stream>>>( \
211+
(const T*)x.data_ptr(), fn.data_ptr<float>(), \
212+
partial.data_ptr<float>(), sqr_partial.data_ptr<float>(), \
213+
num_tokens, K); \
214+
vllm::mhc_rdna2::mhc_reduce_kernel<NOUT> \
215+
<<<num_tokens, ((NOUT) + 32) & ~31, 0, stream>>>( \
216+
partial.data_ptr<float>(), sqr_partial.data_ptr<float>(), \
217+
mixes.data_ptr<float>(), sqrsum.data_ptr<float>(), num_tokens, \
218+
nchunk); \
219+
} while (0)
220+
221+
#define VLLM_MHC_BY_SHAPE(T, NOUT) \
222+
do { \
223+
if (wide) { \
224+
VLLM_MHC_LAUNCH(T, NOUT, 640, 32, 4); \
225+
} else { \
226+
VLLM_MHC_LAUNCH(T, NOUT, 640, 8, 1); \
227+
} \
228+
} while (0)
229+
230+
#define VLLM_MHC_BY_NOUT(T) \
231+
do { \
232+
switch (nout) { \
233+
case 8: VLLM_MHC_BY_SHAPE(T, 8); break; \
234+
case 24: VLLM_MHC_BY_SHAPE(T, 24); break; \
235+
default: \
236+
TORCH_CHECK(false, "mhc_proj_rdna2 has no kernel for nout=", nout); \
237+
} \
238+
} while (0)
239+
240+
if (x.dtype() == torch::kFloat16) {
241+
VLLM_MHC_BY_NOUT(__half);
242+
} else {
243+
VLLM_MHC_BY_NOUT(__hip_bfloat16);
244+
}
245+
246+
#undef VLLM_MHC_BY_NOUT
247+
#undef VLLM_MHC_BY_SHAPE
248+
#undef VLLM_MHC_LAUNCH
249+
250+
return {mixes, sqrsum};
251+
}

csrc/rocm/ops.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,9 @@ torch::Tensor wvSplitK_rdna2_grouped(const at::Tensor& in_a,
4444
const at::Tensor& in_b,
4545
const std::optional<at::Tensor>& out_opt);
4646

47+
std::tuple<torch::Tensor, torch::Tensor> mhc_proj_rdna2(const at::Tensor& x,
48+
const at::Tensor& fn);
49+
4750
torch::Tensor gptq_gemm_rdna3(torch::Tensor a, torch::Tensor b_q_weight,
4851
torch::Tensor b_qzeros, torch::Tensor b_scales,
4952
torch::Tensor b_g_idx, bool use_v2_format);

csrc/rocm/torch_bindings.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,11 @@ TORCH_LIBRARY_EXPAND(TORCH_EXTENSION_NAME, rocm_ops) {
8282
"wvSplitK_rdna2_grouped(Tensor in_a, Tensor in_b, Tensor(a!)? out) "
8383
"-> Tensor");
8484
rocm_ops.impl("wvSplitK_rdna2_grouped", torch::kCUDA, &wvSplitK_rdna2_grouped);
85+
86+
// mHC pre-block projection + sum of squares, fused so the fp32 widening of
87+
// the residual never reaches memory.
88+
rocm_ops.def("mhc_proj_rdna2(Tensor x, Tensor fn) -> (Tensor, Tensor)");
89+
rocm_ops.impl("mhc_proj_rdna2", torch::kCUDA, &mhc_proj_rdna2);
8590
#endif
8691

8792
#ifdef VLLM_ROCM_GFX1100

0 commit comments

Comments
 (0)