This continues from part 1.1 of the ZigLM series.
Here we will start by implementing a naive matmul for 2D f32 tensors, and then implement a SIMD optimization to measure the speedup. Following that I will explore Zig and C interop to integrate with the ggml library and call it directly.
The naive algorithm
The textbook formula for a 2x2 matrix multiplication is:
In pseudocode this looks like:
// A, B, C are 2x2, indexed [row][col]
C[0][0] = A[0][0]*B[0][0] + A[0][1]*B[1][0]
C[0][1] = A[0][0]*B[0][1] + A[0][1]*B[1][1]
C[1][0] = A[1][0]*B[0][0] + A[1][1]*B[1][0]
C[1][1] = A[1][0]*B[0][1] + A[1][1]*B[1][1]
Generalizing, if A is an m × n matrix and B is an n × p matrix, C = AB is defined as an m x p matrix which can be written as a loop:
for i in 0..m: // row of A (and of C)
for j in 0..p: // column of B (and of C)
sum = 0
for k in 0..n: // walk along row i of A and column j of B
sum += A[i][k] * B[k][j]
C[i][j] = sum
So now we have the basic structure of the naive implementation, we need to understand how to map it to the ggml data.
ggml’s tensor layout
ggml data is stored in row-major order, so each row is contiguous.
A is a 4×2 matrix (4 rows, 2 columns), so its ggml shape is {cols, rows} = {2, 4}:
- The first dimension is the size of each row i.e. the number of columns.
- The second dimension is the size of each column i.e. the number of rows.
const rows_a = 4;
const cols_a = 2;
const shape_a = [2]usize{cols_a, rows_a};
const matrix_a = [shape_a[1] * shape_a[0]]f32{
2, 8,
5, 1,
4, 2,
8, 6,
};
const rows_b = 2;
const cols_b = 3;
const shape_b = [2]usize{cols_b, rows_b};
const matrix_b = [shape_b[1] * shape_b[0]]f32{
10, 9, 5,
5, 9, 4,
};
Multiplying these together creates an output matrix of 4x3 (ggml shape {3, 4}):

In code:
const rows_c = 4;
const cols_c = 3;
const shape_c = [2]usize{cols_c, rows_c};
var matrix_c: [cols_c * rows_c]f32 = @splat(0);
var sum: f32 = 0;
const m = shape_c[1];
const p = shape_c[0];
const n = shape_a[0]; // shared dimension
for (0..m) |i| { // row of A (and of C)
std.debug.print("[", .{});
for (0..p) |j| { // column of B (and of C)
sum = 0;
for (0..n) |k| { // walk along row i of A and column j of B
sum += matrix_a[n * i + k] * matrix_b[p * k + j];
}
matrix_c[p * i + j] = sum;
std.debug.print(" {d:>7.1}", .{sum});
}
std.debug.print(" ]\n", .{});
}
Which prints:
[ 60.0 90.0 42.0 ]
[ 55.0 54.0 29.0 ]
[ 50.0 54.0 28.0 ]
[ 110.0 126.0 64.0 ]
SIMD with @Vector
Now the SIMD optimization can be implemented by switching to Zig’s builtin Vector type, which speeds up the summation over the shared dimension n by processing a vector’s worth of elements in each instruction.
The size of the Vector maps to the underlying CPU architecture. Zig gives a suggestion for this with std.simd.suggestVectorLength, although the docs mention that this is not yet implemented for every CPU architecture.
For our small example matrices, they fit into the vector length on my architecture, so A’s rows can be read into a single vector for each operation:
const a_vec: @Vector(n, f32) = matrix_a[n * i ..][0..n].*;
For B, it’s a bit more complicated: we need to walk down a column, but it’s the rows that are contiguous, so we transpose B first:
pub fn transpose(dst: []f32, src: []const f32, cols: usize, rows: usize) void {
for (0..rows) |r| {
for (0..cols) |c| {
dst[c * rows + r] = src[r * cols + c];
}
}
}
Row j of Bᵀ is column j of B, so each element of C becomes a dot product of two contiguous rows:
C[i][j] = (row i of A) · (row j of Bᵀ)
This allows the computation to be expressed using vectors, as we can now read contiguously from each matrix:
const matrix_b = [shape_b[1] * shape_b[0]]f32{ 10, 9, 5, 5, 9, 4 };
var matrix_bt: [shape_b[0] * shape_b[1]]f32 = @splat(0);
ggml.transpose(&matrix_bt, &matrix_b, cols_b, rows_b);
for (0..m) |i| { // row of A (and of C)
std.debug.print("[", .{});
for (0..p) |j| { // column of B (and of C)
sum = 0;
const a_vec: @Vector(n, f32) = matrix_a[n * i ..][0..n].*;
const b_vec: @Vector(n, f32) = matrix_bt[n * j ..][0..n].*;
sum = @reduce(.Add, a_vec * b_vec);
matrix_c[p * i + j] = sum;
std.debug.print(" {d:>7.1}", .{sum});
}
std.debug.print(" ]\n", .{});
}
Chunking for larger matrices
The above works for these small example matrices because n is a compile-time constant. A @Vector’s length has to be known at compile time, but real matrix sizes are only known at runtime, and a vector thousands of elements long wouldn’t fit in registers anyway. So instead we use the native width from suggestVectorLength and walk along each row in chunks:
const len = std.simd.suggestVectorLength(f32) orelse 4; // native vector width for target
for (0..m) |i| { // row of A (and of C)
std.debug.print("[", .{});
for (0..p) |j| { // column of B (and of C)
var acc: @Vector(len, f32) = @splat(0);
var k: usize = 0;
while (k + len <= n) : (k += len) {
const a_chunk: @Vector(len, f32) = matrix_a[n * i + k ..][0..len].*;
const b_chunk: @Vector(len, f32) = matrix_bt[n * j + k ..][0..len].*;
acc += a_chunk * b_chunk;
}
sum = @reduce(.Add, acc);
// remaining elements that don't fill a whole chunk
while (k < n) : (k += 1) {
sum += matrix_a[n * i + k] * matrix_bt[n * j + k];
}
matrix_c[p * i + j] = sum;
std.debug.print(" {d:>7.1}", .{sum});
}
std.debug.print(" ]\n", .{});
}
Benchmark: naive vs SIMD
Now we can handle multiplying 2D matrices of any size with SIMD, let’s compare a 2048x2048 multiplication with each implementation to see the speedup.
I wrapped each implementation in a function with these signatures (bodies omitted):
pub fn matmul(c: []f32, a: []const f32, a_dims: []const u64, b: []const f32, b_dims: []const u64) !void
pub fn matmul_simd(c: []f32, a: []const f32, a_dims: []const u64, bt: []const f32, bt_dims: []const u64) !void
matmul takes B and strides down its columns exactly like the naive loop above, while matmul_simd takes Bᵀ so it can read contiguous rows. So the speedup below comes from both the SIMD width and the better memory layout. For timing square matrices the benchmark passes the same b to both, since only the speed matters here.
The benchmark code:
const N: usize = 2048;
const a = try allocator.alloc(f32, N * N);
defer allocator.free(a);
const b = try allocator.alloc(f32, N * N);
defer allocator.free(b);
for (a, 0..) |*v, n| v.* = @as(f32, @floatFromInt(n));
for (b, 0..) |*v, n| v.* = @as(f32, @floatFromInt(n)) * 0.5;
const out = try allocator.alloc(f32, N * N);
defer allocator.free(out);
var start = std.Io.Timestamp.now(io, .real);
try ggml.matmul(out, a, &.{ N, N }, b, &.{ N, N });
std.mem.doNotOptimizeAway(out);
const matmul_ms = start.untilNow(io, .real).toMilliseconds();
start = std.Io.Timestamp.now(io, .real);
try ggml.matmul_simd(out, a, &.{ N, N }, b, &.{ N, N });
std.mem.doNotOptimizeAway(out);
const matmul_simd_ms = start.untilNow(io, .real).toMilliseconds();
std.debug.print("matmul time: {d:.2} ms\n", .{@as(f64, @floatFromInt(matmul_ms))});
std.debug.print("SIMD time: {d:.2} ms\n", .{@as(f64, @floatFromInt(matmul_simd_ms))});
After running the benchmark five times, the median was 14449ms for naive and 1504ms for SIMD, a 9.6x speedup.
Calling ggml from Zig
As a final step, I want to replace the matmul implementation with an external call to the ggml function, using Zig’s C interop.
To do this, I built ggml from source with CMake (it lives in the ggml folder of the llama.cpp repo) and installed it into a deps/ggml folder in my project:
git clone --depth 1 https://github.com/ggml-org/llama.cpp
cmake -S llama.cpp/ggml -B build \
-DCMAKE_BUILD_TYPE=Release \
-DGGML_BACKEND_DL=OFF \
-DGGML_METAL=OFF -DGGML_BLAS=OFF \
-DGGML_BUILD_TESTS=OFF -DGGML_BUILD_EXAMPLES=OFF \
-DCMAKE_INSTALL_PREFIX="$PWD/deps/ggml"
cmake --build build -j8
cmake --install build
GGML_BACKEND_DL=OFF builds the CPU backend as a normal library (libggml-cpu) rather than a plugin that is loaded at runtime, which means we can link it directly. Metal and BLAS are turned off so the comparison is CPU only.
Then I added a function in my build.zig to include the headers and libraries in the build:
fn linkGgml(b: *std.Build, module: *std.Build.Module, prefix: []const u8) void {
const root = b.pathFromRoot(prefix);
const lib_dir = std.Build.LazyPath{ .cwd_relative = b.fmt("{s}/lib", .{root}) };
module.link_libc = true;
module.addIncludePath(.{ .cwd_relative = b.fmt("{s}/include", .{root}) });
module.addLibraryPath(lib_dir);
module.addRPath(lib_dir);
module.linkSystemLibrary("ggml", .{ .use_pkg_config = .no });
module.linkSystemLibrary("ggml-base", .{ .use_pkg_config = .no });
module.linkSystemLibrary("ggml-cpu", .{ .use_pkg_config = .no });
}
And then call it in the build function, e.g.:
pub fn build(b: *std.Build) void {
...
const ggml_prefix = "deps/ggml";
const exe = b.addExecutable(.{
.name = "ziglm",
...
});
linkGgml(b, exe.root_module, ggml_prefix);
b.installArtifact(exe);
...
}
Then to import we just need to add this to the file we want to call the ggml functions:
const ggml_c = @cImport({
@cInclude("ggml.h");
@cInclude("ggml-cpu.h");
});
Following Hugging Face’s introduction to ggml, we will implement it in Zig.
One thing to note: ggml_mul_mat(a, b) expects both tensors to have the shared dimension first (ne[0]), so every row of a and every row of b is a contiguous vector of length n. It then fills the result with dot products of those rows: result[j][i] = (row i of a) · (row j of b). This is the same trick as the SIMD version above, and for the same reason: dot products over contiguous memory.
So passing A and Bᵀ gives a p × m result, which is (A · B)ᵀ = Cᵀ. To get results that match matmul and matmul_simd, we transpose it back to C.
Also the computation doesn’t actually run when ggml_mul_mat is called, ggml builds a static compute graph first with ggml_build_forward_expand, then ggml_graph_compute_with_ctx triggers the computation.
const matrix_b = [shape_b[1] * shape_b[0]]f32{ 10, 9, 5, 5, 9, 4 };
var matrix_bt: [shape_b[0] * shape_b[1]]f32 = @splat(0);
ggml.transpose(&matrix_bt, &matrix_b, cols_b, rows_b);
var matrix_c: [cols_c * rows_c]f32 = @splat(0);
var matrix_ct: [cols_c * rows_c]f32 = @splat(0);
const num_tensors = 3;
const data_size = (matrix_a.len + matrix_bt.len + matrix_c.len) * @sizeOf(f32);
const ctx = ggml_c.ggml_init(.{
.mem_size = data_size + num_tensors * ggml_c.ggml_tensor_overhead() + ggml_c.ggml_graph_overhead() + 1024,
.mem_buffer = null,
.no_alloc = false,
}) orelse return error.GgmlInitFailed;
defer ggml_c.ggml_free(ctx);
// create tensors
const tensor_a = ggml_c.ggml_new_tensor_2d(ctx, ggml_c.GGML_TYPE_F32, @intCast(shape_a[0]), @intCast(shape_a[1]));
const tensor_bt = ggml_c.ggml_new_tensor_2d(ctx, ggml_c.GGML_TYPE_F32, @intCast(shape_b[1]), @intCast(shape_b[0]));
@memcpy(@as([*]f32, @ptrCast(@alignCast(tensor_a.*.data)))[0..matrix_a.len], &matrix_a);
@memcpy(@as([*]f32, @ptrCast(@alignCast(tensor_bt.*.data)))[0..matrix_bt.len], &matrix_bt);
// create a `ggml_cgraph` for mul_mat operation
const graph = ggml_c.ggml_new_graph(ctx);
// both operands have the shared dimension contiguous; the result is (A·B)ᵀ
const tensor_ct = ggml_c.ggml_mul_mat(ctx, tensor_a, tensor_bt);
// build computation graph
ggml_c.ggml_build_forward_expand(graph, tensor_ct);
const n_threads = 1;
if (ggml_c.ggml_graph_compute_with_ctx(ctx, graph, n_threads) != ggml_c.GGML_STATUS_SUCCESS) return error.ComputeFailed;
@memcpy(&matrix_ct, @as([*]const f32, @ptrCast(@alignCast(tensor_ct.*.data)))[0..matrix_ct.len]);
ggml.transpose(&matrix_c, &matrix_ct, rows_c, cols_c);
Adding this to the same benchmark (2048x2048 multiplication), ggml’s median was 561 ms, so ggml with a single thread is 2.7x faster than my SIMD version. The main difference is that my SIMD chunking loop only uses a single accumulator:
while (k + len <= n) : (k += len) {
const a_chunk: @Vector(len, f32) = matrix_a[n * i + k ..][0..len].*;
const b_chunk: @Vector(len, f32) = matrix_bt[n * j + k ..][0..len].*;
acc += a_chunk * b_chunk;
}
Why ggml was faster: multiple accumulators
I am running on an Apple M3, which uses ARM NEON for its CPU SIMD. This architecture can run multiple vector accumulators in parallel. A simple way to get better performance out of it is to introduce another loop and run more accumulators in parallel, e.g.:
var acc: [4]@Vector(len, f32) = @splat(@splat(0));
var k: usize = 0;
while (k + 4 * len <= n) : (k += 4 * len) {
inline for (0..4) |u| {
const a_chunk: @Vector(len, f32) = matrix_a[n * i + k + u * len ..][0..len].*;
const b_chunk: @Vector(len, f32) = matrix_bt[n * j + k + u * len ..][0..len].*;
acc[u] += a_chunk * b_chunk;
}
}
// leftover whole chunks
while (k + len <= n) : (k += len) {
const a_chunk: @Vector(len, f32) = matrix_a[n * i + k ..][0..len].*;
const b_chunk: @Vector(len, f32) = matrix_bt[n * j + k ..][0..len].*;
acc[0] += a_chunk * b_chunk;
}
sum = @reduce(.Add, (acc[0] + acc[1]) + (acc[2] + acc[3]));
// remaining elements that don't fill a whole chunk
while (k < n) : (k += 1) {
sum += matrix_a[n * i + k] * matrix_bt[n * j + k];
}
Just doing this puts us level with ggml. In fact it’s about 10% faster, but the ggml timing also includes ggml_init, copying both inputs into the tensors and transposing the result, which I didn’t measure separately. The full output from the typical run above:
matmul time: 14803.00 ms
SIMD time: 1443.00 ms
SIMD 4 acc time: 498.00 ms
ggml time: 557.00 ms
Results
Medians of five runs:
| Implementation | Time (ms) | Speedup vs naive |
|---|---|---|
| Naive | 14449 | 1.0x |
| SIMD, 1 accumulator | 1504 | 9.6x |
| ggml, 1 thread | 561 | 25.8x |
| SIMD, 4 accumulators | 505 | 28.6x |
Next up: the tokenizer.