Lesson 4 — Control flow and bounds

GPU kernels are dispatched in workgroups of fixed size (256 threads by default in Sarek's WGSL backend). If your array length is not a multiple of the workgroup size, some threads at the end of the last workgroup will be assigned an out-of-bounds index. Accessing the array at that index is a GPU error; you must guard against it.

if expressions in Sarek

Sarek kernels support if / then / else as expressions (they return a value). Example:

b.(i) <- (if i < n then a.(i) else 0.0)

The WGSL backend compiles this to a select() intrinsic, which is branch-free on most GPU architectures — so bounds-checking is essentially free.

n is a scalar int32 argument. In this lesson n = 128 (half the array), so the second half of b should be zero.

Your task

Complete the kernel: write a.(i) into b.(i) when i < n, and 0.0 otherwise.

Click "Run on my GPU" to execute your kernel.
Hint

(if i < n then a.(i) else 0.0) — use < for integer comparison. The parentheses keep the expression unambiguous.