From 1b7c4b94ea6d170a083afd79592edc138a9cf183 Mon Sep 17 00:00:00 2001 From: Ravi Gupta Date: Sat, 21 Nov 2026 10:10:10 -0600 Subject: [PATCH 1/3] [ROCm][TensorIntrin] Add RDNA (gfx11) WMMA tensor intrinsics TVM has tensor intrinsics for CDNA MFMA (wave64) but none for the WMMA instructions of RDNA GPUs (gfx11, wave32), so tensorized GEMMs cannot use the matrix cores of Radeon RX 7000 / Radeon 8060S (Ryzen AI Max) class GPUs. This adds fill, load (A, B and transposed B from shared memory), multiply (f16 x f16 -> f32, llvm.amdgcn.wmma.f32.16x16x16.f16) and store (global and shared) intrinsics in tensor_intrin/rocm_wmma.py, next to the MFMA ones in rocm.py. On RDNA, lanes 16-31 of a wave hold a copy of the A and B fragments of lanes 0-15, so the A/B descriptors describe the 16 distinct lanes while the implementations run on all 32; the accumulator uses 32 lanes x 8 values (rows 2 * i + lane // 16 of column lane % 16). mfma_schedule in s_tir/testing/tir.py takes a warp_size argument (default 64, unchanged for MFMA) so it can drive the wave32 intrinsics. A numeric test tensorizes a 512x512x512 fp16 GEMM with B in [K, N] and in [N, K] layout and compares with numpy. It is skipped unless an RDNA device with WMMA is present, and passes on gfx1151 (Radeon 8060S). --- python/tvm/s_tir/tensor_intrin/rocm_wmma.py | 329 ++++++++++++++++++ python/tvm/s_tir/testing/tir.py | 5 +- ...ir_schedule_tensorize_wmma_rdna_numeric.py | 122 +++++++ 3 files changed, 454 insertions(+), 2 deletions(-) create mode 100644 python/tvm/s_tir/tensor_intrin/rocm_wmma.py create mode 100644 tests/python/s_tir/schedule/test_tir_schedule_tensorize_wmma_rdna_numeric.py diff --git a/python/tvm/s_tir/tensor_intrin/rocm_wmma.py b/python/tvm/s_tir/tensor_intrin/rocm_wmma.py new file mode 100644 index 000000000000..f942fdd63098 --- /dev/null +++ b/python/tvm/s_tir/tensor_intrin/rocm_wmma.py @@ -0,0 +1,329 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +"""Intrinsics for RDNA (gfx11) WMMA tensorization, wave32. + +`v_wmma_f32_16x16x16_f16` computes D[16x16] = A[16x16] x B[16x16] + C on one wave32 wavefront. +Fragment layout per lane (verified on gfx1151): + A: lane l holds row l % 16, all 16 k values (lanes 16-31 repeat lanes 0-15) + B: lane l holds column l % 16, all 16 k values (lanes 16-31 repeat lanes 0-15) + C/D: lane l holds 8 values, rows 2 * i + l // 16 (i = 0..7) of column l % 16 +As in rocm.py (MFMA), descriptors use the logical (lane, value) layout of the whole wavefront and +implementations bind (1, values_per_lane) local storage per lane. The A/B descriptors describe the +16 distinct fragment lanes; the implementations run on all 32 lanes. +""" + +from tvm.s_tir import script as Ts +from tvm_tirx.ir import IntImm +from tvm_tirx.script import tirx as T + +from .. import TensorIntrin + +WARP_SIZE = 32 +M_DIM = N_DIM = K_DIM = 16 +AB_LOCAL = 16 # values per lane for A and B fragments +AB_LANES = 16 # distinct A/B fragment lanes; lanes 16-31 hold a copy (the descriptors describe 16) +C_LOCAL = 8 # values per lane for the accumulator fragment + + +def shared_16x16_to_local_32x16_layout_A(i, k): + return i, k + + +def thread_id_shared_access_32x16_to_16x16_layout_A(thread_id, local_id): + return thread_id % 16, local_id + + +def shared_16x16_to_local_32x16_layout_B(k, j): + return j, k + + +def thread_id_shared_access_32x16_to_16x16_layout_B(thread_id, local_id): + return local_id, thread_id % 16 + + +def shared_16x16_to_local_32x8_layout_C(i, j): + return j + 16 * (i % 2), i // 2 + + +def thread_id_shared_access_32x8_to_16x16_layout_C(thread_id, local_id): + return 2 * local_id + thread_id // 16, thread_id % 16 + + +def get_wmma_fill_intrin(dtype="float32"): + zero = IntImm("int32", 0).astype(dtype) + + @Ts.function + def fill_desc(C_warp: T.Tensor([WARP_SIZE, C_LOCAL], dtype=dtype, scope="local")) -> None: + with Ts.sblock("root"): + Ts.reads() + Ts.writes(C_warp[0:WARP_SIZE, 0:C_LOCAL]) + for i0, i1 in T.grid(M_DIM, N_DIM): + with Ts.sblock("C_warp"): + i, j = Ts.axis.remap("SS", [i0, i1]) + w = shared_16x16_to_local_32x8_layout_C(i, j) + Ts.reads() + Ts.writes(C_warp[w[0], w[1]]) + C_warp[w[0], w[1]] = zero + + fill_impl_offset = T.dynamic("wmma_fill_impl_offset", "int32") + + @Ts.function + def fill_impl( + C_warp: T.Tensor( + [1, C_LOCAL], + dtype=dtype, + scope="local", + layout=T.TileLayout(T.S[[1, C_LOCAL]] + (fill_impl_offset)), + ), + ) -> None: + with Ts.sblock("root"): + Ts.reads() + Ts.writes(C_warp[0:1, 0:C_LOCAL]) + _tx = T.launch_thread("threadIdx.x", WARP_SIZE) + for local_id in T.serial(0, C_LOCAL): + C_warp[0, local_id] = zero + + return fill_desc, fill_impl + + +def get_wmma_load_intrin(dtype="float16", scope="shared", is_b=False, transposed=False): + """A: memory [M, K]. B: memory [K, N], or [N, K] when `transposed` (weights stored N x K).""" + if not is_b: + memory_shape, index_map, reverse = ( + (M_DIM, K_DIM), + shared_16x16_to_local_32x16_layout_A, + thread_id_shared_access_32x16_to_16x16_layout_A, + ) + elif transposed: # B^T stored [N, K]: lane l reads row l % 16, like A + memory_shape, index_map, reverse = ( + (N_DIM, K_DIM), + shared_16x16_to_local_32x16_layout_A, + thread_id_shared_access_32x16_to_16x16_layout_A, + ) + else: + memory_shape, index_map, reverse = ( + (K_DIM, N_DIM), + shared_16x16_to_local_32x16_layout_B, + thread_id_shared_access_32x16_to_16x16_layout_B, + ) + row_dim, col_dim = memory_shape + desc_reg_off = T.dynamic("wmma_load_desc_reg_offset", "int32") + desc_mem_off = T.dynamic("wmma_load_desc_memory_offset", "int32") + + @Ts.function + def load_desc( + reg: T.Tensor( + (AB_LANES, AB_LOCAL), + dtype, + scope="local", + layout=T.TileLayout(T.S[(AB_LANES, AB_LOCAL)] + (desc_reg_off)), + ), + memory: T.Tensor( + memory_shape, + dtype, + scope=scope, + layout=T.TileLayout(T.S[memory_shape] + (desc_mem_off)), + ), + ) -> None: + with Ts.sblock("root"): + Ts.reads(memory[0:row_dim, 0:col_dim]) + Ts.writes(reg[0:AB_LANES, 0:AB_LOCAL]) + for ax0, ax1 in T.grid(row_dim, col_dim): + with Ts.sblock("memory_reg"): + v0, v1 = Ts.axis.remap("SS", [ax0, ax1]) + w = index_map(v0, v1) + Ts.reads(memory[v0, v1]) + Ts.writes(reg[w[0], w[1]]) + reg[w[0], w[1]] = memory[v0, v1] + + s0 = T.dynamic("s0", "int32") + s1 = T.dynamic("s1", "int32") + impl_reg_off = T.dynamic("wmma_load_impl_reg_offset", "int32") + impl_mem_off = T.dynamic("wmma_load_impl_memory_offset", "int32") + + @Ts.function + def load_impl( + reg: T.Tensor( + (1, AB_LOCAL), + dtype, + align=32, + scope="local", + layout=T.TileLayout(T.S[(1, AB_LOCAL)] + (impl_reg_off)), + ), + memory: T.Tensor( + memory_shape, + dtype, + align=32, + scope=scope, + layout=T.TileLayout(T.S[memory_shape : [s0, s1]] + (impl_mem_off)), + ), + ) -> None: + with Ts.sblock("root"): + Ts.reads(memory[0:row_dim, 0:col_dim]) + Ts.writes(reg[0:1, 0:AB_LOCAL]) + for local_id in T.serial(0, AB_LOCAL): + tx = T.launch_thread("threadIdx.x", WARP_SIZE) + idx = reverse(tx, local_id) + reg[0, local_id] = memory[idx[0], idx[1]] + + return load_desc, load_impl + + +def get_wmma_intrin(in_dtype="float16", out_dtype="float32"): + """D = A x B + C, 16x16x16, wave32. f16 x f16 -> f32 (v_wmma_f32_16x16x16_f16).""" + assert in_dtype == "float16" and out_dtype == "float32", "only f16 -> f32 for now" + intrin = "llvm.amdgcn.wmma.f32.16x16x16.f16" + d_a = T.dynamic("wmma_desc_a_offset", "int32") + d_b = T.dynamic("wmma_desc_b_offset", "int32") + d_c = T.dynamic("wmma_desc_c_offset", "int32") + + @Ts.function + def wmma_desc( + A: T.Tensor( + (AB_LANES, AB_LOCAL), + in_dtype, + scope="local", + layout=T.TileLayout(T.S[(AB_LANES, AB_LOCAL)] + (d_a)), + ), + B: T.Tensor( + (AB_LANES, AB_LOCAL), + in_dtype, + scope="local", + layout=T.TileLayout(T.S[(AB_LANES, AB_LOCAL)] + (d_b)), + ), + C: T.Tensor( + (WARP_SIZE, C_LOCAL), + out_dtype, + scope="local", + layout=T.TileLayout(T.S[(WARP_SIZE, C_LOCAL)] + (d_c)), + ), + ) -> None: + with Ts.sblock("root"): + Ts.reads( + C[0:WARP_SIZE, 0:C_LOCAL], A[0:AB_LANES, 0:AB_LOCAL], B[0:AB_LANES, 0:AB_LOCAL] + ) + Ts.writes(C[0:WARP_SIZE, 0:C_LOCAL]) + for i, j, k in T.grid(M_DIM, N_DIM, K_DIM): + with Ts.sblock("C"): + vi, vj, vk = Ts.axis.remap("SSR", [i, j, k]) + c = shared_16x16_to_local_32x8_layout_C(vi, vj) + a = shared_16x16_to_local_32x16_layout_A(vi, vk) + b = shared_16x16_to_local_32x16_layout_B(vk, vj) + Ts.reads(C[c[0], c[1]], A[a[0], a[1]], B[b[0], b[1]]) + Ts.writes(C[c[0], c[1]]) + C[c[0], c[1]] += T.Cast(out_dtype, A[a[0], a[1]]) * T.Cast( + out_dtype, B[b[0], b[1]] + ) + + i_a = T.dynamic("wmma_impl_a_offset", "int32") + i_b = T.dynamic("wmma_impl_b_offset", "int32") + i_c = T.dynamic("wmma_impl_c_offset", "int32") + + @Ts.function + def wmma_impl( + A: T.Tensor( + (1, AB_LOCAL), in_dtype, scope="local", layout=T.TileLayout(T.S[(1, AB_LOCAL)] + (i_a)) + ), + B: T.Tensor( + (1, AB_LOCAL), in_dtype, scope="local", layout=T.TileLayout(T.S[(1, AB_LOCAL)] + (i_b)) + ), + C: T.Tensor( + (1, C_LOCAL), out_dtype, scope="local", layout=T.TileLayout(T.S[(1, C_LOCAL)] + (i_c)) + ), + ) -> None: + with Ts.sblock("root"): + Ts.reads(A[0:1, 0:AB_LOCAL], B[0:1, 0:AB_LOCAL], C[0:1, 0:C_LOCAL]) + Ts.writes(C[0:1, 0:C_LOCAL]) + _tx = T.launch_thread("threadIdx.x", WARP_SIZE) + C[0, T.ramp(0, 1, C_LOCAL)] = T.call_llvm_pure_intrin( + T.llvm_lookup_intrinsic_id(intrin), + A[0, T.ramp(0, 1, AB_LOCAL)], + B[0, T.ramp(0, 1, AB_LOCAL)], + C[0, T.ramp(0, 1, C_LOCAL)], + ty=f"{out_dtype}x{C_LOCAL}", + ) + + return wmma_desc, wmma_impl + + +def get_wmma_store_intrin(dtype="float32", scope="global"): + @Ts.function + def store_desc( + C_warp: T.Tensor([WARP_SIZE, C_LOCAL], dtype=dtype, scope="local"), + C: T.Tensor([M_DIM, N_DIM], dtype=dtype, scope=scope), + ) -> None: + with Ts.sblock("root"): + Ts.reads(C_warp[0:WARP_SIZE, 0:C_LOCAL]) + Ts.writes(C[0:M_DIM, 0:N_DIM]) + for i0, i1 in T.grid(M_DIM, N_DIM): + with Ts.sblock("C_warp"): + v0, v1 = Ts.axis.remap("SS", [i0, i1]) + w = shared_16x16_to_local_32x8_layout_C(v0, v1) + Ts.reads(C_warp[w[0], w[1]]) + Ts.writes(C[v0, v1]) + C[v0, v1] = C_warp[w[0], w[1]] + + s0 = T.dynamic("s0", "int32") + s1 = T.dynamic("s1", "int32") + o_w = T.dynamic("wmma_store_impl_c_warp_offset", "int32") + o_c = T.dynamic("wmma_store_impl_c_offset", "int32") + + @Ts.function + def store_impl( + C_warp: T.Tensor( + [1, C_LOCAL], dtype=dtype, scope="local", layout=T.TileLayout(T.S[[1, C_LOCAL]] + (o_w)) + ), + C: T.Tensor( + [M_DIM, N_DIM], + dtype=dtype, + scope=scope, + layout=T.TileLayout(T.S[[M_DIM, N_DIM] : [s0, s1]] + (o_c)), + ), + ) -> None: + with Ts.sblock("root"): + Ts.reads(C_warp[0:1, 0:C_LOCAL]) + Ts.writes(C[0:M_DIM, 0:N_DIM]) + tx = T.launch_thread("threadIdx.x", WARP_SIZE) + for i in range(C_LOCAL): + C[2 * i + tx // 16, tx % 16] = C_warp[0, i] + + return store_desc, store_impl + + +ROCM_WMMA_FILL_16x16_F32_INTRIN = "rocm_wmma_fill_16x16_f32" +TensorIntrin.register(ROCM_WMMA_FILL_16x16_F32_INTRIN, *get_wmma_fill_intrin("float32")) +ROCM_WMMA_LOAD_16x16_A_SHARED_F16_INTRIN = "rocm_wmma_load_16x16_a_shared_f16" +TensorIntrin.register( + ROCM_WMMA_LOAD_16x16_A_SHARED_F16_INTRIN, *get_wmma_load_intrin("float16", "shared") +) +ROCM_WMMA_LOAD_16x16_B_SHARED_F16_INTRIN = "rocm_wmma_load_16x16_b_shared_f16" +TensorIntrin.register( + ROCM_WMMA_LOAD_16x16_B_SHARED_F16_INTRIN, *get_wmma_load_intrin("float16", "shared", is_b=True) +) +ROCM_WMMA_LOAD_16x16_B_TRANS_SHARED_F16_INTRIN = "rocm_wmma_load_16x16_b_trans_shared_f16" +TensorIntrin.register( + ROCM_WMMA_LOAD_16x16_B_TRANS_SHARED_F16_INTRIN, + *get_wmma_load_intrin("float16", "shared", is_b=True, transposed=True), +) +ROCM_WMMA_F16F16F32_INTRIN = "rocm_wmma_f16f16f32" +TensorIntrin.register(ROCM_WMMA_F16F16F32_INTRIN, *get_wmma_intrin("float16", "float32")) +ROCM_WMMA_STORE_16x16_F32_INTRIN = "rocm_wmma_store_16x16_f32" +TensorIntrin.register(ROCM_WMMA_STORE_16x16_F32_INTRIN, *get_wmma_store_intrin("float32", "global")) +ROCM_WMMA_STORE_16x16_F32_SHARED_INTRIN = "rocm_wmma_store_16x16_f32_shared" +TensorIntrin.register( + ROCM_WMMA_STORE_16x16_F32_SHARED_INTRIN, *get_wmma_store_intrin("float32", "shared") +) diff --git a/python/tvm/s_tir/testing/tir.py b/python/tvm/s_tir/testing/tir.py index e7c45933aff7..42aa4cf1be47 100644 --- a/python/tvm/s_tir/testing/tir.py +++ b/python/tvm/s_tir/testing/tir.py @@ -35,8 +35,10 @@ def mfma_schedule( mfma_fill_intrin, mfma_store_intrin, shared_scope="shared", + warp_size=64, ): - """Create a tensorized schedule for GEMM with MFMA intrinsics.""" + """Create a tensorized schedule for GEMM with MFMA intrinsics (warp_size=64, CDNA) or + RDNA WMMA intrinsics (warp_size=32).""" import tvm import tvm_tirx @@ -46,7 +48,6 @@ def mfma_schedule( wmma_m = 16 wmma_n = 16 wmma_k = k_inner - warp_size = 64 block = sch.get_sblock("C") i, j, k = sch.get_loops(block) i, i_tc = sch.split(i, factors=[None, wmma_m]) diff --git a/tests/python/s_tir/schedule/test_tir_schedule_tensorize_wmma_rdna_numeric.py b/tests/python/s_tir/schedule/test_tir_schedule_tensorize_wmma_rdna_numeric.py new file mode 100644 index 000000000000..b15d389eb33d --- /dev/null +++ b/tests/python/s_tir/schedule/test_tir_schedule_tensorize_wmma_rdna_numeric.py @@ -0,0 +1,122 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# pylint: disable=missing-docstring +"""Numeric test of the RDNA (gfx11, wave32) WMMA tensor intrinsics in tensor_intrin/rocm_wmma.py.""" + +import numpy as np +import pytest + +import tvm +import tvm_tirx +import tvm_tirx.testing +from tvm import te +from tvm.s_tir.tensor_intrin.rocm_wmma import ( + ROCM_WMMA_F16F16F32_INTRIN, + ROCM_WMMA_FILL_16x16_F32_INTRIN, + ROCM_WMMA_LOAD_16x16_A_SHARED_F16_INTRIN, + ROCM_WMMA_LOAD_16x16_B_SHARED_F16_INTRIN, + ROCM_WMMA_LOAD_16x16_B_TRANS_SHARED_F16_INTRIN, + ROCM_WMMA_STORE_16x16_F32_INTRIN, + shared_16x16_to_local_32x8_layout_C, + shared_16x16_to_local_32x16_layout_A, + shared_16x16_to_local_32x16_layout_B, +) +from tvm.s_tir.testing.tir import mfma_schedule + +M = N = K = 512 + + +def _is_rdna(): + """True if a ROCm device with RDNA WMMA (gfx11/gfx12) is present.""" + if not tvm_tirx.rocm(0).exist: + return False + from tvm_tirx.support import rocm # pylint: disable=import-outside-toplevel + + if hasattr(rocm, "have_rdna_wmma"): + return rocm.have_rdna_wmma() + major = str(tvm_tirx.rocm(0).compute_version).split(".", maxsplit=1)[0] + return major in ("11", "12") + + +def matmul(b_transposed): + a = te.placeholder((M, K), name="A", dtype="float16") + b = te.placeholder((N, K) if b_transposed else (K, N), name="B", dtype="float16") + k = te.reduce_axis((0, K), name="k") + c = te.compute( + (M, N), + lambda i, j: te.sum( + tvm_tirx.tirx.Cast("float32", a[i, k]) + * tvm_tirx.tirx.Cast("float32", b[(j, k) if b_transposed else (k, j)]), + axis=[k], + ), + name="C", + ) + return a, b, c + + +@pytest.mark.gpu +@pytest.mark.skipif(not _is_rdna(), reason="needs an RDNA (gfx11/12) GPU with WMMA") +@pytest.mark.parametrize("b_transposed", [False, True]) +def test_f16f16f32_m16n16k16_wave32(b_transposed, tmp_path): + def tile(mapping): + return lambda i, j: (i // 16, j // 16, *mapping(i % 16, j % 16)) + + index_map_A = tile(shared_16x16_to_local_32x16_layout_A) + # B fragment holds a column per lane: [K, N] -> layout_B; [N, K] (transposed) -> same as A + index_map_B = tile( + shared_16x16_to_local_32x16_layout_A + if b_transposed + else shared_16x16_to_local_32x16_layout_B + ) + index_map_C = tile(shared_16x16_to_local_32x8_layout_C) + sch = mfma_schedule( + te.create_function(matmul(b_transposed)), + 16, + "float16", + b_transposed, + [1, 8, 2, 2, 1], + [1, 8, 2, 1, 2], + [16, 2, 1], + index_map_A, + index_map_B, + index_map_C, + ROCM_WMMA_LOAD_16x16_A_SHARED_F16_INTRIN, + ROCM_WMMA_LOAD_16x16_B_TRANS_SHARED_F16_INTRIN + if b_transposed + else ROCM_WMMA_LOAD_16x16_B_SHARED_F16_INTRIN, + ROCM_WMMA_F16F16F32_INTRIN, + ROCM_WMMA_FILL_16x16_F32_INTRIN, + ROCM_WMMA_STORE_16x16_F32_INTRIN, + warp_size=32, + ) + dev = tvm_tirx.rocm(0) + # mcpu is detected from the device (rocm target canonicalizer); RDNA runs wave32. + lib = tvm.compile(sch.mod["main"], target={"kind": "rocm", "thread_warp_size": 32}) + lib.export_library(str(tmp_path / "wmma.so")) # load as a shared library (no ORC JIT needed) + f = tvm_tirx.runtime.load_module(str(tmp_path / "wmma.so"))["main"] + rng = np.random.default_rng(0) + a_np = rng.uniform(size=(M, K)).astype("float16") + b_np = rng.uniform(size=(N, K) if b_transposed else (K, N)).astype("float16") + ref = a_np.astype("float32") @ ( + b_np.astype("float32").T if b_transposed else b_np.astype("float32") + ) + a = tvm_tirx.runtime.tensor(a_np, dev) + b = tvm_tirx.runtime.tensor(b_np, dev) + c = tvm_tirx.runtime.tensor(np.zeros((M, N), "float32"), dev) + f(a, b, c) + dev.sync() + tvm_tirx.testing.assert_allclose(c.numpy(), ref, rtol=1e-2, atol=1e-2) From cdd88143bece879b16d5410f4e1f00fec4935cd3 Mon Sep 17 00:00:00 2001 From: Ravi Gupta Date: Sat, 21 Nov 2026 10:21:18 -0600 Subject: [PATCH 2/3] [ROCm][DLight] Use RDNA WMMA in dlight Matmul for fp16 GEMMs dlight Matmul schedules every ROCm GEMM with SIMT FMAs, so RDNA GPUs (gfx11, gfx12) leave their WMMA matrix instructions unused. Add a RocmWmmaMatmul rule (dlight/gpu/rocm_wmma_matmul.py) built on the RDNA WMMA tensor intrinsics, and try it from Matmul.apply for rocm targets with an RDNA mcpu and thread_warp_size 32. It handles fp16 x fp16 -> fp32 GEMMs with static or dynamic M, including the forms Relax produces: - prologues (padding for dynamic M, weight dequantization such as int4 -> fp16) are computed while filling LDS, once per block tile; - epilogues (cast, bias, other elementwise ops) are inlined into the output copy kernel. If any block would be left outside a GPU kernel the rule returns None and Matmul falls back to its SIMT schedule. Small static M (< 64, decode GEMVs) also stays on the SIMT path. CUDA, Metal and CDNA targets are unchanged. Tests: selection for plain, cast+bias and int4-dequant GEMMs with static and dynamic M (CPU only), no WMMA for M = 8 or gfx942, and numeric checks of those GEMMs (M = 512 and a ragged dynamic M = 300) on an RDNA GPU. On an idle gfx1151 (Radeon 8060S, ROCm 7.2.1), N = 2048, K = 1536, warm cache: GEMM WMMA SIMT (before) speedup static M=512, plain/cast+bias 0.19-0.21 ms 0.83-0.94 ms 4.0-4.4x static M=512, int4 dequant 0.20 ms 0.66 ms 3.2x dynamic M=512 0.26-0.27 ms 0.68-0.90 ms 2.5-3.3x dynamic M=300 0.20 ms 0.38-0.45 ms 1.9-2.2x --- python/tvm/s_tir/dlight/gpu/matmul.py | 14 + .../tvm/s_tir/dlight/gpu/rocm_wmma_matmul.py | 259 ++++++++++++++++++ .../s_tir/dlight/test_gpu_matmul_rocm_wmma.py | 162 +++++++++++ 3 files changed, 435 insertions(+) create mode 100644 python/tvm/s_tir/dlight/gpu/rocm_wmma_matmul.py create mode 100644 tests/python/s_tir/dlight/test_gpu_matmul_rocm_wmma.py diff --git a/python/tvm/s_tir/dlight/gpu/matmul.py b/python/tvm/s_tir/dlight/gpu/matmul.py index 42299c2a1e09..90dd2889f26e 100644 --- a/python/tvm/s_tir/dlight/gpu/matmul.py +++ b/python/tvm/s_tir/dlight/gpu/matmul.py @@ -583,6 +583,20 @@ def is_inner_reduction(block_stmt, iter_infos): return MetalMatmul().apply(func, target, _) except: # pylint: disable=bare-except pass + # Step 1b. RDNA (gfx11/gfx12, wave32): WMMA-tensorized schedule for fp16 -> fp32 GEMMs. + if target.kind.name == "rocm": + from .rocm_wmma_matmul import ( # pylint: disable=import-outside-toplevel + RocmWmmaMatmul, + is_rdna_target, + ) + + if is_rdna_target(target): + try: + wmma_sch = RocmWmmaMatmul().apply(func, target) + if wmma_sch is not None: + return wmma_sch + except: # pylint: disable=bare-except + pass # Step 2. Schedule matmul y_kernel_size = config.vthread_y * config.block_size_y * config.micro_size_y diff --git a/python/tvm/s_tir/dlight/gpu/rocm_wmma_matmul.py b/python/tvm/s_tir/dlight/gpu/rocm_wmma_matmul.py new file mode 100644 index 000000000000..a27df57676bd --- /dev/null +++ b/python/tvm/s_tir/dlight/gpu/rocm_wmma_matmul.py @@ -0,0 +1,259 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +"""dlight schedule for RDNA (gfx11/gfx12) WMMA: fp16 x fp16 -> fp32 GEMMs on wave32. + +Applies to a matmul already normalized by `Matmul` into C[S, I, J] += A[S, I, K] * B[S, J, K] +(B in [N, K] layout). The block tile is (16 * TI * WY) x (16 * TJ * WX): WY x WX waves per +workgroup, each owning TI x TJ 16x16 WMMA tiles; K advances in steps of 16 * KS through LDS. +""" + +from tvm import s_tir + +from ..analysis import get_root_block +from .matmul import ( + auto_inline_consumer_chain, + auto_inline_producers, + get_index_map, + get_reduction_blocks, +) + + +def is_rdna_target(target) -> bool: + if target.kind.name != "rocm": + return False + mcpu = str(target.attrs.get("mcpu", "")) + return ( + mcpu.startswith(("gfx11", "gfx12")) and int(target.attrs.get("thread_warp_size", 64)) == 32 + ) + + +def _all_blocks_in_kernels(sch: s_tir.Schedule) -> bool: + """True if every top-level block runs under a blockIdx binding (nothing left on the host).""" + for block in sch.get_child_blocks(get_root_block(sch)): + tags = [ + str(sch.get(lp).annotations.get("thread_binding", "")) for lp in sch.get_loops(block) + ] + if not any(tag.startswith("blockIdx") for tag in tags): + return False + return True + + +def _inline_pad_copy(sch: s_tir.Schedule, reindex_c_name: str) -> None: + """With a dynamic M, pad_einsum leaves a copy out of the padded C buffer in front of the C + reindex block; fold it into that block so no copy runs outside a kernel.""" + for blk in sch.get_child_blocks(get_root_block(sch)): + if sch.get(blk).name_hint == reindex_c_name + "_pad": + sch.compute_inline(blk) + + +class RocmWmmaMatmul: + """Tensorized schedule; returns None if the block does not fit (dtype / shape).""" + + def __init__( + self, + TI: int = 4, + TJ: int = 4, + WY: int = 2, + WX: int = 2, + KS: int = 2, + stage_c_in_shared: bool = False, + ): + self.TI, self.TJ, self.WY, self.WX, self.KS = TI, TJ, WY, WX, KS + # Staging C in LDS avoids an fp32 round trip through global memory but needs + # 16*16*TI*TJ*WY*WX*4 bytes of LDS (64 KB limit), i.e. smaller tiles. + self.stage_c_in_shared = stage_c_in_shared + + def apply(self, func, target): + """Normalize the matmul (as MetalMatmul does), then tensorize; None if not applicable.""" + if not is_rdna_target(target): + return None + sch = s_tir.Schedule(func) + blocks = sch.get_child_blocks(get_root_block(sch)) + reduction_blocks = get_reduction_blocks(sch, blocks) + if reduction_blocks is None: + return None + main_block = reduction_blocks[0] + stmt = sch.get(main_block) + # Small static M (decode GEMVs) would mostly pad a 16*TI*WY-row tile: leave them to Matmul. + spatial = [iv.dom.extent for iv in stmt.iter_vars if iv.iter_type == 0] + if spatial and all(hasattr(e, "value") for e in spatial[:-1]): + m = 1 + for e in spatial[:-1]: + m *= int(e.value) + if m < 64: + return None + in_dtype = str(stmt.reads[0].source.ty.dtype) + out_dtype = str(stmt.writes[0].source.ty.dtype) + reindex_a = sch.reindex(main_block, ("read", 0)) + reindex_b = sch.reindex(main_block, ("read", 1)) + reindex_c = sch.reindex(main_block, ("write", 0)) + reindex_c_name = sch.get(reindex_c).name_hint + index_maps = get_index_map(sch.get(main_block)) + if index_maps is None: + return None + matmul_map, a_map, b_map, c_map = index_maps + sch.transform_layout(reindex_a, ("write", 0), a_map) + sch.transform_layout(reindex_b, ("write", 0), b_map) + sch.transform_layout(reindex_c, ("read", 0), c_map) + sch.transform_block_layout(main_block, matmul_map) + sch.compute_inline(reindex_a) + sch.compute_inline(reindex_b) + out = self.schedule( + sch, + main_block, + in_dtype, + out_dtype, + reindex_c_name=reindex_c_name if self.stage_c_in_shared else None, + ) + if out is None: + return None + if not self.stage_c_in_shared: # C reindex as a separate thread-bound copy epilogue + rc = sch.get_sblock(reindex_c_name) + _inline_pad_copy(sch, reindex_c_name) + auto_inline_consumer_chain(sch, rc) # cast / bias / elementwise epilogues + fused = sch.fuse(*sch.get_loops(rc)) + bx, tx = sch.split(fused, [None, 256]) + sch.bind(bx, "blockIdx.x") + sch.bind(tx, "threadIdx.x") + if not _all_blocks_in_kernels(sch): + return None # e.g. a prologue that could not be computed in the LDS fill + return sch + + def schedule( + self, + sch: s_tir.Schedule, + main_block, + in_dtype: str, + out_dtype: str, + reindex_c_name: str | None = None, + ): + # pylint: disable=import-outside-toplevel + from tvm.s_tir.tensor_intrin.rocm_wmma import ( + ROCM_WMMA_F16F16F32_INTRIN, + ROCM_WMMA_FILL_16x16_F32_INTRIN, + ROCM_WMMA_LOAD_16x16_A_SHARED_F16_INTRIN, + ROCM_WMMA_LOAD_16x16_B_TRANS_SHARED_F16_INTRIN, + ROCM_WMMA_STORE_16x16_F32_INTRIN, + ROCM_WMMA_STORE_16x16_F32_SHARED_INTRIN, + shared_16x16_to_local_32x8_layout_C, + shared_16x16_to_local_32x16_layout_A, + ) + + if in_dtype != "float16" or out_dtype != "float32": + return None + TI, TJ, WY, WX, KS = self.TI, self.TJ, self.WY, self.WX, self.KS + warp = 32 + BM, BN, BK = 16 * TI * WY, 16 * TJ * WX, 16 * KS + + sch.pad_einsum(main_block, [1, BM, BN, BK]) + batch, i, j, k = sch.get_loops(main_block) + i, i_tc = sch.split(i, [None, 16]) + j, j_tc = sch.split(j, [None, 16]) + k, k_tc = sch.split(k, [None, 16]) + sch.reorder(i, j, k, i_tc, j_tc, k_tc) + block_inner = main_block + block_outer = sch.blockize(i_tc) + + i0, i1, i2 = sch.split(i, [None, WY, TI]) + j0, j1, j2 = sch.split(j, [None, WX, TJ]) + k0, k1 = sch.split(k, [None, KS]) + sch.reorder(batch, i0, j0, i1, j1, k0, k1, i2, j2) + sch.bind(batch, "blockIdx.z") + block_loop = sch.fuse(i0, j0) + sch.bind(block_loop, "blockIdx.x") + wave = sch.fuse(i1, j1) + sch.bind(wave, "threadIdx.y") + + def fetch_to_shared(idx): + rd = sch.cache_read(block_outer, idx, "shared") + sch.compute_at(rd, k0) + fused = sch.fuse(*sch.get_loops(rd)[-2:]) + _, ty, tx, vec = sch.split(fused, [None, WY * WX, warp, 8]) + sch.bind(ty, "threadIdx.y") + sch.bind(tx, "threadIdx.x") + sch.vectorize(vec) + return rd + + a_g2s = fetch_to_shared(0) + b_g2s = fetch_to_shared(1) + # Padding (dynamic M) and prologues such as weight dequantization are computed while + # filling LDS, once per block tile. + auto_inline_producers(sch, a_g2s) + auto_inline_producers(sch, b_g2s) + + a_loc = sch.cache_read(block_outer, 0, "local") + b_loc = sch.cache_read(block_outer, 1, "local") + sch.compute_at(a_loc, k1) + sch.compute_at(b_loc, k1) + c_loc = sch.cache_write(block_outer, 0, "local") + sch.reverse_compute_at(c_loc, wave) + stage_c_in_shared = reindex_c_name is not None + if stage_c_in_shared: + # C reindex copy per wave out of LDS: no fp32 round trip through global memory. + _inline_pad_copy(sch, reindex_c_name) + rc = sch.get_sblock(reindex_c_name) + auto_inline_consumer_chain(sch, rc) + sch.reverse_compute_at(rc, wave) + sch.set_scope(c_loc, 0, "shared") + rc_loops = sch.get_loops(rc) + wave_stmt = sch.get(wave) + pos = next(i for i, lp in enumerate(rc_loops) if sch.get(lp).same_as(wave_stmt)) + fused = sch.fuse(*rc_loops[pos + 1 :]) + _, tx = sch.split(fused, [None, 32]) + sch.bind(tx, "threadIdx.x") + ii, jj = sch.get_loops(c_loc)[-2:] + io, ii = sch.split(ii, [None, 16]) + jo, ji = sch.split(jj, [None, 16]) + sch.reorder(io, jo, ii, ji) + + init = sch.decompose_reduction(block_outer, k0) + + def frag(blk): + a, b = sch.get_loops(blk)[-2:] + a0, a1 = sch.split(a, [None, 16]) + b0, b1 = sch.split(b, [None, 16]) + sch.reorder(a0, b0, a1, b1) + return a1 + + la, lb = frag(a_loc), frag(b_loc) + + def tile(mapping): + return lambda *idx: ( + *idx[:-2], + idx[-2] // 16, + idx[-1] // 16, + *mapping(idx[-2] % 16, idx[-1] % 16), + ) + + sch.transform_layout(a_loc, ("write", 0), tile(shared_16x16_to_local_32x16_layout_A)) + sch.transform_layout( + b_loc, ("write", 0), tile(shared_16x16_to_local_32x16_layout_A) + ) # B is [N, K] + sch.transform_layout(c_loc, ("read", 0), tile(shared_16x16_to_local_32x8_layout_C)) + sch.tensorize(la, ROCM_WMMA_LOAD_16x16_A_SHARED_F16_INTRIN) + sch.tensorize(lb, ROCM_WMMA_LOAD_16x16_B_TRANS_SHARED_F16_INTRIN) + sch.tensorize(sch.get_loops(block_inner)[-3], ROCM_WMMA_F16F16F32_INTRIN) + inner_init = sch.get_child_blocks(init) + init_loops = sch.get_loops(inner_init[0] if inner_init else init) + sch.tensorize(init_loops[-2], ROCM_WMMA_FILL_16x16_F32_INTRIN) + store = ( + ROCM_WMMA_STORE_16x16_F32_SHARED_INTRIN + if stage_c_in_shared + else ROCM_WMMA_STORE_16x16_F32_INTRIN + ) + sch.tensorize(sch.get_loops(c_loc)[-2], store) + return sch diff --git a/tests/python/s_tir/dlight/test_gpu_matmul_rocm_wmma.py b/tests/python/s_tir/dlight/test_gpu_matmul_rocm_wmma.py new file mode 100644 index 000000000000..c0a5b48fb73d --- /dev/null +++ b/tests/python/s_tir/dlight/test_gpu_matmul_rocm_wmma.py @@ -0,0 +1,162 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# pylint: disable=missing-docstring +"""dlight Matmul on RDNA (gfx11, wave32): WMMA-tensorized schedule for fp16 -> fp32 GEMMs.""" + +import numpy as np +import pytest + +import tvm +import tvm_tirx +from tvm import s_tir, te +from tvm.s_tir import dlight +from tvm.s_tir.dlight.analysis import get_root_block +from tvm_tirx import tirx + +RDNA_TARGET = {"kind": "rocm", "mcpu": "gfx1151", "thread_warp_size": 32} +GROUP = 128 + + +def _rows(m): + return tirx.Var("m", "int32") if m is None else m + + +def _gemm(m, n, k, epilogue="none"): + """fp16 x fp16 -> fp32 GEMM (B in [N, K]); epilogue "cast_bias" adds a cast and a bias.""" + rows = _rows(m) + a = te.placeholder((rows, k), "float16", name="A") + b = te.placeholder((n, k), "float16", name="B") + r = te.reduce_axis((0, k), name="k") + c = te.compute( + (rows, n), + lambda i, j: te.sum(a[i, r].astype("float32") * b[j, r].astype("float32"), axis=r), + name="C", + ) + if epilogue == "none": + return tvm_tirx.IRModule({"main": te.create_function([a, b, c])}) + bias = te.placeholder((n,), "float16", name="bias") + d = te.compute((rows, n), lambda i, j: c[i, j].astype("float16") + bias[j], name="D") + return tvm_tirx.IRModule({"main": te.create_function([a, b, bias, d])}) + + +def _w4_gemm(m, n, k): + """int4 weights (8 per uint32, zero point 8, fp16 scale per 128) dequantized in a prologue.""" + rows = _rows(m) + x = te.placeholder((rows, k), "float16", name="X") + packed = te.placeholder((n, k // 8), "uint32", name="W") + scale = te.placeholder((n, k // GROUP), "float16", name="S") + + def dequantize(i, j): + nibble = (packed[i, j // 8] >> ((j % 8) * 4).astype("uint32")) & tirx.const(15, "uint32") + return (nibble.astype("float16") - tirx.const(8, "float16")) * scale[i, j // GROUP] + + w = te.compute((n, k), dequantize, name="dequantize") + r = te.reduce_axis((0, k), name="k") + acc = te.compute( + (rows, n), + lambda i, j: te.sum(x[i, r].astype("float32") * w[j, r].astype("float32"), axis=r), + name="matmul", + ) + out = te.compute((rows, n), lambda i, j: acc[i, j].astype("float16"), name="cast") + return tvm_tirx.IRModule({"main": te.create_function([x, packed, scale, out])}) + + +def _make(kind, m, n, k): + return _w4_gemm(m, n, k) if kind == "w4" else _gemm(m, n, k, kind) + + +def _schedule(mod, target): + return dlight.ApplyDefaultSchedule(dlight.gpu.Matmul(), target=target)(mod) + + +def _all_blocks_in_kernels(mod): + sch = s_tir.Schedule(mod["main"]) + for block in sch.get_child_blocks(get_root_block(sch)): + tags = [ + str(sch.get(lp).annotations.get("thread_binding", "")) for lp in sch.get_loops(block) + ] + if not any(tag.startswith("blockIdx") for tag in tags): + return False + return True + + +@pytest.mark.parametrize("kind", ["none", "cast_bias", "w4"]) +@pytest.mark.parametrize("m", [None, 512]) +def test_rdna_matmul_selects_wmma(kind, m): + mod = _schedule(_make(kind, m, 2048, 1536), tvm_tirx.target.Target(RDNA_TARGET)) + assert "wmma" in mod["main"].script() + # Prologue (padding, dequantization) and epilogue (cast, bias) all run inside GPU kernels. + assert _all_blocks_in_kernels(mod) + + +def test_rdna_small_static_m_uses_simt(): + mod = _schedule(_gemm(8, 2048, 1536), tvm_tirx.target.Target(RDNA_TARGET)) + assert "wmma" not in mod["main"].script() + + +def test_non_rdna_rocm_unchanged(): + mod = _schedule( + _gemm(512, 2048, 1536), tvm_tirx.target.Target({"kind": "rocm", "mcpu": "gfx942"}) + ) + assert "wmma" not in mod["main"].script() + + +def _has_rdna_wmma(): + if not tvm_tirx.rocm(0).exist: + return False + from tvm_tirx.support import rocm # pylint: disable=import-outside-toplevel + + if hasattr(rocm, "have_rdna_wmma"): + return rocm.have_rdna_wmma() + return str(tvm_tirx.rocm(0).compute_version).split(".", maxsplit=1)[0] in ("11", "12") + + +def _inputs(kind, m, n, k, rng): + if kind == "w4": + x = rng.uniform(-1, 1, (m, k)).astype("float16") + q = rng.integers(0, 16, (n, k), dtype=np.uint32) + shifts = np.arange(8, dtype=np.uint32) * 4 + packed = (q.reshape(n, k // 8, 8) << shifts).sum(-1).astype(np.uint32) + scale = rng.uniform(0.001, 0.02, (n, k // GROUP)).astype("float16") + w = (q.astype("float32") - 8) * np.repeat(scale.astype("float32"), GROUP, axis=1) + return [x, packed, scale], x.astype("float32") @ w.T, "float16" + a = rng.uniform(-1, 1, (m, k)).astype("float16") + b = rng.uniform(-1, 1, (n, k)).astype("float16") + ref = a.astype("float32") @ b.astype("float32").T + if kind == "none": + return [a, b], ref, "float32" + bias = rng.uniform(-1, 1, (n,)).astype("float16") + return [a, b, bias], ref + bias.astype("float32"), "float16" + + +@pytest.mark.gpu +@pytest.mark.skipif(not _has_rdna_wmma(), reason="needs an RDNA GPU with WMMA") +@pytest.mark.parametrize("kind", ["none", "cast_bias", "w4"]) +@pytest.mark.parametrize("m, rows", [(512, 512), (None, 300)]) +def test_rdna_matmul_wmma_numeric(tmp_path, kind, m, rows): + n, k = 1024, 512 + target = tvm_tirx.target.Target({"kind": "rocm", "thread_warp_size": 32}) + lib = tvm.compile(_schedule(_make(kind, m, n, k), target), target=target) + lib.export_library(str(tmp_path / "gemm.so")) + f = tvm_tirx.runtime.load_module(str(tmp_path / "gemm.so"))["main"] + ins, ref, out_dtype = _inputs(kind, rows, n, k, np.random.default_rng(0)) + dev = tvm_tirx.rocm(0) + args = [tvm_tirx.runtime.tensor(x, dev) for x in ins] + out = tvm_tirx.runtime.tensor(np.zeros((rows, n), out_dtype), dev) + f(*args, out) + dev.sync() + np.testing.assert_allclose(out.numpy().astype("float32"), ref, rtol=1e-2, atol=1e-2) From efb90bebb28c79c9b739608c8bb9d316333db85a Mon Sep 17 00:00:00 2001 From: Ravi Gupta Date: Wed, 25 Nov 2026 13:17:29 -0600 Subject: [PATCH 3/3] [ROCm][DLight] Support bf16 in the RDNA WMMA intrinsics and dlight Matmul Add bf16 x bf16 -> fp32 WMMA tensor intrinsics (llvm.amdgcn.wmma.f32.16x16x16.bf16; on gfx11 the operands are passed as <16 x i16> bit patterns, so the bf16 fragments are reinterpreted as int16) and let RocmWmmaMatmul pick the fp16 or bf16 intrinsics by the input dtype. Requires the tvm-tirx fix that keeps bit-reinterpreted bf16 tensors in bf16 storage during BF16ComputeLegalize; without it LLVM rejects the fragment bitcast. Tests: bf16 selection (static and dynamic M) and numeric checks on an RDNA GPU (M = 512 and a ragged dynamic M = 300) against numpy; all 18 tests in the file pass on gfx1151. --- 3rdparty/tvm-tirx | 2 +- .../tvm/s_tir/dlight/gpu/rocm_wmma_matmul.py | 26 ++++++++--- python/tvm/s_tir/tensor_intrin/rocm_wmma.py | 37 +++++++++++++--- .../s_tir/dlight/test_gpu_matmul_rocm_wmma.py | 43 +++++++++++++++++++ 4 files changed, 97 insertions(+), 11 deletions(-) diff --git a/3rdparty/tvm-tirx b/3rdparty/tvm-tirx index f43b3030d331..02312480918a 160000 --- a/3rdparty/tvm-tirx +++ b/3rdparty/tvm-tirx @@ -1 +1 @@ -Subproject commit f43b3030d33196d3a5f21e56b37549a6d3a5c70b +Subproject commit 02312480918afb304cd0a230c1fcba1a2200082f diff --git a/python/tvm/s_tir/dlight/gpu/rocm_wmma_matmul.py b/python/tvm/s_tir/dlight/gpu/rocm_wmma_matmul.py index a27df57676bd..ac762d46428f 100644 --- a/python/tvm/s_tir/dlight/gpu/rocm_wmma_matmul.py +++ b/python/tvm/s_tir/dlight/gpu/rocm_wmma_matmul.py @@ -14,7 +14,7 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. -"""dlight schedule for RDNA (gfx11/gfx12) WMMA: fp16 x fp16 -> fp32 GEMMs on wave32. +"""dlight schedule for RDNA (gfx11/gfx12) WMMA: fp16 or bf16 x same -> fp32 GEMMs on wave32. Applies to a matmul already normalized by `Matmul` into C[S, I, J] += A[S, I, K] * B[S, J, K] (B in [N, K] layout). The block tile is (16 * TI * WY) x (16 * TJ * WX): WY x WX waves per @@ -143,9 +143,12 @@ def schedule( ): # pylint: disable=import-outside-toplevel from tvm.s_tir.tensor_intrin.rocm_wmma import ( + ROCM_WMMA_BF16BF16F32_INTRIN, ROCM_WMMA_F16F16F32_INTRIN, ROCM_WMMA_FILL_16x16_F32_INTRIN, + ROCM_WMMA_LOAD_16x16_A_SHARED_BF16_INTRIN, ROCM_WMMA_LOAD_16x16_A_SHARED_F16_INTRIN, + ROCM_WMMA_LOAD_16x16_B_TRANS_SHARED_BF16_INTRIN, ROCM_WMMA_LOAD_16x16_B_TRANS_SHARED_F16_INTRIN, ROCM_WMMA_STORE_16x16_F32_INTRIN, ROCM_WMMA_STORE_16x16_F32_SHARED_INTRIN, @@ -153,8 +156,21 @@ def schedule( shared_16x16_to_local_32x16_layout_A, ) - if in_dtype != "float16" or out_dtype != "float32": + intrins = { + "float16": ( + ROCM_WMMA_LOAD_16x16_A_SHARED_F16_INTRIN, + ROCM_WMMA_LOAD_16x16_B_TRANS_SHARED_F16_INTRIN, + ROCM_WMMA_F16F16F32_INTRIN, + ), + "bfloat16": ( + ROCM_WMMA_LOAD_16x16_A_SHARED_BF16_INTRIN, + ROCM_WMMA_LOAD_16x16_B_TRANS_SHARED_BF16_INTRIN, + ROCM_WMMA_BF16BF16F32_INTRIN, + ), + } + if in_dtype not in intrins or out_dtype != "float32": return None + load_a_intrin, load_b_intrin, mma_intrin = intrins[in_dtype] TI, TJ, WY, WX, KS = self.TI, self.TJ, self.WY, self.WX, self.KS warp = 32 BM, BN, BK = 16 * TI * WY, 16 * TJ * WX, 16 * KS @@ -244,9 +260,9 @@ def tile(mapping): b_loc, ("write", 0), tile(shared_16x16_to_local_32x16_layout_A) ) # B is [N, K] sch.transform_layout(c_loc, ("read", 0), tile(shared_16x16_to_local_32x8_layout_C)) - sch.tensorize(la, ROCM_WMMA_LOAD_16x16_A_SHARED_F16_INTRIN) - sch.tensorize(lb, ROCM_WMMA_LOAD_16x16_B_TRANS_SHARED_F16_INTRIN) - sch.tensorize(sch.get_loops(block_inner)[-3], ROCM_WMMA_F16F16F32_INTRIN) + sch.tensorize(la, load_a_intrin) + sch.tensorize(lb, load_b_intrin) + sch.tensorize(sch.get_loops(block_inner)[-3], mma_intrin) inner_init = sch.get_child_blocks(init) init_loops = sch.get_loops(inner_init[0] if inner_init else init) sch.tensorize(init_loops[-2], ROCM_WMMA_FILL_16x16_F32_INTRIN) diff --git a/python/tvm/s_tir/tensor_intrin/rocm_wmma.py b/python/tvm/s_tir/tensor_intrin/rocm_wmma.py index f942fdd63098..05ef854f222e 100644 --- a/python/tvm/s_tir/tensor_intrin/rocm_wmma.py +++ b/python/tvm/s_tir/tensor_intrin/rocm_wmma.py @@ -184,9 +184,20 @@ def load_impl( def get_wmma_intrin(in_dtype="float16", out_dtype="float32"): - """D = A x B + C, 16x16x16, wave32. f16 x f16 -> f32 (v_wmma_f32_16x16x16_f16).""" - assert in_dtype == "float16" and out_dtype == "float32", "only f16 -> f32 for now" - intrin = "llvm.amdgcn.wmma.f32.16x16x16.f16" + """D = A x B + C, 16x16x16, wave32: f16 x f16 -> f32 (v_wmma_f32_16x16x16_f16) or + bf16 x bf16 -> f32 (v_wmma_f32_16x16x16_bf16).""" + assert in_dtype in ("float16", "bfloat16") and out_dtype == "float32", (in_dtype, out_dtype) + intrin = ( + "llvm.amdgcn.wmma.f32.16x16x16.f16" + if in_dtype == "float16" + else "llvm.amdgcn.wmma.f32.16x16x16.bf16" + ) + # On gfx11 the bf16 intrinsic takes the bf16 values as <16 x i16> bit patterns. + operand = ( + (lambda v: v) + if in_dtype == "float16" + else (lambda v: T.reinterpret(v, ty=f"int16x{AB_LOCAL}")) + ) d_a = T.dynamic("wmma_desc_a_offset", "int32") d_b = T.dynamic("wmma_desc_b_offset", "int32") d_c = T.dynamic("wmma_desc_c_offset", "int32") @@ -251,8 +262,8 @@ def wmma_impl( _tx = T.launch_thread("threadIdx.x", WARP_SIZE) C[0, T.ramp(0, 1, C_LOCAL)] = T.call_llvm_pure_intrin( T.llvm_lookup_intrinsic_id(intrin), - A[0, T.ramp(0, 1, AB_LOCAL)], - B[0, T.ramp(0, 1, AB_LOCAL)], + operand(A[0, T.ramp(0, 1, AB_LOCAL)]), + operand(B[0, T.ramp(0, 1, AB_LOCAL)]), C[0, T.ramp(0, 1, C_LOCAL)], ty=f"{out_dtype}x{C_LOCAL}", ) @@ -321,6 +332,22 @@ def store_impl( ) ROCM_WMMA_F16F16F32_INTRIN = "rocm_wmma_f16f16f32" TensorIntrin.register(ROCM_WMMA_F16F16F32_INTRIN, *get_wmma_intrin("float16", "float32")) +ROCM_WMMA_LOAD_16x16_A_SHARED_BF16_INTRIN = "rocm_wmma_load_16x16_a_shared_bf16" +TensorIntrin.register( + ROCM_WMMA_LOAD_16x16_A_SHARED_BF16_INTRIN, *get_wmma_load_intrin("bfloat16", "shared") +) +ROCM_WMMA_LOAD_16x16_B_SHARED_BF16_INTRIN = "rocm_wmma_load_16x16_b_shared_bf16" +TensorIntrin.register( + ROCM_WMMA_LOAD_16x16_B_SHARED_BF16_INTRIN, + *get_wmma_load_intrin("bfloat16", "shared", is_b=True), +) +ROCM_WMMA_LOAD_16x16_B_TRANS_SHARED_BF16_INTRIN = "rocm_wmma_load_16x16_b_trans_shared_bf16" +TensorIntrin.register( + ROCM_WMMA_LOAD_16x16_B_TRANS_SHARED_BF16_INTRIN, + *get_wmma_load_intrin("bfloat16", "shared", is_b=True, transposed=True), +) +ROCM_WMMA_BF16BF16F32_INTRIN = "rocm_wmma_bf16bf16f32" +TensorIntrin.register(ROCM_WMMA_BF16BF16F32_INTRIN, *get_wmma_intrin("bfloat16", "float32")) ROCM_WMMA_STORE_16x16_F32_INTRIN = "rocm_wmma_store_16x16_f32" TensorIntrin.register(ROCM_WMMA_STORE_16x16_F32_INTRIN, *get_wmma_store_intrin("float32", "global")) ROCM_WMMA_STORE_16x16_F32_SHARED_INTRIN = "rocm_wmma_store_16x16_f32_shared" diff --git a/tests/python/s_tir/dlight/test_gpu_matmul_rocm_wmma.py b/tests/python/s_tir/dlight/test_gpu_matmul_rocm_wmma.py index c0a5b48fb73d..e1c3566d77cd 100644 --- a/tests/python/s_tir/dlight/test_gpu_matmul_rocm_wmma.py +++ b/tests/python/s_tir/dlight/test_gpu_matmul_rocm_wmma.py @@ -160,3 +160,46 @@ def test_rdna_matmul_wmma_numeric(tmp_path, kind, m, rows): f(*args, out) dev.sync() np.testing.assert_allclose(out.numpy().astype("float32"), ref, rtol=1e-2, atol=1e-2) + + +def _gemm_bf16(m, n, k): + """bf16 x bf16 -> fp32 GEMM (B in [N, K]).""" + rows = _rows(m) + a = te.placeholder((rows, k), "bfloat16", name="A") + b = te.placeholder((n, k), "bfloat16", name="B") + r = te.reduce_axis((0, k), name="k") + c = te.compute( + (rows, n), + lambda i, j: te.sum(a[i, r].astype("float32") * b[j, r].astype("float32"), axis=r), + name="C", + ) + return tvm_tirx.IRModule({"main": te.create_function([a, b, c])}) + + +@pytest.mark.parametrize("m", [None, 512]) +def test_rdna_matmul_selects_wmma_bf16(m): + mod = _schedule(_gemm_bf16(m, 2048, 1536), tvm_tirx.target.Target(RDNA_TARGET)) + assert "wmma" in mod["main"].script() + assert _all_blocks_in_kernels(mod) + + +@pytest.mark.gpu +@pytest.mark.skipif(not _has_rdna_wmma(), reason="needs an RDNA GPU with WMMA") +@pytest.mark.parametrize("m, rows", [(512, 512), (None, 300)]) +def test_rdna_matmul_wmma_numeric_bf16(tmp_path, m, rows): + ml_dtypes = pytest.importorskip("ml_dtypes") + n, k = 1024, 512 + target = tvm_tirx.target.Target({"kind": "rocm", "thread_warp_size": 32}) + lib = tvm.compile(_schedule(_gemm_bf16(m, n, k), target), target=target) + lib.export_library(str(tmp_path / "gemm.so")) + f = tvm_tirx.runtime.load_module(str(tmp_path / "gemm.so"))["main"] + rng = np.random.default_rng(0) + a_np = rng.uniform(-1, 1, (rows, k)).astype(ml_dtypes.bfloat16) + b_np = rng.uniform(-1, 1, (n, k)).astype(ml_dtypes.bfloat16) + dev = tvm_tirx.rocm(0) + a, b = tvm_tirx.runtime.tensor(a_np, dev), tvm_tirx.runtime.tensor(b_np, dev) + c = tvm_tirx.runtime.tensor(np.zeros((rows, n), "float32"), dev) + f(a, b, c) + dev.sync() + ref = a_np.astype("float32") @ b_np.astype("float32").T + np.testing.assert_allclose(c.numpy(), ref, rtol=1e-2, atol=1e-2)