GPU kernels
Extension — not covered by the 1.0 stability promise (
gpu; the core)
A kernel is a function that runs once for each index of a range, all at once
on a GPU. You write it as any other function, in the action language, and say
its range. archec reads the same model four ways. The simulator runs the
kernel one index after the other. archec gen --target opencl, cuda and
metal write it for a GPU, with the code that launches it.
archec test --target opencl (or metal, cuda) runs the test cases on that
code. archec import x.cl reads kernels you already have into a model, and
archec conform --gpu checks that the model and the code still agree.
This page builds a FIR filter. The finished model is
examples/gpu-fir/main.arche. examples/gpu-signal/main.arche adds what
a FIR filter does not need: a reduction, an array a group shares, a stream, a
record and an enum. A third one is the FFT of
examples/5g-cell-search (gpufft.arche): each pass of butterflies is a
kernel. In the autonomous car (examples/autonomous-car/perception.arche), a
kernel finds the nearest lidar return in the driving corridor, a reduction
over the returns of a block.
What you need#
Writing, checking, simulating, generating, importing and conforming need nothing more than archec. Running the generated code needs what runs it. arche-lang downloads none of it.
| To run | You need |
|---|---|
--target opencl |
PoCL, an OpenCL that runs anywhere, on the processor. |
--target metal |
A Mac, with the command line tools (xcode-select --install). |
--target cuda |
The CUDA toolkit (nvcc) and an NVIDIA GPU. Without them, a clang++ checks the syntax of the file. |
1. A kernel#
component Fir "FIR filter" {
var taps: float32[8] = [0.03125, 0.0625, 0.125, 0.28125, 0.28125, 0.125, 0.0625, 0.03125]
var x: float32[64]
var y: float32[64]
/// y[i] = Σ taps[k] · x[i - k]: each sample of the result is one index.
fn filter(n: uint32) "Filter" {
kernel i in 0..<n
group 16
var acc: float32 = 0.0
for k in 0..<TAPS {
if i >= k {
acc += taps[k] * x[i - k]
}
}
y[i] = acc
}
}
| You write | Meaning |
|---|---|
kernel i in 0..<n |
The function is a kernel. Its body runs once for each i from 0 to n - 1. 0...n counts n too. |
kernel r in 0..<h, c in 0..<w |
Up to three indexes. The first is the slowest, the last the fastest: on a GPU the last is axis 0 (x), so that neighbouring threads read neighbouring elements of a[r * w + c]. |
group 16 |
The size of a work group (OpenCL), a block (CUDA), a threadgroup (Metal). One number for each index: group 8, 8. Left out, the target chooses. |
kernel and group are properties of a fn: they go in its block, before
its statements. There is no new keyword. A range is made of whole numbers,
the kernel's integer parameters, constants and the part's integer variables.
Another function of the part launches a kernel by calling it:
filter(SAMPLES). The call returns when every index has run.
A return in a kernel leaves the index, not the kernel.
What a kernel is given#
| In the body | On the device |
|---|---|
an array parameter (a: float32[]) |
a buffer. An array with no size comes with its length: len(a) works. |
an array of the part (x, y) |
a buffer |
an array of the part no function writes and no test case sets (do fir.taps[0] = …) (taps) |
a constant: its values are in the kernel's source, nothing is copied |
| a parameter that is a number, a number of the part the body reads | a value, copied at the launch |
an array declared in the body (var buf: float32[8]) |
the index's own |
| a constant | its value |
| a function of the part the body calls | a function on the device. It reads its parameters and constants only. |
a record of numbers (struct Vec3 { x: float32 … }), an array of them, an enum |
a struct laid out as the C target's (a field in its order, a bool a byte), an enum its number. pts[i].x = … writes a field of the element at its own index. |
A record whose fields are numbers, records of numbers, enums and arrays of
them goes to the device. One with an optional field or a union, a string, a
list, stays on the host. The generated host code includes the C target's
arche_types.h, written beside it.
What is copied#
The copies between the processor and the device are not written. They follow from what the kernel does with each array:
| The kernel | Before the launch | After it |
|---|---|---|
| reads the array | copied to the device | |
| writes it (one index) on every path, and never reads it | the elements of the range are copied back | |
reads and writes it, writes it over several indexes, or only on some paths (if x[i] > 0.0 { y[i] = … }, a write after a return) |
copied to the device | copied back |
A write is on every path when it is at the top of the body, before any
return. One on some paths only leaves the other elements as they were: they
are copied to the device first, so that what comes back is the host's values,
not what the device's memory held.
In the example, x goes to the device, y comes back, taps never moves.
A sum over the indexes: reduce#
Every index writes only its own element: a sum of all of them is a reduction, written as one more property.
var energy: float32 = 0.0
var peak: float32 = 0.0
fn measure(n: uint32) {
kernel i in 0..<n
group 64
reduce sum into energy, max into peak
energy += x[i] * x[i]
peak = max(peak, x[i])
}
| You write | Meaning |
|---|---|
reduce sum into energy |
energy is a number of the part. An index adds to it, energy += e, as many times as it likes. |
reduce min into lo, reduce max into hi |
lo = min(lo, e), hi = max(hi, e). |
| several, with commas | each its own. |
Anything else the body does with energy (read it, energy = 0.0) is
refused: its value is known when the kernel has run. Set it before the
launch, read it after.
The result is the same bits on the simulator, in C and on every GPU. A float
sum depends on its order ((a + b) + c is not always a + (b + c)), so the
order is the rule:
- Each index combines what it adds in the order it adds it.
- The indexes are then combined two by two, in their order: index 0 with 1, 2 with 3, …; then each pair with the next pair; then by eights, and so on. An index with no next one at a step waits for the next step. An index that added nothing is left out.
- The result is combined once with the variable's value before the launch:
energy = energy + result.
Every target computes that same tree. On a GPU a group (a power of two: 64
when group is left out) does the first steps in its shared memory, the host
the last ones with the groups' results. The simulator and the C target count
the indexes as they go, with the slots of a binary counter: no array of all of
them. The test rungs compare a reduction bit for bit, not within a tolerance.
A reduction runs over one index (kernel k in 0..<h * w, then
var r = k / w, var c = k % w), has no barrier() of its own and is not
launched on a stream.
Memory a group shares: shared and barrier()#
The indexes of a group can share an array, and wait for each other:
fn tiles(n: uint32) {
kernel i in 0..<n
group 64
shared tile: float32[TILE]
var own: float32 = x[i]
tile[i % TILE] = own
barrier()
var at: int32 = int32(i % TILE)
smooth[i] = if at > 0 { (tile[at - 1] + own) * 0.5 } else { own }
}
| You write | Meaning |
|---|---|
shared tile: float32[64] |
One array for each group: __local in OpenCL, __shared__ in CUDA, threadgroup in Metal. Its size is a number or a constant. Several with commas. |
barrier() |
Every index of the group waits there for the others: what one wrote in a shared array (or the device's arrays) is then seen by all. |
i % 64 |
The index's place in its group, when the range starts at 0: group 64 holds the indexes 0 to 63, then 64 to 127, … |
The simulator runs the indexes of a group one after the other up to the next
barrier, then all of them on to the next one. A variable an index keeps across
a barrier (own) is one for each index of the group. A GPU runs them at once;
the result is the same, because the checker refuses what would make it
differ:
- a barrier under an
if, awhile, or in aforwhose range depends on the index: every index of the group must reach it, as many times (for t in 0..<n / 16 { … barrier() … }is fine); - a
returnin the kernel: that index would not reach the next barrier; - between two barriers, an element of a shared array one index writes and
another reads, or that every index writes (
tile[0] = …): write the element of its own place,tile[i % 64], and put a barrier between the write and the read [gpu-race]; - a variable kept across a barrier with no type, or that is an array
[
gpu-barrier].
An index past the end of the range still takes part in the barriers; it runs
none of the statements. A kernel with a barrier says its group.
Launches that return at once: streams#
A kernel on a stream returns at once. The host goes on; the launches of one stream run in their order; calling the stream waits for them.
fn pipeline() {
stream
}
fn scale(n: uint32) {
kernel i in 0..<n
stream pipeline
scaled[i] = x[i] * gain.scale
}
fn on_block() {
scale(SAMPLES) // returns at once
offset(SAMPLES) // runs after scale: the same stream
pipeline() // waits for both; scaled is back on the host
blocks_done += 1
}
| You write | Meaning |
|---|---|
fn pipeline() { stream } |
A stream: a function with stream alone, no parameter and no statement. Calling it waits for what was launched on it, and copies back what those launches wrote. |
stream pipeline on a kernel |
Its launches are queued on pipeline. |
after copy on a kernel on a stream |
Each launch waits, on the device, for what was launched on copy before it. |
The arrays a launch on a stream uses stay on the device from their first
launch until every stream that used them was waited for: offset reads what
scale wrote there, nothing goes back and forth between them. Its arrays are
the part's (an array parameter is refused); its numbers are copied at the
launch.
The order is checked, in each function of the part, statement by statement
(both arms of an if; a loop's body twice) [gpu-stream]:
- the host does not read an array a pending launch writes, nor write one it uses, before it waits for that stream;
- a launch on another stream (or with none) does not use an array a pending
launch writes, nor write one it reads, unless it is
afterthat stream; - a function waits for every stream it launched on before it returns.
main.arche:24:5 error other on the stream side uses y, which scale on the stream compute writes and may not have finished: launch it `after compute`, on the same stream, or wait for compute first (`compute()`) [gpu-stream]
The simulator runs a launch at its call: with the order checked, waiting
changes nothing it computes. On a GPU a stream is an in-order command queue
(OpenCL), a cudaStream_t with events for after (CUDA), a command queue with
an MTLEvent (Metal).
2. What a GPU cannot run#
archec check reads every kernel and says what a GPU cannot run, where it is
written:
main.arche:29:5 error a kernel writes only the element at its own index, `y[i]`: two indexes that write `y[0]` would write the same element at once — a sum over the indexes is a reduction (`reduce sum into total`) [gpu-race]
main.arche:31:5 error a while loop has no known number of turns, and one index that never ends stops the whole kernel: write `for k in 0..<N { … }` [gpu-kernel]
main.arche:26:6 warning filter computes in float64: an OpenCL device may not have it (the generated code asks for cl_khr_fp64 and says when it is missing), and Metal has none — use float32 where its 7 digits are enough [gpu-float64]
| Refused | Write instead |
|---|---|
A write to anything but the element at the kernel's own index: y[0] = …, total += … |
y[i] = …. Over two indexes, y[r * w + c] (in any order: y[c + w * r] is the same index). A sum: reduce sum into total. |
A read of an array the kernel writes, at another index: y[i - 1] |
Write the result in another array. |
while c { … } |
for k in 0..<N { … } |
| A function that calls itself | The loop it stands for. |
| An array with no size in the body | var buf: float32[8] |
| A string, a record with an optional field or a union, a duration | Numbers, records of numbers, enums, and arrays of them. |
send, goto, wait, log, kick, now() |
Do it on the host, before or after the kernel. |
port.op(…), a call of another kernel |
Call it on the host and give the kernel the result. |
| A Python or TypeScript body | The action language. |
A result (-> int32) |
An array the kernel writes. |
The rule on writes is what makes the kernel safe to run all at once: no two indexes write the same element, and none reads what another writes. The result is then the same in any order, and the simulator's order is one of them.
A range whose ends are constants that take the own index past the end of an
array it indexes is a warning (gpu-range): kernel i in 0..<32 over a
float32[16].
float64 is a warning (gpu-float64), not an error. An OpenCL device may
not have it. Metal has none: the kernel is written for OpenCL and CUDA, not
for Metal, and a note says so.
In VS Code these appear in the editor as you type.
3. Simulate it#
The simulator runs a kernel as the loops it stands for, the first index the
outermost. Nothing else changes: test cases, archec sim, archec why work
as for any function.
$ archec test main.arche
PASS TP-FIR/TC-IMPULSE An impulse gives the taps
PASS TP-FIR/TC-DELAYED An impulse later gives the taps later
PASS TP-FIR/TC-STEP A step settles at 1
3/3 passed
The C, C++, Rust and Go targets write the same loops: a model with kernels still builds for a machine with no GPU.
4. Generate the code#
archec gen main.arche --target opencl -o generated
archec gen main.arche --target cuda -o generated
archec gen main.arche --target metal -o generated
| Target | Files |
|---|---|
opencl |
opencl/fir_kernels.cl, the kernels. fir_gpu.h and fir_gpu.c, the C that launches them. arche_gpu.h and arche_gpu_opencl.c, the device. |
cuda |
cuda/fir_kernels.cu, the kernels and their launches in one file. fir_gpu.h. |
metal |
metal/fir_kernels.metal, the kernels. fir_gpu.h and fir_gpu.m, the Objective-C that launches them. fir_gpu.swift, the same functions in Swift, with fir_gpu_swift.h and arche_gpu_swift.h, the C it reads: link the .m or the .swift. |
Every target gives C the same function for a kernel:
int fir_filter_gpu(uint32_t n, const float *x, float *y);
The kernel's parameters come first, as written; then the part's arrays it
uses, then the part's numbers it reads. It copies what the kernel reads,
launches it over its range, waits, and copies back what it wrote. It returns
0, or -1 when there is no device or the device said no (the reason is on
stderr). A reduction's variable comes last, as a pointer the result is
combined into. A kernel on a stream returns at once; fir_pipeline_wait()
waits for the stream pipeline.
Metal from Swift#
fir_gpu.swift defines the same C functions with Swift's Metal
(@_cdecl("fir_filter_gpu")): a C, Objective-C or Swift program calls them
the same way. What is C in the Objective-C host (the range's counts, the
copies back, a reduction's last steps) stays C, in fir_gpu_swift.h, so both
hosts compute it with the same lines:
swiftc -swift-version 5 -parse-as-library -import-objc-header arche_gpu_swift.h -c fir_gpu.swift
archec test --target metal --host swift runs the cases on it.
The kernel in OpenCL C:
/* @arche Fir.filter main.arche:67 kernel i in 0..<n group 16 */
__kernel void fir_filter(const uint32_t n, __global const float *x, __global float *y)
{
const uint32_t i = (uint32_t)get_global_id(0);
if (!(i < n)) { return; }
float acc = 0.0f;
for (int32_t k = 0; k < TAPS; k++) {
if ((int64_t)(i) >= (int64_t)(k)) {
acc += fir_taps[k] * x[arche_sub_i32((int32_t)(i), k)];
}
}
y[i] = acc;
}
| In the model | OpenCL | CUDA | Metal |
|---|---|---|---|
the index i (the last of several: c of r, c) |
get_global_id(0) |
blockIdx.x * blockDim.x + threadIdx.x |
gid.x of [[thread_position_in_grid]] |
the index before it (r of r, c), the one before that |
get_global_id(1), (2) |
.y, .z |
gid.y, gid.z |
| the range | rounded up to whole groups; the kernel leaves at once for an index beyond it | the same, in blocks | the same, in threadgroups |
group 16 |
the local work size | the block | the threadgroup |
group 2, 4 of r, c (by index) |
{ 4, 2 } (by axis) |
dim3 block(4, 2) |
{ 4, 2, 1 } |
| an array | __global float * |
float * |
device float *, a buffer |
| a constant array | __constant float t[8] = {…} |
__device__ static const |
constant float t[8] = {…} |
| a number | an argument | an argument | a field of one struct, in the buffer after the arrays |
The same numbers everywhere#
The body is the C target's own. An integer wraps at its width through the
same helpers (arche_add_i32…), and int() of a float saturates
(arche_sat_i32…), as on the simulator (the spec). A multiply
then an add is computed as written, never as one fused operation:
#pragma OPENCL FP_CONTRACT OFF in OpenCL, --fmad=false for nvcc, fast
math off in Metal. No fast-math option is given anywhere.
A name the model uses that a GPU language keeps for itself (half in Metal,
global in OpenCL) is written with a _ after it in the generated code.
archec status names the lines a requirement is built into
(built into arche-out/opencl/fir_kernels.cl:18-30): the line above each
kernel (/* @arche Fir.filter main.arche:67 kernel i in 0..<n group 16 */)
says which element it is, and its indexes and group as the model writes them:
the last index is axis 0.
5. Test it on a GPU#
$ archec test main.arche --target metal
1 kernel(s) of Fir written for metal
the Mac's GPU: Metal | Apple M4 Max
PASS TP-FIR/TC-IMPULSE An impulse gives the taps — 1 launch(es), each the same as the C target's loop
PASS TP-FIR/TC-DELAYED An impulse later gives the taps later — 1 launch(es), each the same as the C target's loop
PASS TP-FIR/TC-STEP A step settles at 1 — 1 launch(es), each the same as the C target's loop
3/3 passed on Metal
It writes the kernels as archec gen does, and beside them
(arche-out/metal-tests) the model's C unit tests
(--target c-tests) with each kernel's loop replaced
by a launch on the device. The cases then run as they are written: a message
arrives, a function launches the kernel, an expectation reads the result.
The differential check#
Every launch is followed by the C target's own loop, on a copy of what the
kernel was given. What the two wrote is compared: an integer exactly, a float
within 1e-9 of its size (1e-5 for a float32), as
the Python importer's check does; a
record field by field; a reduction bit for bit. A launch on a stream is
compared when the stream is waited for, with the C target's loops run on a
copy of the part, launch after launch. A case passes when its expectations
held and no launch differed:
FAIL TP-FIR/TC-STEP A step settles at 1
Fir.filter differs from the C target at y[11]: 0.96875 on the device, 1 in C
Where each target runs#
| Target | Runs on | When it cannot |
|---|---|---|
opencl |
PoCL. --opencl system runs on the machine's own OpenCL instead (Apple's on a Mac): its records are at the place opencl system, on a rung of their own (opencl-system), to say it is not the pinned one. |
No PoCL: the message says what to install. Exit 2. |
metal |
The Mac's GPU. The host compiles the kernels when it starts. --host swift: from the Swift host, built with swiftc. |
Not a Mac, or no Metal device (or no swiftc, for --host swift). Exit 2. |
cuda |
An NVIDIA GPU, built with nvcc --fmad=false -arch=native (the GPU's machine code, so a driver older than the toolkit runs it; an nvcc before 11.5 builds without -arch=native). |
No nvcc or no NVIDIA GPU: a clang++ reads the .cu (-fsyntax-only, with no toolkit), nothing runs and nothing is recorded. Exit 2. |
A case that launches no kernel is not run there: it would prove nothing about
the GPU. The C unit tests say less than the simulator does: a case whose
lines they cannot say is skipped, with why (not run on Metal — the C tests cannot say it: do g.y[0] = 3.0). An expectation of an element outside
the array (fir.y[64] of 64) is one of them: it is said, not read as the last
element. Drive a kernel's part with
messages and read numbers and array elements, and its cases run everywhere.
A model the C target cannot write whole (one with FPGA parts beside its
kernels) is not run on a device this way. Check its kernels on a bench of
their own, as examples/5g-cell-search/gpufft-bench.arche does for the
receiver's FFT.
What it proves#
Each case that launched a kernel is evidence, at the place opencl, metal
or cuda. These are rungs of the test ladder,
and archec test --ladder runs them for a model with kernels:
archec test --ladder main.arche
✓ sim 3 case(s) passed on Arche's simulator
– renode skipped: no deployment with a binary on a board
– opencl skipped: PoCL is not on this machine (the opencl rung is pinned to PoCL 7.1; archec does not download it)
✓ metal 3 case(s) passed on the kernels' Metal (Metal | Apple M4 Max)
– cuda skipped: nvcc is not on this machine (the CUDA toolkit: CUDA_HOME, or the PATH); clang read the .cu with no error
– board skipped: no deployment with a binary on a board
✓ ladder: held up to metal
$ archec status main.arche
REQ-IMPULSE Impulse response
satisfied by Fir (fir)
built into arche-out/metal/fir_kernels.metal:14-27
highest rung metal (sim ✓, renode –, metal ✓, board –)
✓ test TP-FIR/TC-IMPULSE metal just now 1 launch(es) the same as the C target's loop, on Metal | Apple M4 Max
✓ test TP-FIR/TC-IMPULSE sim just now
The record keeps the hash of the kernels and of the host code it ran. Change the model or the code, and the proof is out of date until the case runs again.
6. The system#
component Gpu "GPU" {
kind gpu
}
system Filter "Filter" {
part gpu: Gpu
part fir: Fir
}
deployment OnGpu "On the GPU" {
system Filter
platform Filter
binary kernels "fir.cl" on gpu {
thread launch "Launches" { runs fir }
}
}kind gpu is hardware with no cores, as an FPGA is. A binary on it holds the
parts whose kernels it runs.
A part another part calls through a port runs where its caller does: put it
on the processor's thread. Its kernels are launched from there. The
receiver of examples/5g-cell-search does this for its FFT.
The targets write every kernel of the model, whatever the deployment
(--deployment is only checked to name one of the model's).
7. Read existing OpenCL and CUDA#
$ archec import scale.cu -o scale.arche
kernel scale.cu:6 scale → Scale.scale (kernel i in 0..<n, group 256)
opaque scale.cu:13 tk — a template is not translated: the model has one kernel for each type
opaque scale.cu:14 sum — an atomic operation is not translated: a kernel of the model writes only the element at its own index
✓ scale.arche — 1 kernel(s) translated, 2 kept opaque, 1 function(s) they call; .archec/gpu-map.json
From this CUDA:
__device__ float half(float v) { return v * 0.5f; }
__global__ void scale(const real *x, float *y, int n, float g)
{
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) {
y[i] = half(x[i]) * g + (i > 0 ? x[i - 1] : 0.0f);
}
}
it writes:
component Scale "scale.cu" {
source "scale.cu"
fn half(v: float32) -> float32 {
source "scale.cu:5"
return v * 0.5
}
fn scale(x: float32[], y: float32[], n: int32, g: float32) {
source "scale.cu:6"
kernel i in 0..<n
group 256
y[i] = (half(x[i]) * g) + (if i > 0 { x[i - 1] } else { 0.0 })
}
}For an OpenCL file, name the files that launch its kernels after it:
archec import fir.cl host.c -o fir.arche. The group and the copies are read
there.
| In the code | In the model |
|---|---|
__kernel void f(…), __global__ void f(…) |
fn f(…) with source "file:line" |
T i = get_global_id(0);, T i = blockIdx.x * blockDim.x + threadIdx.x; |
the index i |
col = blockIdx.x…; row = blockIdx.y… (get_global_id(0), (1)) |
kernel row in 0..<h, col in 0..<w: x, the fastest, is the last index. The launch's block (dim3 block(16, 8)) is the group by index: group 8, 16. |
a name that is a word of the action language (in, match) |
the name with a _ after it (in_). The map keeps its name in the code. |
if (i >= n) return;, if (i < n) { … } around the body |
the range 0..<n. The guard is the range: it is not kept in the body. |
f<<<grid, block>>>(…), the local size of clEnqueueNDRangeKernel |
group, when it is a number |
| a pointer parameter | an array parameter. x_len after x is len(x). |
__global, __constant, __local on a parameter |
recorded in the map. A __local parameter keeps the kernel opaque. |
| a constant array of the file | a variable of the component with its values: a constant on the device |
#define N 8 |
const N = 8 |
| a function of the file a kernel calls | a fn of the component |
clEnqueueWriteBuffer, clEnqueueReadBuffer, cudaMemcpy |
the copies the code makes, in the map beside the ones the model derives. A note says where they differ. |
declarations, assignments, if, a counted for, return, arithmetic, ?: |
the action language |
tree-sitter reads the files. It ships with archec and with the VS Code
extension: importing needs no network and no compiler. When clang is on the
PATH, archec also asks it what the typedefs of included headers stand for
(clang -Xclang -ast-dump=json); without it, a parameter of such a type
keeps its kernel opaque. The map records whether clang read the files, and
what the typedefs the files name stand for: archec conform --gpu on a
machine with no clang reads the files again with those, and says so
(clang-missing).
What stays opaque#
A kernel the importer cannot translate is kept as a fn with its source
and no body, the reason above it:
// opaque: an atomic operation is not translated: a kernel of the model writes only the element at its own index
fn sum(a: float32[], out: float32[], n: int32) {
source "scale.cu:14"
}
It is bound by name to its file, as
the Python importer's simulation functions
are. archec check warns (gpu-opaque). The simulator does not run it, no
target writes it, and archec status says that what its component satisfies
is not proved:
REQ-SCALE Scaled (nothing proves it)
· check the kernel Scale.sum cannot be said: opaque: its code stays in scale.cu:14, the model has no body for it
What keeps a kernel opaque:
- an atomic operation, a memory fence or a barrier of part of a group
(
mem_fence,__syncwarp); memory shared by a group anywhere but at the top of the kernel, or with a first value; - a barrier in a kernel whose group no launch says, or its place in its group
(
threadIdx.x) with no group known; - a texture or an image, a stream or an event;
- a template, a vector type (
float4), a struct, pointer arithmetic; - a
whileloop, aswitch, a call the importer does not know; - a macro that hides code, an index used without a name;
- a range that is not in the file: no guard says where the index ends.
Memory a group shares#
A kernel that shares an array and waits at a barrier is read into shared
and barrier():
__global__ void smooth(const float *x, float *y, int n)
{
__shared__ float tile[64];
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) {
tile[threadIdx.x] = x[i];
}
__syncthreads();
if (i < n) {
float left = threadIdx.x > 0 ? tile[threadIdx.x - 1] : tile[threadIdx.x];
y[i] = (left + tile[threadIdx.x]) * 0.5f;
}
}
fn smooth(x: float32[], y: float32[], n: int32) {
source "smooth.cu:3"
kernel i in 0..<n
group 64
shared tile: float32[64]
tile[i % 64] = x[i]
barrier()
var left: float32 = if i % 64 > 0 { tile[i % 64 - 1] } else { tile[i % 64] }
y[i] = (left + tile[i % 64]) * 0.5
}
__syncthreads(), barrier(…) and work_group_barrier(…) are barrier().
With a barrier the range's guard cannot leave the kernel: an if (i < n)
around the statements says the range, and stands for them (every index of the
model is in its range). The index's place in its group (threadIdx.x,
get_local_id(0)), the group's (blockIdx.x, get_group_id(0)) and its size
(blockDim.x, get_local_size(0)) are written from the group the launch
gives: name the host file when the kernel's is not beside it.
archec conform --gpu compares the shared arrays too.
The map#
With -o, .archec/gpu-map.json beside the model says, for each kernel:
its name in the code and in the model, its file and line, its range and
where it was read, its group and the launch, each parameter's address space,
the copies of the code and the derived ones, and the body as it was read.
--report r.json writes the same with the notes.
Round trip#
The OpenCL archec writes can be read back. Its @arche lines name the
elements, so the kernels come back under their names. A kernel whose arrays
are its parameters comes back the same: generating from the model read back
writes the same kernels, byte for byte. An array that was the part's comes
back as a parameter.
8. Keep the model and the code together#
$ archec conform scale.arche --gpu
Kernels whose range or group changed (1)
error scale.cu:6: Scale.scale has the group 256 in the model, 128 in the code (scale.cu:25)
Kernels whose body changed (1)
error scale.cu:6: Scale.scale and scale (scale.cu:6) no longer say the same — the code changed since the import: import again, or change the model too. First difference: `y[i] = (half(x[i]) * g) + (if i > 0 { x[i - 1] } else { 0.0 })` in the model, `y[i] = half(x[i]) * g` in the code
3 of 3 kernel(s) of the model found in scale.cu (3 there, 2 opaque: not compared, not proven)
✗ the model and the code differ (2 error(s))
The files the model was read from are read again, as the importer reads them, and compared with the model as it is now:
| Finding | Meaning | |
|---|---|---|
kernel-only-in-code |
A kernel of the code the model has no fn for. |
error |
kernel-gone |
A kernel of the model whose code is no longer there. | error |
signature-changed |
Its parameters differ. | error |
launch-changed |
Its range or its group differs. | error |
body-changed |
Its body differs. The message says which side changed since the import. | error |
became-opaque |
The importer can no longer translate it, and why. | error (a warning when clang read the files at the import and is not here now) |
now-translatable |
An opaque kernel the importer can translate now. | warning |
clang-missing |
clang read the files at the import and is not on this machine: the typedefs the map recorded stand in for it. A header changed since is not seen. | warning |
generated-edited |
A file archec gen wrote for opencl, cuda or metal is not what the model says: it was edited, or the model changed since. |
error |
The last one needs no import: it compares each generated folder beside the model with what the model says now. A generated kernel is changed in the model, then generated again.
Exit 1 on an error. archec ci runs the same check as the gate
conform-gpu for a model with a map beside it. --json and --junit give
the findings to a pipeline.
Where PoCL comes from#
The opencl rung runs on PoCL, a free OpenCL
(MIT license) that runs on the processor: the same kernels run on a laptop
and in a pipeline with no GPU. archec looks for it in this order:
ARCHE_POCL (the folder it is installed in), ~/.arche/gpu/pocl
(ARCHE_GPU_HOME), Homebrew's, then the system's packages.
archec does not download it: you install it.
brew install pocl # macOS
apt install pocl-opencl-icd ocl-icd-opencl-dev # Debian, Ubuntu
The version is pinned in tools/gpu/pocl.json (7.1). A run on another
version works, and its record says which. The pin was written from the
project's release notes: no run on PoCL has checked it yet.
Limits#
- A reduction runs over one index. Over two, make them one:
kernel k in 0..<h * w, thenvar r = k / wandvar c = k % w. - A barrier is the whole group's, at the top of the body or in a loop
every index turns the same times, and a kernel with one has no
return. That is the rule of OpenCL, CUDA and Metal: a barrier some indexes of a group do not reach stops the group. - No string, list, optional field or union in a kernel: their size is not
known on the device. No vector type (
float4): a record of numbers stands for one, laid out as the C target's. - A part reached through a port runs on its caller's processor, and its kernels are launched from there.
- The test rungs go through the C unit tests. That is the differential
check: each launch is compared with the C target's loop. A model the C
target cannot write whole, and a case the C tests cannot say, do not run on
a device. Check its kernels on a bench of their own, as
examples/autonomous-car/perception-bench.archedoes for the car's corridor filter. - The Swift host is built with
-swift-version 5(its state is global, as the Objective-C host's is) and needs the command line tools'swiftc. - The importer reads kernel files, not the host's code. A kernel's range
is read from its own guard (
if (i < n)): a kernel with no guard stays opaque, even when its launch says the range. Add the guard to the kernel, or write the range in the model. - Conform compares what the importer reads. A change in code the importer does not read (a host function, a comment) is not seen.
Not done yet#
- A reduction is a sum, a min or a max, with no barrier of its own and on no stream. The importer does not read one: an atomic or a tree written by hand stays opaque.
- A stream's kernels use the part's arrays (no array parameter); a launch that returns at once does not carry a reduction. A launch with no stream makes its buffers and copies them at each launch.
- The importer reads no struct.
- Which GPU. The model does not say which GPU a part's kernels use.