Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <name>` is required and must appear first. `\! param <name> i64[<N>]` becomes a `memref<Nxi64>` argument; `\! param <name> i64` becomes an `i64` argument. `\! param <name> f64[<N>]` becomes a `memref<Nxf64>` argument; `\! param <name> 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 <name> i64[<N>]` or `\! shared <name> f64[<N>]` 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.
Expand Down
2 changes: 2 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ add_custom_target(check-clang-tidy
DEPENDS
MLIRConversionPassIncGen
MLIRForthOpsIncGen
MLIRForthOpsEnumsIncGen
COMMENT "Running clang-tidy"
VERBATIM
)
Expand All @@ -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
)
Expand Down
6 changes: 3 additions & 3 deletions benchmarks/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
9 changes: 4 additions & 5 deletions benchmarks/cases/attention_f32.forth
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 1 addition & 2 deletions benchmarks/cases/reduce_sum_f64.forth
Original file line number Diff line number Diff line change
Expand Up @@ -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 >
Expand Down
40 changes: 40 additions & 0 deletions docs/language.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```
2 changes: 1 addition & 1 deletion gpu_test/test_bench_cases.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
225 changes: 225 additions & 0 deletions gpu_test/test_kernels.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,17 @@

from __future__ import annotations

import math
import operator
import struct
from typing import TYPE_CHECKING

import numpy as np
import pytest

if TYPE_CHECKING:
from collections.abc import Callable

from conftest import KernelRunner

pytestmark = pytest.mark.gpu
Expand Down Expand Up @@ -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("<q", struct.pack("<d", value))[0]


def _bits_f64(cell: int) -> float:
return struct.unpack("<d", struct.pack("<q", cell))[0]


def _lane_cell(lane: int) -> 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)]
7 changes: 5 additions & 2 deletions include/warpforth/Conversion/Passes.td
Original file line number Diff line number Diff line change
Expand Up @@ -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()";
Expand All @@ -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"> {
Expand All @@ -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()";
Expand Down
5 changes: 5 additions & 0 deletions include/warpforth/Dialect/Forth/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -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)
Loading
Loading