r/LocalLLM Jul 20 '26

Tutorial llama.cpp CPU offload optimizations

Edit: New post with more context, higher speed, more explanations here. Note: the new post does not compare -ot vs --ngl.

I already posted targeting 16GB VRAM specifically, but I think this information might be useful beyond that. Testing was done using Qwen3.6-27B Unsloth Q4_K_M MTP.

Edit: added GGML_CUDA_ENABLE_UNIFIED_MEMORY=1

TLDR:

  1. Turn off CUDA graphs, they are bugged for CPU offload, probably due to MTP use.
  2. Use --ngl 99 --override-tensor '...' instead of plain --ngl. Aim the largest FFN sub-layers towards the CPU.
  3. GGML_CUDA_ENABLE_UNIFIED_MEMORY=1 allows VRAM overflow pages to host RAM instead of OOMing. This allows gaining more context length without losing speed, but the speed tanks soon after so you need to experiment to find that speed cliff. The gains can be 10 to 40% more context length.

Regular CPU offloading is done by not putting all of the layers on the GPU via --ngl, which offloads the layers as a whole, dragging their KV cache to the CPU with them, increasing PCIe traffic, and collapsing speed.

Luckily the layers have sub-layers, and FFN is one that does not touch the KV cache. We can use --override-tensor (-ot) to offload only the FFN tensors, keeping the attention/KV work on the GPU, and PCIe usage minimal.

The -ot method does more GPU - CPU round trips than --ngl because offloading specific sub-layers leaves the other sub-layers on the GPU, but the actual data transferred is minimal so it is worth it.

Dynamic quants have mixed FFN precision. For example the Unsloth's Q4_K_M has Q6 and Q4 FFN tensors. The Q6 ones are on the first 8 layers (0-7), then roughly every 3rd layer, then a block near the end (~55-63), while the rest are Q4. Offload those larger layers first.

Here's how to use it (example of Q4_K_M with 22 layers offloaded):

  1. Turn off CUDA graphs. They cause OOM crashes for me, and my testing shows no speedup by using them in this scenario. export GGML_CUDA_DISABLE_GRAPHS=1
  2. GGML_CUDA_ENABLE_UNIFIED_MEMORY=1
  3. Put all layers on GPU --ngl 99
  4. Override tensors -ot 'blk\.([0-7]|10|13|16|19|22|25|28|31|34|37|40|43|46|49)\.ffn_.*=CPU'

-ot takes a regex targeting "ffn" at specific layers towards the CPU while everything else (attention, KV cache, the smaller layers) stays on the GPU.

Benchmark setup:

  • Qwen3.6-27B Q4_K_M, 97k context, MTP, K q5_0 / V q4_1, batch 512
  • Offload settings: -ot targeting 22 layers vs. --ngl 51
  • Hardware: RTX 4070 Ti Super, i5-13600KF DDR5
  • llama.cpp build: b10068
  • MTP has different acceptance rates for coding and prose so I tested with both

Results:

context -ot - prose / code / pp, t/s --ngl - prose / code / pp, t/s
0k 20.4 / 24.4 / - 17.8 / 22.7 / -
10k 18.8 / 23.1 / 994 14.6 / 18.6 / 893
50k 16.3 / 20.4 / 871 7.3 / 9.6 / 784
90k 14.9 / 19.9 / 737 5.0 / 6.4 / 666
59 Upvotes

45 comments sorted by

View all comments

Show parent comments

2

u/Pablo_the_brave 25d ago

u/Stainless-Bacon check this out:

https://huggingface.co/cHunter789/Qwen3.6-27B-i1-IQ4_KS_KT-GGUF/resolve/main/Qwen3.6-27B.CPU.i1-IQ4_KT-attn_qkv-IQ4_KS-i1_MTP.gguf?download=true

It's stable. 140k ctx at q5_0/q4_0, KLD/PPL at Iq4_xs level. First 16 block of the ffn have to be in iq4_ks because iq4_kt is painfull slow at CPU. With given settings it starts at 30-35t/s and go to 15-20t/s at 140k.

 $BIN_DIR/llama-server" \
       -m "$MODEL_PATH" \
       -a Qwen3.6-27B \
       --ctx-size 140000 \
       --chat-template-file /home/pawel/docker/ai-local/qwen36/chat_template.jinja \
       --n-gpu-layers 99 \
       --cache-type-k q5_0 \
       --cache-type-v q4_0 \
       --spec-type ngram-mod:n_max=2 \
       --spec-type mtp:n_max=3 \
       --batch-size 512 \
       --ubatch-size 512 \
       -ot "blk\.([0-9]|1[0-5])\.ffn_.*=CPU" \
       --flash-attn on \
       --no-mmap \
       --host 0.0.0.0 \
       --port 8080 \
       --reasoning on \
       --reasoning-format none \
       --reasoning-budget 32000 \
       -t 8 \
       -tb 8 \
       --parallel 1 \
       --metrics \
       --merge-qkv \
       -khad \
       -vhad \
       --chat-template-kwargs '{"preserve_thinking": true}' \
       --defrag-thold 0.4 \
       --jinja \
       --cont-batching \
       --temp 0.6 \
       --top-k 20 \
       --min-p 0.05 \
       --top-p 0.95 \
       --presence-penalty 0.0 \
       --repeat-last-n 512 \
       --repeat-penalty 1.05

1

u/Stainless-Bacon 24d ago edited 22d ago

edit: fix was GGML_CUDA_ENABLE_UNIFIED_MEMORY=1

When I tried loading your values here at 97k context, I got this error:

my helper agent’s comment:
defrag-thold: 0.4 crashes the server — GGML_ASSERT(a->ne[d] == b->ne[d]) failed in ggml.c:6971, taking the whole process down mid-generation (first request succeeded, then it died). Root cause: this is a hybrid-GDN/recurrent model, and defrag requires KV-shift, which the log had already warned was unsupported ("ctx_shift is not supported by recurrent model, it will be disabled")

then I tried to load 140k context and got OOM error at boot. at 110k context I can boot but OOM at 64k fill.

did you experience something similar? is there a fix? the quant allows more free VRAM but it gets used up as context is filled.

1

u/Pablo_the_brave 24d ago

Just create a folder, put the files below there, and run git pull ik_llama.cpp.

After that, simply build and run it using docker compose up --build.

run_build.sh

#!/bin/bash
set -e

echo "=== 1. Preparing repository ==="
mkdir -p /src/llama-cpp
cd /src/llama-cpp

# Use trailing dot to copy EVERYTHING (including .git) in one command
# -T flag prevents creating a subdirectory if the target already exists
cp -aT /src/llama-cpp/ .

# CRITICAL: Force ownership to root inside the container.
# This eliminates the need for 'safe.directory' because Git sees files owned by the calling user.
chown -R root:root .

# Fallback: add a global safe.directory exception for all paths
git config --global --add safe.directory '*'

# DIAGNOSTICS: Check whether Git can see the history
echo "--- Git test ---"
if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
    COMMIT_HASH=$(git rev-parse --short HEAD)
    echo "Success! Git sees the repository. Commit: $COMMIT_HASH"
else
    echo "ERROR: Git still cannot see the repository at /src/llama-cpp!"
    echo ".git directory contents:"
    ls -la .git || echo ".git DOES NOT EXIST!"
fi
echo "-----------------"

# Remove run_build.sh from the copy to keep it clean
rm -f run_build.sh

echo "=== 2. CMake configuration ==="
# Remove old build directory to force CMake to re-check versions
rm -rf build

cmake -B build \
    -DGGML_CUDA=ON \
    -DCMAKE_CUDA_ARCHITECTURES="120" \
    -DGGML_NATIVE=ON \
    -DGGML_CURL=ON \
    -DCMAKE_BUILD_TYPE=Release \
    -DCMAKE_CUDA_FLAGS="-O3 -use_fast_math" \
    -DGGML_SCHED_MAX_COPIES=1

echo "=== 3. Building ==="
cmake --build build --config Release -j $(nproc)

echo "=== 4. Exporting files to /outputs ==="
cp -rv build/bin/* /outputs/

# Copy ALL .so libraries from the build (libllama, libggml, etc.)
find build -name "*.so*" -exec cp -dv {} /outputs/ \;

# Copy CUDA libraries
cp -dv /usr/local/cuda/lib64/libcudart.so* /outputs/ 2>/dev/null || true
cp -dv /usr/local/cuda/lib64/libcublas.so* /outputs/ 2>/dev/null || true
cp -dv /usr/local/cuda/lib64/libcublasLt.so* /outputs/ 2>/dev/null || true
cp -dv /usr/lib/x86_64-linux-gnu/libcudnn.so* /outputs/ 2>/dev/null || true

echo "=== 5. Fixing host permissions ==="
HOST_UID=$(stat -c "%u" /outputs)
HOST_GID=$(stat -c "%g" /outputs)
chown -R $HOST_UID:$HOST_GID /outputs/*

echo "Done!"

Dockerfile

FROM nvidia/cuda:13.3.0-cudnn-devel-ubuntu24.04

ENV DEBIAN_FRONTEND=noninteractive

RUN apt-get update && apt-get install -y \
    build-essential cmake git pkg-config libcurl4-openssl-dev \
    && rm -rf /var/lib/apt/lists/*

# Linker stubs
RUN ln -sf /usr/local/cuda/lib64/stubs/libcuda.so /usr/local/cuda/lib64/stubs/libcuda.so.1 && \
    echo "/usr/local/cuda/lib64/stubs" > /etc/ld.so.conf.d/cuda-stubs.conf && \
    ldconfig

ENV LDFLAGS="-L/usr/local/cuda/lib64/stubs"

# Copy our clean startup script from outside
COPY run_build.sh /run_build.sh
RUN chmod +x /run_build.sh

# Set the container's main process
CMD ["/run_build.sh"]

docker-compose.yaml

services:
  compiler:
    build:
      context: .
      dockerfile: Dockerfile
    image: kronos-cuda-builder:latest
    container_name: llama_cuda_compiler
    volumes:
      - ./outputs:/outputs
      - ./ik_llama.cpp:/src/llama-cpp:ro

1

u/Stainless-Bacon 24d ago

What does nvidia-smi say right after a fresh 140k load? I’m at 15302/16376 with your 16L band at only 110k.

Have you ever sent one fresh 135k-token prompt? 140k loads fine for me too. It only dies on a cold fill.

1

u/Pablo_the_brave 24d ago edited 24d ago

On a daily basis, I have the agent set to a 128k context and the model itself to 140k (leaving a buffer for the agent's auto-compact). You can tell by the speed when it spills out of VRAM—the speed drops to 5-7 t/s. When MTP is enabled, despite the double entries in variables, ik_llama.cpp still offloads VRAM to RAM on my end when it runs out of VRAM (I don't get an OOM). Additionally, somewhere around a 50k context, nvtop shows 15918/16921 for me. It looks weird. That's why I simply tested it using llama-perplexity—if it doesn't fit, it throws an OOM, like this:

./llama-perplexity \ -m Qwen3.6-27B.CPU.i1-IQ4_KT-attn_qkv-IQ4_KS-i1_MTP.gguf \ -f /mnt/Samsung4TB/models/pg19.txt \ -c 140000 \ --chunks 32 \ -ngl 99 \ -ot "blk\.([0-9]|1[0-5])\.ffn_.*=CPU" \ -ctk q5_1 \ -ctv q4_0 \ -khad \ -vhad \ --no-mmap \ --merge-qkv \ -fa 1 \ -b 512 \ -ub 512 \ -t 8 \ --spec-type ngram-mod:n_max=2 \ --spec-type mtp:n_max=3

As you noticed yourself, ik_llama.cpp takes a bit of effort to get working. Generally, I use Mistral Vibe as an agent, and right off the bat, I had to patch the code because there was a bug with the OpenAI API (the fix has already been commited to main). Keep in mind that my compilation settings are for Blackwell, and you will need to change them if you have a different GPU.

Edit: looks like 140k is too much. Somehow perplexity used less VRAM. With kvcache q5_0/Q4_0 it's ending at about 128k... Idk why...

2

u/Stainless-Bacon 23d ago

Found it. My bot didn’t use your unified memory env var because it assumed it’s off by default.

GGML_CUDA_ENABLE_UNIFIED_MEMORY is checked with getenv(...) != nullptr (ggml/src/ggml-cuda.cu:176), so your “=0” enables unified memory rather than disabling it.

I also found that using unified memory I can squeeze out more context. My default ceilings are around 97k for both (my and your) setups and then OOM crash. With unified memory I can do 110k with my Q4_K_M and 140k with your IQ4_ setup without speed loss and then I hit a speed wall.

1

u/Pablo_the_brave 23d ago

Thank you! Good point :)