🎓 A1Learner
🔍
0 of 46 lessons completed

Zig SIMD Reductions

A SIMD reduction is an operation that combines every lane of a vector into one single value. A sum is a reduction, and so are a minimum and a maximum.

Sum the lanes

This program adds all four lanes into one total.

const std = @import("std");
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const v: @Vector(4, i32) = .{ 1, 2, 3, 4 };
    try out.print("{d}", .{@reduce(.Add, v)});
}

Smallest and largest

This program finds the smallest lane, then the largest lane.

const std = @import("std");
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const v: @Vector(4, i32) = .{ 5, 2, 9, 1 };
    try out.print("{d}\n", .{@reduce(.Min, v)});
    try out.print("{d}", .{@reduce(.Max, v)});
}

Combine true and false lanes

This program checks whether every lane is true, then whether any lane is true.

const std = @import("std");
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const b: @Vector(4, bool) = .{ true, false, true, true };
    try out.print("{}\n", .{@reduce(.And, b)});
    try out.print("{}", .{@reduce(.Or, b)});
}

Example

const std = @import("std");
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const scores: @Vector(4, i32) = .{ 4, 8, 12, 16 };
    const total = @reduce(.Add, scores);
    try out.print("{d} {d}", .{ total, total / 4 });
}

Key points

  • Reduction: a reduction is an operation that combines every lane of a vector into one value.
  • In Zig, @reduce takes an operation name and a vector, and returns one value.
  • The .Add operation adds every lane together into a total.
  • The .Min operation returns the smallest lane.
  • The .Max operation returns the largest lane.
  • The .Mul operation multiplies every lane together into a product.
  • A boolean vector can also be combined, so .And is true only when every lane is true.

The code builds a four-lane vector of scores. @reduce with .Add combines the lanes into a total of 40. Dividing by the lane count gives an average of 10.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does @reduce(.Add, v) return when v holds 3, 1, 4, and 2?