Task 4 of 6

Read the Results Back

A kernel's return value doesn't stay on the GPU — awaiting the call hands you the finished result as an ordinary (typed) array. From there it's plain JavaScript: loop over it, sum it, feed it to a chart, whatever you like.

This round trip is the heartbeat of GPGPU: upload → compute in parallel → read back. Here the parallel part computes 128 squares; the read-back part totals them.

Goal: make the kernel return for each thread, then sum the returned array in plain JavaScript and log the total with console.log.

Requirements

Hint 1 — what comes back?

With output: [128], await squares() gives you a Float32Array of 128 numbers. It's indexable and loopable like any array.

Hint 2 — the sum

A plain for loop after the kernel call:

let total = 0;
for (let i = 0; i < result.length; i++) {
  total += result[i];
}

Same idea elsewhere

Read-back is never free: CUDA's cudaMemcpy device→host and WebGPU's mapAsync staging buffers exist for exactly this step — and minimizing round trips is rule one of real GPU performance (Pipelines & Textures makes a whole meal of it).

All tasks in Data In, Data Out

  1. Pass an Array In
  2. Shape the Output: 2D
  3. Grayscale, the GPU way
  4. Read the Results Back
  5. Images Are Just Arrays
  6. Put It Together: Two Kernels

This page is an interactive exercise — the editor, the GPU runner and your saved progress need JavaScript. The text above is the full brief.