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
30 changes: 19 additions & 11 deletions docs/gpu.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,17 @@ across launches, and a `GpuArray` lives there for as long as the program keeps i
100 elements and changes no others. A call of the kernel on the CPU, `k(i, a)`, works on the same elements
(and a write past them stops the program, as above, rather than reach the elements around a subarray).
Each launch copies it, but inside `gpuBatch` it stays on the GPU between launches (below), as does a
`GpuArray`; `Uint8ClampedArray` and `Float16Array` are not taken. `tslang/test/gpu/gpu_typed_arrays.ts` and
`gpu_batch_views.ts` run them.
`GpuArray`. `tslang/test/gpu/gpu_typed_arrays.ts` and `gpu_batch_views.ts` run them.
- A `Uint8ClampedArray` and a `Float16Array` are taken too, and keep JavaScript's rules in the kernel:
- A `Uint8ClampedArray` (`px: Uint8ClampedArray`) is a `u8[]` there whose writes are clamped as JavaScript's
are: into 0..255, rounded half to even, NaN 0. That is every write to `px[i]`: `=`, `+=` and the rest, `++`
and `--` (`px[i]++` is the element before). `Atomics` on one is an error, as in JavaScript. A function the
kernel hands `px` to sees a `u8[]`, whose writes wrap.
- A `Float16Array` (`h: Float16Array`) is an `f16[]` there: a read is the binary16's value, a write rounds to
the nearest binary16 (ties to even; too large is Infinity). Arithmetic with an integer stays in `f16`
(`h[i] * 2`), with a `number` is in `number`. Intel's GPUs need half floats for it (Xe GPUs have them).
- `tslang/test/gpu/gpu_clamped_half.ts` runs each kernel on the GPU and on the CPU, whose typed arrays are the
default library's, and checks that they agree (ties, the ends, NaN, `++` at 255, overflow to Infinity).
- It can do what a function on numbers and arrays does: arithmetic, branches, loops, locals, other functions of
the program that do the same.
- Of `Math`, it can use:
Expand Down Expand Up @@ -275,7 +284,8 @@ The GPU runs a block's threads in warps, groups whose lanes run each step togeth
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.
as gfx906); 16 on Intel's (each kernel's subgroup is pinned at 16, which every Intel GPU has, so
that all of a program's kernels have the same). 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
Expand Down Expand Up @@ -566,13 +576,11 @@ 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 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
whose CUDA driver is the Windows one's: the running tests below pass there too). The Intel path runs on a Core Ultra
9 285K's integrated GPU (Intel Graphics, Level Zero on Windows): the running tests below and `tslang/test/gpu/faults` pass there,
as executables and under the JIT. The AMD one is checked as far as its compiled code goes (the code object's kernel
table): it has not been run on an AMD 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_warp.ts`, `gpu_scan.ts`, `gpu_structs.ts`.

## Not yet

- `Uint8ClampedArray` and `Float16Array` as kernel arguments.
`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`, `gpu_structs.ts`, `gpu_batch_views.ts`,
`gpu_clamped_half.ts`.
87 changes: 86 additions & 1 deletion tslang/lib/TypeScript/MLIRGenAccessCall.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2795,10 +2795,68 @@ namespace mlirgen
return callOp.getResult(0);
}

// A field of a class's storage by name
static mlir::Type classFieldType(mlir_ts::ClassType classType, StringRef name)
{
auto storageType = dyn_cast<mlir_ts::ClassStorageType>(classType.getStorageType());
if (!storageType)
{
return mlir::Type();
}

for (auto field : storageType.getFields())
{
if (auto id = dyn_cast<mlir::StringAttr>(field.id); id && id.getValue() == name)
{
return field.type;
}
}

return mlir::Type();
}

// The two typed arrays whose element is not a C type, the default library's ConvertingTypedArray<S> around a
// TypedArray<S>: Uint8ClampedArray (S u8), Float16Array (S u16, a binary16's bits). Its inner TypedArray, or
// none for another type.
mlir_ts::ClassType MLIRGenImpl::convertingTypedArrayInner(mlir::Type type)
{
auto classType = dyn_cast_or_null<mlir_ts::ClassType>(type);
if (!classType || !classType.getName().getValue().starts_with("ConvertingTypedArray<"))
{
return mlir_ts::ClassType();
}

return dyn_cast_or_null<mlir_ts::ClassType>(classFieldType(classType, "elements"));
}

// whether a typed array is a Uint8ClampedArray: a kernel's writes to it are clamped (docs/gpu.md)
bool MLIRGenImpl::isClampedTypedArray(mlir::Type type)
{
auto inner = convertingTypedArrayInner(type);
auto element = inner ? typedArrayElementType(inner) : mlir::Type();
auto integerType = dyn_cast_or_null<mlir::IntegerType>(element);
return integerType && integerType.getWidth() == 8;
}

// A typed array (Float32Array and the rest: the default library's TypedArray<T>, a view of `count` elements
// from `first` of a shared T[] store): its T, or none for another type
// from `first` of a shared T[] store): its T, or none for another type. A kernel's element of the two
// converting ones: a Uint8ClampedArray's u8, a Float16Array's f16 (its u16 store is a binary16's bits).
mlir::Type MLIRGenImpl::typedArrayElementType(mlir::Type type)
{
if (auto inner = convertingTypedArrayInner(type))
{
auto element = typedArrayElementType(inner);
if (auto integerType = dyn_cast_or_null<mlir::IntegerType>(element))
{
if (integerType.getWidth() == 16)
return builder.getF16Type();
if (integerType.getWidth() == 8)
return element;
}

return mlir::Type();
}

auto classType = dyn_cast_or_null<mlir_ts::ClassType>(type);
if (!classType || !classType.getName().getValue().starts_with("TypedArray<"))
{
Expand Down Expand Up @@ -2837,6 +2895,18 @@ namespace mlirgen
ValueOrLogicalResult MLIRGenImpl::mlirGenTypedArrayView(mlir::Location location, mlir::Value typedArray,
const GenContext &genContext, mlir::Type asElementType)
{
// a Uint8ClampedArray or Float16Array: the view of the TypedArray inside it, seen as its kernel element
// (a Float16Array's u16 store as f16)
if (auto inner = convertingTypedArrayInner(typedArray.getType()))
{
GenContext classContext(genContext);
classContext.thisClassType = mlir::cast<mlir_ts::ClassType>(typedArray.getType());
auto elements = mlirGenPropertyAccessExpression(location, typedArray, "elements", classContext);
EXIT_IF_FAILED_OR_NO_VALUE(elements)
return mlirGenTypedArrayView(location, V(elements), genContext,
asElementType ? asElementType : typedArrayElementType(typedArray.getType()));
}

auto classType = mlir::cast<mlir_ts::ClassType>(typedArray.getType());
auto elementType = typedArrayElementType(classType);
auto arrayType = mlir_ts::ArrayType::get(elementType);
Expand Down Expand Up @@ -3527,6 +3597,21 @@ namespace mlirgen
}

auto arguments = callExpression->arguments;

// a kernel's Uint8ClampedArray (a u8[] there): JavaScript's Atomics do not take one
if (!arguments.empty() && arguments.front() == SyntaxKind::Identifier && genContext.funcOp)
{
auto funcOp = genContext.funcOp;
auto found = gpuClampedParams.find(funcOp.getName().str());
if (found != gpuClampedParams.end() &&
found->second.count(MLIRHelper::getName(arguments.front().as<Identifier>())))
{
emitError(location) << "Atomics." << op << " does not take a Uint8ClampedArray (JavaScript's does not "
"either): use a Uint8Array";
return mlir::failure();
}
}

auto firstType = evaluate(arguments.front(), genContext);
auto arrayType = firstType ? dyn_cast<mlir_ts::ArrayType>(mth.wideStorageType(mth.stripLiteralType(firstType)))
: mlir_ts::ArrayType();
Expand Down
133 changes: 133 additions & 0 deletions tslang/lib/TypeScript/MLIRGenExpressions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -785,12 +785,23 @@ namespace mlirgen
mlir_ts::BoundIndirectAccessorOp, mlir_ts::BoundIndirectIndexAccessorOp>(defOp);
}

static bool isClampedElement(Expression target, const std::map<std::string, std::set<std::string>> &clamped,
const GenContext &genContext);

ValueOrLogicalResult MLIRGenImpl::mlirGen(PrefixUnaryExpression prefixUnaryExpressionAST, const GenContext &genContext)
{
auto location = loc(prefixUnaryExpressionAST);

auto opCode = prefixUnaryExpressionAST->_operator;

// `++a[i]` on a kernel's Uint8ClampedArray: `a[i] += 1`, clamped
if ((opCode == SyntaxKind::PlusPlusToken || opCode == SyntaxKind::MinusMinusToken) &&
isClampedElement(prefixUnaryExpressionAST->operand, gpuClampedParams, genContext))
{
return mlirGenClampedStep(prefixUnaryExpressionAST->operand, opCode, true, prefixUnaryExpressionAST,
genContext);
}

auto expression = prefixUnaryExpressionAST->operand;
auto result = mlirGen(expression, genContext);
EXIT_IF_FAILED_OR_NO_VALUE(result)
Expand Down Expand Up @@ -885,6 +896,14 @@ namespace mlirgen

auto opCode = postfixUnaryExpressionAST->_operator;

// `a[i]++` on a kernel's Uint8ClampedArray: `a[i] += 1`, clamped, its value the element before
if ((opCode == SyntaxKind::PlusPlusToken || opCode == SyntaxKind::MinusMinusToken) &&
isClampedElement(postfixUnaryExpressionAST->operand, gpuClampedParams, genContext))
{
return mlirGenClampedStep(postfixUnaryExpressionAST->operand, opCode, false, postfixUnaryExpressionAST,
genContext);
}

auto expression = postfixUnaryExpressionAST->operand;
auto result = mlirGen(expression, genContext);
EXIT_IF_FAILED_OR_NO_VALUE(result)
Expand Down Expand Up @@ -1211,12 +1230,126 @@ namespace mlirgen
return ifOp.getResult(0);
}

// JavaScript's ToUint8Clamp, a Uint8ClampedArray's write: into 0..255, rounded half to even, NaN 0. Generic (as
// the Math helpers), so that it is made where it is used: a function made while a kernel was only looked at
// (evaluate) is not kept, though its name would be
static const char *U8_CLAMP_HELPER_SOURCE =
"function __u8_clamp<TU8Clamp = int>(__v: number): number {\n"
" if (!(__v > 0)) return 0;\n"
" if (__v >= 255) return 255;\n"
" const __f = call_intrinsic<number>(\"llvm.floor\", __v);\n"
" const __h = __f + 0.5;\n"
" if (__v > __h) return __f + 1;\n"
" if (__v < __h) return __f;\n"
" return call_intrinsic<number>(\"llvm.floor\", __f * 0.5) * 2 == __f ? __f : __f + 1;\n"
"}\n";

// whether `target` is an element of the current @kernel's Uint8ClampedArray parameter (`a[i]`)
static bool isClampedElement(Expression target, const std::map<std::string, std::set<std::string>> &clamped,
const GenContext &genContext)
{
if (clamped.empty() || !genContext.funcOp || target != SyntaxKind::ElementAccessExpression)
{
return false;
}

auto base = target.as<ElementAccessExpression>()->expression;
if (base != SyntaxKind::Identifier)
{
return false;
}

auto funcOp = genContext.funcOp;
auto found = clamped.find(funcOp.getName().str());
return found != clamped.end() && found->second.count(MLIRHelper::getName(base.as<Identifier>())) > 0;
}

// A write to an element of a kernel's Uint8ClampedArray (a u8[] there) is clamped, as JavaScript's: `a[i] = v`
// is `a[i] = .u8_clamp(v)`, `a[i] += v` is `a[i] = .u8_clamp(a[i] + v)` (docs/gpu.md). The write itself is
// then as any element's, its checks included.
ValueOrLogicalResult MLIRGenImpl::mlirGenClampedWrite(BinaryExpression binaryExpressionAST,
const GenContext &genContext)
{
auto location = loc(binaryExpressionAST);
if (!ensureSourceHelper(location, "u8_clamp", U8_CLAMP_HELPER_SOURCE, genContext))
{
return mlir::failure();
}

auto opCode = (SyntaxKind)binaryExpressionAST->operatorToken;
MLIRLogicHelper::isNeededToSaveData(opCode);
NodeFactory nf(NodeFactoryFlags::None);
Expression value = binaryExpressionAST->right;
if (opCode != SyntaxKind::EqualsToken)
{
value = nf.createBinaryExpression(binaryExpressionAST->left, nf.createToken(opCode), value);
value->pos = binaryExpressionAST->pos;
value->_end = binaryExpressionAST->_end;
}

NodeArray<Expression> arguments;
arguments.push_back(value);
auto clamp = nf.createCallExpression(nf.createIdentifier(S(".u8_clamp")), undefined, arguments);
clamp->pos = binaryExpressionAST->pos;
clamp->_end = binaryExpressionAST->_end;
auto assignment =
nf.createBinaryExpression(binaryExpressionAST->left, nf.createToken(SyntaxKind::EqualsToken), clamp);
assignment->pos = binaryExpressionAST->pos;
assignment->_end = binaryExpressionAST->_end;
return mlirGen(assignment.as<BinaryExpression>(), genContext);
}

// `++a[i]`, `a[i]--` and the rest on a kernel's Uint8ClampedArray: `a[i] += 1` (or -= 1), clamped; the value is
// the element after (prefix) or before (postfix)
ValueOrLogicalResult MLIRGenImpl::mlirGenClampedStep(Expression operand, SyntaxKind opCode, bool prefix, Node at,
const GenContext &genContext)
{
mlir::Value before;
if (!prefix)
{
auto read = mlirGen(operand, genContext);
EXIT_IF_FAILED_OR_NO_VALUE(read)
before = V(read);
}

NodeFactory nf(NodeFactoryFlags::None);
auto step = nf.createBinaryExpression(
operand,
nf.createToken(opCode == SyntaxKind::PlusPlusToken ? SyntaxKind::PlusEqualsToken : SyntaxKind::MinusEqualsToken),
nf.createNumericLiteral(S("1")));
step->pos = at->pos;
step->_end = at->_end;
auto written = mlirGen(step.as<BinaryExpression>(), genContext);
EXIT_IF_FAILED(written)
if (prefix)
{
return mlirGen(operand, genContext);
}

return before;
}

ValueOrLogicalResult MLIRGenImpl::mlirGen(BinaryExpression binaryExpressionAST, const GenContext &genContext)
{
auto location = loc(binaryExpressionAST);

auto opCode = (SyntaxKind)binaryExpressionAST->operatorToken;

// a write to a kernel's Uint8ClampedArray: clamped (once: the rewritten write's value is the clamp's call)
if (isClampedElement(binaryExpressionAST->left, gpuClampedParams, genContext))
{
auto right = binaryExpressionAST->right;
auto isClampCall = opCode == SyntaxKind::EqualsToken && right == SyntaxKind::CallExpression &&
right.as<CallExpression>()->expression == SyntaxKind::Identifier &&
MLIRHelper::getName(right.as<CallExpression>()->expression.as<Identifier>()) == ".u8_clamp";
// `=`, or a compound one (`+=`: isNeededToSaveData says, for those only)
auto assigns = opCode;
if (!isClampCall && (opCode == SyntaxKind::EqualsToken || MLIRLogicHelper::isNeededToSaveData(assigns)))
{
return mlirGenClampedWrite(binaryExpressionAST, genContext);
}
}

auto saveResult = MLIRLogicHelper::isNeededToSaveData(opCode);

auto leftExpression = binaryExpressionAST->left;
Expand Down
7 changes: 7 additions & 0 deletions tslang/lib/TypeScript/MLIRGenFunctions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,13 @@ namespace mlirgen
typedElement && (MLIRHelper::hasDecorator(parametersContextAST, "kernel") ||
MLIRHelper::hasDecorator(parametersContextAST, "gpu")))
{
// a Uint8ClampedArray is a u8[] there whose writes are clamped (mlirGenClampedWrite)
if (isClampedTypedArray(type))
{
gpuClampedParams[MLIRHelper::getName(parametersContextAST->name, stringAllocator).str()]
.insert(namePtr.str());
}

type = mlir_ts::ArrayType::get(typedElement);
}
}
Expand Down
Loading
Loading