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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions docs/gpu.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
153 changes: 147 additions & 6 deletions tslang/lib/TypeScriptAsyncRuntime/GpuRuntime.c
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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)
{
Expand All @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
{
Expand All @@ -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);
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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)
{
Expand All @@ -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)
Expand Down Expand Up @@ -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++)
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand All @@ -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) : "";
Expand All @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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;

Expand Down
30 changes: 30 additions & 0 deletions tslang/test/gpu/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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 $<TARGET_FILE:tslang> --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
Expand Down
23 changes: 23 additions & 0 deletions tslang/test/gpu/compile/faults.ts
Original file line number Diff line number Diff line change
@@ -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);
}
11 changes: 11 additions & 0 deletions tslang/test/gpu/faults/README.md
Original file line number Diff line number Diff line change
@@ -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 <index> of <length> (GPU thread <x>)

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
13 changes: 13 additions & 0 deletions tslang/test/gpu/faults/add_assign.ts
Original file line number Diff line number Diff line change
@@ -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");
}
Loading
Loading