From 1fb78579caf771c6b4df93ce2c0946bc33bb726a Mon Sep 17 00:00:00 2001 From: Alex Cameron Date: Mon, 9 Nov 2026 03:25:55 +0000 Subject: [PATCH 1/2] feat(dialect): add warp shuffle words SHFL-DOWN, SHFL-UP, SHFL-XOR, and SHFL-IDX move one i64 stack cell across a warp. The memref pass emits gpu.shuffle of that cell at width 32, and the NVVM pass splits it into two shfl.sync instructions with a full mask. LANE-ID reads %laneid. WARP-SIZE is the constant 32. --- AGENTS.md | 2 +- CMakeLists.txt | 2 + docs/language.md | 40 ++++ gpu_test/test_kernels.py | 225 ++++++++++++++++++ include/warpforth/Conversion/Passes.td | 7 +- .../warpforth/Dialect/Forth/CMakeLists.txt | 5 + .../warpforth/Dialect/Forth/ForthDialect.h | 7 + include/warpforth/Dialect/Forth/ForthOps.td | 51 ++++ lib/Conversion/ForthToGPU/ForthToGPU.cpp | 8 +- lib/Conversion/ForthToMemRef/CMakeLists.txt | 1 + .../ForthToMemRef/ForthToMemRef.cpp | 52 +++- lib/Dialect/Forth/CMakeLists.txt | 1 + lib/Dialect/Forth/ForthDialect.cpp | 2 + lib/Translation/ForthToMLIR/ForthToMLIR.cpp | 21 ++ .../ForthToGPU/intrinsic-conversion.mlir | 5 + .../ForthToMemRef/warp-shuffle.mlir | 41 ++++ test/Dialect/Forth/warp-ops.mlir | 24 ++ test/Pipeline/warp-shuffle.forth | 19 ++ test/Translation/Forth/warp-words.forth | 16 ++ 19 files changed, 521 insertions(+), 8 deletions(-) create mode 100644 test/Conversion/ForthToMemRef/warp-shuffle.mlir create mode 100644 test/Dialect/Forth/warp-ops.mlir create mode 100644 test/Pipeline/warp-shuffle.forth create mode 100644 test/Translation/Forth/warp-words.forth diff --git a/AGENTS.md b/AGENTS.md index e102e8e..64bf21a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -97,7 +97,7 @@ uv run ruff format gpu_test/ - **Stack Type**: `!forth.stack` - untyped stack, programmer ensures type safety - **Operations**: All take stack as input and produce stack as output (except `forth.stack`) -- **Supported Words**: literals (integer `42` and float `3.14`), `\ ...` (line comments), `( ... )` (paren comments, may span lines), `DUP DROP SWAP OVER ROT NIP TUCK PICK ROLL`, `+ - * / MOD`, `F+ F- F* F/` (float arithmetic), `FEXP FSQRT FLOG FABS FNEG` (float math intrinsics), `FMAX FMIN` (float min/max), `AND OR XOR NOT LSHIFT RSHIFT`, `= < > <> <= >= 0=`, `F= F< F> F<> F<= F>=` (float comparison), `S>F F>S` (int/float conversion), `@ !` (global memory), `F@ F!` (float global memory), `S@ S!` (shared memory), `SF@ SF!` (float shared memory), `I8@ I8! SI8@ SI8!` (i8 memory), `I16@ I16! SI16@ SI16!` (i16 memory), `I32@ I32! SI32@ SI32!` (i32 memory), `HF@ HF! SHF@ SHF!` (f16 memory), `BF@ BF! SBF@ SBF!` (bf16 memory), `F32@ F32! SF32@ SF32!` (f32 memory), `CELLS`, `IF ELSE THEN`, `BEGIN UNTIL`, `BEGIN WHILE REPEAT`, `DO LOOP +LOOP I J K`, `LEAVE UNLOOP EXIT`, `{ a b -- }` (local variables in word definitions), `TID-X/Y/Z BID-X/Y/Z BDIM-X/Y/Z GDIM-X/Y/Z GLOBAL-ID` (GPU indexing), `BARRIER` (thread block synchronization). +- **Supported Words**: literals (integer `42` and float `3.14`), `\ ...` (line comments), `( ... )` (paren comments, may span lines), `DUP DROP SWAP OVER ROT NIP TUCK PICK ROLL`, `+ - * / MOD`, `F+ F- F* F/` (float arithmetic), `FEXP FSQRT FLOG FABS FNEG` (float math intrinsics), `FMAX FMIN` (float min/max), `AND OR XOR NOT LSHIFT RSHIFT`, `= < > <> <= >= 0=`, `F= F< F> F<> F<= F>=` (float comparison), `S>F F>S` (int/float conversion), `@ !` (global memory), `F@ F!` (float global memory), `S@ S!` (shared memory), `SF@ SF!` (float shared memory), `I8@ I8! SI8@ SI8!` (i8 memory), `I16@ I16! SI16@ SI16!` (i16 memory), `I32@ I32! SI32@ SI32!` (i32 memory), `HF@ HF! SHF@ SHF!` (f16 memory), `BF@ BF! SBF@ SBF!` (bf16 memory), `F32@ F32! SF32@ SF32!` (f32 memory), `CELLS`, `IF ELSE THEN`, `BEGIN UNTIL`, `BEGIN WHILE REPEAT`, `DO LOOP +LOOP I J K`, `LEAVE UNLOOP EXIT`, `{ a b -- }` (local variables in word definitions), `TID-X/Y/Z BID-X/Y/Z BDIM-X/Y/Z GDIM-X/Y/Z GLOBAL-ID` (GPU indexing), `BARRIER` (thread block synchronization), `SHFL-DOWN SHFL-UP SHFL-XOR SHFL-IDX` (warp shuffles of one 64-bit cell), `LANE-ID WARP-SIZE` (lane within the warp, and the constant 32). - **Float Literals**: Numbers containing `.` or `e`/`E` are parsed as f64 (e.g. `3.14`, `-2.0`, `1.0e-5`, `1e3`). Stored on the stack as i64 bit patterns; F-prefixed words perform bitcast before/after operations. - **Kernel Parameters**: Declared in the `\!` header. `\! kernel ` is required and must appear first. `\! param i64[]` becomes a `memref` argument; `\! param i64` becomes an `i64` argument. `\! param f64[]` becomes a `memref` argument; `\! param f64` becomes an `f64` argument (bitcast to i64 when pushed to stack). Using a param name in code emits `forth.param_ref` (arrays push address; scalars push value). - **Shared Memory**: `\! shared i64[]` or `\! shared f64[]` declares GPU shared (workgroup) memory. Emits a tagged `memref.alloca` at kernel entry; ForthToGPU converts it to a `gpu.func` workgroup attribution. Using the shared name in code pushes its base address onto the stack. Use `S@`/`S!` for i64 or `SF@`/`SF!` for f64 shared accesses. Cannot be referenced inside word definitions. diff --git a/CMakeLists.txt b/CMakeLists.txt index 8ee1636..accf8c2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -59,6 +59,7 @@ add_custom_target(check-clang-tidy DEPENDS MLIRConversionPassIncGen MLIRForthOpsIncGen + MLIRForthOpsEnumsIncGen COMMENT "Running clang-tidy" VERBATIM ) @@ -78,6 +79,7 @@ if(IWYU_EXECUTABLE AND IWYU_TOOL_EXECUTABLE) DEPENDS MLIRConversionPassIncGen MLIRForthOpsIncGen + MLIRForthOpsEnumsIncGen COMMENT "Checking C++ includes with include-what-you-use" VERBATIM ) diff --git a/docs/language.md b/docs/language.md index 6b513df..e2420ef 100644 --- a/docs/language.md +++ b/docs/language.md @@ -322,3 +322,43 @@ n +LOOP \ increment index by n instead of 1 | Word | Stack Effect | Description | |------|-------------|-------------| | `BARRIER` | `( -- )` | Thread block barrier (`__syncthreads`) | + +### Warp Operations + +A warp is a group of 32 threads in a block. Lane k is a thread's position in its warp, from 0 to 31. + +| Word | Stack Effect | Description | +|------|-------------|-------------| +| `SHFL-DOWN` | `( x n -- y )` | Lane k gets x from lane k+n, or keeps its own x when k+n > 31 | +| `SHFL-UP` | `( x n -- y )` | Lane k gets x from lane k-n, or keeps its own x when k-n < 0 | +| `SHFL-XOR` | `( x m -- y )` | Lane k gets x from lane k XOR m | +| `SHFL-IDX` | `( x j -- y )` | Lane k gets x from lane j | +| `LANE-ID` | `( -- k )` | This thread's lane number, 0 to 31 | +| `WARP-SIZE` | `( -- 32 )` | The constant 32 | + +The warp words follow these rules: + +1. x is any cell. Integers and f64 values arrive bit for bit. +2. Only the low five bits of n, m, and j count. `33 SHFL-IDX` reads lane 1. +3. Every launched lane of a warp must execute the same SHFL word together. Shuffle first, then branch on the result. A SHFL word inside an `IF` that sends part of a warp elsewhere is undefined. +4. A warp is partial when the block does not fill it. A one-dimensional block of 8 threads is one partial warp. Reading a lane that was not launched gives an unspecified value. `WARP-LANES` below is `min(BDIM-X, 32)`. That is the launched lane count for a one-dimensional block of at most 32 threads, and for every warp of a one-dimensional block whose size is a multiple of 32. +5. `LANE-ID` is the hardware lane number. It equals `TID-X 32 MOD` only in a one-dimensional block. + +```forth +\ ( -- n ) min(BDIM-X, 32). +: WARP-LANES BDIM-X DUP WARP-SIZE > IF DROP WARP-SIZE THEN ; + +\ ( f n -- sum ) Butterfly sum over lanes 0 to n-1. Each of those lanes ends with the same bits. +\ n is a power of two from 1 to WARP-SIZE. Every lane of the warp calls it. +: WARP-FSUM + 2 / + BEGIN DUP 0 > WHILE + OVER OVER SHFL-XOR + ROT F+ SWAP + 2 / + REPEAT + DROP +; + +GLOBAL-ID CELLS INPUT + F@ WARP-LANES WARP-FSUM +``` diff --git a/gpu_test/test_kernels.py b/gpu_test/test_kernels.py index 96a08f3..7040bdb 100644 --- a/gpu_test/test_kernels.py +++ b/gpu_test/test_kernels.py @@ -2,6 +2,8 @@ from __future__ import annotations +import math +import operator import struct from typing import TYPE_CHECKING @@ -9,6 +11,8 @@ import pytest if TYPE_CHECKING: + from collections.abc import Callable + from conftest import KernelRunner pytestmark = pytest.mark.gpu @@ -873,3 +877,224 @@ def test_naive_attention_f32(kernel_runner: KernelRunner) -> None: output = _unpack_i64_to_f32(result, n) assert output == [pytest.approx(v, rel=1e-5) for v in expected] + + +_WARP_SIZE = 32 + +_WARP_WORDS = """\ +: WARP-LANES BDIM-X DUP WARP-SIZE > IF DROP WARP-SIZE THEN ; +: NWARPS BDIM-X WARP-LANES / ; +: WARP-FMAX 2 / BEGIN DUP 0 > WHILE OVER OVER SHFL-XOR ROT FMAX SWAP 2 / REPEAT DROP ; +: WARP-FSUM 2 / BEGIN DUP 0 > WHILE OVER OVER SHFL-XOR ROT F+ SWAP 2 / REPEAT DROP ; +""" + + +def _f64_bits(value: float) -> int: + return struct.unpack(" float: + return struct.unpack(" int: + high = lane - 16 + low = lane * 0x0808_0808 + return (high << 32) | low + + +def _shfl_source(mode: str, lane: int, operand: int) -> int: + b = operand & (_WARP_SIZE - 1) + if mode == "DOWN": + return lane + b if lane + b < _WARP_SIZE else lane + if mode == "UP": + return lane - b if lane - b >= 0 else lane + if mode == "XOR": + return lane ^ b + return b + + +def _butterfly(values: list[float], combine: Callable[[float, float], float]) -> list[float]: + lanes = list(values) + stride = len(lanes) // 2 + while stride: + lanes = [combine(lanes[k ^ stride], lanes[k]) for k in range(len(lanes))] + stride //= 2 + return lanes + + +def test_shfl_modes_move_whole_cells(kernel_runner: KernelRunner) -> None: + cells = [_lane_cell(lane) for lane in range(_WARP_SIZE)] + floats = [(-1.0) ** lane * (lane + 1) / 3.0 for lane in range(_WARP_SIZE)] + wrapped = 3 + _WARP_SIZE + result = kernel_runner.run( + forth_source=( + "\\! kernel main\n" + "\\! param IN i64[32]\n" + "\\! param FIN f64[32]\n" + "\\! param OUT i64[192]\n" + "TID-X CELLS IN + @ 3 SHFL-DOWN TID-X CELLS OUT + !\n" + "TID-X CELLS IN + @ 3 SHFL-UP TID-X 32 + CELLS OUT + !\n" + "TID-X CELLS IN + @ 3 SHFL-XOR TID-X 64 + CELLS OUT + !\n" + f"TID-X CELLS IN + @ {wrapped} SHFL-XOR TID-X 96 + CELLS OUT + !\n" + "TID-X CELLS IN + @ 3 SHFL-IDX TID-X 128 + CELLS OUT + !\n" + "TID-X CELLS FIN + F@ 5 SHFL-XOR TID-X 160 + CELLS OUT + !" + ), + params={"IN": cells, "FIN": floats}, + block=(_WARP_SIZE, 1, 1), + output_param=2, + output_count=192, + ) + + lanes = range(_WARP_SIZE) + for slot, (mode, operand) in enumerate( + [("DOWN", 3), ("UP", 3), ("XOR", 3), ("XOR", wrapped), ("IDX", 3)] + ): + got = result[slot * _WARP_SIZE : (slot + 1) * _WARP_SIZE] + assert got == [cells[_shfl_source(mode, k, operand)] for k in lanes], f"{mode} {operand}" + assert result[160:192] == [_f64_bits(floats[_shfl_source("XOR", k, 5)]) for k in lanes] + + +@pytest.mark.parametrize("block_x", [8, 32]) +def test_shfl_partial_warp(kernel_runner: KernelRunner, block_x: int) -> None: + x = (np.random.default_rng(7).standard_normal(_WARP_SIZE) * 100.0).tolist() + folds = kernel_runner.run( + forth_source=( + "\\! kernel main\n\\! param X f64[32]\n\\! param OUT f64[64]\n" + + _WARP_WORDS + + "TID-X CELLS X + F@ WARP-LANES WARP-FMAX TID-X CELLS OUT + F!\n" + "TID-X CELLS X + F@ WARP-LANES WARP-FSUM TID-X 32 + CELLS OUT + F!" + ), + params={"X": x}, + block=(block_x, 1, 1), + output_param=1, + output_count=64, + ) + assert folds[:block_x] == _butterfly(x[:block_x], max) + assert folds[32 : 32 + block_x] == _butterfly(x[:block_x], operator.add) + + +@pytest.mark.parametrize("block_x", [8, 32]) +def test_shfl_idx_broadcasts_both_halves(kernel_runner: KernelRunner, block_x: int) -> None: + both_halves = (1 << 32) + 1 + broadcast = kernel_runner.run( + forth_source=( + "\\! kernel main\n\\! param OUT i64[32]\n" + "TID-X 0= IF 1 32 LSHIFT 1 OR ELSE 0 THEN\n" + "0 SHFL-IDX\n" + "TID-X CELLS OUT + !" + ), + block=(block_x, 1, 1), + output_count=block_x, + ) + assert broadcast == [both_halves] * block_x + + +_BLOCK_REDUCE_KERNEL = ( + """\ +\\! kernel main +\\! param N i64 +\\! param INPUT f64[4096] +\\! param OUTPUT f64[1] +\\! shared PART f64[32] +""" + + _WARP_WORDS + + """\ +: WARP-FSUM0 2 / BEGIN DUP 0 > WHILE OVER OVER SHFL-DOWN ROT F+ SWAP 2 / REPEAT DROP ; +0.0 +GLOBAL-ID +BEGIN DUP N < WHILE + DUP CELLS INPUT + F@ + ROT F+ + SWAP + BDIM-X + +REPEAT +DROP +WARP-LANES WARP-FSUM0 +LANE-ID 0= IF DUP TID-X WARP-SIZE / CELLS PART + SF! THEN +DROP +BARRIER +TID-X WARP-SIZE < IF + TID-X NWARPS < IF TID-X CELLS PART + SF@ ELSE 0.0 THEN + NWARPS WARP-FSUM0 + TID-X 0= IF 0 CELLS OUTPUT + F! ELSE DROP THEN +THEN +""" +) + + +@pytest.mark.parametrize("block_x", [64, 256]) +def test_block_reduce(kernel_runner: KernelRunner, block_x: int) -> None: + n = 3000 + values = (np.random.default_rng(42).standard_normal(n) * 10.0).tolist() + result = kernel_runner.run( + forth_source=_BLOCK_REDUCE_KERNEL, + params={"N": n, "INPUT": values}, + block=(block_x, 1, 1), + output_param=2, + output_count=1, + ) + assert result[0] == pytest.approx(math.fsum(values), rel=1e-9, abs=1e-9) + + +_BLOCK_ALLREDUCE_KERNEL = ( + """\ +\\! kernel main +\\! param X f64[64] +\\! param OUT i64[128] +\\! shared RED f64[32] +""" + + _WARP_WORDS + + """\ +: BLOCK-FMAX { rdz -- } + WARP-LANES WARP-FMAX + LANE-ID 0= IF DUP TID-X WARP-SIZE / CELLS rdz + SF! THEN + DROP + BARRIER + LANE-ID NWARPS < IF LANE-ID CELLS rdz + SF@ ELSE -1.0e30 THEN + NWARPS WARP-FMAX + 0 SHFL-IDX +; +: BLOCK-FSUM { rdz -- } + WARP-LANES WARP-FSUM + LANE-ID 0= IF DUP TID-X WARP-SIZE / CELLS rdz + SF! THEN + DROP + BARRIER + LANE-ID NWARPS < IF LANE-ID CELLS rdz + SF@ ELSE 0.0 THEN + NWARPS WARP-FSUM + 0 SHFL-IDX +; +TID-X CELLS X + F@ RED BLOCK-FMAX TID-X CELLS OUT + ! +BARRIER +TID-X CELLS X + F@ RED BLOCK-FSUM TID-X 64 + CELLS OUT + ! +""" +) + + +@pytest.mark.parametrize("block_x", [8, 64]) +def test_block_allreduce_same_bits(kernel_runner: KernelRunner, block_x: int) -> None: + x = (np.random.default_rng(11).standard_normal(64) * 100.0).tolist() + result = kernel_runner.run( + forth_source=_BLOCK_ALLREDUCE_KERNEL, + params={"X": x}, + block=(block_x, 1, 1), + output_param=1, + output_count=128, + ) + maxes = result[:block_x] + sums = result[64 : 64 + block_x] + assert len(set(maxes)) == 1 + assert len(set(sums)) == 1 + assert _bits_f64(maxes[0]) == max(x[:block_x]) + assert _bits_f64(sums[0]) == pytest.approx(math.fsum(x[:block_x]), rel=1e-9, abs=1e-9) + + +def test_lane_id_follows_linear_thread_index(kernel_runner: KernelRunner) -> None: + result = kernel_runner.run( + forth_source=( + "\\! kernel main\n\\! param OUT i64[64]\nLANE-ID TID-Y BDIM-X * TID-X + CELLS OUT + !" + ), + block=(16, 4, 1), + output_count=64, + ) + assert result == [index % _WARP_SIZE for index in range(64)] diff --git a/include/warpforth/Conversion/Passes.td b/include/warpforth/Conversion/Passes.td index be86499..7ae92c5 100644 --- a/include/warpforth/Conversion/Passes.td +++ b/include/warpforth/Conversion/Passes.td @@ -21,6 +21,8 @@ def ConvertForthToMemRef Forth operations are converted to corresponding memref load/store operations with explicit stack pointer arithmetic. + + `forth.shuffle` becomes a `gpu.shuffle` of the whole i64 cell at width 32. }]; let constructor = "mlir::warpforth::createConvertForthToMemRefPass()"; @@ -29,7 +31,8 @@ def ConvertForthToMemRef "mlir::arith::ArithDialect", "mlir::LLVM::LLVMDialect", "mlir::cf::ControlFlowDialect", - "mlir::math::MathDialect"]; + "mlir::math::MathDialect", + "mlir::gpu::GPUDialect"]; } def ConvertForthToGPU : Pass<"convert-forth-to-gpu", "mlir::ModuleOp"> { @@ -44,7 +47,7 @@ def ConvertForthToGPU : Pass<"convert-forth-to-gpu", "mlir::ModuleOp"> { Additionally, the pass lowers forth.intrinsic operations to corresponding GPU dialect operations (gpu.thread_id, gpu.block_id, gpu.block_dim, - gpu.grid_dim). + gpu.grid_dim, gpu.lane_id). }]; let constructor = "mlir::warpforth::createConvertForthToGPUPass()"; diff --git a/include/warpforth/Dialect/Forth/CMakeLists.txt b/include/warpforth/Dialect/Forth/CMakeLists.txt index 9dadd3d..93ae20b 100644 --- a/include/warpforth/Dialect/Forth/CMakeLists.txt +++ b/include/warpforth/Dialect/Forth/CMakeLists.txt @@ -1,5 +1,10 @@ add_mlir_dialect(ForthOps forth) +set(LLVM_TARGET_DEFINITIONS ForthOps.td) +mlir_tablegen(ForthOpsEnums.h.inc -gen-enum-decls) +mlir_tablegen(ForthOpsEnums.cpp.inc -gen-enum-defs) +add_public_tablegen_target(MLIRForthOpsEnumsIncGen) + set(LLVM_TARGET_DEFINITIONS ForthOps.td) mlir_tablegen(ForthDialect.md -gen-dialect-doc) add_public_tablegen_target(ForthDialectDocGen) diff --git a/include/warpforth/Dialect/Forth/ForthDialect.h b/include/warpforth/Dialect/Forth/ForthDialect.h index 44131da..3748c39 100644 --- a/include/warpforth/Dialect/Forth/ForthDialect.h +++ b/include/warpforth/Dialect/Forth/ForthDialect.h @@ -9,13 +9,20 @@ #include "mlir/Bytecode/BytecodeOpInterface.h" // IWYU pragma: keep #include "mlir/Interfaces/SideEffectInterfaces.h" // IWYU pragma: keep +#include #include "warpforth/Dialect/Forth/ForthOpsDialect.h.inc" // IWYU pragma: keep #define GET_TYPEDEF_CLASSES #include "warpforth/Dialect/Forth/ForthOpsTypes.h.inc" +#include "warpforth/Dialect/Forth/ForthOpsEnums.h.inc" // IWYU pragma: keep + #define GET_OP_CLASSES #include "warpforth/Dialect/Forth/ForthOps.h.inc" +namespace mlir::forth { +inline constexpr int64_t kWarpSize = 32; +} // namespace mlir::forth + #endif diff --git a/include/warpforth/Dialect/Forth/ForthOps.td b/include/warpforth/Dialect/Forth/ForthOps.td index 9a571f9..57502b9 100644 --- a/include/warpforth/Dialect/Forth/ForthOps.td +++ b/include/warpforth/Dialect/Forth/ForthOps.td @@ -8,6 +8,7 @@ #define FORTH_OPS include "warpforth/Dialect/Forth/ForthDialect.td" +include "mlir/IR/EnumAttr.td" include "mlir/Interfaces/SideEffectInterfaces.td" //===----------------------------------------------------------------------===// @@ -731,6 +732,56 @@ def Forth_GlobalIdOp : Forth_StackOpBase<"global_id"> { }]; } +//===----------------------------------------------------------------------===// +// Warp operations. +//===----------------------------------------------------------------------===// + +def Forth_ShuffleModeDown : I32EnumAttrCase<"Down", 0, "down">; +def Forth_ShuffleModeUp : I32EnumAttrCase<"Up", 1, "up">; +def Forth_ShuffleModeXor : I32EnumAttrCase<"Xor", 2, "xor">; +def Forth_ShuffleModeIdx : I32EnumAttrCase<"Idx", 3, "idx">; + +def Forth_ShuffleMode : I32EnumAttr<"ShuffleMode", + "rule that picks the source lane of a warp shuffle", + [Forth_ShuffleModeDown, Forth_ShuffleModeUp, Forth_ShuffleModeXor, + Forth_ShuffleModeIdx]> { + let cppNamespace = "::mlir::forth"; +} + +def Forth_ShuffleOp : Forth_Op<"shuffle", []> { + let summary = "Read the top cell from another lane of the warp"; + let description = [{ + Pops b, then x, and pushes the x that source lane j held. For lane k, + with b taken modulo 32: + + - down: j = k + b, or k when k + b > 31 + - up: j = k - b, or k when k - b < 0 + - xor: j = k xor b + - idx: j = b + + The whole 64-bit cell moves. All 32 lanes take part with member mask + 0xFFFFFFFF, and every launched lane of the warp must execute the op + together. A source lane that was not launched yields an unspecified + value. + + Forth semantics: ( x b -- y ) + }]; + let arguments = (ins Forth_StackType:$input_stack, + Forth_ShuffleMode:$mode); + let results = (outs Forth_StackType:$output_stack); + let assemblyFormat = [{ + $mode $input_stack attr-dict `:` type($input_stack) `->` type($output_stack) + }]; +} + +def Forth_LaneIdOp : Forth_StackOpBase<"lane_id"> { + let summary = "Push this thread's lane within its warp"; + let description = [{ + Pushes the hardware lane number, 0 to 31 (PTX %laneid). + Forth semantics: ( -- lane ) + }]; +} + //===----------------------------------------------------------------------===// // Synchronization operations. //===----------------------------------------------------------------------===// diff --git a/lib/Conversion/ForthToGPU/ForthToGPU.cpp b/lib/Conversion/ForthToGPU/ForthToGPU.cpp index 6a363e6..e271201 100644 --- a/lib/Conversion/ForthToGPU/ForthToGPU.cpp +++ b/lib/Conversion/ForthToGPU/ForthToGPU.cpp @@ -36,9 +36,6 @@ static gpu::Dimension getDimensionFromIntrinsic(StringRef intrinsic) { return gpu::Dimension::x; // Default } -/// Conversion pattern for forth.intrinsic to GPU dialect operations. -/// Maps intrinsic names like "tid-x", "bid-x", etc. to gpu.thread_id, -/// gpu.block_id, gpu.block_dim, gpu.grid_dim operations. struct IntrinsicOpConversion : public OpConversionPattern { using OpConversionPattern::OpConversionPattern; @@ -50,7 +47,10 @@ struct IntrinsicOpConversion : public OpConversionPattern { gpu::Dimension dim = getDimensionFromIntrinsic(intrinsic); Value result; - if (intrinsic.starts_with("tid-")) { + if (intrinsic == "lane-id") { + IntegerAttr noUpperBound; + result = rewriter.create(loc, noUpperBound); + } else if (intrinsic.starts_with("tid-")) { // thread_id: tid-x, tid-y, tid-z result = rewriter.create(loc, rewriter.getIndexType(), dim); diff --git a/lib/Conversion/ForthToMemRef/CMakeLists.txt b/lib/Conversion/ForthToMemRef/CMakeLists.txt index 1f85b95..f898394 100644 --- a/lib/Conversion/ForthToMemRef/CMakeLists.txt +++ b/lib/Conversion/ForthToMemRef/CMakeLists.txt @@ -13,6 +13,7 @@ add_mlir_conversion_library(MLIRForthToMemRefConversion MLIRArithDialect MLIRLLVMDialect MLIRFuncDialect + MLIRGPUDialect MLIRControlFlowDialect MLIRMathDialect MLIRForth diff --git a/lib/Conversion/ForthToMemRef/ForthToMemRef.cpp b/lib/Conversion/ForthToMemRef/ForthToMemRef.cpp index 4772660..b3fabc8 100644 --- a/lib/Conversion/ForthToMemRef/ForthToMemRef.cpp +++ b/lib/Conversion/ForthToMemRef/ForthToMemRef.cpp @@ -9,6 +9,7 @@ #include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h" #include "mlir/Dialect/Func/IR/FuncOps.h" #include "mlir/Dialect/Func/Transforms/FuncConversions.h" +#include "mlir/Dialect/GPU/IR/GPUDialect.h" #include "mlir/Dialect/LLVMIR/LLVMDialect.h" #include "mlir/Dialect/LLVMIR/NVVMDialect.h" #include "mlir/Dialect/Math/IR/Math.h" @@ -1053,6 +1054,51 @@ struct GlobalIdOpConversion : public StackEffectConversion { } }; +static gpu::ShuffleMode toGpuShuffleMode(forth::ShuffleMode mode) { + switch (mode) { + case forth::ShuffleMode::Down: + return gpu::ShuffleMode::DOWN; + case forth::ShuffleMode::Up: + return gpu::ShuffleMode::UP; + case forth::ShuffleMode::Xor: + return gpu::ShuffleMode::XOR; + case forth::ShuffleMode::Idx: + return gpu::ShuffleMode::IDX; + } + llvm_unreachable("unknown forth::ShuffleMode"); +} + +struct ShuffleOpConversion : public StackEffectConversion { + using StackEffectConversion::StackEffectConversion; + + FailureOr + rewriteStack(forth::ShuffleOp op, OneToNOpAdaptor adaptor, Value memref, + Value stackPtr, + ConversionPatternRewriter &rewriter) const override { + auto loc = op.getLoc(); + + Value one = rewriter.create(loc, 1); + Value b = rewriter.create(loc, memref, stackPtr); + Value spMinus1 = rewriter.create(loc, stackPtr, one); + Value x = rewriter.create(loc, memref, spMinus1); + + Value offset32 = + rewriter.create(loc, rewriter.getI32Type(), b); + Value laneMask = rewriter.create( + loc, forth::kWarpSize - 1, rewriter.getI32Type()); + Value offset = rewriter.create(loc, offset32, laneMask); + Value width = rewriter.create(loc, forth::kWarpSize, + rewriter.getI32Type()); + Value y = rewriter + .create(loc, x, offset, width, + toGpuShuffleMode(op.getMode())) + .getShuffleResult(); + + rewriter.create(loc, y, memref, spMinus1); + return spMinus1; + } +}; + /// Conversion pattern for forth.pop_flag operation. /// Pops top of stack, compares != 0, returns (memref, newSP, i1 flag). struct PopFlagOpConversion : public OpConversionPattern { @@ -1201,9 +1247,9 @@ struct ConvertForthToMemRefPass LLVM::LLVMDialect, cf::ControlFlowDialect, math::MathDialect>(); - // Mark IntrinsicOp and BarrierOp as legal (to be lowered later) target.addLegalOp(); target.addLegalOp(); + target.addLegalOp(); // Use dynamic legality for func operations to ensure they're properly // converted @@ -1310,10 +1356,14 @@ struct ConvertForthToMemRefPass context, "gdim-y"); patterns.add>(typeConverter, context, "gdim-z"); + patterns.add>(typeConverter, context, + "lane-id"); // GlobalIdOp has custom pattern patterns.add(typeConverter, context); + patterns.add(typeConverter, context); + populateFunctionOpInterfaceTypeConversionPattern( patterns, typeConverter); diff --git a/lib/Dialect/Forth/CMakeLists.txt b/lib/Dialect/Forth/CMakeLists.txt index 7057154..1f1630e 100644 --- a/lib/Dialect/Forth/CMakeLists.txt +++ b/lib/Dialect/Forth/CMakeLists.txt @@ -6,6 +6,7 @@ add_mlir_dialect_library(MLIRForth DEPENDS MLIRForthOpsIncGen + MLIRForthOpsEnumsIncGen LINK_LIBS PUBLIC MLIRControlFlowInterfaces diff --git a/lib/Dialect/Forth/ForthDialect.cpp b/lib/Dialect/Forth/ForthDialect.cpp index aa410a3..d890acc 100644 --- a/lib/Dialect/Forth/ForthDialect.cpp +++ b/lib/Dialect/Forth/ForthDialect.cpp @@ -17,6 +17,8 @@ using namespace mlir::forth; #define GET_TYPEDEF_CLASSES #include "warpforth/Dialect/Forth/ForthOpsTypes.cpp.inc" +#include "warpforth/Dialect/Forth/ForthOpsEnums.cpp.inc" // IWYU pragma: keep + #define GET_OP_CLASSES #include "warpforth/Dialect/Forth/ForthOps.cpp.inc" diff --git a/lib/Translation/ForthToMLIR/ForthToMLIR.cpp b/lib/Translation/ForthToMLIR/ForthToMLIR.cpp index a4eb94a..14b5763 100644 --- a/lib/Translation/ForthToMLIR/ForthToMLIR.cpp +++ b/lib/Translation/ForthToMLIR/ForthToMLIR.cpp @@ -489,6 +489,21 @@ static Value emitBarrier(OpBuilder &builder, Location loc, Value inputStack) { return inputStack; } +template +static Value emitShuffle(OpBuilder &builder, Location loc, Value inputStack) { + Type stackType = forth::StackType::get(builder.getContext()); + return builder.create(loc, stackType, inputStack, Mode) + .getResult(); +} + +static Value emitWarpSize(OpBuilder &builder, Location loc, Value inputStack) { + Type stackType = forth::StackType::get(builder.getContext()); + return builder + .create(loc, stackType, inputStack, + builder.getI64IntegerAttr(forth::kWarpSize)) + .getResult(); +} + static const llvm::StringMap &getBuiltinWords() { static const llvm::StringMap words = { {"CELLS", emitCells}, @@ -573,6 +588,12 @@ static const llvm::StringMap &getBuiltinWords() { {"GDIM-Y", emitSimple}, {"GDIM-Z", emitSimple}, {"GLOBAL-ID", emitSimple}, + {"SHFL-DOWN", emitShuffle}, + {"SHFL-UP", emitShuffle}, + {"SHFL-XOR", emitShuffle}, + {"SHFL-IDX", emitShuffle}, + {"LANE-ID", emitSimple}, + {"WARP-SIZE", emitWarpSize}, {"=", emitSimple}, {"<", emitSimple}, {">", emitSimple}, diff --git a/test/Conversion/ForthToGPU/intrinsic-conversion.mlir b/test/Conversion/ForthToGPU/intrinsic-conversion.mlir index 0c94ed7..54423c6 100644 --- a/test/Conversion/ForthToGPU/intrinsic-conversion.mlir +++ b/test/Conversion/ForthToGPU/intrinsic-conversion.mlir @@ -8,6 +8,7 @@ // CHECK: gpu.block_id z // CHECK: gpu.block_dim x // CHECK: gpu.grid_dim y +// CHECK: gpu.lane_id module { func.func private @main() attributes {forth.kernel} { @@ -34,6 +35,10 @@ module { %13 = forth.intrinsic "gdim-y" : index %14 = arith.index_cast %13 : index to i64 memref.store %14, %alloca[%12] : memref<256xi64> + %15 = arith.addi %12, %c1 : index + %16 = forth.intrinsic "lane-id" : index + %17 = arith.index_cast %16 : index to i64 + memref.store %17, %alloca[%15] : memref<256xi64> return } } diff --git a/test/Conversion/ForthToMemRef/warp-shuffle.mlir b/test/Conversion/ForthToMemRef/warp-shuffle.mlir new file mode 100644 index 0000000..e3cffe3 --- /dev/null +++ b/test/Conversion/ForthToMemRef/warp-shuffle.mlir @@ -0,0 +1,41 @@ +// RUN: %warpforth-opt --convert-forth-to-memref %s | %FileCheck %s + +// CHECK-LABEL: func.func private @shuffle_xor +// CHECK: %[[MEM:.*]] = memref.alloca() : memref<256xi64> +// CHECK: %[[B:.*]] = memref.load %[[MEM]][%[[SP:.*]]] : memref<256xi64> +// CHECK: %[[SPM1:.*]] = arith.subi %[[SP]], %{{.*}} : index +// CHECK: %[[X:.*]] = memref.load %[[MEM]][%[[SPM1]]] : memref<256xi64> +// CHECK: %[[B32:.*]] = arith.trunci %[[B]] : i64 to i32 +// CHECK: %[[MASK:.*]] = arith.constant 31 : i32 +// CHECK: %[[BMOD:.*]] = arith.andi %[[B32]], %[[MASK]] : i32 +// CHECK: %[[W:.*]] = arith.constant 32 : i32 +// CHECK: %[[Y:.*]], %{{.*}} = gpu.shuffle xor %[[X]], %[[BMOD]], %[[W]] : i64 +// CHECK: memref.store %[[Y]], %[[MEM]][%[[SPM1]]] : memref<256xi64> +// CHECK: %[[LANE:.*]] = forth.intrinsic "lane-id" : index +// CHECK: %[[LANE64:.*]] = arith.index_cast %[[LANE]] : index to i64 +// CHECK: %[[SP2:.*]] = arith.addi %[[SPM1]], %{{.*}} : index +// CHECK: memref.store %[[LANE64]], %[[MEM]][%[[SP2]]] : memref<256xi64> +func.func private @shuffle_xor() { + %0 = forth.stack !forth.stack + %1 = forth.constant %0(7 : i64) : !forth.stack -> !forth.stack + %2 = forth.constant %1(3 : i64) : !forth.stack -> !forth.stack + %3 = forth.shuffle xor %2 : !forth.stack -> !forth.stack + %4 = forth.lane_id %3 : !forth.stack -> !forth.stack + return +} + +// CHECK-LABEL: func.func private @shuffle_modes +// CHECK: gpu.shuffle down +// CHECK: gpu.shuffle up +// CHECK: gpu.shuffle idx +func.func private @shuffle_modes() { + %0 = forth.stack !forth.stack + %1 = forth.constant %0(7 : i64) : !forth.stack -> !forth.stack + %2 = forth.constant %1(1 : i64) : !forth.stack -> !forth.stack + %3 = forth.shuffle down %2 : !forth.stack -> !forth.stack + %4 = forth.constant %3(1 : i64) : !forth.stack -> !forth.stack + %5 = forth.shuffle up %4 : !forth.stack -> !forth.stack + %6 = forth.constant %5(0 : i64) : !forth.stack -> !forth.stack + %7 = forth.shuffle idx %6 : !forth.stack -> !forth.stack + return +} diff --git a/test/Dialect/Forth/warp-ops.mlir b/test/Dialect/Forth/warp-ops.mlir new file mode 100644 index 0000000..5065089 --- /dev/null +++ b/test/Dialect/Forth/warp-ops.mlir @@ -0,0 +1,24 @@ +// RUN: %warpforth-opt --split-input-file --verify-diagnostics %s | %warpforth-opt | %FileCheck %s + +// CHECK-LABEL: func.func private @warp_ops +// CHECK: forth.shuffle down %{{.*}} : !forth.stack -> !forth.stack +// CHECK: forth.shuffle up %{{.*}} : !forth.stack -> !forth.stack +// CHECK: forth.shuffle xor %{{.*}} : !forth.stack -> !forth.stack +// CHECK: forth.shuffle idx %{{.*}} : !forth.stack -> !forth.stack +// CHECK: forth.lane_id %{{.*}} : !forth.stack -> !forth.stack +func.func private @warp_ops(%s: !forth.stack) -> !forth.stack { + %0 = forth.shuffle down %s : !forth.stack -> !forth.stack + %1 = forth.shuffle up %0 : !forth.stack -> !forth.stack + %2 = forth.shuffle xor %1 : !forth.stack -> !forth.stack + %3 = forth.shuffle idx %2 : !forth.stack -> !forth.stack + %4 = forth.lane_id %3 : !forth.stack -> !forth.stack + return %4 : !forth.stack +} + +// ----- + +func.func private @unknown_mode(%s: !forth.stack) -> !forth.stack { + // expected-error @+1 {{expected string or keyword containing one of the following enum values for attribute 'mode' [down, up, xor, idx]}} + %0 = forth.shuffle sideways %s : !forth.stack -> !forth.stack + return %0 : !forth.stack +} diff --git a/test/Pipeline/warp-shuffle.forth b/test/Pipeline/warp-shuffle.forth new file mode 100644 index 0000000..e512794 --- /dev/null +++ b/test/Pipeline/warp-shuffle.forth @@ -0,0 +1,19 @@ +\ RUN: %warpforthc %s -o %t.ptx +\ RUN: %FileCheck %s --implicit-check-not=.func --implicit-check-not=shfl.sync < %t.ptx +\ RUN: %FileCheck %s --check-prefix=LANE < %t.ptx + +\ CHECK-LABEL: .entry main +\ CHECK-COUNT-2: shfl.sync.down.b32 {{.*}}, -1; +\ CHECK-COUNT-2: shfl.sync.up.b32 {{.*}}, -1; +\ CHECK-COUNT-2: shfl.sync.bfly.b32 {{.*}}, -1; +\ CHECK-COUNT-2: shfl.sync.idx.b32 {{.*}}, -1; + +\ LANE: mov.u32 %r{{[0-9]+}}, %laneid; + +\! kernel main +\! param DATA i64[256] +: BFLY SHFL-XOR ; +GLOBAL-ID CELLS DATA + @ +1 SHFL-DOWN 2 SHFL-UP 3 BFLY 4 SHFL-IDX +LANE-ID + +GLOBAL-ID CELLS DATA + ! diff --git a/test/Translation/Forth/warp-words.forth b/test/Translation/Forth/warp-words.forth new file mode 100644 index 0000000..2fbc7b3 --- /dev/null +++ b/test/Translation/Forth/warp-words.forth @@ -0,0 +1,16 @@ +\ RUN: %warpforth-translate --forth-to-mlir %s | %FileCheck %s + +\ CHECK: %[[X:.*]] = forth.constant %{{.*}}(1 : i64) +\ CHECK-NEXT: %[[B0:.*]] = forth.constant %[[X]](2 : i64) +\ CHECK-NEXT: %[[S0:.*]] = forth.shuffle down %[[B0]] : !forth.stack -> !forth.stack +\ CHECK-NEXT: %[[B1:.*]] = forth.constant %[[S0]](3 : i64) +\ CHECK-NEXT: %[[S1:.*]] = forth.shuffle up %[[B1]] : !forth.stack -> !forth.stack +\ CHECK-NEXT: %[[B2:.*]] = forth.constant %[[S1]](4 : i64) +\ CHECK-NEXT: %[[S2:.*]] = forth.shuffle xor %[[B2]] : !forth.stack -> !forth.stack +\ CHECK-NEXT: %[[B3:.*]] = forth.constant %[[S2]](5 : i64) +\ CHECK-NEXT: %[[S3:.*]] = forth.shuffle idx %[[B3]] : !forth.stack -> !forth.stack +\ CHECK-NEXT: %[[L:.*]] = forth.lane_id %[[S3]] : !forth.stack -> !forth.stack +\ CHECK-NEXT: forth.constant %[[L]](32 : i64) : !forth.stack -> !forth.stack +\ CHECK-NEXT: return +\! kernel main +1 2 shfl-down 3 Shfl-Up 4 SHFL-xor 5 sHfL-iDx Lane-Id warp-size From f8ef969cfd422da60eb155a3186aada49800d40d Mon Sep 17 00:00:00 2001 From: Alex Cameron Date: Mon, 9 Nov 2026 03:35:34 +0000 Subject: [PATCH 2/2] bench(cases): keep the shared reduction trees A shuffle fold of the same partials was correct and not faster. On one RTX 2070, 50 paired samples, noise floor 2%: reduce_sum_f64 moved 1140 us to 1137 us (no change), and attention_f32 moved 1188 us to 1222 us (slower). The trees stay. Comments no longer say the word set has no warp shuffle. --- benchmarks/README.md | 6 +++--- benchmarks/cases/attention_f32.forth | 9 ++++----- benchmarks/cases/reduce_sum_f64.forth | 3 +-- gpu_test/test_bench_cases.py | 2 +- 4 files changed, 9 insertions(+), 11 deletions(-) diff --git a/benchmarks/README.md b/benchmarks/README.md index a702bad..ba1608e 100644 --- a/benchmarks/README.md +++ b/benchmarks/README.md @@ -25,9 +25,9 @@ torch and compiles a large CUDA extension from source; the cuDNN frontend needs graph build. The hand-written kernel covers the same ground: online softmax fused with the output accumulation in one pass, so a row of scores never touches memory. -Hand-written baselines deliberately use hardware WarpForth cannot express yet, so the measured gap -is a feature gap and not a tiling accident. The suite covers 128-bit vector loads, warp shuffles, -register-resident accumulators, fused multiply-add, and fused online softmax. +Hand-written baselines deliberately use hardware the Forth kernels do not match, so the measured +gap is a feature gap and not a tiling accident. The suite covers 128-bit vector loads, warp +shuffles, register-resident accumulators, fused multiply-add, and fused online softmax. ## Numerics diff --git a/benchmarks/cases/attention_f32.forth b/benchmarks/cases/attention_f32.forth index 278224d..1ac4b9b 100644 --- a/benchmarks/cases/attention_f32.forth +++ b/benchmarks/cases/attention_f32.forth @@ -16,11 +16,10 @@ \ reciprocal square root. SCORES needs NKEY entries and RED one per thread. \ HDIM must be a multiple of BDIM, because thread d owns output dimension d and threads with \ d >= HDIM skip the output pass. -\ Each reduction is a shared tree, because the word set has no warp shuffle, and the row of scores -\ lives in shared memory, because there are no registers to hold it. Every word takes its result -\ out of shared memory rather than the data stack, so an iteration adds nothing to the stack and -\ the loop cannot overrun the 2 KiB per-thread buffer. RED[0] carries the row maximum and then the -\ row sum between stages. +\ Each reduction is a shared tree. The row of scores lives in shared memory, because there are no +\ registers to hold it. Every word takes its result out of shared memory rather than the data +\ stack, so an iteration adds nothing to the stack and the loop cannot overrun the 2 KiB per-thread +\ buffer. RED[0] carries the row maximum and then the row sum between stages. : FDOT { pa pb dim -- dot } 0.0 diff --git a/benchmarks/cases/reduce_sum_f64.forth b/benchmarks/cases/reduce_sum_f64.forth index 619b60f..193f49c 100644 --- a/benchmarks/cases/reduce_sum_f64.forth +++ b/benchmarks/cases/reduce_sum_f64.forth @@ -18,8 +18,7 @@ DROP TID-X CELLS PART + SF! BARRIER -\ Shared tree fold, halving the stride each level. No warp shuffle and no register accumulator, -\ so every level costs a block barrier. +\ Shared tree fold, halving the stride each level. Each level costs a block barrier. BDIM-X 2 / BEGIN DUP 0 > WHILE DUP TID-X > diff --git a/gpu_test/test_bench_cases.py b/gpu_test/test_bench_cases.py index 0537300..cf4ce0d 100644 --- a/gpu_test/test_bench_cases.py +++ b/gpu_test/test_bench_cases.py @@ -31,7 +31,7 @@ COMPILER = manifest.find_compiler(REPO_ROOT) CASE_IDS = [case.id for case in CASES] -# Features WarpForth cannot express yet. The suite must exercise all of them at least once, so a +# Features the Forth kernels do not match. The suite must exercise all of them at least once, so a # gap it reports is a feature gap and not just a tiling difference. REQUIRED_FEATURES = ( "128-bit vector",