Skip to content
Closed
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
45 changes: 42 additions & 3 deletions docs/gpu.md
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,46 @@ gpuLaunch(matmul, [p, m], a, b, c, m, k, p);
- `tslang/test/gpu/gpu_blocks.ts` checks a block sum in blocks of 128, a 70 x 90 tiled matrix product (not a
multiple of 16), a 4 x 4 x 4 block, and blocks of 64 and 512 sharing a function, against the CPU.

## Threads that run together: warps

The GPU runs a block's threads in warps, groups whose lanes run each step together and can read each other's
values directly, without shared memory or a barrier: a warp's sum, a vote, a prefix sum.

- `gpuWarpSize()`: the warp's lanes. 32 on NVIDIA's GPUs and on AMD's from gfx10 on (RDNA; 64 on the ones before,
as gfx906); on Intel's the driver picks 8, 16 or 32 for each kernel. Use it rather than a number.
- `gpuLaneIndex()`: the thread's lane, 0 to `gpuWarpSize() - 1`. In a block of one dimension the warps are the
block's threads in order: lane `gpuThreadIndex() % gpuWarpSize()`.
- `gpuShuffle(v, lane)`: `v` of the warp's lane `lane` (modulo the warp's size). `gpuShuffleDown(v, d)`: of the lane
`d` above, `gpuShuffleUp(v, d)` of the lane `d` below, `gpuShuffleXor(v, m)` of lane `^ m`; a thread whose lane
would be outside the warp gets its own `v`. `v` is a number of 4 or 8 bytes (`number`, `float`, `int`, ...),
as CUDA's `__shfl_sync`, `__shfl_down_sync`, `__shfl_up_sync`, `__shfl_xor_sync`.
- `gpuBallot(p)`: an `int` with a bit for each lane `p` is true for (lane 0 the lowest). `gpuAll(p)`, `gpuAny(p)`:
whether `p` is true for all, or any, of the warp's lanes.

```ts
// each warp's sum, which its lane 0 writes
@kernel
function warpSums(i: int, n: int, a: number[], sums: number[]) {
let v = i < n ? a[i] : 0;
for (let d = gpuWarpSize() >> 1; d > 0; d = d >> 1) v += gpuShuffleDown(v, d);
if (gpuLaneIndex() == 0) sums[i] = v;
}
```

- The lanes have to run together, so a kernel that uses these runs as one that waits at `gpuBarrier` does (above):
on every thread of its blocks, past `n` too, with its array accesses guarded. A thread past `n` is in no vote
(it is no bit of a ballot, no `gpuAny`'s true, no `gpuAll`'s false), but what it gives a shuffle is its own
`v`: so `warpSums` gives 0 past `n` itself (`i < n ? a[i] : 0`).
- A shuffle reads the lanes that run with it: in an `if` only some lanes take, a lane that does not is not there
to read (on NVIDIA its value is undefined). `gpuShuffleXor(v, 2)` among the even lanes is fine; reading an odd
lane from there is not.
- Its block is of whole warps, a multiple of 32 threads (`@kernel({ block: 100 })` is an error); `gpuReduce` does
not take it, and a call of it on the CPU is an error, as for a barrier kernel. On AMD's GPUs before gfx10
`gpuBallot` is an error: their 64 lanes do not fit in an `int`.
- `tslang/test/gpu/gpu_warp.ts` checks each of them on 1000 threads (the last warp partly past `n`), with arrays
longer than that; `gpu_scan.ts` is a prefix sum of 100000 values: each warp's of `gpuShuffleUp`, each block's of
its warps' totals in shared memory, then the blocks' (on the RTX 5080: warps of 32).

## Combining what the threads find: `Atomics`

Threads that write the same element would overwrite each other. `Atomics.add(a, i, v)` and the rest, given a
Expand Down Expand Up @@ -497,13 +537,12 @@ Arithmetic on `number`s brings 64-bit floats back: `Math.sqrt(v) + 1` is a `numb
## What has been run

The NVIDIA path runs on an RTX 5080, as executables and under the JIT, on Windows and on Linux (Ubuntu under WSL2,
whose CUDA driver is the Windows one's: the running tests below up to `gpu_call.ts` pass there too; those after it
have been run on Windows only so far). The AMD and Intel ones are checked as
whose CUDA driver is the Windows one's: the running tests below pass there too). The AMD and Intel ones are checked as
far as their compiled code goes (the AMD code object's kernel table, the SPIR-V by `spirv-val`): neither has
been run on its GPU yet. The test suite compiles a kernel for every GPU there is a backend for, and checks the
errors (`tslang/test/gpu`). Running ones, which need a GPU: `tslang/test/gpu/gpu_add_arrays.ts`,
`gpu_saxpy_table.ts`, `gpu_add_ints.ts`, `gpu_math.ts`, `gpu_copy_back.ts`, `gpu_batch.ts`, `gpu_float.ts`,
`gpu_atomics.ts`, `gpu_reduce.ts`, `gpu_batch_temporaries.ts`, `gpu_math_library.ts`, `gpu_shared.ts`, `gpu_grid.ts`, `gpu_call.ts`, `gpu_min_max.ts`, `gpu_array.ts`, `gpu_array_collect.ts`, `gpu_async.ts`, `gpu_barrier_guard.ts`, `gpu_blocks.ts`, `gpu_typed_arrays.ts`.
`gpu_atomics.ts`, `gpu_reduce.ts`, `gpu_batch_temporaries.ts`, `gpu_math_library.ts`, `gpu_shared.ts`, `gpu_grid.ts`, `gpu_call.ts`, `gpu_min_max.ts`, `gpu_array.ts`, `gpu_array_collect.ts`, `gpu_async.ts`, `gpu_barrier_guard.ts`, `gpu_blocks.ts`, `gpu_typed_arrays.ts`, `gpu_warp.ts`, `gpu_scan.ts`.

## Not yet

Expand Down
4 changes: 2 additions & 2 deletions tslang/include/TypeScript/MLIRLogic/MLIRCodeLogic.h
Original file line number Diff line number Diff line change
Expand Up @@ -420,7 +420,7 @@ class MLIRCustomMethods
static std::map<std::string, bool> m {
{"print", true}, {"convertf", true}, {"assert", true}, {"parseInt", true}, {"parseFloat", true}, {"isNaN", true}, {"sizeof", true}, {GENERATOR_SWITCHSTATE, true},
{"LoadLibraryPermanently", true}, { "SearchForAddressOfSymbol", true }, { "LoadReference", true }, { "ReferenceOf", true }, { "Deref", true }, { "Ref", true },
{"atomicrmw", true}, {"cmpxchg", true}, {"atomicload", true}, {"atomicstore", true}, {"fence", true}, {"inline_asm", true}, {"call_intrinsic", true}, {"linker_options", true}, {"gpuLaunch", true}, {"gpuReduce", true}, {"gpuBatch", true}, {"gpuThreadIndex", true}, {"gpuBlockIndex", true}, {"gpuBlockSize", true}, {"gpuBarrier", true}, {"gpuShared", true}, {"gpuArray", true}, {"gpuRead", true}, {"gpuWrite", true}, {"gpuFree", true}
{"atomicrmw", true}, {"cmpxchg", true}, {"atomicload", true}, {"atomicstore", true}, {"fence", true}, {"inline_asm", true}, {"call_intrinsic", true}, {"linker_options", true}, {"gpuLaunch", true}, {"gpuReduce", true}, {"gpuBatch", true}, {"gpuThreadIndex", true}, {"gpuBlockIndex", true}, {"gpuBlockSize", true}, {"gpuBarrier", true}, {"gpuShared", true}, {"gpuArray", true}, {"gpuRead", true}, {"gpuWrite", true}, {"gpuFree", true}, {"gpuLaneIndex", true}, {"gpuWarpSize", true}, {"gpuShuffle", true}, {"gpuShuffleDown", true}, {"gpuShuffleUp", true}, {"gpuShuffleXor", true}, {"gpuBallot", true}, {"gpuAll", true}, {"gpuAny", true}
};
return m[functionName.str()];
}
Expand All @@ -430,7 +430,7 @@ class MLIRCustomMethods
static std::map<std::string, bool> m {
{"print", true}, {"convertf", true}, {"assert", true}, {"sizeof", true}, {GENERATOR_SWITCHSTATE, true},
{"LoadLibraryPermanently", true}, { "SearchForAddressOfSymbol", true }, { "LoadReference", true }, { "ReferenceOf", true }, { "Deref", true }, { "Ref", true },
{"atomicrmw", true}, {"cmpxchg", true}, {"atomicload", true}, {"atomicstore", true}, {"fence", true}, {"inline_asm", true}, {"call_intrinsic", true}, {"linker_options", true}, {"gpuLaunch", true}, {"gpuReduce", true}, {"gpuBatch", true}, {"gpuThreadIndex", true}, {"gpuBlockIndex", true}, {"gpuBlockSize", true}, {"gpuBarrier", true}, {"gpuShared", true}, {"gpuArray", true}, {"gpuRead", true}, {"gpuWrite", true}, {"gpuFree", true}
{"atomicrmw", true}, {"cmpxchg", true}, {"atomicload", true}, {"atomicstore", true}, {"fence", true}, {"inline_asm", true}, {"call_intrinsic", true}, {"linker_options", true}, {"gpuLaunch", true}, {"gpuReduce", true}, {"gpuBatch", true}, {"gpuThreadIndex", true}, {"gpuBlockIndex", true}, {"gpuBlockSize", true}, {"gpuBarrier", true}, {"gpuShared", true}, {"gpuArray", true}, {"gpuRead", true}, {"gpuWrite", true}, {"gpuFree", true}, {"gpuLaneIndex", true}, {"gpuWarpSize", true}, {"gpuShuffle", true}, {"gpuShuffleDown", true}, {"gpuShuffleUp", true}, {"gpuShuffleXor", true}, {"gpuBallot", true}, {"gpuAll", true}, {"gpuAny", true}
};
return m[functionName.str()];
}
Expand Down
104 changes: 104 additions & 0 deletions tslang/lib/TypeScript/MLIRGenAccessCall.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2343,6 +2343,14 @@ namespace mlirgen
return mlirGenGpuBlockBuiltin(location, functionName, typeArguments, operands, genContext);
}

if (functionName == "gpuLaneIndex" || functionName == "gpuWarpSize" || functionName == "gpuShuffle" ||
functionName == "gpuShuffleDown" || functionName == "gpuShuffleUp" || functionName == "gpuShuffleXor" ||
functionName == "gpuBallot" ||
functionName == "gpuAll" || functionName == "gpuAny")
{
return mlirGenGpuWarpBuiltin(location, functionName, operands, genContext);
}

// `print(x)` prints x as console.log does (`[ 1, 'a' ]`), not as String() makes it
if (functionName == "print")
{
Expand Down Expand Up @@ -3245,6 +3253,102 @@ namespace mlirgen
return V(callOp.getResult(0));
}

// What a warp's threads share (docs/gpu.md): the GPU runs a block's threads in warps (NVIDIA's 32, AMD's
// wavefronts, Intel's sub-groups), whose lanes run together and can see each other's values. gpuLaneIndex() (the
// thread's lane), gpuWarpSize(), gpuShuffle(v, lane) (v of the warp's lane `lane`), gpuShuffleDown(v, d) (of the
// lane d above, a thread's own past the warp's end), gpuShuffleUp(v, d) (of the lane d below, a thread's own
// below lane 0), gpuShuffleXor(v, m) (of lane ^ m), gpuBallot(p) (an int, a
// bit per lane p is true for), gpuAll(p) and gpuAny(p). Each is a call of a declared stub,
// `__tslang_gpu_warp_<what>`, as gpuBarrier's (tslang/gpu.cpp lowers them per GPU); a shuffle's is
// `__tslang_gpu_warp_shuffle.<idx|down|xor>.<the value's type>`, so that each type has a stub of its own.
ValueOrLogicalResult MLIRGenImpl::mlirGenGpuWarpBuiltin(mlir::Location location, StringRef functionName,
SmallVector<mlir::Value, 4> &operands,
const GenContext &genContext)
{
auto call = [&](StringRef name, mlir::Type result, mlir::ValueRange args) -> ValueOrLogicalResult {
auto funcOp = theModule.lookupSymbol<mlir_ts::FuncOp>(name);
if (!funcOp)
{
SmallVector<mlir::Type> inputs;
for (auto arg : args)
{
inputs.push_back(arg.getType());
}

auto funcType = mlir_ts::FunctionType::get(builder.getContext(), inputs, {result}, false);
mlir::OpBuilder::InsertionGuard guard(builder);
builder.setInsertionPointToStart(theModule.getBody());
funcOp = mlir_ts::FuncOp::create(stripMetadata(location), name, funcType);
funcOp.setPrivate();
pushFunction(funcOp);
}

auto callOp = builder.create<mlir_ts::CallOp>(location, funcOp, args);
return V(callOp.getResult(0));
};

auto intType = builder.getIntegerType(32, true);
if (functionName == "gpuLaneIndex" || functionName == "gpuWarpSize")
{
if (!operands.empty())
{
emitError(location) << functionName << "() takes no arguments";
return mlir::failure();
}

return call(functionName == "gpuLaneIndex" ? "__tslang_gpu_warp_lane" : "__tslang_gpu_warp_size", intType,
{});
}

if (functionName == "gpuBallot" || functionName == "gpuAll" || functionName == "gpuAny")
{
if (operands.size() != 1)
{
emitError(location) << functionName << "(p) takes one argument, whether it is true for the thread";
return mlir::failure();
}

CAST_A(predicate, location, getBooleanType(), operands[0], genContext);
auto name = functionName == "gpuBallot" ? "__tslang_gpu_warp_ballot"
: functionName == "gpuAll" ? "__tslang_gpu_warp_all"
: "__tslang_gpu_warp_any";
mlir::Type result = functionName == "gpuBallot" ? mlir::Type(intType) : mlir::Type(getBooleanType());
return call(name, result, {predicate});
}

// gpuShuffle(v, lane), gpuShuffleDown(v, delta), gpuShuffleXor(v, mask): v a number of 4 or 8 bytes
if (operands.size() != 2)
{
emitError(location) << functionName << "(v, "
<< (functionName == "gpuShuffle" ? "lane" : functionName == "gpuShuffleXor" ? "mask" : "delta")
<< ") takes the value and an int";
return mlir::failure();
}

auto valueType = mth.wideStorageType(mth.stripLiteralType(operands[0].getType()));
std::string typeName;
if (isa<mlir_ts::NumberType>(valueType))
typeName = "number";
else if (auto floatType = dyn_cast<mlir::FloatType>(valueType); floatType && (floatType.getWidth() == 32 || floatType.getWidth() == 64))
typeName = "f" + std::to_string(floatType.getWidth());
else if (auto integerType = dyn_cast<mlir::IntegerType>(valueType); integerType && (integerType.getWidth() == 32 || integerType.getWidth() == 64))
typeName = (integerType.isUnsigned() ? "u" : integerType.isSigned() ? "s" : "i") + std::to_string(integerType.getWidth());
if (typeName.empty())
{
emitError(location) << functionName << "'s value is a number of 4 or 8 bytes (number, float, int, ...), not '"
<< to_print(operands[0].getType()) << "'";
return mlir::failure();
}

CAST_A(value, location, valueType, operands[0], genContext);
CAST_A(lane, location, intType, operands[1], genContext);
auto mode = functionName == "gpuShuffle" ? "idx"
: functionName == "gpuShuffleDown" ? "down"
: functionName == "gpuShuffleUp" ? "up"
: "xor";
return call((llvm::Twine("__tslang_gpu_warp_shuffle.") + mode + "." + typeName).str(), valueType, {value, lane});
}

// Math.min, Math.max and Math.hypot of two or three numbers (number, an integer, float), compiled as they are:
// the default library's take their arguments as an array, made on the heap for each call, which a GPU kernel
// cannot make (docs/gpu.md), and which is slow on the CPU too. Their results are JavaScript's: a NaN makes min
Expand Down
3 changes: 3 additions & 0 deletions tslang/lib/TypeScript/MLIRGenImpl.h
Original file line number Diff line number Diff line change
Expand Up @@ -14864,6 +14864,9 @@ class MLIRGenImpl
NodeArray<TypeNode> typeArguments, SmallVector<mlir::Value, 4> &operands,
const GenContext &genContext);

ValueOrLogicalResult mlirGenGpuWarpBuiltin(mlir::Location location, StringRef functionName,
SmallVector<mlir::Value, 4> &operands, const GenContext &genContext);

ValueOrLogicalResult mlirGenMathMinMaxHypot(mlir::Location location, CallExpression callExpression, StringRef name,
const GenContext &genContext);

Expand Down
51 changes: 51 additions & 0 deletions tslang/test/gpu/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,57 @@ if (gpu_any_backend)
FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed" TIMEOUT 120)
endforeach()

# a warp's builtins, for every GPU this tslang has a backend for: NVIDIA's shuffles and votes, Intel's SPIR-V
# (SPV_INTEL_subgroups) valid, AMD's linked when an ld.lld is there
set(gpu_warp_pass "call void @__tslang_gpu_run")
if ("NVPTX" IN_LIST LLVM_TARGETS_TO_BUILD)
set(gpu_warp_pass "shfl\\.sync\\.idx\\.b32.*vote\\.sync\\.ballot\\.b32")
endif()
add_test(NAME test-gpu-compile-warp
COMMAND $<TARGET_FILE:tslang> --emit=llvm --no-default-lib "${gpu_compile_dir}/warp.ts" -o -)
set_tests_properties(test-gpu-compile-warp PROPERTIES
PASS_REGULAR_EXPRESSION "${gpu_warp_pass}"
FAIL_REGULAR_EXPRESSION "${gpu_fail_pattern}|LLVM ERROR"
TIMEOUT 120)
set(gpu_warp_environment "")
if (TSLANG_GPU_LLD AND gpu_lld_result EQUAL 0)
list(APPEND gpu_warp_environment "TSLANG_LLD=${TSLANG_GPU_LLD}")
endif()
if (TSLANG_SPIRV_VAL)
list(APPEND gpu_warp_environment "TSLANG_GPU_DUMP=${CMAKE_CURRENT_BINARY_DIR}/warp")
set_tests_properties(test-gpu-compile-warp PROPERTIES FIXTURES_SETUP gpu-intel-warp)
add_test(NAME test-gpu-spirv-val-warp
COMMAND "${TSLANG_SPIRV_VAL}" --target-env opencl2.2 "${CMAKE_CURRENT_BINARY_DIR}/warp.intel")
set_tests_properties(test-gpu-spirv-val-warp PROPERTIES FIXTURES_REQUIRED gpu-intel-warp TIMEOUT 60)
endif()
if (gpu_warp_environment)
set_tests_properties(test-gpu-compile-warp PROPERTIES ENVIRONMENT "${gpu_warp_environment}")
endif()
foreach(gpu_warp_error
"warp_block|'k' uses gpuShuffleDown\\(\\), so its block is of whole warps, a multiple of 32 threads: not 100"
"warp_reduce|gpuReduce cannot add up 'k': it waits at gpuBarrier or uses a warp's builtins"
"warp_cpu_call|'main' calls 'k' on the CPU, which uses gpuBallot\\(\\)"
"warp_value|gpuShuffle's value is a number of 4 or 8 bytes")
string(FIND "${gpu_warp_error}" "|" gpu_warp_sep)
string(SUBSTRING "${gpu_warp_error}" 0 ${gpu_warp_sep} gpu_warp_name)
math(EXPR gpu_warp_sep "${gpu_warp_sep} + 1")
string(SUBSTRING "${gpu_warp_error}" ${gpu_warp_sep} -1 gpu_warp_message)
string(REPLACE "_" "-" gpu_warp_test "${gpu_warp_name}")
add_test(NAME test-gpu-error-${gpu_warp_test}
COMMAND $<TARGET_FILE:tslang> --emit=llvm --no-default-lib "${gpu_compile_dir}/${gpu_warp_name}.ts" -o -)
set_tests_properties(test-gpu-error-${gpu_warp_test} PROPERTIES
PASS_REGULAR_EXPRESSION "${gpu_warp_message}"
FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed" TIMEOUT 120)
endforeach()
# AMD's GPUs before gfx10 have wavefronts of 64, more lanes than gpuBallot's int has bits
if ("AMDGPU" IN_LIST LLVM_TARGETS_TO_BUILD)
add_test(NAME test-gpu-error-warp-ballot-wave64
COMMAND $<TARGET_FILE:tslang> --emit=llvm --no-default-lib --gpu-arch=gfx906 "${gpu_compile_dir}/warp.ts" -o -)
set_tests_properties(test-gpu-error-warp-ballot-wave64 PROPERTIES
PASS_REGULAR_EXPRESSION "gpuBallot\\(\\) is a mask of 32 lanes, and gfx906's wavefronts have 64"
FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed" TIMEOUT 120)
endif()

# typed arrays: a launch gives a kernel the typed array's view, copied for that launch alone (4 | 0x20000, a
# float's), and a call on the CPU gives it the view too; a typed array of other elements is an error
add_test(NAME test-gpu-compile-typed-arrays
Expand Down
21 changes: 21 additions & 0 deletions tslang/test/gpu/compile/warp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// A warp's builtins (docs/gpu.md), each for every GPU: lanes, shuffles of 4- and 8-byte values, votes
@kernel
function warps(i: int, a: number[], f: float[], ints: int[], masks: int[]) {
const lane = gpuLaneIndex();
const size = gpuWarpSize();
let sum = a[i];
for (let d = size >> 1; d > 0; d = d >> 1) sum += gpuShuffleDown(sum, d);
a[i] = sum + gpuShuffle(a[i], 0) + gpuShuffleXor(a[i], 1);
f[i] = gpuShuffle(f[i], lane + 1) + gpuShuffleXor(f[i], 2);
ints[i] = gpuShuffleDown(ints[i], 3) + gpuShuffleUp(ints[i], 2) + gpuShuffle(7, 0);
const mask = gpuBallot(a[i] > 0);
if (gpuAll(ints[i] > 0) || gpuAny(f[i] < 0)) masks[i] = mask;
}

function main() {
const a: number[] = [1, 2, 3];
const f: float[] = [1, 2, 3];
const ints: int[] = [1, 2, 3];
const masks: int[] = [0, 0, 0];
gpuLaunch(warps, 3, a, f, ints, masks);
}
10 changes: 10 additions & 0 deletions tslang/test/gpu/compile/warp_block.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// a kernel that uses a warp's builtins has blocks of whole warps: 100 threads is not
@kernel({ block: 100 })
function k(i: int, a: number[]) {
a[i] = gpuShuffleDown(a[i], 1);
}

function main() {
const a: number[] = [1, 2, 3];
gpuLaunch(k, 3, a);
}
Loading
Loading