Task 4 of 6
Now ride it all the way: 1,024 → 512 → 256 → … → 1. Ten rungs and the array is
a scalar. That means the same kernel has to run at a different size on every
call — two options make that legal: dynamicOutput: true lets
setOutput() shrink the thread grid between calls, and
dynamicArguments: true lets the input shrink with it.
The driving loop lives in JavaScript, but every rung of actual work stays parallel
on the GPU: log₂(1024) = 10 launches instead of 1,023 serial additions. One real-world
wrinkle, already wired into the driver: gpu.js locks an argument's type on the
kernel's first call, so the ladder starts from a Float32Array — the same
type every rung's output comes back as.
data to a single
total by iterating the halving rung, and log the result.dynamicOutput: true and dynamicArguments: truethis.output.x, exactly like the last taskn > 1, halve n, setOutput([n]), re-invokeconsole.log the final scalarhalve.setOutput([n]) takes the new output shape as an array.
Call it before each invocation, with n already halved.
let n = values.length;
while (n > 1) {
n = n / 2;
// …
}
— inside the loop, resize, re-invoke, and keep the returned array for the next rung.
while (n > 1) {
n = n / 2;
halve.setOutput([n]);
values = await halve(values);
}
— then the answer is values[0].
This page is an interactive exercise — the editor, the GPU runner and your saved progress need JavaScript. The text above is the full brief.