From 8a4cf84ce181e1a83fc1bb2899b26c9a0f83bbd9 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Wed, 2 Dec 2026 17:25:02 +0000 Subject: [PATCH 1/2] Uint8ClampedArray and Float16Array as kernel arguments; an f16 with an integer is an f16 The two typed arrays the default library makes as ConvertingTypedArray around a TypedArray are taken by a launch, gpuReduce, gpuBatch and a CPU call as the inner TypedArray's view: a Float16Array's u16 store seen as f16[], a Uint8ClampedArray's as u8[]. A kernel's Uint8ClampedArray parameter keeps JavaScript's rule: each write to its elements (=, +=..., ++/--, the postfix's value the element before) goes through ToUint8Clamp (a generic source helper, .u8_clamp: into 0..255, half to even, NaN 0); Atomics on one is an error, as in JavaScript. Language fix found on the way: the promotion ladder had f16 below s32, so `f16 * 2` was an s32 multiply (0.3 * 2 was 0). f16 now sits with f32, above the 32-bit integers: an f16 with an integer is an f16, as a float is a float. 00f16_conversions.ts checks it. gpu_clamped_half.ts runs each kernel on the GPU and on the CPU (the default library's typed arrays) and they agree: ties, ends, NaN, ++ at 255, binary16 rounding, overflow to Infinity, gpuReduce and gpuBatch; RTX 5080, JIT and exe. Co-Authored-By: Claude Opus 5.5 --- docs/gpu.md | 20 ++- tslang/lib/TypeScript/MLIRGenAccessCall.cpp | 87 +++++++++++- tslang/lib/TypeScript/MLIRGenExpressions.cpp | 133 ++++++++++++++++++ tslang/lib/TypeScript/MLIRGenFunctions.cpp | 7 + tslang/lib/TypeScript/MLIRGenImpl.h | 19 ++- tslang/test/gpu/CMakeLists.txt | 28 ++++ tslang/test/gpu/compile/clamped_atomics.ts | 32 +++++ tslang/test/gpu/compile/clamped_half.ts | 47 +++++++ tslang/test/gpu/gpu_clamped_half.ts | 122 ++++++++++++++++ tslang/test/tester/tests/00f16_conversions.ts | 10 ++ 10 files changed, 495 insertions(+), 10 deletions(-) create mode 100644 tslang/test/gpu/compile/clamped_atomics.ts create mode 100644 tslang/test/gpu/compile/clamped_half.ts create mode 100644 tslang/test/gpu/gpu_clamped_half.ts diff --git a/docs/gpu.md b/docs/gpu.md index c13c67c88..9ad5db8f7 100644 --- a/docs/gpu.md +++ b/docs/gpu.md @@ -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: @@ -571,8 +580,5 @@ far as their compiled code goes (the AMD code object's kernel table, the SPIR-V 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_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`. diff --git a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp index bce4bd49b..7a368cd68 100644 --- a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp +++ b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp @@ -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(classType.getStorageType()); + if (!storageType) + { + return mlir::Type(); + } + + for (auto field : storageType.getFields()) + { + if (auto id = dyn_cast(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 around a + // TypedArray: 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(type); + if (!classType || !classType.getName().getValue().starts_with("ConvertingTypedArray<")) + { + return mlir_ts::ClassType(); + } + + return dyn_cast_or_null(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(element); + return integerType && integerType.getWidth() == 8; + } + // A typed array (Float32Array and the rest: the default library's TypedArray, 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(element)) + { + if (integerType.getWidth() == 16) + return builder.getF16Type(); + if (integerType.getWidth() == 8) + return element; + } + + return mlir::Type(); + } + auto classType = dyn_cast_or_null(type); if (!classType || !classType.getName().getValue().starts_with("TypedArray<")) { @@ -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(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(typedArray.getType()); auto elementType = typedArrayElementType(classType); auto arrayType = mlir_ts::ArrayType::get(elementType); @@ -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()))) + { + 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(mth.wideStorageType(mth.stripLiteralType(firstType))) : mlir_ts::ArrayType(); diff --git a/tslang/lib/TypeScript/MLIRGenExpressions.cpp b/tslang/lib/TypeScript/MLIRGenExpressions.cpp index 679651dab..4670f1885 100644 --- a/tslang/lib/TypeScript/MLIRGenExpressions.cpp +++ b/tslang/lib/TypeScript/MLIRGenExpressions.cpp @@ -785,12 +785,23 @@ namespace mlirgen mlir_ts::BoundIndirectAccessorOp, mlir_ts::BoundIndirectIndexAccessorOp>(defOp); } + static bool isClampedElement(Expression target, const std::map> &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) @@ -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) @@ -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(__v: number): number {\n" + " if (!(__v > 0)) return 0;\n" + " if (__v >= 255) return 255;\n" + " const __f = call_intrinsic(\"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(\"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> &clamped, + const GenContext &genContext) + { + if (clamped.empty() || !genContext.funcOp || target != SyntaxKind::ElementAccessExpression) + { + return false; + } + + auto base = target.as()->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())) > 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 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(), 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(), 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()->expression == SyntaxKind::Identifier && + MLIRHelper::getName(right.as()->expression.as()) == ".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; diff --git a/tslang/lib/TypeScript/MLIRGenFunctions.cpp b/tslang/lib/TypeScript/MLIRGenFunctions.cpp index e2d0f3d34..af2c6b12a 100644 --- a/tslang/lib/TypeScript/MLIRGenFunctions.cpp +++ b/tslang/lib/TypeScript/MLIRGenFunctions.cpp @@ -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); } } diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 5e5f0d087..50142de70 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -12102,9 +12102,11 @@ class MLIRGenImpl // ladder, `u64 * 2` found only the literal's s32 and multiplied in 32 bits. // A bigint is a 64-bit integer, and the rung above the others of its width: missing from the // ladder, `n * 1000000000` found only the literal's s32 and multiplied in 32 bits. + // A float is above the integers of its width and narrower, as `float` is above s32: `f16 * 2` stays an + // f16 (below s32 it was an s32 multiply, 0.3 * 2 was 0 - a Float16Array's element in a kernel). getNumberType(), builder.getF64Type(), getBigIntType(), builder.getI64Type(), SInt(64), UInt(64), builder.getIndexType(), - builder.getF32Type(), SInt(32), builder.getI32Type(), UInt(32), - builder.getF16Type(), SInt(16), builder.getI16Type(), UInt(16), + builder.getF32Type(), builder.getF16Type(), SInt(32), builder.getI32Type(), UInt(32), + SInt(16), builder.getI16Type(), UInt(16), SInt(8), builder.getI8Type(), UInt(8) }; } @@ -14857,6 +14859,19 @@ class MLIRGenImpl mlir::Type typedArrayElementType(mlir::Type type); + mlir_ts::ClassType convertingTypedArrayInner(mlir::Type type); + + bool isClampedTypedArray(mlir::Type type); + + // per @kernel (its name), its Uint8ClampedArray parameters: a write to one of their elements is clamped + // (mlirGenClampedWrite) + std::map> gpuClampedParams; + + ValueOrLogicalResult mlirGenClampedWrite(BinaryExpression binaryExpressionAST, const GenContext &genContext); + + ValueOrLogicalResult mlirGenClampedStep(Expression operand, SyntaxKind opCode, bool prefix, Node at, + const GenContext &genContext); + ValueOrLogicalResult mlirGenTypedArrayView(mlir::Location location, mlir::Value typedArray, const GenContext &genContext, mlir::Type asElementType = mlir::Type()); diff --git a/tslang/test/gpu/CMakeLists.txt b/tslang/test/gpu/CMakeLists.txt index 6c40273b6..6b46702f2 100644 --- a/tslang/test/gpu/CMakeLists.txt +++ b/tslang/test/gpu/CMakeLists.txt @@ -456,6 +456,34 @@ if (gpu_any_backend) FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed" TIMEOUT 120) endif() + # Uint8ClampedArray (1 | 0x80000, its writes clamped) and Float16Array (2 | 0x80000, an f16[]) as kernel + # arguments, for every GPU; Intel's SPIR-V valid; Atomics on a Uint8ClampedArray is an error + add_test(NAME test-gpu-compile-clamped-half + COMMAND $ --emit=llvm --no-default-lib "${gpu_compile_dir}/clamped_half.ts" -o -) + set_tests_properties(test-gpu-compile-clamped-half PROPERTIES + PASS_REGULAR_EXPRESSION "\\[2 x i32\\] \\[i32 524289, i32 -1\\].*\\[1 x i32\\] \\[i32 524290\\]" + FAIL_REGULAR_EXPRESSION "${gpu_fail_pattern}|LLVM ERROR" + TIMEOUT 120) + set(gpu_clamped_environment "") + if (TSLANG_GPU_LLD AND gpu_lld_result EQUAL 0) + list(APPEND gpu_clamped_environment "TSLANG_LLD=${TSLANG_GPU_LLD}") + endif() + if (TSLANG_SPIRV_VAL) + list(APPEND gpu_clamped_environment "TSLANG_GPU_DUMP=${CMAKE_CURRENT_BINARY_DIR}/clamped_half") + set_tests_properties(test-gpu-compile-clamped-half PROPERTIES FIXTURES_SETUP gpu-intel-clamped-half) + add_test(NAME test-gpu-spirv-val-clamped-half + COMMAND "${TSLANG_SPIRV_VAL}" --target-env opencl2.2 "${CMAKE_CURRENT_BINARY_DIR}/clamped_half.intel") + set_tests_properties(test-gpu-spirv-val-clamped-half PROPERTIES FIXTURES_REQUIRED gpu-intel-clamped-half TIMEOUT 60) + endif() + if (gpu_clamped_environment) + set_tests_properties(test-gpu-compile-clamped-half PROPERTIES ENVIRONMENT "${gpu_clamped_environment}") + endif() + add_test(NAME test-gpu-error-clamped-atomics + COMMAND $ --emit=llvm --no-default-lib "${gpu_compile_dir}/clamped_atomics.ts" -o -) + set_tests_properties(test-gpu-error-clamped-atomics PROPERTIES + PASS_REGULAR_EXPRESSION "Atomics\\.add does not take a Uint8ClampedArray" + FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed" TIMEOUT 120) + # a kernel's writes past an array's end are recorded, not trapped: every way of writing an element is guarded # (6 calls of the record, no trap left), and the record is the module's own for the runtime to find; for every # GPU, Intel's SPIR-V valid diff --git a/tslang/test/gpu/compile/clamped_atomics.ts b/tslang/test/gpu/compile/clamped_atomics.ts new file mode 100644 index 000000000..2370a684c --- /dev/null +++ b/tslang/test/gpu/compile/clamped_atomics.ts @@ -0,0 +1,32 @@ +// JavaScript's Atomics do not take a Uint8ClampedArray, nor does a kernel's +class TypedArray { + private store: Shared; + private first: int; + private count: int; + + constructor(data: T[]) { + this.store = new Shared(data); + this.first = 0; + this.count = data.length; + } +} + +class ConvertingTypedArray { + private elements: TypedArray; + + constructor(data: S[]) { + this.elements = new TypedArray(data); + } +} + +type Uint8ClampedArray = ConvertingTypedArray; + +@kernel +function k(i: int, px: Uint8ClampedArray) { + Atomics.add(px, i, 1); +} + +function main() { + const bytes: u8[] = [1]; + gpuLaunch(k, 1, new ConvertingTypedArray(bytes)); +} diff --git a/tslang/test/gpu/compile/clamped_half.ts b/tslang/test/gpu/compile/clamped_half.ts new file mode 100644 index 000000000..828222771 --- /dev/null +++ b/tslang/test/gpu/compile/clamped_half.ts @@ -0,0 +1,47 @@ +// Uint8ClampedArray and Float16Array as kernel arguments (docs/gpu.md), for every GPU: a Uint8ClampedArray is a u8[] +// in a kernel whose writes call the clamp (`=`, `+=`, `++`), a Float16Array an f16[] (a view of its u16 store, +// 2 | 0x80000 in the launch), and `f16 * 2` an f16 multiply. Compiled only (test/gpu/CMakeLists.txt), with no +// default library: the two classes here are laid out as the default library's are. +class TypedArray { + private store: Shared; + private first: int; + private count: int; + + constructor(data: T[], first: int, count: int) { + this.store = new Shared(data); + this.first = first; + this.count = count; + } +} + +class ConvertingTypedArray { + private elements: TypedArray; + + constructor(data: S[]) { + this.elements = new TypedArray(data, 0, data.length); + } +} + +type Uint8ClampedArray = ConvertingTypedArray; +type Float16Array = ConvertingTypedArray; + +@kernel +function brighten(i: int, px: Uint8ClampedArray, by: number) { + px[i] = px[i] * by; + px[i] += 10; + px[i]++; +} + +@kernel +function half(i: int, h: Float16Array) { + h[i] = h[i] * 2 + 0.5; +} + +function main() { + const bytes: u8[] = [1, 2, 3]; + const px = new ConvertingTypedArray(bytes); + gpuLaunch(brighten, 3, px, 1.5); + const bits: u16[] = [0, 15360]; + const h = new ConvertingTypedArray(bits); + gpuLaunch(half, 2, h); +} diff --git a/tslang/test/gpu/gpu_clamped_half.ts b/tslang/test/gpu/gpu_clamped_half.ts new file mode 100644 index 000000000..61105e1bc --- /dev/null +++ b/tslang/test/gpu/gpu_clamped_half.ts @@ -0,0 +1,122 @@ +// Uint8ClampedArray and Float16Array as kernel arguments (docs/gpu.md). In a kernel a Uint8ClampedArray is a u8[] +// whose writes are clamped as JavaScript's are (into 0..255, rounded half to even, NaN 0), by `=`, `+=` and the +// rest, `++` and `--` too; a Float16Array is an f16[]: a write rounds to the nearest binary16, ties to even, too +// large is Infinity. Each kernel runs on the GPU and, the same, on the CPU, whose typed arrays are the default +// library's: the two agree. Needs a GPU and its driver, so it is not part of the test suite. +// +// tslang --emit=exe gpu_clamped_half.ts -o gpu_clamped_half.exe (or tslang --emit=jit gpu_clamped_half.ts) + +@kernel +function scale(i: int, px: Uint8ClampedArray, by: number) { + px[i] = px[i] * by; +} + +@kernel +function darken(i: int, px: Uint8ClampedArray) { + px[i] -= 300; +} + +// each value as it is written: ties, the ends, NaN +@kernel +function put(i: int, px: Uint8ClampedArray, values: number[]) { + px[i] = values[i]; +} + +// ++ and -- at the ends: 255 stays 255, 0 stays 0; a postfix's value is the element before +@kernel +function step(i: int, px: Uint8ClampedArray, before: int[]) { + before[i] = px[i]++; + ++px[i]; + if (i % 2 == 1) { px[i]--; --px[i]; --px[i]; } +} + +@kernel +function half(i: int, h: Float16Array, x: number[]) { + h[i] = h[i] * 2 + x[i]; +} + +@kernel +function halfSum(i: int, h: Float16Array): number { + return h[i]; +} + +function clampedOf(values: number[]): Uint8ClampedArray { + const a = new Uint8ClampedArray(values.length); + for (let i = 0; i < values.length; i++) a[i] = values[i]; + return a; +} + +function main() { + // scaled past 255 on both + const values: number[] = []; + for (let i = 0; i < 1000; i++) values.push(i % 256); + const gpu = clampedOf(values); + const cpu = clampedOf(values); + gpuLaunch(scale, 1000, gpu, 1.7); + for (let i = 0; i < 1000; i++) scale(i, cpu, 1.7); + gpuLaunch(darken, 500, gpu.subarray(0, 500)); + for (let i = 0; i < 500; i++) darken(i, cpu.subarray(0, 500)); + let wrong = 0; + for (let i = 0; i < 1000; i++) if (gpu[i] != cpu[i]) wrong++; + print("scale: gpu[200] =", gpu[200], "gpu[700] =", gpu[700], "gpu[100] =", gpu[100], "wrong =", wrong); + assert(wrong == 0 && gpu[700] == 255 && gpu[200] == 0 && gpu[600] == cpu[600]); + + // ToUint8Clamp's cases + const inputs: number[] = [0.5, 1.5, 2.5, 3.5, -1, 300, 0 / 0, 254.5, 254.51, 255.5, 1 / 0, -1 / 0, 127.49]; + const expected: number[] = [0, 2, 2, 4, 0, 255, 0, 254, 255, 255, 255, 0, 127]; + const ties = new Uint8ClampedArray(inputs.length); + gpuLaunch(put, inputs.length, ties, inputs); + const tiesCpu = new Uint8ClampedArray(inputs.length); + for (let i = 0; i < inputs.length; i++) tiesCpu[i] = inputs[i]; + wrong = 0; + for (let i = 0; i < inputs.length; i++) if (ties[i] != expected[i] || tiesCpu[i] != expected[i]) wrong++; + print("ties:", ties[0], ties[1], ties[2], ties[3], ties[6], ties[7], ties[8], "wrong =", wrong); + assert(wrong == 0); + + // ++ and -- at the ends + const ends = clampedOf([254, 255, 0, 1, 100, 101]); + const before: int[] = [0, 0, 0, 0, 0, 0]; + gpuLaunch(step, 6, ends, before); + const endsCpu = clampedOf([254, 255, 0, 1, 100, 101]); + const beforeCpu: int[] = [0, 0, 0, 0, 0, 0]; + for (let i = 0; i < 6; i++) step(i, endsCpu, beforeCpu); + wrong = 0; + for (let i = 0; i < 6; i++) if (ends[i] != endsCpu[i] || before[i] != beforeCpu[i]) wrong++; + print("steps:", ends[0], ends[1], ends[2], ends[3], ends[4], ends[5], "before", before[1], "wrong =", wrong); + // 254 -> 255 -> 255; 255 -> 255 -> 255, then three down: 252; 1 -> 2 -> 3, three down: 0 + assert(wrong == 0 && ends[0] == 255 && ends[1] == 252 && ends[3] == 0 && before[1] == 255); + + // Float16Array: rounding, the largest binary16, overflow to Infinity + const n = 1000; + const h = new Float16Array(n); + const hCpu = new Float16Array(n); + const x: number[] = []; + for (let i = 0; i < n; i++) { + h[i] = i * 0.1; + hCpu[i] = i * 0.1; + x.push(i == 999 ? 70000 : i == 998 ? 65504 - 998 * 0.1 * 2 : 0.001 * i); + } + gpuLaunch(half, n, h, x); + for (let i = 0; i < n; i++) half(i, hCpu, x); + wrong = 0; + for (let i = 0; i < n; i++) if (h[i] != hCpu[i]) wrong++; + print("half: h[3] =", h[3], "h[500] =", h[500], "h[999] =", h[999], "wrong =", wrong); + assert(wrong == 0 && h[999] == 1 / 0); + + // gpuReduce of a Float16Array's elements, and one kept in gpuBatch + const small = new Float16Array(64); + for (let i = 0; i < 64; i++) small[i] = i * 0.5; + const sum = gpuReduce(halfSum, 64, small); + gpuBatch(() => { + for (let k = 0; k < 4; k++) gpuLaunch(half, 64, small, x); + }); + const smallCpu = new Float16Array(64); + for (let i = 0; i < 64; i++) smallCpu[i] = i * 0.5; + for (let k = 0; k < 4; k++) for (let i = 0; i < 64; i++) half(i, smallCpu, x); + wrong = 0; + for (let i = 0; i < 64; i++) if (small[i] != smallCpu[i]) wrong++; + print("reduce:", sum, "batch: small[10] =", small[10], "wrong =", wrong); + assert(sum == 63 * 64 / 4 && wrong == 0); + + print("clamped and half: ok"); +} diff --git a/tslang/test/tester/tests/00f16_conversions.ts b/tslang/test/tester/tests/00f16_conversions.ts index a0d3211d0..1a05248d1 100644 --- a/tslang/test/tester/tests/00f16_conversions.ts +++ b/tslang/test/tester/tests/00f16_conversions.ts @@ -28,5 +28,15 @@ function main() { assert(1 / back(toHalf(-0)) == -Infinity, "-0 stays -0"); assert(isNaN(back(toHalf(NaN))), "NaN"); assert(back32(toHalf32(3.25)) == 3.25, "through f32"); + + // an f16 with an integer is an f16 (as a float with one is a float): it was an integer, 0.3 * 2 was 0 + const h = toHalf(0.3); + const two = 2; + assert(back(h * 2) == back(toHalf(0.6000976562)), "f16 * 2"); + assert(back(h * two) == back(h * 2), "f16 * an int"); + assert(back(2 * h) == back(h * 2), "2 * f16"); + assert(back(h + 1) == back(toHalf(1.3)), "f16 + 1"); + assert(back(h - 1) == back(toHalf(-0.7)), "f16 - 1"); + assert(h < 1 && h > 0, "f16 compared with ints"); print("done."); } From a47cf736de0b00ffc2059a2b1cda669afe9633fd Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Wed, 2 Dec 2026 18:26:12 +0000 Subject: [PATCH 2/2] GPU on Intel: run on the hardware; shared-memory kernels load, barriers no longer hang, warps of 16, exact float sqrt and ceil First run on an Intel GPU (Core Ultra 9 285K's integrated one, Level Zero on Windows). 19 of the 26 GPU programs passed; these fixes make all 26 pass, as executables and under the JIT, and the 11 fault cases: - Shared-memory kernels did not load: the barrier guard asks to_local(p), and the Intel driver has no to_local for the pointer types the backend gives it. After O3 a pointer followed to its object is known (shared, or not); one known only on the GPU is checked against the shared arrays of the kernels that reach it. - Barrier kernels hung: O3's loop unswitching and jump threading copied OpenCL's barrier, a plain function to them, into branches a block's threads take apart, and an Intel subgroup waits at one copy for its lanes at the other. Every device function is now convergent, as clang has a CUDA or OpenCL one (NVIDIA's bar.sync counts threads, so it ran there). - gpuWarpSize() differed between kernels (the driver picks 8, 16 or 32 per kernel): each Intel kernel's subgroup is pinned at 16 (intel_reqd_sub_group_size), which every Intel GPU has. - A float's sqrt was not correctly rounded (OpenCL allows 3 ulps): the module is built with -cl-fp32-correctly-rounded-divide-sqrt. - Math.ceil of a v in (-1, -0] gave 0, not -0: copysign(ceil(v), v), exact on every GPU. NVIDIA rerun: all 26 programs pass, JIT and exe. GPU and f16 ctests pass (90). Co-Authored-By: Claude Opus 5.5 --- docs/gpu.md | 10 +- .../lib/TypeScriptAsyncRuntime/GpuRuntime.c | 3 +- tslang/tslang/gpu.cpp | 140 +++++++++++++++++- 3 files changed, 147 insertions(+), 6 deletions(-) diff --git a/docs/gpu.md b/docs/gpu.md index 9ad5db8f7..ee26f8b3c 100644 --- a/docs/gpu.md +++ b/docs/gpu.md @@ -284,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 @@ -575,9 +576,10 @@ 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`, `gpu_batch_views.ts`, diff --git a/tslang/lib/TypeScriptAsyncRuntime/GpuRuntime.c b/tslang/lib/TypeScriptAsyncRuntime/GpuRuntime.c index 811506db2..314d9125d 100644 --- a/tslang/lib/TypeScriptAsyncRuntime/GpuRuntime.c +++ b/tslang/lib/TypeScriptAsyncRuntime/GpuRuntime.c @@ -448,8 +448,9 @@ static struct static void *levelZeroLoadModule(const void *code, size_t size, char *log, size_t logSize, GpuResult *result) { + // a float's sqrt and division correctly rounded, as on the CPU and the other GPUs (OpenCL allows 3 ulps) ze_module_desc_t desc = {ZE_STRUCTURE_TYPE_MODULE_DESC, NULL, ZE_MODULE_FORMAT_IL_SPIRV, size, - (const uint8_t *)code, "", NULL}; + (const uint8_t *)code, "-cl-fp32-correctly-rounded-divide-sqrt", NULL}; void *module = NULL; void *buildLog = NULL; *result = ze.zeModuleCreate(ze.context, ze.device, &desc, &module, &buildLog); diff --git a/tslang/tslang/gpu.cpp b/tslang/tslang/gpu.cpp index b93536144..9b60ac367 100644 --- a/tslang/tslang/gpu.cpp +++ b/tslang/tslang/gpu.cpp @@ -55,6 +55,7 @@ #include "llvm/MC/MCSubtargetInfo.h" #include "llvm/MC/TargetRegistry.h" #include "llvm/Support/CommandLine.h" +#include "llvm/Analysis/ValueTracking.h" #include "llvm/Passes/PassBuilder.h" #include "llvm/Support/Error.h" #include "llvm/Support/FileSystem.h" @@ -144,6 +145,8 @@ constexpr int32_t gpuBlockThreads = 256; // the device module's own (guardBarrierKernels): whether a pointer is into the block's shared memory; and a // barrier kernel's mark, whose last parameter is whether the thread runs for an index below n #define IS_SHARED_STUB "__tslang_gpu_is_shared" +// the lanes of an Intel kernel's subgroup (a warp), pinned so that every kernel has the same +#define INTEL_SUBGROUP_SIZE 16 #define ACTIVE_ATTR "tslang.gpu_active" // a kernel's first write past an array's end (recordKernelFaults), which GpuRuntime.c reads after the kernel ran: // { i32 flag, i32 thread, i64 index, i64 length }; the thread (its x) is the GPU's to say @@ -990,7 +993,12 @@ void inlineMathFunctions(llvm::Module &device) {"Math.sqrt", unary(llvm::Intrinsic::sqrt)}, {"Math.abs", unary(llvm::Intrinsic::fabs)}, {"Math.floor", unary(llvm::Intrinsic::floor)}, - {"Math.ceil", unary(llvm::Intrinsic::ceil)}, + // -0 for a v in (-1, -0], which Intel's ceil gives as 0: v's sign is ceil(v)'s for every v + {"Math.ceil", + [](llvm::IRBuilder<> &builder, llvm::Value *v) -> llvm::Value * { + return builder.CreateBinaryIntrinsic(llvm::Intrinsic::copysign, + builder.CreateUnaryIntrinsic(llvm::Intrinsic::ceil, v), v); + }}, {"Math.trunc", unary(llvm::Intrinsic::trunc)}, // halves up: floor(v), plus one when what it dropped is .5 or more; -0 for a v in [-0.5, -0] {"Math.round", @@ -1367,6 +1375,70 @@ std::set reachedFrom(llvm::ArrayRef roots) return reached; } +// the work-group (shared) arrays that the kernels which reach `function` use, there or in what they call +std::vector sharedArraysReaching(llvm::Module &device, llvm::Function *function) +{ + std::set found; + for (auto &entry : device) + { + if (entry.isDeclaration() || entry.getCallingConv() != llvm::CallingConv::SPIR_KERNEL) + { + continue; + } + + auto reached = reachedFrom({&entry}); + if (!reached.count(function)) + { + continue; + } + + llvm::SmallVector work; + llvm::SmallPtrSet seen; + for (auto reachedFunction : reached) + { + for (auto &instruction : llvm::instructions(*reachedFunction)) + { + for (auto &operand : instruction.operands()) + { + if (llvm::isa(operand)) + { + work.push_back(operand); + } + } + } + } + + while (!work.empty()) + { + auto value = work.pop_back_val(); + if (!seen.insert(value).second) + { + continue; + } + + if (auto global = llvm::dyn_cast(value)) + { + if (global->getAddressSpace() == 3) + { + found.insert(global); + } + } + else if (auto constant = llvm::dyn_cast(value)) + { + for (auto &operand : constant->operands()) + { + work.push_back(operand); + } + } + } + } + + // in the order of their names, so that the code is the same from one compile to the next + std::vector arrays(found.begin(), found.end()); + llvm::sort(arrays, [](auto left, auto right) { return left->getName() < right->getName(); }); + return arrays; +} + // an array's { data, length, capacity } header, as LowerToLLVM makes it bool isArrayHeader(llvm::Type *type) { @@ -2417,6 +2489,11 @@ llvm::Expected compileForTarget(const llvm::Module &prepared, break; case GpuTarget::Intel: entry->setCallingConv(llvm::CallingConv::SPIR_KERNEL); + // the driver picks a subgroup (warp) of 8, 16 or 32 per kernel, so one kernel's gpuWarpSize() could + // be another's half (an int kernel 32, a number one 16): each is 16, which every Intel GPU has + entry->setMetadata("intel_reqd_sub_group_size", + llvm::MDNode::get(context, {llvm::ConstantAsMetadata::get( + llvm::ConstantInt::get(i32, INTEL_SUBGROUP_SIZE))})); break; default: entry->setCallingConv(llvm::CallingConv::PTX_Kernel); @@ -2642,6 +2719,18 @@ llvm::Expected compileForTarget(const llvm::Module &prepared, return makeError("the device module is not valid: " + verifyErrors); } + // every function convergent, as clang has a CUDA or OpenCL one: a barrier (and what calls one) is not copied + // into branches that a block's threads take apart, as O3's loop unswitching and jump threading did with + // OpenCL's barrier, a plain function to them; a subgroup of Intel's then waits at one copy for its lanes at the + // other for ever (NVIDIA's bar.sync counts its threads, whichever copy, so it ran there) + for (auto &function : *device) + { + if (!function.isIntrinsic()) + { + function.addFnAttr(llvm::Attribute::Convergent); + } + } + // O3: the kernel inlined into its entry, its locals in registers { llvm::LoopAnalysisManager lam; @@ -2661,6 +2750,55 @@ llvm::Expected compileForTarget(const llvm::Module &prepared, // function has them: reverse post-order is such an order (the Math library's loops were not) if (target.intel()) { + // OpenCL's to_local(p) of a pointer the optimizer has followed to its object is known here: the Intel driver + // has no to_local for a pointer to an array, which is what the backend types a shared array's pointer as + // (the GPU did not load the module), so it is not asked + if (auto toLocal = device->getFunction("_Z8to_localPv")) + { + auto i64 = llvm::Type::getInt64Ty(context); + for (auto user : llvm::make_early_inc_range(toLocal->users())) + { + auto call = llvm::dyn_cast(user); + if (!call || call->getCalledFunction() != toLocal) + { + continue; + } + + auto pointer = call->getArgOperand(0); + auto object = llvm::getUnderlyingObject(pointer, 0); + auto space = llvm::cast(object->getType())->getAddressSpace(); + auto resultType = llvm::cast(call->getType()); + auto local = llvm::ConstantExpr::getIntToPtr(llvm::ConstantInt::get(i64, 1), resultType); + auto notLocal = llvm::ConstantPointerNull::get(resultType); + llvm::Value *result; + if (space != 4) + { + result = space == 3 ? (llvm::Constant *)local : notLocal; + } + else + { + // known only on the GPU: whether it is in one of the shared arrays of the kernels that reach + // the function (theirs already, so no kernel has more of the work-group's memory) + llvm::IRBuilder<> builder(call); + auto address = builder.CreatePtrToInt(pointer, i64); + llvm::Value *inside = builder.getFalse(); + for (auto shared : sharedArraysReaching(*device, call->getFunction())) + { + auto first = builder.CreatePtrToInt(builder.CreateAddrSpaceCast(shared, pointer->getType()), i64); + auto size = device->getDataLayout().getTypeAllocSize(shared->getValueType()); + auto end = builder.CreateAdd(first, llvm::ConstantInt::get(i64, size)); + inside = builder.CreateOr(inside, builder.CreateAnd(builder.CreateICmpUGE(address, first), + builder.CreateICmpULT(address, end))); + } + + result = builder.CreateSelect(inside, local, notLocal); + } + + call->replaceAllUsesWith(result); + call->eraseFromParent(); + } + } + for (auto &function : *device) { if (function.isDeclaration())