Sub topic 12
Splitting a model between GPU and CPU
This chapter assumes you can estimate weight memory and KV cache size from earlier chapters. It also assumes you know the difference between VRAM and system RAM, and that decode speed is bounded by memory bandwidth divided by model size. Here you will see what happens when a model does not fit in VRAM, how to choose how many layers go to the GPU, and why speed does not fall off in a straight line.
What partial offload is
A transformer model is a stack of layers, such as 32 for an 8B model. Each layer has its own weights. Partial GPU offload places the first N layers in VRAM and leaves the rest in system RAM. The CPU runs the layers in RAM, and the GPU runs the layers in VRAM.
In llama.cpp the setting is -ngl (long form --n-gpu-layers). Three values cover most cases:
-ngl 0keeps everything on the CPU.-ngl 18offloads 18 layers.-ngl 99offloads everything. Any number at or above the layer count means "all", which is why 99 is a common default.
The weights never travel back and forth during generation. Each layer stays where it was loaded. For each token, only the small activation vector (a few thousand numbers) crosses the PCIe bus at the boundary between the GPU layers and the CPU layers. The cost of a split is therefore not transfer time. The cost is that the CPU layers run at system RAM bandwidth instead of VRAM bandwidth.
What goes into the per-layer cost
A layer you offload costs VRAM in two ways:
- Its share of the weights.
- Its share of the KV cache. By default llama.cpp stores each layer's K and V tensors on the same device as that layer.
You also need room for the runtime's own buffers. These include the compute scratch space, which grows with the batch size you set. The GPU's display output may also take some VRAM. Reserve roughly 0.5 to 1.5 GiB for this, and check the real figure in the load log.
The helper below turns that into a layer count. It reuses the numbers from the memory estimate chapter: 4.52 GiB of weights and 1.0 GiB of KV cache at 8192 tokens.
def layers_that_fit(vram_gib, weights_gib, kv_gib, n_layers, overhead_gib=1.0):
# Each offloaded layer holds its share of weights and of the KV cache.
per_layer = (weights_gib + kv_gib) / n_layers
budget = vram_gib - overhead_gib
return max(0, min(n_layers, int(budget // per_layer)))
weights = 8.0e9 * 4.85 / 8 / 2**30 # about 4.52 GiB
kv = 2 * 32 * 8 * 128 * 8192 * 2 / 2**30 # 1.0 GiB at 8192 tokens
n = layers_that_fit(vram_gib=4.0, weights_gib=weights, kv_gib=kv,
n_layers=32, overhead_gib=0.8)
print(f"offload {n} of 32 layers")With a 4 GiB card and 0.8 GiB reserved, each layer costs about 0.17 GiB, so 18 layers fit. The function rounds down, because a layer that does not fit fully cannot be placed partly.
This is a starting estimate. The model also has a token embedding table and an output projection that are not part of the 32 repeated layers. The runtime counts the output layer as one more offloadable unit. Treat the result as a first guess, then confirm it from the load log and a benchmark.
Why speed is not linear in layers offloaded
Each generated token passes through every layer once. The time to produce a token is the sum of the time spent on each device:
time per token = (GPU share of bytes ÷ GPU bandwidth) + (CPU share of bytes ÷ CPU bandwidth)
The ceiling in tokens per second is the inverse of that time. This extends the single-device ceiling from the previous chapter.
def split_ceiling_tokens_per_s(model_file_gb, gpu_fraction,
gpu_bw_gb_s, cpu_bw_gb_s):
gpu_time = model_file_gb * gpu_fraction / gpu_bw_gb_s
cpu_time = model_file_gb * (1 - gpu_fraction) / cpu_bw_gb_s
return 1 / (gpu_time + cpu_time)
fraction = 18 / 32
print(f"{split_ceiling_tokens_per_s(4.9, fraction, 300, 50):.1f} tokens/s ceiling")This prints about 19.2 tokens per second for a 4.9 GB file, a 300 GB/s GPU and 50 GB/s of system RAM bandwidth. The table shows how the ceiling changes with the fraction on the GPU, using the same hardware:
| Fraction on GPU | Ceiling (tokens/s) |
|---|---|
| 0% | 10.2 |
| 25% | 12.9 |
| 50% | 17.5 |
| 75% | 27.2 |
| 90% | 40.8 |
| 100% | 61.2 |
The first quarter of the model moved to the GPU gains about 2.7 tokens per second. The last quarter gains about 34. The slow CPU portion dominates the total time until it is almost gone. Offloading 56% of the layers gives roughly a third of the full-GPU ceiling, not 56% of it.
Prompt processing behaves differently
Prompt processing (prefill) is limited more by compute than by bandwidth. A GPU has far more arithmetic throughput than a typical CPU, so layers left on the CPU slow prefill sharply. This matters for long prompts, such as pasted documents or retrieval results. A setup that generates at an acceptable speed may still take a long time before the first token appears. Benchmark both numbers.
Choosing the split in practice
Work through these steps:
- Pick the context length you actually need. The KV cache is part of the budget, so a larger context means fewer offloaded layers.
- Estimate the layer count with the helper above, then start the runtime and read the log. llama.cpp reports how many layers it placed on the GPU and the size of each buffer.
- Raise
-ngluntil you get an out-of-memory error, then step back by a few layers. Keep a margin of a few hundred MiB, because memory use can rise with longer prompts and larger batches. - Compare options that trade the same VRAM differently. Dropping the context from 16K to 8K may free enough VRAM for several more layers. A lower quantisation (a smaller file) may let all layers fit.
llama-bench -m model-Q4_K_M.gguf -p 512 -n 128 -ngl 0,12,18,24,32llama-bench accepts a comma-separated list for most parameters and runs each combination. The output has one row per setting for prompt processing and one for generation, so you can plot the curve for your own machine and compare it with the table above.
Edge cases and failure modes
- Fully fitting is a threshold, not a gradient. Going from 31 of 32 layers on the GPU to all 32 can produce a larger speedup than any other single step, because the CPU path disappears. If you are one or two layers short, a smaller quantisation or a shorter context is usually worth more than tuning
-ngl. - KV cache placement. The option
--no-kv-offload(-nkvo) keeps the KV cache in system RAM while the weights stay on the GPU. This frees VRAM for more layers but makes the attention step read the cache over the slower path. It can help with very long contexts, but measure it. - Memory that silently spills. Some driver and OS configurations let the GPU allocate beyond VRAM into system memory. Speed then falls sharply even though nothing fails. If a benchmark shows a cliff at a certain
-nglthat your estimate did not predict, check VRAM use with the vendor's monitoring tool. - System RAM must hold the rest. Layers not on the GPU need RAM. If the file is larger than free RAM plus VRAM, the OS pages the model from disk and speed drops to a crawl.
- Unified memory. On machines where the CPU and GPU share one memory pool, offloading means which processor runs the layers, not where the bytes live. There is no VRAM cliff, and
-ngl 99is usually the right choice. - Mixture-of-experts models. Most of an MoE model's weights are expert tensors that are only partly used per token. Recent llama.cpp builds can keep the experts in system RAM and the attention layers on the GPU (see
--cpu-moeand--n-cpu-moe). This often beats a plain layer split.
Exercise
A model file is 8.0 GB with 40 layers. Your GPU has 400 GB/s of bandwidth and your system RAM has 40 GB/s. You can offload 30 of the 40 layers. Estimate the decode ceiling in tokens per second, and compare it with the ceiling if all layers fit on the GPU.
Show answer
The GPU fraction is 30/40 = 0.75. GPU time = 8.0 × 0.75 / 400 = 0.015 s. CPU time = 8.0 × 0.25 / 40 = 0.05 s. Total = 0.065 s, so the ceiling is about 15.4 tokens/s. With all layers on the GPU, the ceiling is 400 / 8.0 = 50 tokens/s. The 10 layers left on the CPU make up a quarter of the file but take over three quarters of the per-token time.
Exercise
Your benchmark with -ngl 24 is far slower than your estimate, and the GPU monitor shows VRAM full. What are two likely causes, and what is one change that would help?
Show answer
Likely causes: the runtime or driver is spilling GPU allocations into system memory, or the KV cache and compute buffers take more VRAM than the estimate assumed, which leaves fewer useful layers on the GPU. A change that helps is to lower -ngl a few layers or reduce the context length so everything placed on the GPU stays within VRAM, then re-run llama-bench to confirm the speed returns to the predicted curve.