From b9898f041764c1affabd43d007dd349b277df540 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Wed, 2 Dec 2026 14:53:31 +0000 Subject: [PATCH 1/2] GPU: a kernel's write past an array's end is reported by name, on every GPU, instead of a bare driver error A trap made it "running the kernel failed (719 unspecified launch failure)" on NVIDIA and AMD, and undefined on Intel. Now each element write in a kernel that does not wait at a barrier (a store, +=, Atomics, a tuple's field or whole element, in the kernel or a function it calls) is made only inside the array; the first one past the end is recorded in the module's __tslang_gpu_fault (a cmpxchg on its flag, then thread, index, length), and the runtime reads it where it waits for the kernel (the launch's own sync, gpuWait, the program's end) and stops: "tslang gpu: the kernel 'k' wrote past the end of an array: element 1000 of 1000 (GPU thread 995)", exit 1. The compiler's own check before a write goes only where that write is guarded; any other stays a trap. Drivers look the record up with cuModuleGetGlobal_v2 / hipModuleGetGlobal / zeModuleGetGlobalPointer, optional (missing: no report, the driver still runs). Barrier kernels keep dropping such writes silently. The write costs the one comparison it had; a launch's time is unchanged (0.066 ms median either way). tslang/test/gpu/faults/ has a program per way of writing: all 11 report right on the RTX 5080, JIT and exe. Co-Authored-By: Claude Opus 5.5 --- docs/gpu.md | 20 +- .../lib/TypeScriptAsyncRuntime/GpuRuntime.c | 153 ++++++++- tslang/test/gpu/CMakeLists.txt | 30 ++ tslang/test/gpu/compile/faults.ts | 23 ++ tslang/test/gpu/faults/README.md | 11 + tslang/test/gpu/faults/add_assign.ts | 13 + tslang/test/gpu/faults/atomics.ts | 12 + tslang/test/gpu/faults/batch.ts | 14 + tslang/test/gpu/faults/element.ts | 12 + tslang/test/gpu/faults/field.ts | 12 + tslang/test/gpu/faults/gpu_array_end.ts | 12 + tslang/test/gpu/faults/gpu_array_read.ts | 14 + tslang/test/gpu/faults/helper.ts | 17 + tslang/test/gpu/faults/negative.ts | 12 + tslang/test/gpu/faults/store.ts | 13 + tslang/test/gpu/faults/typed_array.ts | 12 + tslang/tslang/gpu.cpp | 293 +++++++++++++++--- 17 files changed, 622 insertions(+), 51 deletions(-) create mode 100644 tslang/test/gpu/compile/faults.ts create mode 100644 tslang/test/gpu/faults/README.md create mode 100644 tslang/test/gpu/faults/add_assign.ts create mode 100644 tslang/test/gpu/faults/atomics.ts create mode 100644 tslang/test/gpu/faults/batch.ts create mode 100644 tslang/test/gpu/faults/element.ts create mode 100644 tslang/test/gpu/faults/field.ts create mode 100644 tslang/test/gpu/faults/gpu_array_end.ts create mode 100644 tslang/test/gpu/faults/gpu_array_read.ts create mode 100644 tslang/test/gpu/faults/helper.ts create mode 100644 tslang/test/gpu/faults/negative.ts create mode 100644 tslang/test/gpu/faults/store.ts create mode 100644 tslang/test/gpu/faults/typed_array.ts diff --git a/docs/gpu.md b/docs/gpu.md index 3f2d19806..77e8042b6 100644 --- a/docs/gpu.md +++ b/docs/gpu.md @@ -77,10 +77,22 @@ across launches, and a `GpuArray` lives there for as long as the program keeps i error: gpuLaunch: a kernel reads the program's variable 'scale', which the GPU does not share: pass it to the kernel as an argument ``` -- A write past an array's end, which would grow it on the CPU, stops the kernel with a trap on NVIDIA and AMD. - On Intel it is undefined. In a kernel that waits at `gpuBarrier` it does nothing instead (below). A kernel - called on the CPU does not grow the array either: the write stops the program (`a kernel called on the CPU - wrote past the end of an array`). +- A write past an array's end (or below 0), which would grow the array on the CPU, is not made on the GPU: the + kernel records the first one and goes on, and after it has run the program stops, saying where: + + ``` + tslang gpu: the kernel 'k' wrote past the end of an array: element 1000 of 1000 (GPU thread 995) + ``` + + with exit code 1. That is every way of writing an element: `a[i] = v`, `a[i] += v`, an `Atomics`, a field of a + tuple element (`ps[i].y = v`), a whole element, in the kernel or in a function it calls, on any GPU. The + thread is its `x` among the launch's threads (`i` for `gpuLaunch(k, n, ...)`). A launch that does not wait for + its kernel (its arrays are all `GpuArray`s, or inside `gpuBatch`) reports it where the runtime next waits: + `gpuRead`, `gpuWrite`, `gpuFree`, the batch's end, or the program's end. The check is the one the CPU makes + before such a write anyway, a comparison per write. In a kernel that waits at `gpuBarrier` such a write does + nothing instead, silently (below). A kernel called on the CPU does not grow the array either: the write stops + the program (`a kernel called on the CPU wrote past the end of an array`). `tslang/test/gpu/faults/` has a + program for each way. - `gpuLaunch`, `gpuReduce` and `gpuBatch` need the default memory model (`-mm=gc`). ## The GPU's `Math` library diff --git a/tslang/lib/TypeScriptAsyncRuntime/GpuRuntime.c b/tslang/lib/TypeScriptAsyncRuntime/GpuRuntime.c index cd3f413a0..20de901a7 100644 --- a/tslang/lib/TypeScriptAsyncRuntime/GpuRuntime.c +++ b/tslang/lib/TypeScriptAsyncRuntime/GpuRuntime.c @@ -92,6 +92,9 @@ typedef struct GpuResult (*synchronize)(void); const char *(*errorText)(GpuResult result); GpuResult (*makeCurrent)(void); // before a launch from this thread (CUDA's context); may be NULL + // where a module's global variable is on the GPU, and its bytes; NULL when the driver has no such entry point + // (then a kernel's faults are not reported by name: gpuFaultWatch) + GpuResult (*getGlobal)(void *module, const char *name, GpuPtr *ptr, size_t *bytes); } GpuDriver; static void gpuFail(GpuDriver *driver, const char *what, GpuResult r) @@ -160,6 +163,7 @@ static struct void **, void **); GpuResult (*cuCtxSynchronize)(void); GpuResult (*cuGetErrorString)(GpuResult, const char **); + GpuResult (*cuModuleGetGlobal)(GpuPtr *, size_t *, void *, const char *); void *ctx; } cu; @@ -194,9 +198,13 @@ static const char *cudaErrorText(GpuResult r) return text; } static GpuResult cudaMakeCurrent(void) { return cu.cuCtxSetCurrent(cu.ctx); } +static GpuResult cudaGetGlobal(void *module, const char *name, GpuPtr *ptr, size_t *bytes) +{ + return cu.cuModuleGetGlobal(ptr, bytes, module, name); +} static GpuDriver cudaDriver = {"cuda", 0, "", cudaLoadModule, cudaGetFunction, cudaAlloc, cudaFree, cudaToDevice, - cudaToHost, cudaLaunch, cudaSynchronize, cudaErrorText, cudaMakeCurrent}; + cudaToHost, cudaLaunch, cudaSynchronize, cudaErrorText, cudaMakeCurrent, NULL}; static GpuDriver *cudaInit(void) { @@ -217,6 +225,9 @@ static GpuDriver *cudaInit(void) GPU_SYM(driver, lib, cu.cuLaunchKernel, "cuLaunchKernel"); GPU_SYM(driver, lib, cu.cuCtxSynchronize, "cuCtxSynchronize"); GPU_SYM(driver, lib, cu.cuGetErrorString, "cuGetErrorString"); + // optional: without it the driver still runs kernels, only not reporting their faults by name + if ((*(void **)&cu.cuModuleGetGlobal = gpuSym(lib, "cuModuleGetGlobal_v2"))) + driver->getGlobal = cudaGetGlobal; int dev; GpuResult r = cu.cuInit(0); if (r != 0) @@ -247,6 +258,7 @@ static struct void *, void **, void **); GpuResult (*hipDeviceSynchronize)(void); const char *(*hipGetErrorString)(GpuResult); + GpuResult (*hipModuleGetGlobal)(void **, size_t *, void *, const char *); } hip; static void *hipLoadModule(const void *code, size_t size, char *log, size_t logSize, GpuResult *result) @@ -286,9 +298,16 @@ static GpuResult hipLaunch(void *fn, const unsigned *grid, const unsigned *block static GpuResult hipSynchronize(void) { return hip.hipDeviceSynchronize(); } static const char *hipErrorText(GpuResult r) { return hip.hipGetErrorString ? hip.hipGetErrorString(r) : ""; } static GpuResult hipMakeCurrent(void) { return hip.hipSetDevice(0); } +static GpuResult hipGetGlobal(void *module, const char *name, GpuPtr *ptr, size_t *bytes) +{ + void *p = NULL; + GpuResult r = hip.hipModuleGetGlobal(&p, bytes, module, name); + *ptr = (GpuPtr)(uintptr_t)p; + return r; +} static GpuDriver hipDriver = {"hip", 0, "", hipLoadModule, hipGetFunction, hipAlloc, hipFreeBuffer, hipToDevice, - hipToHost, hipLaunch, hipSynchronize, hipErrorText, hipMakeCurrent}; + hipToHost, hipLaunch, hipSynchronize, hipErrorText, hipMakeCurrent, NULL}; static GpuDriver *hipInitDriver(void) { @@ -307,6 +326,8 @@ static GpuDriver *hipInitDriver(void) GPU_SYM(driver, lib, hip.hipModuleLaunchKernel, "hipModuleLaunchKernel"); GPU_SYM(driver, lib, hip.hipDeviceSynchronize, "hipDeviceSynchronize"); GPU_SYM(driver, lib, hip.hipGetErrorString, "hipGetErrorString"); + if ((*(void **)&hip.hipModuleGetGlobal = gpuSym(lib, "hipModuleGetGlobal"))) + driver->getGlobal = hipGetGlobal; GpuResult r = hip.hipInit(0); if (r != 0) return gpuUnusable(driver, "hipInit failed: no AMD GPU", r); @@ -413,6 +434,7 @@ static struct GpuResult (*zeKernelSetIndirectAccess)(void *, uint32_t); GpuResult (*zeCommandListAppendLaunchKernel)(void *, void *, const ze_group_count_t *, void *, uint32_t, void **); GpuResult (*zeDriverGetLastErrorDescription)(void *, const char **); // since 1.6; may be missing + GpuResult (*zeModuleGetGlobalPointer)(void *, const char *, size_t *, void **); void *driver; void *device; void *context; @@ -510,9 +532,17 @@ static const char *levelZeroErrorText(GpuResult r) return text; } +static GpuResult levelZeroGetGlobal(void *module, const char *name, GpuPtr *ptr, size_t *bytes) +{ + void *p = NULL; + GpuResult r = ze.zeModuleGetGlobalPointer(module, name, bytes, &p); + *ptr = (GpuPtr)(uintptr_t)p; + return r; +} + static GpuDriver levelZeroDriver = {"level zero", 0, "", levelZeroLoadModule, levelZeroGetFunction, levelZeroAlloc, levelZeroFree, levelZeroToDevice, levelZeroToHost, - levelZeroLaunch, levelZeroSynchronize, levelZeroErrorText, NULL}; + levelZeroLaunch, levelZeroSynchronize, levelZeroErrorText, NULL, NULL}; static GpuDriver *levelZeroInit(void) { @@ -539,6 +569,8 @@ static GpuDriver *levelZeroInit(void) GPU_SYM(driver, lib, ze.zeKernelSetIndirectAccess, "zeKernelSetIndirectAccess"); GPU_SYM(driver, lib, ze.zeCommandListAppendLaunchKernel, "zeCommandListAppendLaunchKernel"); *(void **)&ze.zeDriverGetLastErrorDescription = gpuSym(lib, "zeDriverGetLastErrorDescription"); + if ((*(void **)&ze.zeModuleGetGlobalPointer = gpuSym(lib, "zeModuleGetGlobalPointer"))) + driver->getGlobal = levelZeroGetGlobal; // GPU drivers only (not the NPU's), and of their devices the first GPU if (ze.zeInit(ZE_INIT_FLAG_GPU_ONLY) == 0) @@ -684,6 +716,97 @@ static void gpuAppend(char *text, size_t size, const char *line) snprintf(text + used, size - used, " %s\n", line); } +// ---- a kernel's fault: a write past an array's end +// +// On the GPU such a write is not made (there is no growing an array there): the kernel records the first one in +// its module's global `__tslang_gpu_fault` (tslang/gpu.cpp's recordKernelFaults) and goes on. After the kernel has +// run, wherever the runtime waits for it, the record is read, and a fault stops the program, as the same write +// past the end does in a kernel called on the CPU. +typedef struct +{ + int32_t flag; // 1: a fault is recorded + int32_t thread; // the GPU thread that made it (its x) + int64_t index; // the element written + int64_t length; // the array's length +} GpuFault; + +#define GPU_FAULT_GLOBAL "__tslang_gpu_fault" + +static struct +{ + GpuDriver *driver; + GpuPtr record; +} gpuFaults[16]; +static int gpuFaultCount; + +// a kernel queued without waiting for it (gpuLaunched): the last one's name, and how many since the last wait +static const char *gpuQueuedKernel; +static int gpuQueuedCount; + +static void gpuFaultWatch(GpuDriver *driver, void *module) +{ + GpuPtr record = 0; + size_t bytes = 0; + if (!driver->getGlobal || gpuFaultCount >= 16 || + driver->getGlobal(module, GPU_FAULT_GLOBAL, &record, &bytes) != 0 || !record || bytes < sizeof(GpuFault)) + return; + gpuFaults[gpuFaultCount].driver = driver; + gpuFaults[gpuFaultCount++].record = record; +} + +// the program's name of a kernel's entry: __gpu_k, __gpu_k_2d, __gpu_reduce_k are k's +static void gpuKernelName(const char *entry, char *name, size_t size) +{ + const char *start = entry; + if (strncmp(start, "__gpu_reduce_", 13) == 0) + start += 13; + else if (strncmp(start, "__gpu_", 6) == 0) + start += 6; + size_t length = strlen(start); + if (length > 3 && start[length - 3] == '_' && (start[length - 2] == '2' || start[length - 2] == '3') && + start[length - 1] == 'd') + length -= 3; + snprintf(name, size, "%.*s", (int)length, start); +} + +// After `driver` has run its kernels: 1 when one of them recorded a fault, said on stderr. `entry` is the kernel +// waited for, or NULL for those queued since the last wait. +static int gpuFaultReport(GpuDriver *driver, const char *entry) +{ + for (int i = 0; i < gpuFaultCount; i++) + { + GpuFault fault; + if (gpuFaults[i].driver != driver || driver->toHost(&fault, gpuFaults[i].record, sizeof(fault)) != 0 || + !fault.flag) + continue; + + char name[256]; + char which[512]; + if (!entry && gpuQueuedCount == 1) + entry = gpuQueuedKernel; + if (entry) + { + gpuKernelName(entry, name, sizeof(name)); + snprintf(which, sizeof(which), "the kernel '%s'", name); + } + else + { + gpuKernelName(gpuQueuedKernel ? gpuQueuedKernel : "?", name, sizeof(name)); + snprintf(which, sizeof(which), + "a kernel launched since the last wait (the last was '%s'; TSLANG_GPU_SYNC=1 says which)", name); + } + + // what the program printed comes first + fflush(stdout); + fprintf(stderr, "tslang gpu: %s wrote past the end of an array: element %lld of %lld (GPU thread %d)\n", + which, (long long)fault.index, (long long)fault.length, fault.thread); + fflush(stderr); + return 1; + } + + return 0; +} + static GpuDriver *gpuChoose(const TsGpuImage *images, int32_t imageCount, void **module) { for (int i = 0; i < gpuChosenCount; i++) @@ -728,6 +851,7 @@ static GpuDriver *gpuChoose(const TsGpuImage *images, int32_t imageCount, void * if (getenv("TSLANG_GPU_VERBOSE")) fprintf(stderr, "tslang gpu: running the kernels through %s (%s)\n", driver->name, images[i].arch); + gpuFaultWatch(driver, loaded); if (gpuChosenCount < 16) { gpuChosen[gpuChosenCount].images = images; @@ -822,6 +946,9 @@ static void gpuWait(void) if (driver->makeCurrent) GPU(driver, driver->makeCurrent(), "making the GPU current"); GPU(driver, driver->synchronize(), "running a kernel (an earlier launch's: TSLANG_GPU_SYNC=1 says which)"); + if (gpuFaultReport(driver, NULL)) + exit(1); + gpuQueuedCount = 0; } // At the program's end: the launches still running finish, and an error of theirs is reported. 0, or 1 when a @@ -837,7 +964,7 @@ TSLANG_GPU_EXPORT int __tslang_gpu_finish(void) if (r == 0) r = driver->synchronize(); if (r == 0) - return 0; + return gpuFaultReport(driver, NULL); // what the program printed comes first fflush(stdout); const char *text = driver->errorText ? driver->errorText(r) : ""; @@ -856,7 +983,7 @@ static void gpuWaitAtExit(void) } } -static void gpuLaunched(GpuDriver *driver) +static void gpuLaunched(GpuDriver *driver, const char *entry) { static int atExit; if (!atExit) @@ -868,6 +995,8 @@ static void gpuLaunched(GpuDriver *driver) if (gpuPending && gpuPending != driver) gpuWait(); gpuPending = driver; + gpuQueuedKernel = entry; + gpuQueuedCount++; } // ---- gpuBatch: arrays that stay on the GPU between launches @@ -1478,12 +1607,24 @@ TSLANG_GPU_EXPORT void __tslang_gpu_run(const TsGpuImage *images, int32_t imageC if (copied || gpuSyncEachLaunch()) { GPU(driver, driver->synchronize(), "running the kernel"); + // the kernels queued before it ran too: a fault is this one's, or one of theirs + int queued = gpuPending == driver && gpuQueuedCount > 0; + if (queued) + { + gpuQueuedKernel = kernelName; + gpuQueuedCount++; + } + if (gpuFaultReport(driver, queued ? NULL : kernelName)) + exit(1); if (gpuPending == driver) + { gpuPending = NULL; + gpuQueuedCount = 0; + } } else { - gpuLaunched(driver); + gpuLaunched(driver, kernelName); } double ran = profile ? gpuNow() : 0; diff --git a/tslang/test/gpu/CMakeLists.txt b/tslang/test/gpu/CMakeLists.txt index 62774cfd7..ab27b200b 100644 --- a/tslang/test/gpu/CMakeLists.txt +++ b/tslang/test/gpu/CMakeLists.txt @@ -456,6 +456,36 @@ if (gpu_any_backend) FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed" TIMEOUT 120) endif() + # 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 + set(gpu_faults_pass "call void @__tslang_gpu_run") + if ("NVPTX" IN_LIST LLVM_TARGETS_TO_BUILD) + # (CMake's expressions have no {6}) + set(gpu_faults_call ".*call\\.uni __tslang_gpu_fault_record") + set(gpu_faults_pass "\\.visible \\.global \\.align 8 \\.b8 __tslang_gpu_fault\\[24\\]${gpu_faults_call}${gpu_faults_call}${gpu_faults_call}${gpu_faults_call}${gpu_faults_call}${gpu_faults_call}") + endif() + add_test(NAME test-gpu-compile-faults + COMMAND $ --emit=llvm --no-default-lib "${gpu_compile_dir}/faults.ts" -o -) + set_tests_properties(test-gpu-compile-faults PROPERTIES + PASS_REGULAR_EXPRESSION "${gpu_faults_pass}" + FAIL_REGULAR_EXPRESSION "${gpu_fail_pattern}|LLVM ERROR|trap;" + TIMEOUT 120) + set(gpu_faults_environment "") + if (TSLANG_GPU_LLD AND gpu_lld_result EQUAL 0) + list(APPEND gpu_faults_environment "TSLANG_LLD=${TSLANG_GPU_LLD}") + endif() + if (TSLANG_SPIRV_VAL) + list(APPEND gpu_faults_environment "TSLANG_GPU_DUMP=${CMAKE_CURRENT_BINARY_DIR}/faults") + set_tests_properties(test-gpu-compile-faults PROPERTIES FIXTURES_SETUP gpu-intel-faults) + add_test(NAME test-gpu-spirv-val-faults + COMMAND "${TSLANG_SPIRV_VAL}" --target-env opencl2.2 "${CMAKE_CURRENT_BINARY_DIR}/faults.intel") + set_tests_properties(test-gpu-spirv-val-faults PROPERTIES FIXTURES_REQUIRED gpu-intel-faults TIMEOUT 60) + endif() + if (gpu_faults_environment) + set_tests_properties(test-gpu-compile-faults PROPERTIES ENVIRONMENT "${gpu_faults_environment}") + endif() + # arrays of tuples and object types: each element's bytes as LLVM lays them out (Mixed 32 with its padding, # [number, int] 16 and only read, 0x10000), for every GPU; Intel's SPIR-V valid add_test(NAME test-gpu-compile-structs diff --git a/tslang/test/gpu/compile/faults.ts b/tslang/test/gpu/compile/faults.ts new file mode 100644 index 000000000..f75031b69 --- /dev/null +++ b/tslang/test/gpu/compile/faults.ts @@ -0,0 +1,23 @@ +// every way a kernel writes an element is guarded and recorded, so no trap is left: a store, `+=`, an Atomics, a +// tuple's field, a whole element, a helper's write (a typed array's: faults/typed_array.ts) +function put(a: number[], at: int, v: number) { + a[at] = v; +} + +@kernel +function k(i: int, a: number[], counts: int[], ps: { x: number, y: number }[], ts: [number, int][]) { + a[i + 1] = i; + counts[i] += 2; + Atomics.add(counts, i, 1); + ps[i].y = 3; + ts[i] = [i, i]; + put(a, i + 2, 1); +} + +function main() { + const a: number[] = [0]; + const counts: int[] = [0]; + const ps: { x: number, y: number }[] = [{ x: 0, y: 0 }]; + const ts: [number, int][] = [[0, 0]]; + gpuLaunch(k, 1, a, counts, ps, ts); +} diff --git a/tslang/test/gpu/faults/README.md b/tslang/test/gpu/faults/README.md new file mode 100644 index 000000000..73a763c79 --- /dev/null +++ b/tslang/test/gpu/faults/README.md @@ -0,0 +1,11 @@ +# Kernel faults + +Each program here has a kernel write past the end of an array, in one way or another, on the GPU. That write is not +made, and the program stops after the kernel with (on stderr, exit code 1): + + tslang gpu: the kernel 'k' wrote past the end of an array: element of (GPU thread ) + +Each prints `before` first, and never `after`. They need a GPU and its driver, so they are not part of the test +suite; run each under the JIT and as an executable: + + for f in tslang/test/gpu/faults/*.ts; do tslang --emit=jit $f; echo "exit $?"; done diff --git a/tslang/test/gpu/faults/add_assign.ts b/tslang/test/gpu/faults/add_assign.ts new file mode 100644 index 000000000..80b192070 --- /dev/null +++ b/tslang/test/gpu/faults/add_assign.ts @@ -0,0 +1,13 @@ +// `+=` past the end (a read and a write) +@kernel +function k(i: int, a: int[]) { + a[i * 2] += 1; +} + +function main() { + const a: int[] = []; + for (let i = 0; i < 100; i++) a.push(0); + print("before"); + gpuLaunch(k, 100, a); + print("after"); +} diff --git a/tslang/test/gpu/faults/atomics.ts b/tslang/test/gpu/faults/atomics.ts new file mode 100644 index 000000000..e91d96a84 --- /dev/null +++ b/tslang/test/gpu/faults/atomics.ts @@ -0,0 +1,12 @@ +// an Atomics past the end +@kernel +function k(i: int, counts: int[]) { + Atomics.add(counts, i, 1); +} + +function main() { + const counts: int[] = [0, 0, 0]; + print("before"); + gpuLaunch(k, 64, counts); + print("after"); +} diff --git a/tslang/test/gpu/faults/batch.ts b/tslang/test/gpu/faults/batch.ts new file mode 100644 index 000000000..1ca1b89fb --- /dev/null +++ b/tslang/test/gpu/faults/batch.ts @@ -0,0 +1,14 @@ +// inside gpuBatch: reported at the batch's end, where its arrays are copied back +@kernel +function k(i: int, a: number[]) { + a[i + 2] = i; +} + +function main() { + const a: number[] = [0, 0, 0, 0]; + print("before"); + gpuBatch(() => { + gpuLaunch(k, 4, a); + }); + print("after"); +} diff --git a/tslang/test/gpu/faults/element.ts b/tslang/test/gpu/faults/element.ts new file mode 100644 index 000000000..22c470cd1 --- /dev/null +++ b/tslang/test/gpu/faults/element.ts @@ -0,0 +1,12 @@ +// a whole tuple element past the end +@kernel +function k(i: int, ps: [number, int][]) { + ps[i + 3] = [i, i]; +} + +function main() { + const ps: [number, int][] = [[0, 0], [0, 0], [0, 0]]; + print("before"); + gpuLaunch(k, 3, ps); + print("after"); +} diff --git a/tslang/test/gpu/faults/field.ts b/tslang/test/gpu/faults/field.ts new file mode 100644 index 000000000..180d836f8 --- /dev/null +++ b/tslang/test/gpu/faults/field.ts @@ -0,0 +1,12 @@ +// a field of a tuple element past the end +@kernel +function k(i: int, ps: { x: number, y: number }[]) { + ps[i + 1].y = i; +} + +function main() { + const ps: { x: number, y: number }[] = [{ x: 0, y: 0 }, { x: 0, y: 0 }]; + print("before"); + gpuLaunch(k, 2, ps); + print("after"); +} diff --git a/tslang/test/gpu/faults/gpu_array_end.ts b/tslang/test/gpu/faults/gpu_array_end.ts new file mode 100644 index 000000000..ed4a519b0 --- /dev/null +++ b/tslang/test/gpu/faults/gpu_array_end.ts @@ -0,0 +1,12 @@ +// a launch on a GpuArray nothing waits for: its fault is reported when the program ends +@kernel +function k(i: int, a: number[]) { + a[i + 1] = i; +} + +function main() { + const a: number[] = [0, 0, 0, 0]; + const onGpu = gpuArray(a); + gpuLaunch(k, 4, onGpu); + print("before"); +} diff --git a/tslang/test/gpu/faults/gpu_array_read.ts b/tslang/test/gpu/faults/gpu_array_read.ts new file mode 100644 index 000000000..098f7f94b --- /dev/null +++ b/tslang/test/gpu/faults/gpu_array_read.ts @@ -0,0 +1,14 @@ +// a launch on a GpuArray does not wait for the kernel: its fault is reported at gpuRead, which waits +@kernel +function k(i: int, a: number[]) { + a[i + 1] = i; +} + +function main() { + const a: number[] = [0, 0, 0, 0]; + const onGpu = gpuArray(a); + gpuLaunch(k, 4, onGpu); + print("before"); + gpuRead(onGpu, a); + print("after"); +} diff --git a/tslang/test/gpu/faults/helper.ts b/tslang/test/gpu/faults/helper.ts new file mode 100644 index 000000000..6763427a4 --- /dev/null +++ b/tslang/test/gpu/faults/helper.ts @@ -0,0 +1,17 @@ +// a write past the end in a function the kernel calls (not a kernel itself: its write would grow the array on the +// CPU) +function put(a: number[], at: int, v: number) { + a[at] = v; +} + +@kernel +function k(i: int, a: number[]) { + put(a, i + 1, i); +} + +function main() { + const a: number[] = [0, 0, 0, 0]; + print("before"); + gpuLaunch(k, 4, a); + print("after"); +} diff --git a/tslang/test/gpu/faults/negative.ts b/tslang/test/gpu/faults/negative.ts new file mode 100644 index 000000000..425952e55 --- /dev/null +++ b/tslang/test/gpu/faults/negative.ts @@ -0,0 +1,12 @@ +// an index below 0 is past the end too +@kernel +function k(i: int, a: number[]) { + a[i - 1] = i; +} + +function main() { + const a: number[] = [0, 0, 0]; + print("before"); + gpuLaunch(k, 3, a); + print("after"); +} diff --git a/tslang/test/gpu/faults/store.ts b/tslang/test/gpu/faults/store.ts new file mode 100644 index 000000000..90f3aede9 --- /dev/null +++ b/tslang/test/gpu/faults/store.ts @@ -0,0 +1,13 @@ +// a plain store past the end, by the last five threads +@kernel +function k(i: int, a: number[]) { + a[i + 5] = i; +} + +function main() { + const a: number[] = []; + for (let i = 0; i < 1000; i++) a.push(0); + print("before"); + gpuLaunch(k, 1000, a); + print("after"); +} diff --git a/tslang/test/gpu/faults/typed_array.ts b/tslang/test/gpu/faults/typed_array.ts new file mode 100644 index 000000000..4f83cc34f --- /dev/null +++ b/tslang/test/gpu/faults/typed_array.ts @@ -0,0 +1,12 @@ +// a typed array's view: past its end, not past the buffer's (the elements after the subarray are not touched) +@kernel +function k(i: int, a: Float32Array) { + a[i + 1] = 7; +} + +function main() { + const big = new Float32Array(10); + print("before"); + gpuLaunch(k, 5, big.subarray(0, 5)); + print("after"); +} diff --git a/tslang/tslang/gpu.cpp b/tslang/tslang/gpu.cpp index 8f440b9eb..b93536144 100644 --- a/tslang/tslang/gpu.cpp +++ b/tslang/tslang/gpu.cpp @@ -145,6 +145,11 @@ constexpr int32_t gpuBlockThreads = 256; // 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" #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 +#define FAULT_GLOBAL "__tslang_gpu_fault" +#define FAULT_RECORD_FUNCTION "__tslang_gpu_fault_record" +#define FAULT_THREAD_STUB "__tslang_gpu_fault_thread" // What a warp's threads share (MLIRGenImpl::mlirGenGpuWarpBuiltin; docs/gpu.md): its lanes run together, and a // kernel that uses these runs like a barrier kernel, on every thread of its blocks (reachesBarrier), so that no // lane of a warp is left out by the `i < n` check. gpuShuffle's stubs are @@ -204,7 +209,8 @@ bool isBlockBuiltin(llvm::StringRef name) { auto stub = blockBuiltinOf(name).first; return stub == THREAD_INDEX_STUB || stub == BLOCK_INDEX_STUB || stub == BLOCK_SIZE_STUB || name == BARRIER_STUB || - name.starts_with(SHARED_STUB_PREFIX) || name == IS_SHARED_STUB || name.starts_with(WARP_STUB_PREFIX); + name.starts_with(SHARED_STUB_PREFIX) || name == IS_SHARED_STUB || name.starts_with(WARP_STUB_PREFIX) || + name == FAULT_THREAD_STUB; } BlockShape kernelBlock(const llvm::Function *kernel) @@ -1361,6 +1367,60 @@ std::set reachedFrom(llvm::ArrayRef roots) return reached; } +// an array's { data, length, capacity } header, as LowerToLLVM makes it +bool isArrayHeader(llvm::Type *type) +{ + auto structType = llvm::dyn_cast(type); + return structType && structType->getNumElements() == 3 && structType->getElementType(0)->isPointerTy() && + structType->getElementType(1)->isIntegerTy(64) && structType->getElementType(2)->isIntegerTy(64); +} + +// An element of an array (or a field of one) that `pointer` points at, as LowerToLLVM makes the access: `gep T, +// data, index`, data loaded from the header's first field (`load (gep { ptr, i64, i64 }, header, 0, 0)`), and a +// tuple element's field `gep S, element, 0, field` (fields of fields too). The header, the data and the element. +struct ElementAccess +{ + llvm::Value *header; + llvm::LoadInst *data; + llvm::GetElementPtrInst *element; +}; + +std::optional matchElementAccess(llvm::Value *pointer) +{ + while (auto field = llvm::dyn_cast(pointer)) + { + auto first = field->getNumIndices() >= 2 ? llvm::dyn_cast(*field->idx_begin()) : nullptr; + if (!first || !first->isZero() || !field->getSourceElementType()->isStructTy() || + isArrayHeader(field->getSourceElementType())) + { + break; + } + + pointer = field->getPointerOperand(); + } + + auto element = llvm::dyn_cast(pointer); + if (!element || element->getNumIndices() != 1) + { + return std::nullopt; + } + + auto data = llvm::dyn_cast(element->getPointerOperand()); + if (!data || !data->getType()->isPointerTy()) + { + return std::nullopt; + } + + auto dataField = llvm::dyn_cast(data->getPointerOperand()); + if (!dataField || !isArrayHeader(dataField->getSourceElementType()) || dataField->getNumIndices() != 2 || + !dataField->hasAllZeroIndices()) + { + return std::nullopt; + } + + return ElementAccess{dataField->getPointerOperand(), data, element}; +} + // A kernel that waits at gpuBarrier runs on every thread of its blocks, the last block's past n too (a barrier is // reached by all of a block's threads, or it waits for ever). So that it need not check i < n itself, its array // accesses are guarded, in it and in what it calls (docs/gpu.md): @@ -1497,12 +1557,6 @@ void guardBarrierKernels(llvm::Module &device, const std::set &kern } } - auto isHeader = [&](llvm::Type *type) { - auto structType = llvm::dyn_cast(type); - return structType && structType->getNumElements() == 3 && structType->getElementType(0)->isPointerTy() && - structType->getElementType(1)->isIntegerTy(64) && structType->getElementType(2)->isIntegerTy(64); - }; - for (auto [original, function] : guarded) { auto active = function->getArg(function->arg_size() - 1); @@ -1539,41 +1593,13 @@ void guardBarrierKernels(llvm::Module &device, const std::set &kern : llvm::cast(access)->getPointerOperand(); } - // a field of a tuple element (`ps[i].x`): gep S, element, 0, field (fields of fields too) - while (auto field = llvm::dyn_cast(pointer)) - { - auto first = field->getNumIndices() >= 2 ? llvm::dyn_cast(*field->idx_begin()) - : nullptr; - if (!first || !first->isZero() || !field->getSourceElementType()->isStructTy() || - isHeader(field->getSourceElementType())) - { - break; - } - - pointer = field->getPointerOperand(); - } - - // gep T, data, index; data = load (gep { ptr, i64, i64 }, header, 0, 0) - auto element = llvm::dyn_cast(pointer); - if (!element || element->getNumIndices() != 1) + auto matched = matchElementAccess(pointer); + if (!matched) { continue; } - auto data = llvm::dyn_cast(element->getPointerOperand()); - if (!data || !data->getType()->isPointerTy()) - { - continue; - } - - auto dataField = llvm::dyn_cast(data->getPointerOperand()); - if (!dataField || !isHeader(dataField->getSourceElementType()) || dataField->getNumIndices() != 2 || - !dataField->hasAllZeroIndices()) - { - continue; - } - - auto header = dataField->getPointerOperand(); + auto [header, data, element] = *matched; auto writes = !llvm::isa(access); llvm::IRBuilder<> builder(access); @@ -1602,6 +1628,174 @@ void guardBarrierKernels(llvm::Module &device, const std::set &kern } } +// an index as it was before it was widened or narrowed for a comparison or an address +llvm::Value *stripIndexCasts(llvm::Value *value) +{ + while (llvm::isa(value)) + { + value = llvm::cast(value)->getOperand(0); + } + + return value; +} + +// A write past an array's end grows the array on the CPU; a GPU cannot (its memory is not the heap). In the +// kernels that do not wait at a barrier (whose guard drops such writes: guardBarrierKernels), and what they call, +// each write of an array's element (a store, an Atomics; a field of a tuple element too) is made only inside the +// array: past its end it is not made, and the first such write is recorded in FAULT_GLOBAL, which the runtime +// reads after the kernel and stops the program with (GpuRuntime.c's gpuFaultReport). The compiler's own check +// before such a write (the CPU's grow, or in a @kernel __tslang_gpu_past_end) goes when the write it is for is +// guarded here; one whose write is not recognized stays a trap, so that no write past the end is made unseen. +void recordKernelFaults(llvm::Module &device, const std::set &kernelNames) +{ + llvm::SmallVector kernels; + for (auto &kernelName : kernelNames) + { + if (auto kernel = device.getFunction(kernelName); kernel && !kernel->hasFnAttribute(ACTIVE_ATTR)) + { + kernels.push_back(kernel); + } + } + + if (kernels.empty()) + { + return; + } + + auto &context = device.getContext(); + auto i32 = llvm::Type::getInt32Ty(context); + auto i64 = llvm::Type::getInt64Ty(context); + auto ptr = llvm::PointerType::get(context, 0); + auto headerType = llvm::StructType::get(context, {ptr, i64, i64}); + auto faultType = llvm::StructType::get(context, {i32, i32, i64, i64}); + auto fault = device.getGlobalVariable(FAULT_GLOBAL); + if (!fault) + { + fault = new llvm::GlobalVariable(device, faultType, false, llvm::GlobalValue::ExternalLinkage, + llvm::ConstantAggregateZero::get(faultType), FAULT_GLOBAL); + fault->setAlignment(llvm::Align(8)); + } + + // the record: the first fault's thread, index and length (the flag taken by one thread only) + auto record = device.getFunction(FAULT_RECORD_FUNCTION); + if (!record) + { + record = llvm::Function::Create(llvm::FunctionType::get(llvm::Type::getVoidTy(context), {i64, i64}, false), + llvm::GlobalValue::InternalLinkage, FAULT_RECORD_FUNCTION, device); + record->addFnAttr(llvm::Attribute::Cold); + record->addFnAttr(llvm::Attribute::NoInline); + auto entry = llvm::BasicBlock::Create(context, "entry", record); + auto write = llvm::BasicBlock::Create(context, "write", record); + auto done = llvm::BasicBlock::Create(context, "done", record); + llvm::IRBuilder<> builder(entry); + auto exchange = builder.CreateAtomicCmpXchg(builder.CreateStructGEP(faultType, fault, 0), builder.getInt32(0), + builder.getInt32(1), llvm::MaybeAlign(4), + llvm::AtomicOrdering::Monotonic, llvm::AtomicOrdering::Monotonic); + builder.CreateCondBr(builder.CreateExtractValue(exchange, 1), write, done); + builder.SetInsertPoint(write); + auto thread = builder.CreateCall(device.getOrInsertFunction(FAULT_THREAD_STUB, llvm::FunctionType::get(i32, false))); + builder.CreateStore(thread, builder.CreateStructGEP(faultType, fault, 1)); + builder.CreateStore(record->getArg(0), builder.CreateStructGEP(faultType, fault, 2)); + builder.CreateStore(record->getArg(1), builder.CreateStructGEP(faultType, fault, 3)); + builder.CreateBr(done); + builder.SetInsertPoint(done); + builder.CreateRetVoid(); + } + + for (auto function : reachedFrom(kernels)) + { + if (function == record || function->getName().starts_with(".array_grow.")) + { + continue; + } + + llvm::SmallVector writes; + llvm::SmallVector checks; + for (auto &instruction : llvm::instructions(*function)) + { + if (llvm::isa(&instruction)) + { + writes.push_back(&instruction); + } + else if (auto call = llvm::dyn_cast(&instruction)) + { + if (auto callee = call->getCalledFunction(); + callee && (callee->getName().starts_with(".array_grow.") || callee->getName() == "__tslang_gpu_past_end")) + { + checks.push_back(call); + } + } + } + + // the indices whose writes are guarded + llvm::SmallPtrSet guarded; + for (auto access : writes) + { + auto pointer = llvm::getLoadStorePointerOperand(access); + if (!pointer) + { + pointer = llvm::isa(access) + ? llvm::cast(access)->getPointerOperand() + : llvm::cast(access)->getPointerOperand(); + } + + auto matched = matchElementAccess(pointer); + if (!matched) + { + continue; + } + + auto [header, data, element] = *matched; + llvm::IRBuilder<> builder(access); + auto length = builder.CreateLoad(i64, builder.CreateStructGEP(headerType, header, 1), "gpu.length"); + auto index = builder.CreateSExtOrTrunc(*element->idx_begin(), i64); + // unsigned: a negative index is past the end too + auto inside = builder.CreateICmpULT(index, length, "gpu.inside"); + llvm::Instruction *thenTerminator = nullptr; + llvm::Instruction *elseTerminator = nullptr; + llvm::SplitBlockAndInsertIfThenElse(inside, access->getIterator(), &thenTerminator, &elseTerminator); + auto tail = access->getParent(); + access->moveBefore(thenTerminator->getIterator()); + llvm::IRBuilder<> faultBuilder(elseTerminator); + faultBuilder.CreateCall(record, {index, length}); + if (!access->getType()->isVoidTy()) + { + // what the skipped Atomics gives: 0 + auto phi = llvm::PHINode::Create(access->getType(), 2, "gpu.written", tail->begin()); + access->replaceAllUsesWith(phi); + phi->addIncoming(access, thenTerminator->getParent()); + phi->addIncoming(llvm::Constant::getNullValue(access->getType()), elseTerminator->getParent()); + } + + guarded.insert(stripIndexCasts(*element->idx_begin())); + } + + // the compiler's check before a write: `br (index >= length), check, write` + for (auto call : checks) + { + auto covered = false; + if (auto before = call->getParent()->getSinglePredecessor()) + { + if (auto branch = llvm::dyn_cast(before->getTerminator())) + { + if (auto compare = llvm::dyn_cast(branch->getCondition())) + { + covered = guarded.count(stripIndexCasts(compare->getOperand(0))) > 0; + } + } + } + + if (!covered) + { + llvm::IRBuilder<> builder(call); + builder.CreateIntrinsic(llvm::Intrinsic::trap, {}); + } + + call->eraseFromParent(); + } + } +} + // the device module, whatever the GPU: the kernels and what they reach, or an error for what cannot run on one llvm::Expected> prepareDeviceModule(llvm::Module &hostModule, const std::set &kernelNames) @@ -1622,7 +1816,11 @@ llvm::Expected> prepareDeviceModule(llvm::Module & // a kernel that waits at gpuBarrier: its array accesses guarded, as it runs past n guardBarrierKernels(*device, kernelNames); - // a write past an array's end grows it on the CPU (the heap): on the GPU it traps + // the other kernels: a write past an array's end is not made, and recorded for the runtime to report + recordKernelFaults(*device, kernelNames); + + // a write past an array's end that is left (not recognized above) grows it on the CPU (the heap): on the GPU + // it traps llvm::SmallVector growCalls; for (auto &function : *device) { @@ -1694,7 +1892,8 @@ llvm::Expected> prepareDeviceModule(llvm::Module & for (auto &global : device->globals()) { - if (!global.isDeclaration()) + // the fault record stays the module's own, for the runtime to find by name + if (!global.isDeclaration() && global.getName() != FAULT_GLOBAL) { global.setLinkage(llvm::GlobalValue::InternalLinkage); } @@ -1747,7 +1946,7 @@ llvm::Expected> prepareDeviceModule(llvm::Module & // a variable of the program is set when it runs (its initializer is the startup code's, which the GPU // does not run): on the GPU it would stay as it was compiled, and reading it as the program sees it // would be wrong, silently. Only constants (literal text, tables) go to the GPU. - if (!global.isConstant() && !global.use_empty()) + if (!global.isConstant() && !global.use_empty() && global.getName() != FAULT_GLOBAL) { return makeError("a kernel reads the program's variable '" + global.getName() + "', which the GPU does not share: pass it to the kernel as an argument"); @@ -1980,6 +2179,13 @@ llvm::Error lowerBlockBuiltins(llvm::Module &device, const GpuTarget &target, un builder.CreateIntrinsic(llvm::Intrinsic::nvvm_barrier_cta_sync_all, {builder.getInt32(0)}); } } + else if (name == FAULT_THREAD_STUB) + { + // the thread's x among all the launch's threads + result = builder.CreateAdd(builder.CreateMul(blockValue(builder, target, BlockValue::Block, 0), + blockValue(builder, target, BlockValue::Size, 0)), + blockValue(builder, target, BlockValue::Thread, 0)); + } else if (name == WARP_LANE_STUB) { result = warpLane(builder, target); @@ -2152,6 +2358,11 @@ llvm::Expected compileForTarget(const llvm::Module &prepared, if (target.amd()) { moveToAmdAddressSpaces(*device); + // the fault record, as HIP's own device variables are: protected, found by name (hipModuleGetGlobal) + if (auto fault = device->getGlobalVariable(FAULT_GLOBAL)) + { + fault->setVisibility(llvm::GlobalValue::ProtectedVisibility); + } // code object v5 (ROCm 5.0 and newer load it), not LLVM's newer default v6, which older ROCm refuses; a // family's (gfx11-generic) needs v6 device->addModuleFlag(llvm::Module::Error, "amdhsa_code_object_version", From 6626ae66c60901d0ad48db634285f63f54352a6a Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Wed, 2 Dec 2026 15:25:55 +0000 Subject: [PATCH 2/2] gpuBatch keeps typed arrays on the GPU too, by their elements A typed array reaches a launch as a view header of its own (made for the launch), so gpuBatch could not find it again and copied it each launch (GPU_ARRAY_PER_LAUNCH). Now its kind says GPU_ARRAY_VIEW (0x80000) and the batch keeps it by its first element, length and element size: the same typed array, or a new subarray of the same elements, is the GPU's copy at every launch after the first. A view whose elements overlap another the GPU holds (subarrays of one buffer) sends that one back first (after the GPU is done with it) and is copied in from there, so the two copies never part. The table's pointer into the elements keeps the typed array's store alive (the collector takes interior pointers). gpu_batch_views.ts: 100 saxpy launches copy in once; apart, overlapping and temporary (collected between steps) typed arrays all right on the RTX 5080. The stale "on the GPU that is a trap" in __tslang_gpu_past_end's message is gone. Co-Authored-By: Claude Opus 5.5 --- docs/gpu.md | 13 ++- tslang/lib/TypeScript/MLIRGenAccessCall.cpp | 6 +- .../lib/TypeScriptAsyncRuntime/GpuRuntime.c | 71 +++++++++++--- tslang/test/gpu/CMakeLists.txt | 7 +- tslang/test/gpu/gpu_batch_views.ts | 92 +++++++++++++++++++ tslang/test/gpu/gpu_typed_arrays.ts | 2 +- 6 files changed, 166 insertions(+), 25 deletions(-) create mode 100644 tslang/test/gpu/gpu_batch_views.ts diff --git a/docs/gpu.md b/docs/gpu.md index 77e8042b6..c13c67c88 100644 --- a/docs/gpu.md +++ b/docs/gpu.md @@ -46,8 +46,9 @@ across launches, and a `GpuArray` lives there for as long as the program keeps i GPU and back into it, and a subarray's are only its slice: `gpuLaunch(k, 100, big.subarray(100, 200))` sees 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, inside `gpuBatch` too (a `GpuArray` stays on the GPU); `Uint8ClampedArray` and - `Float16Array` are not taken. `tslang/test/gpu/gpu_typed_arrays.ts` runs them. + 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. - 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: @@ -462,6 +463,13 @@ without it. - An array a launch gives the GPU stays alive until the batch ends, even one the program has stopped using (an array made for one step of a loop): the batch's list of them is the collector's to see. +- A typed array stays on the GPU in the batch too, by its elements: `x`, or `big.subarray(100, 200)` given to + each launch, is the same array on the GPU every time (a new subarray of the same elements included). Two + subarrays of one buffer whose elements do not overlap are two arrays there. One whose elements overlap + another's that the GPU holds (`big.subarray(0, 100)`, then `big.subarray(50, 150)`) is not kept beside it, as + the two copies would part: the first comes back to the CPU (the GPU finishes with it first), and the second + is copied in from there, so it sees what the kernels wrote to the first. Launches that go back and forth + between such subarrays copy each time. - An exception out of `fn` ends the batch as well: the arrays come back before it goes on. - A `gpuBatch` inside another one is part of it: the arrays come back when the outermost one ends. - With `TSLANG_GPU_PROFILE=1`, the end of a batch prints what it copied back. @@ -567,5 +575,4 @@ errors (`tslang/test/gpu`). Running ones, which need a GPU: `tslang/test/gpu/gpu ## Not yet -- `gpuBatch` keeping a typed array on the GPU between launches (each launch copies it: use a `GpuArray`). - `Uint8ClampedArray` and `Float16Array` as kernel arguments. diff --git a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp index 17727d424..bce4bd49b 100644 --- a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp +++ b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp @@ -2543,8 +2543,8 @@ namespace mlirgen } // a typed array (Float32Array, ...) where the kernel has a T[] (or the typed array, which a kernel has as - // a T[]): its view, copied in and back for this launch alone (GPU_ARRAY_PER_LAUNCH: gpuBatch does not - // keep it, as each launch's view is a header of its own) + // a T[]): its view, a header of this launch's own (GpuRuntime.c's GPU_ARRAY_VIEW: gpuBatch keeps it by + // its elements, not by the header) if (auto typedElement = typedArrayElementType(operand.getType())) { // (a Float64Array's f64 is a number[]'s number) @@ -2563,7 +2563,7 @@ namespace mlirgen EXIT_IF_FAILED_OR_NO_VALUE(view) if (!kinds.empty()) kinds += ","; - kinds += std::to_string(byteSize(typedElement) | 0x20000); + kinds += std::to_string(byteSize(typedElement) | 0x80000); callOperands.push_back(V(view)); stubInputs.push_back(arrayType); continue; diff --git a/tslang/lib/TypeScriptAsyncRuntime/GpuRuntime.c b/tslang/lib/TypeScriptAsyncRuntime/GpuRuntime.c index 20de901a7..811506db2 100644 --- a/tslang/lib/TypeScriptAsyncRuntime/GpuRuntime.c +++ b/tslang/lib/TypeScriptAsyncRuntime/GpuRuntime.c @@ -892,6 +892,9 @@ typedef struct #define GPU_ARRAY_PER_LAUNCH 0x20000 // a GpuArray (below): the argument is the runtime's record of an array that lives on the GPU #define GPU_ARRAY_DEVICE 0x40000 +// a typed array's view (MLIRGenImpl's mlirGenTypedArrayView): a header made for this launch, so gpuBatch keeps it by +// its elements, not by the header +#define GPU_ARRAY_VIEW 0x80000 // TSLANG_GPU_PROFILE=1: what each launch spent its time on static int gpuProfile(void) @@ -1016,8 +1019,9 @@ static void gpuLaunched(GpuDriver *driver, const char *entry) typedef struct { - TsArray *host; // the array as the program has it - void *hostData; // its storage and length when copied in + TsArray *host; // the array as the program has it (NULL for a typed array's view: GPU_ARRAY_VIEW) + void *hostData; // its storage and length when copied in (a view's: its first element, which keeps the + // typed array's store alive, as the collector takes a pointer into an object for it) int64_t length; size_t elementSize; GpuDriver *driver; @@ -1040,6 +1044,9 @@ static GpuTableFree gpuResidentFree; static void gpuResidentCheck(GpuResident *resident) { + // a typed array's elements do not move, nor does its length change + if (!resident->host) + return; if (resident->host->data != resident->hostData || resident->host->length != resident->length) { fprintf(stderr, "tslang gpu: an array the GPU holds in gpuBatch was resized by the CPU (length %lld, now " @@ -1068,23 +1075,54 @@ static size_t gpuResidentRelease(GpuResident *resident) return bytes; } -// the GPU's copy of the array, made (and copied in) on its first launch in the batch -static GpuResident *gpuResidentFor(GpuDriver *driver, TsArray *array, size_t elementSize, size_t *bytesIn) +// whether a resident's elements and `count` bytes at `data` share any +static int gpuResidentOverlaps(const GpuResident *resident, const void *data, size_t count) +{ + const char *start = (const char *)resident->hostData; + const char *end = start + (size_t)resident->length * resident->elementSize; + return start < (const char *)data + count && (const char *)data < end; +} + +// the GPU's copy of the array, made (and copied in) on its first launch in the batch. A typed array's view +// (`view`: its header is the launch's own, made for it) is the same one when its elements are: the same first +// element, length and element size. One whose elements overlap another's that the GPU holds (subarrays of one +// buffer that overlap) is not kept beside it, as the two copies would part: the GPU's finishes, that one goes +// back to the CPU, and this one is copied in from there. +static GpuResident *gpuResidentFor(GpuDriver *driver, TsArray *array, size_t elementSize, int view, size_t *bytesIn) { + size_t viewBytes = (size_t)array->length * elementSize; for (int i = 0; i < gpuResidentCount; i++) { GpuResident *resident = &gpuResident[i]; - if (resident->host != array) - continue; - gpuResidentCheck(resident); - if (resident->driver == driver && resident->elementSize == elementSize) + int same; + if (view) + { + if (resident->host || !gpuResidentOverlaps(resident, array->data, viewBytes ? viewBytes : 1)) + continue; + same = resident->hostData == array->data && resident->length == array->length; + } + else + { + if (resident->host != array) + continue; + gpuResidentCheck(resident); + same = 1; + } + if (same && resident->driver == driver && resident->elementSize == elementSize) return resident; - // handed to another GPU (a kernel of another program's table), or seen as other elements: start over + // handed to another GPU (a kernel of another program's table), seen as other elements, or a view that + // overlaps this one: start over gpuWait(); gpuResidentRelease(resident); gpuResident[i] = gpuResident[--gpuResidentCount]; // the slot left holds no array the collector should keep memset(&gpuResident[gpuResidentCount], 0, sizeof(GpuResident)); + // a view may overlap more than one: look again from the start (this slot now holds another) + if (view) + { + i = -1; + continue; + } break; } @@ -1111,7 +1149,7 @@ static GpuResident *gpuResidentFor(GpuDriver *driver, TsArray *array, size_t ele GpuResident *resident = &gpuResident[gpuResidentCount++]; memset(resident, 0, sizeof(*resident)); - resident->host = array; + resident->host = view ? NULL : array; resident->hostData = array->data; resident->length = array->length; resident->elementSize = elementSize; @@ -1153,13 +1191,14 @@ TSLANG_GPU_EXPORT void __tslang_gpu_cpu_only(const char *what) exit(1); } -// a kernel called on the CPU wrote past an array's end, which a kernel does not grow (on the GPU it traps); the -// array may be a typed array's view, elements of another's store (MLIRGenImpl's mlirGenGrowArrayForWrite) +// a kernel called on the CPU wrote past an array's end, which a kernel does not grow (on the GPU the write is not +// made, and reported: gpuFaultReport); the array may be a typed array's view, elements of another's store +// (MLIRGenImpl's mlirGenGrowArrayForWrite) TSLANG_GPU_EXPORT void __tslang_gpu_past_end(void) { fflush(stdout); fprintf(stderr, "tslang gpu: a kernel called on the CPU wrote past the end of an array, which a kernel does not " - "grow (on the GPU that is a trap)\n"); + "grow\n"); exit(1); } @@ -1565,10 +1604,12 @@ TSLANG_GPU_EXPORT void __tslang_gpu_run(const TsGpuImage *images, int32_t imageC slots[k] = (int64_t)array->header; resident[k] = 1; } - else if (kinds[k] > 0 && gpuBatchDepth > 0 && argv[k] && !(kinds[k] & GPU_ARRAY_PER_LAUNCH)) + else if (kinds[k] > 0 && gpuBatchDepth > 0 && argv[k] && !(kinds[k] & GPU_ARRAY_PER_LAUNCH) && + !((kinds[k] & GPU_ARRAY_VIEW) && ((TsArray *)(intptr_t)argv[k])->length == 0)) { GpuResident *kept = gpuResidentFor(driver, (TsArray *)(intptr_t)argv[k], - (size_t)GPU_ARRAY_ELEMENT_SIZE(kinds[k]), &bytesIn); + (size_t)GPU_ARRAY_ELEMENT_SIZE(kinds[k]), + (kinds[k] & GPU_ARRAY_VIEW) != 0, &bytesIn); if (!(kinds[k] & GPU_ARRAY_READ_ONLY)) kept->written = 1; slots[k] = (int64_t)kept->header; diff --git a/tslang/test/gpu/CMakeLists.txt b/tslang/test/gpu/CMakeLists.txt index ab27b200b..6c40273b6 100644 --- a/tslang/test/gpu/CMakeLists.txt +++ b/tslang/test/gpu/CMakeLists.txt @@ -514,12 +514,13 @@ if (gpu_any_backend) PASS_REGULAR_EXPRESSION "a @kernel parameter is a number, or an array of numbers or of tuples and object types of numbers" FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed" TIMEOUT 120) - # 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 + # typed arrays: a launch gives a kernel the typed array's view, a header of its own that gpuBatch keeps by its + # elements (4 | 0x80000, 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 COMMAND $ --emit=llvm --no-default-lib "${gpu_compile_dir}/typed_arrays.ts" -o -) set_tests_properties(test-gpu-compile-typed-arrays PROPERTIES - PASS_REGULAR_EXPRESSION "\\[i32 131076,.*call void @__tslang_gpu_run.*call void @scale\\(i32 0, ptr %\\.gpu\\.view" + PASS_REGULAR_EXPRESSION "\\[i32 524292,.*call void @__tslang_gpu_run.*call void @scale\\(i32 0, ptr %\\.gpu\\.view" FAIL_REGULAR_EXPRESSION "${gpu_fail_pattern}|LLVM ERROR|@\"__tslang_gpu_view" TIMEOUT 120) # a kernel called on the CPU does not grow an array: past a typed array's view it stops the program (no GPU: diff --git a/tslang/test/gpu/gpu_batch_views.ts b/tslang/test/gpu/gpu_batch_views.ts new file mode 100644 index 000000000..382f71b64 --- /dev/null +++ b/tslang/test/gpu/gpu_batch_views.ts @@ -0,0 +1,92 @@ +// Typed arrays inside gpuBatch (docs/gpu.md): each launch's view is a header of its own, and the batch keeps the +// typed array on the GPU by its elements. The same typed array (or a new subarray of the same elements) is copied +// in once; subarrays of one buffer that do not overlap are two arrays on the GPU; one that overlaps another the GPU +// holds sends that one back first, so it sees what the kernels wrote. TSLANG_GPU_PROFILE=1 shows the copies (none +// after a typed array's first launch). Needs a GPU and its driver, so it is not part of the test suite. +// +// tslang --emit=exe gpu_batch_views.ts -o gpu_batch_views.exe (or tslang --emit=jit gpu_batch_views.ts) + +declare function GC_gcollect(): void; + +@kernel +function saxpy(i: int, x: Float32Array, y: Float32Array, a: float) { + y[i] = a * x[i] + y[i]; +} + +@kernel +function add(i: int, a: Float64Array, v: number) { + a[i] = a[i] + v; +} + +// a typed array into an ordinary array +@kernel +function sumInto(i: int, from: Int32Array, to: int[]) { + to[i] = to[i] + from[i]; +} + +function main() { + // the same typed arrays in each launch + const n = 10000; + const x = new Float32Array(n); + const y = new Float32Array(n); + for (let i = 0; i < n; i++) { x[i] = i; y[i] = 0; } + gpuBatch(() => { + for (let k = 0; k < 100; k++) gpuLaunch(saxpy, n, x, y, 1); + }); + let wrong = 0; + for (let i = 0; i < n; i++) if (y[i] != 100 * i) wrong++; + print("same arrays: y[3] =", y[3], "wrong =", wrong); + assert(wrong == 0); + + // subarrays of one buffer that do not overlap, a new subarray each launch: two arrays on the GPU + const big = new Float64Array(300); + gpuBatch(() => { + for (let k = 0; k < 10; k++) { + gpuLaunch(add, 100, big.subarray(0, 100), 1); + gpuLaunch(add, 100, big.subarray(100, 200), 2); + } + }); + wrong = 0; + for (let i = 0; i < 300; i++) if (big[i] != (i < 100 ? 10 : i < 200 ? 20 : 0)) wrong++; + print("apart: big[0] =", big[0], "big[150] =", big[150], "big[250] =", big[250], "wrong =", wrong); + assert(wrong == 0); + + // subarrays that overlap: the second sees what the kernels wrote to the first, and back again + const over = new Float64Array(200); + gpuBatch(() => { + for (let k = 0; k < 5; k++) gpuLaunch(add, 100, over.subarray(0, 100), 1); + for (let k = 0; k < 5; k++) gpuLaunch(add, 100, over.subarray(50, 150), 10); + gpuLaunch(add, 100, over.subarray(0, 100), 100); + }); + wrong = 0; + for (let i = 0; i < 200; i++) { + const expected = (i < 100 ? 5 + 100 : 0) + (i >= 50 && i < 150 ? 50 : 0); + if (over[i] != expected) wrong++; + } + print("overlap: over[10] =", over[10], "over[60] =", over[60], "over[120] =", over[120], "wrong =", wrong); + assert(wrong == 0); + + // a typed array made for each step and dropped, the collector run between the steps, beside an ordinary array + const total: int[] = []; + for (let i = 0; i < 64; i++) total.push(0); + gpuBatch(() => { + for (let k = 0; k < 50; k++) { + const step = new Int32Array(64); + for (let i = 0; i < 64; i++) step[i] = k; + gpuLaunch(sumInto, 64, step, total); + for (let g = 0; g < 20; g++) { const junk = new Int32Array(64); junk[0] = g; } + GC_gcollect(); + } + }); + wrong = 0; + for (let i = 0; i < 64; i++) if (total[i] != 49 * 50 / 2) wrong++; + print("temporaries: total[0] =", total[0], "wrong =", wrong); + assert(wrong == 0); + + // an empty one, in a batch + gpuBatch(() => { + gpuLaunch(add, 0, new Float64Array(0), 1); + }); + + print("batch views: ok"); +} diff --git a/tslang/test/gpu/gpu_typed_arrays.ts b/tslang/test/gpu/gpu_typed_arrays.ts index eeec19fc9..5406efb17 100644 --- a/tslang/test/gpu/gpu_typed_arrays.ts +++ b/tslang/test/gpu/gpu_typed_arrays.ts @@ -111,7 +111,7 @@ function main() { addIndex(0, middle, ints); assert(y[5] == 61 && big[100] == 100 && ints[0] == 100 * 2 + 100); - // inside gpuBatch: copied for each launch, as typed arrays are not kept + // inside gpuBatch: kept on the GPU between the launches (gpu_batch_views.ts has more) gpuBatch(() => { for (let k = 0; k < 3; k++) gpuLaunch(saxpy, n, x, y, 1); });