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
13 changes: 10 additions & 3 deletions docs/gpu.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.
6 changes: 3 additions & 3 deletions tslang/lib/TypeScript/MLIRGenAccessCall.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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;
Expand Down
71 changes: 56 additions & 15 deletions tslang/lib/TypeScriptAsyncRuntime/GpuRuntime.c
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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;
Expand All @@ -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 "
Expand Down Expand Up @@ -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;
}

Expand All @@ -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;
Expand Down Expand Up @@ -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);
}

Expand Down Expand Up @@ -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;
Expand Down
7 changes: 4 additions & 3 deletions tslang/test/gpu/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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 $<TARGET_FILE:tslang> --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:
Expand Down
92 changes: 92 additions & 0 deletions tslang/test/gpu/gpu_batch_views.ts
Original file line number Diff line number Diff line change
@@ -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");
}
2 changes: 1 addition & 1 deletion tslang/test/gpu/gpu_typed_arrays.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
Expand Down
Loading