#4011·candle

Metal: power-of-two buffer pooling doubles peak memory for large intermediates (conv1d im2col) and OOMs on long sequences

Author: adamswanglinCreated Sep 29, 2026Updated Sep 29, 2026

Summary

The Metal backend's buffer pool rounds every allocation up to the next power of two (buf_size in candle-core/src/metal_backend/device.rs):

rust
fn buf_size(size: usize) -> usize {
    size.next_power_of_two()
}

This is a nice reuse optimization for small intermediates, but for very large allocations it backfires: a ~2.2 GiB intermediate receives a 4 GiB buffer, nearly doubling peak memory and frequently exceeding the GPU memory limit where the exact size would have fit.

A concrete case is conv1d: the im2col intermediate has l_out × c_in × k_size elements, which grows linearly with sequence length and easily crosses the 2 GiB boundary for long inputs.

Reproduction

Real workload: decoding audio with the modded-DAC codec from fishaudio/s1-mini (conv1d-heavy: 4 decoder blocks × 3 residual units, k=7, 1536 channels) on an M-series Mac with 16 GB unified memory, candle built with --features metal.

codec frames audio candle 0.11.0 / main (5ba5d5b4)
384 (~17.8 s) full decode works
391 (~18.1 s) full decode Metal error Command buffer had following error: Insufficient Memory (00000008:kIOGPUCommandBufferCallbackErrorOutOfMemory)

The cliff at 391 frames is exactly where the largest im2col intermediates cross 2^31 bytes and get rounded up to 4 GiB buffers. Peak process memory for a successful 390-frame decode is ~10 GB for ~18 s of audio, i.e. the pow2 rounding + per-size-class pooling dominate the footprint.

Behavior is identical on the latest main (5ba5d5b4); new_private_buffer no longer pools, but conv1d's im2col buffer still goes through the pooled new_buffer path with pow2 rounding.

Suggested fix

Cap the pow2 rounding so multi-GiB buffers are pooled at their exact size (the reuse benefit of pooling such buffers is marginal anyway):

rust
const POOL_POW2_MAX: usize = 1 << 24; // 16 MiB

fn buf_size(size: usize) -> usize {
    if size <= POOL_POW2_MAX {
        size.next_power_of_two()
    } else {
        size
    }
}

With this one-liner, the 391-frame decode above goes from the OOM error to completing at 3.6 GB peak RSS, with output matching the CPU reference bit-near-exactly (corr = 1.000000, maxdiff = 1e-5). All existing candle-core metal tests still pass. I have this on a branch and am happy to open a PR.

Related

While bisecting this I also hit the buffer-reuse correctness race in the 0.11.0 release (pooled HazardTrackingModeUntracked buffers reused by a new command buffer while the previous one was still in flight → deterministic garbage output for large conv1d workloads). That one appears to be fixed on main by the fence-based cross-encoder ordering (#3919 / #3954) — the same workload now produces bit-identical output with and without explicit synchronize(). Possibly relevant to #3705.