Skip to content
Engineering

My Mac's GPU, from inside a Linux pod

Christopher Maher

Christopher Maher

15 min read

The guest kernel died with zeros where its code should have been.

pc : virtio_read+0x0/0xe8 [virtio_rng]
Code: 00000000 00000000 00000000 00000000 (00000000)

It happened on my second Mac, an M6 with 32 GB, during a benchmark run. A page of kernel code in the Linux guest had read back as zeros. About half an hour earlier, the same setup had frozen with every vCPU spinning.

I was sure I knew whose fault it was. Mine. My virtio device puts a window of host memory into the guest's address space, and a zeroed page looks a lot like a mapping gone wrong.

It wasn't mine, and proving that took a VM with no custom device in it at all. That's a fair picture of the whole project: something works, something breaks, and my first theory about why is wrong. This is the road in order, wrong turns left in, with a guide at the end that should save you most of them.

I wanted a GPU in an ordinary pod, with no agent on the side

A Linux container on a Mac has no GPU. LLMKube, my Kubernetes operator for local inference, works around that with a metal-agent that runs the engine natively and relays it into the cluster. It works, but it's one more thing to run on every Mac, and the workload isn't a normal pod.

macOS 27 added VZCustomVirtioDevice, a public API for writing your own virtio device in Swift. That made a different plan possible: a virtio-gpu device the stock Linux driver already knows, carrying Metal calls to the host's real GPU. I didn't know whether the driver would accept it, or what the VM boundary would cost. That was the exciting part.

As far as I know, nobody had done it this way before: llama.cpp and MLX running with their Metal backends inside a Linux VM, their Metal calls going through the stock virtio_gpu driver, and a pod on a Mac running Metal code itself. Others have reached the Mac's GPU from Linux in other ways, and I list them near the end.

Almost none of the hard parts are mine. llama.cpp's Metal backend does the real work, and its kernels run unchanged. MLX needed a 39-line patch. Apple's metal-cpp headers build on Linux without a byte changed, and the stock Linux virtio_gpu driver needed nothing from me.

The stock driver bound once I offered a feature I don't implement

The first spike was a throwaway: a Swift device with one new context type, and a stock Debian kernel. The driver turned out to gate everything I needed behind the VIRGL feature bit. So my device offers OpenGL support it doesn't have, and the driver bound:

[drm] features: +virgl -edid +resource_blob +host_visible
[drm] features: +context_init
[drm] Initialized virtio_gpu 0.1.0 for 0000:00:0a.0 on minor 0

A render node appeared, with no kernel changes. Buffers were zero-copy too, mapped into the guest through the device's shared-memory region.

That region was the first wall. Anything bigger than 8 GiB passed validate(). Then the VM powered off about 55 ms after start, with no firmware output. Later, the second Mac, with a quarter of the memory, did exactly the same.

I took it as a fixed limit and designed around it. Model weights get copied once into GPU-only host memory, outside the region, so a 38 GiB model loads and runs. I'll come back to the ceiling, because it turned out not to be one.

llama.cpp needed two new files, not a port

The first guest library, mtlv, is a hand-written subset: the roughly 40 Metal calls that llama.cpp's Metal backend makes. Its ops and .metal kernels run as they are, and only its two Objective-C files needed a Linux counterpart.

On my M5 Max laptop, test-backend-ops passed the same set of tests in the guest as on native Metal, and greedy output matched byte for byte. My spike notes had guessed the boundary would cost under 1%, and that held for the big models. On a tiny model, the fixed cost of each round trip shows up as about 4 to 5% on generation.

Then a patch put the same device into apple/container as --gpus. A container machine became a single-node Kubernetes cluster, and unmodified LLMKube served a 27B model from an ordinary pod, keeping pace with native llama-server under concurrent load. That was when it stopped feeling like a spike.

The second Mac found two bugs, and only one of them was mine

The M6 was supposed to be a quick second data point. Right away it showed that my host probed GPU families only up to Apple10, so for long KV caches llama.cpp in the guest was quietly picking the M5 Max's flash-attention tuning. I probe further now, and the guest reports Apple11, like native.

Then came the crash from the top of this post.

My first suspect was the shared-memory window, since it's where host memory shows up inside the guest. Then a run crashed when the device had only negotiated features and created two contexts. No blob existed, and the window code had never run. So I moved my suspicion to the device's mere presence, and my first no-device runs came back clean, which seemed to agree.

So I kept running controls. A short run with no custom device at all, under the same host pressure, panicked on a corrupted kernel stack 56 seconds after boot.

Setup, same host swap pressureRunsCrashed
no GPU device31
device, no shared window52
device with the 8 GiB window72

Every damaged page I could see was kernel memory; a pattern check in guest userspace never found a bad one. The M5 Max never showed it; with 128 GB it never got deep into swap in these runs. Whatever this is, it lives below anything my code controls. I'll come back to this one too.

A generic Metal executor is a VM escape until you prove otherwise

The mtlv subset was enough for llama.cpp and nothing else, so I switched the guest side to Apple's metal-cpp, 1:1. Every metal-cpp call becomes an objc_msgSend, and Linux has no Objective-C runtime, so the guest gets a tiny one. An AArch64 trampoline saves the argument registers, a table generated from Apple's headers says how to decode them, and the host replays each message on a real MTLDevice.

Before I pushed the first end-to-end version, a security review flagged it as a VM escape. It was right: a host that runs whatever message a guest names is a remote control for the host. Since then, a message runs only if its class and selector are on an allowlist generated from metal-cpp, minus the entries that reach host files, processes or Mach ports, and every argument has to fit the method's real type. A test sends hand-built messages that skip metal-cpp:

# poc/mtlcpp/tests/escape.cpp: every one of these is refused
+[NSTask ...]
-[NSString writeToFile:...]
newLibraryWithURL:
setBytes claiming 1 MiB, with 4 bytes sent
an out-parameter where Metal reads an array of 1000
NULL where Metal writes

Then Metal itself bit me. It ends its process on API misuse, like committing a command buffer with an encoder still open, so one guest program's mistake ended the device for every guest. Each guest context got its own executor process, under a deny-by-default sandbox modeled on the profile macOS ships for its paravirtualized GPU process.

I built that for crash isolation. A later test showed what it's really for. Metal 4 binds memory by GPU address, and a guest can put any number there. So one guest program held a buffer of a known pattern, and a second tried to read it by address:

Where the executors runValues read from the other program's buffer
native, two processes0 of 1,024
guest, all executors in one process1,024 of 1,024
guest, one process per guest context0 of 1,024

No GPU error showed up in any case. The process boundary is the memory boundary. That holds for the metal-cpp path. The mtlv path, the one llama.cpp uses, still runs in the device's own process, so the device takes one mtlv tenant at a time. The separate process costs about 15 µs per round trip.

The MLX "first-run stall" had nothing to do with the first run

MLX was a non-goal in my design doc. It built in the guest anyway, on its Metal backend, and printed exactly what it prints natively. Except once: the first run after a build didn't finish within 300 seconds.

I named it the first-run stall and went looking for cold-start costs. Cold shader compiles, cold paging over virtio-fs and MLX's fences were all ruled out. So I made the next hang leave evidence: a guard script that dumps every guest thread's backtrace at the time limit. It caught one. The hang came about once in 25 to 40 runs, and it wasn't tied to the first run at all.

The backtrace showed a lock-order inversion in my guest runtime. The events thread freed a finished completion handler while holding the callbacks lock. Freeing it released MLX buffers the handler had captured, and releasing a buffer takes the transport lock. Meanwhile, another thread held the transport lock and was adding a handler, which needs the callbacks lock. The host sat idle the whole time.

A test with 2,000 handlers hung every time before the fix. The fix was to free handlers with no lock held, and MLX has matched native in 100 runs of 100 since.

Speed came the same way. SmolLM2-360M on MLX gave the same tokens as native, but slowly. Counting the calls that waited on the host showed about 1,000 round trips per token, nearly all for answers that never change. Once the host marked those replies as constant, plus a few changes like it, decode fell to 9.4 ms per token.

A Mac joined my home cluster through a route, not a bridge

A Kubernetes worker has to be reachable, but apple/container gives a machine a NAT or host-only network, and bridged networking in Virtualization.framework needs a restricted entitlement. So I routed instead.

Every other node got a route to the VM subnet via the Mac, and Calico was told to accept VXLAN from the Mac's address, since traffic the VM starts leaves NATed to it. LLMKube scheduled a model onto the new node, and a pod on another node called it across the overlay and got the right answer.

The 8 GiB ceiling was an alignment rule, not a limit

Under EFI boot, the firmware stops the VM before it touches the device, so there was nothing to read. apple/container boots the kernel directly, so I tried a direct-boot VM, and the guest said exactly what was wrong:

pci 0000:00:07.0: BAR 4 [mem size 0x400000000 64bit]: can't assign; no space
vp_get_shm_region: bar shorter than cap offset+len

The guest gets one 64-bit MMIO window of exactly 16 GiB. For every RAM size I measured, it starts 2 GiB above the guest's RAM size. The shared region becomes a PCI BAR, which is a power of two and must start on a multiple of its own size. So a 9 GiB region rounds up to the next power of two. That BAR only fits when the window happens to start on a 16 GiB boundary. An 8 GiB BAR always fits, which is why it looked like a law.

To check, I picked guest RAM sizes that move the window:

Guest RAM16 GiB region, direct boot
2 GiBcan't assign
14 GiBmaps
16 GiBcan't assign
30 GiBmaps
48 GiBcan't assign

EFI still stops at that size. Under direct boot a bad size fails quietly instead: the VM runs, and virtio-gpu comes up without the region.

So the ceiling is a choice of memory size. A container machine now takes gpu-shm=16, and it refuses a memory size that can't map it rather than failing quietly.

A 512K context fit, and then generation ran at a tenth of native

I gave a 30 GiB machine the 16 GiB region and put Qwen4-35B-A3B on it, with its vision projector and MTP drafting, at a 512K-token context. About 22 GiB of weights sit in GPU-only host memory outside the region. The KV cache and compute buffers take about 8.3 GiB inside it.

It generated 7 tokens a second, against about 80 natively. My first guess was that the weights were paging, and locking them in memory changed nothing. The host side looked healthy, at 27 command buffers per token. The guest was the odd part: nearly idle, and waiting on reads.

Qwen4 keeps a 10.7 GiB n-gram embedding table on the CPU side, and llama.cpp reads its rows lazily, a few at a time, straight from the model file. My container read that file over a virtio-fs share. Reading the table whole at load, with --lazy-mode off, took generation to 84.5 tokens a second in the guest.

From a pod, through LLMKube, it now serves with that 512K window. Short prompts generate at 88 to 97 tokens a second with drafting on, and the longest prompt I've sent so far, 126,505 tokens, prefilled at about 1,130 a second.

Then the benchmark split in two. Some runs prefilled at native speed and others at about half, and each run stayed in its mode. My first guess was the scheduler putting the VM on efficiency cores. But the guest was only 6 to 10% busy in fast and slow runs alike, and the host saw exactly the same work every time.

Then I looked at the Mac instead of the VM. It was deep in swap. My node VM already held the model, and each benchmark started a second large VM beside it, so every run pulled about 10 GiB back in. The device keeps the guest's weights in ordinary host memory that nothing pins, where native llama.cpp maps the model file. That's my leading suspect, not a proven cause: every run in my swap capture was a slow one, so it can't show what picks the mode. Pinning those weights on the host is the next test. Benchmarked as a pod on the node, with nothing else started, generation runs at 95 to 97% of native.

The swap crashes have only ever hit 4K guests

The host uses 16 KiB pages. Debian's arm64 kernel uses 4 KiB pages. So on the M6 I made two copies of one Debian disk that differ only in the kernel package, and every check passed on both at the same speed.

Then I ran an A/B with the same swap harness and no GPU device, 12 rounds, with the order flipped each round.

Guest kernelRuns that crashed
4K pages3 of 12
16K pages0 of 12

That's suggestive, not proof. A one-sided Fisher's exact test gives p ≈ 0.11, and the 4K runs swapped a little more. Still, every crash I've seen so far was on a 4K guest. I later found that onexay/msl, a WSL-style Linux environment for macOS 27, hit the same corruption with 4K guest pages under memory pressure. Its notes blame Virtualization.framework's 4 KiB IPA granule path (msl#42), and it runs 16K pages for that reason. I haven't confirmed that mechanism myself, but it fits everything I saw. If I set up a Mac node today, I'd use a 16K guest kernel and leave the host memory to spare.

The numbers: generation lands at parity, and the boundary shows on tiny models

llama.cpp generation on my M5 Max laptop (128 GB), in tokens per second. Each is the mean of three interleaved rounds of llama-bench on a quiet machine.

tg128nativeVMcontainerLLMKube pod
Qwen3-0.6B Q8_0385.6366.6369.4367.1
Qwen3-8B Q4_K_M94.394.495.495.0
Qwen3.8-27B Q4_K_M25.4525.1525.3625.70

The M6 (32 GB), llama.cpp 1.0.0, in tokens per second:

pp512tg128
Qwen3-8B Q4_K_M, native, before873.630.27
Qwen3-8B Q4_K_M, 4K guest861.230.63
Qwen3-8B Q4_K_M, 16K guest859.530.72
Qwen3-8B Q4_K_M, native, after858.929.81
Gemma 3 12B Q5_K_M, native553.117.20
Gemma 3 12B Q5_K_M, guest552.917.15

The Qwen3-8B rows are one back-to-back run each; the Gemma rows are the mean of three interleaved rounds, from an earlier day. On the release build (llama.cpp e339c7d31), built fresh on the M6 with nothing but Command Line Tools, Qwen3-8B and Gemma 3 12B ran at native speed in a --gpus container, five interleaved rounds each.

And the rest:

nativeguest
test-backend-ops, llama.cpp 1.0.0 (M6)19,266 of 19,26619,266 of 19,266, same test names
Qwen3.8-27B, 4 concurrent streams, aggregate t/s (M5 Max)44.144.4 in the LLMKube pod
Qwen3-8B generation, called from a pod on another node (M6)28.1 (native llama-bench at the time)27.6
SmolLM2-360M on MLX, ms per token (M6)5.859.4, down from 64
MLX round trips for one 32-token run179, down from 33,965
100 dispatches per command buffer, waited (M6)170 µs298 µs metal-cpp, 234 µs mtlv

From 8B up, generation is at parity in a VM, a container and a pod. The tiny model shows the fixed cost of the boundary, and MLX still pays for how many messages it sends.

It has real limits. It needs macOS 27, and the shared region is 8 GiB, or 16 GiB in a container machine with 14 or 30 GiB of memory. The mtlv path, the one llama.cpp and the pods use, still runs in the device's own process, so two pods can share one node's device only with an opt-in, and then they aren't isolated from each other. The swap crashes are open, and TensorFold, another Metal engine, doesn't run in the guest yet.

A security review before launch found more than I expected

I had planned to publish a week earlier. Before that, I had two independent, AI-assisted security reviews read the device and the executor the way an attacker in the guest would, and I moved the date to fix what they found.

The lesson that surprised me most: release Metal trusts every number you hand it. An argument index of 1,000 returns "normally" after writing outside the encoder's table, and a threadgroup memory index does the same. Swift is the opposite, and traps on an overflowing addition, which takes the whole VM down with it.

So I checked those numbers, then had a fresh review read the fixes. It found more of the same kind: other tables Metal indexes without looking, a sampler "resource ID" that Metal multiplies by 32 and reads as an address, a function-constant index that trips an assertion Metal keeps on in release builds. Checking numbers one at a time doesn't end. Now the generator that builds the allowlist leaves off any method with an index, offset or range argument that nothing checks, and the ones MLX needs get checked against their real sizes.

The others were about where the boundaries really were. The executor's sandbox still let it read the user-wide caches every app shares, Metal's shader cache among them, so each executor now gets a private directory and nothing else. The standalone VM shared my repo read-write, binaries included, which made guest root a way onto the Mac, so the repo is now shared read-only. And all llama.cpp contexts in one VM share a GPU address space, so the device takes one at a time unless you opt in. MetalPassthrough, below, already gives every guest process its own host process; moving the mtlv path onto per-context executors is next on my list.

The fixes have tests that failed first, the same fixes go into the apple/container patches, and SECURITY.md lists what is still open.

Others are getting the Mac's GPU into Linux too

The closest is MetalPassthrough, published in November independently of this work. It runs Metal compute shaders, and CUDA/PTX programs translated to Metal, from apple/container Linux containers on the Mac's GPU, through its own API and a custom virtio device that maps the container's memory zero-copy. Where this project forwards the Metal API itself, so code written against Metal runs in the guest with little or no change, MetalPassthrough gives you a new API and brings CUDA along. Its per-process isolation is ahead of my mtlv path.

Others take a different road. llama.cpp's ggml-virtgpu forwards ggml operations over virtio-gpu to a host backend. krunkit gives VMs Vulkan through Venus, translated to Metal on the host. minikube has run llama.cpp with GPU acceleration in Kubernetes pods on a Mac since September 2025, through an experimental krunkit driver. kiac runs Kubernetes on apple/container; its GPU workers are krunkit VMs on Venus, and its Metal service on the Mac lets pods on apple/container nodes lease inference that runs on the host. container-toolkit-mlx does the same for MLX from apple/container. onexay/msl has spiked a GPU path, a custom device and guest driver that carry llama.cpp's ggml-rpc to a Metal server on the host, though it doesn't ship one yet, and it found the same 4K-page trouble under memory pressure.

The prototype works, and the next step is a real home for the device

I'd like a generic virtio-gpu device to land in apple/containerization, and I want to work toward that through that project's contribution process. Until then, everything is in defilantech/metal-virtio.

If you have a Mac on macOS 27, the README has a quickstart that serves a small model from a --gpus container in about the time the build takes. Then tell me how it went on your hardware, worked or not. There's an issue form for exactly that, and reports from Macs I don't have are the most useful thing anyone can send.

If you try this, here's what I'd tell myself on day one

  1. Start from the stock virtio_gpu driver. Offer the VIRGL bit even without OpenGL, and keep the context type ID under 31.
  2. Round every mappable blob to the host's 16 KiB pages.
  3. Keep model weights out of the shared region.
  4. Size the region to the guest's 64-bit window, and check the guest log for +host_visible, because a bad size fails silently.
  5. Confirm every blob creation from the guest. The Linux driver won't tell userspace it failed.
  6. Give each guest context its own executor process from day one. It's the memory boundary.
  7. Generate the forwarding from the headers, then allowlist it and type-check every argument.
  8. Count round trips before you optimize anything else.
  9. Run a no-device control before you blame your device, and prefer a 16K guest kernel.
  10. Watch the host's swap-ins before you blame the boundary for a slow run.
  11. Make hangs leave evidence: dump every thread's backtrace at the timeout.
  12. Don't hand release Metal a guest's number. Check it against the real size, or leave the method out.
  13. Share nothing writable with the guest that the host will later run.

Where the receipts are

Everything here is in defilantech/metal-virtio. docs/spike-results.md has the first night with the device. docs/poc-results.md has llama.cpp, apple/container, Kubernetes and the swap runs, with raw outputs in docs/results/. docs/metal-cpp-spike.md has the metal-cpp runtime, the executor, the security tests and the MLX hang, docs/window-and-page-size.md has the 64-bit window and the 4K vs 16K runs, and docs/design.md has the design.

LLMKube

Kubernetes for Local LLMs. Deploy, manage, and scale AI inference workloads with production-grade orchestration.

© 2026 Defilan Technologies LLC

Community

Built for the Kubernetes and AI communities

LLMKube is not affiliated with or endorsed by the Cloud Native Computing Foundation or the Kubernetes project. Kubernetes® is a registered trademark of The Linux Foundation.