heap-kv-allocator
Zero-cgo Metal placement-heap KV-cache block allocator benchmark built on
github.com/tmc/apple/x/metalheap.
What it measures
Paged-attention LLM inference allocates and recycles fixed-size KV-cache blocks
as sequences grow and finish. This benchmark simulates a sliding window of 64
active 256 KiB KV blocks (16 MiB total heap capacity) across 2,000 alloc/free
cycles (median of 3 rounds) and compares:
- Per-block
MTLDevice.NewBufferWithLengthOptions: allocates and releases
an independent shared MTLBuffer on every cycle.
x/metalheap placement sub-allocation: allocates a single 16 MiB
MTLHeapTypePlacement heap once, commits it in bulk via MTLResidencySet,
and serves sub-allocated KV blocks through Heap.AllocBuffer / Heap.Free
with HeapBufferSizeAndAlignWithLengthOptions alignment and free-list reuse.
It also verifies four Metal heap invariants on live hardware:
- Exact
HeapOffset alignment: every sub-allocated buffer's HeapOffset()
matches the tracked offset and is aligned to HeapBufferSizeAndAlignWithLengthOptions.
MakeAliasable byte sharing: writes a deterministic 256 KiB pattern into
a placement buffer, calls MakeAliasable, aliases a second buffer at the same
offset via AllocAt, and verifies both initial pattern equality and
bidirectional mutation visibility.
- Purgeability round-trip: transitions the heap
MTLPurgeableStateNonVolatile → MTLPurgeableStateVolatile →
MTLPurgeableStateNonVolatile.
- Bulk residency accounting: commits the heap into an
MTLResidencySet via
metalheap.NewResidency and verifies AllocatedSize() covers the full heap.
Usage
CGO_ENABLED=0 go run ./examples/metal/heap-kv-allocator
CGO_ENABLED=0 go run ./examples/metal/heap-kv-allocator -cycles 2000 -pool-blocks 64 -block-bytes 262144
CGO_ENABLED=0 go test -v -count=1 ./examples/metal/heap-kv-allocator
Live Results (Apple M4 Max)
Recorded on Apple M4 Max, CGO_ENABLED=0, block-bytes=262144 (256 KiB,
align=256), pool-blocks=64 (heap=16,777,216 bytes), cycles=2000 (median
of 3 rounds):
| Allocator |
Latency (µs/alloc) |
Total (2,000 cycles) |
Speedup |
MTLDevice.NewBufferWithLengthOptions |
27.59 |
55.177 ms |
1.00x |
x/metalheap placement sub-allocation |
2.06 |
4.124 ms |
13.38x |
Verification results:
HeapOffset alignment (align=256): true (max offset=16515072)
MakeAliasable byte sharing: pattern=true, mutation=true
- Purgeable round-trip:
MTLPurgeableStateNonVolatile -> MTLPurgeableStateVolatile -> MTLPurgeableStateNonVolatile (ok=true)
MTLResidencySet: allocations=1, allocatedSize=16777216 bytes (coversHeap=true)