Task 2 of 6
The fix: give every thread a slice. 64 threads, each summing 64 of the 4,096 values, produce 64 partial sums — and 64 leftover numbers are cheap to finish off in plain JavaScript.
Watch the reading pattern, though. Thread x does not take a
contiguous block; it reads data[x], data[x + 64],
data[x + 128], … — a strided walk. At every step of the
loop, neighbouring threads touch neighbouring elements, which is exactly the access
pattern GPU memory hardware is built to serve in one go.
this.constants.chunk timesi of thread x is data[i * this.constants.threads + this.thread.x]console.log the totalThread x owns elements x, x + 64,
x + 128, … so its i-th element sits at index
i * 64 + x.
sum += data[i * this.constants.threads + this.thread.x];After const partial = await partials(data); a plain loop does it:
let total = 0;
for (let i = 0; i < partial.length; i++) {
total += partial[i];
}This page is an interactive exercise — the editor, the GPU runner and your saved progress need JavaScript. The text above is the full brief.