Running 35B MoE Models on Low VRAM: A CPU Offloading Guide

    Running large Mixture of Experts (MoE) models in a low VRAM environment can be challenging, but CPU offloading offers a viable solution. This article provides a practical guide on how to run a 35B parameter MoE model on a machine with only 8GB of VRAM and 16GB of system RAM. By keeping expert weights in system memory and computing them via the CPU while leaving the attention layers on the GPU, you can bypass VRAM limitations. We cover everything from compiling llama.cpp for specific CPU instruction sets and choosing the right GGUF quantization file, to estimating memory requirements, configuring launch commands, and testing performance. Troubleshooting tips and scope of application are also included to ensure stable inference performance.

    Conclusion First

    Running a MoE model with 35B total parameters and 3B activated parameters on a machine equipped with 8GB of VRAM and 16GB of system RAM is feasible. The approach is to keep the attention layers and shared components on the GPU, while placing the majority of the expert weights in system memory to be computed by the CPU. Generation speed is primarily affected by memory bandwidth and CPU performance. As the context length grows, the KV Cache will fill up the VRAM first, which requires separate handling.

    1. Why MoE Models Can Be Split This Way

    MoE models consist of numerous expert networks, with each token only calling upon a few of them. Although the model’s total parameter count is massive, the computational load per step is determined by the activated parameters. Therefore, placing infrequently used expert weights in system memory and only having the CPU compute them when needed can bypass VRAM capacity limits.

    This method comes with trade-offs. Computing expert layers on the CPU means the speed is constrained by memory bandwidth and CPU compute power. The GPU portion calculates quickly, but every layer must wait for the CPU to finish the expert calculations, creating a bottleneck between the two parts. Thus, finding a balance point when splitting layers is necessary. The more layers offloaded to the CPU, the less VRAM pressure, but the slower the generation speed.

    2. Compiling the Inference Framework from Source

    Pre-compiled versions are typically built for generic CPU instruction sets. Compiling from source allows you to enable the instruction sets supported by your current CPU as well as CUDA acceleration. Taking llama.cpp as an example, the commands are as follows:

    1. git clone https://github.com/ggml-org/llama.cpp
    2. cd llama.cpp
    3. cmake -B build -DGGML_CUDA=ON -DGGML_NATIVE=ON
    4. cmake --build build --config Release -j 8

    -DGGML_CUDA=ON enables the CUDA backend; you will need to install the CUDA Toolkit that matches your GPU driver version prior to compilation. -DGGML_NATIVE=ON instructs the compiler to generate code tailored for the local CPU. The number following -j should be set to your CPU core count.

    Once compiled, the system_info line in the program startup logs will list the enabled features, allowing you to confirm whether CUDA and instruction sets like AVX2 or AVX-512 are active. On Linux systems, you can use the lscpu command to check if your CPU supports the avx512 flag.

    Parameter names depend on the version you are using. Parameters related to expert offloading are only available in newer versions. If you cannot find --n-cpu-moe in --help, you will need to update the source code and recompile.

    3. Choosing the Quantization File

    Model files read by llama.cpp use the GGUF format. The quantization method determines the file size and precision. IQ4_NL is a 4-bit non-linear quantization that uses a codebook to represent weights rather than an equidistant scale. At the same bit count, this method usually incurs less error. For a 35B model, such a file is approximately 18 to 20GB in size.

    File size determines disk usage and indirectly impacts memory pressure. When selecting a file, note three things: First, download from a trusted source and verify the file’s checksum. Second, read the license agreement on the model’s page to confirm if your intended use is permitted. Third, ensure that the remaining disk space is significantly larger than the file to accommodate system cache and temporary files.

    4. Estimating VRAM and System RAM

    By adding --n-cpu-moe N, the expert weights of the first N layers will remain in system memory to be computed by the CPU, while attention layers, word embeddings, and shared components stay on the GPU. Consequently, the system memory required roughly equals the total size of the expert tensors in those N layers. To see how much space each type of tensor occupies, you can first run pip install gguf, then use the included gguf-dump tool.

    By default, llama.cpp uses memory mapping to read model files. Memory mapping does not mean the entire file resides in memory. The system only reads a specific data segment into the page cache when it is accessed; when memory is low, old pages are discarded and later re-read from the disk. If the expert weights required by the CPU exceed the available memory, every token might trigger disk reads, leading to a significant drop in speed. Adding --no-mmap will read the entire model into memory at startup, resulting in a slower start but more stable runtime. This option is only suitable when your memory can fully accommodate the model.

    The KV Cache stores the attention keys and values for each processed token, and its size is independent of the activated parameters. The calculation formula is as follows:

    KV Cache bytes = 2 × number of layers × number of KV heads × dimension per head × context length × bytes per element

    The “2” represents the two caches for K and V. Each element takes 2 bytes in FP16, and about 1 byte in q8_0 quantization. Here is an example calculation: 40 layers, 8 KV heads, 128 dimensions per head, a context length of 32768, using FP16, totaling approximately 5 GiB. This merely demonstrates the calculation method and does not represent the actual values for this specific model. The number of layers, KV heads, and dimensions should be read from the config.json in the model directory.

    The crucial point is that even if the expert layers have been offloaded to the CPU, the KV Cache usually remains on the GPU. As the context lengthens, the VRAM will be filled by it. There are two ways to handle this: reduce the context length specified by -c, or quantize the KV Cache using --cache-type-k q8_0 --cache-type-v q8_0. Quantizing the V cache requires enabling --flash-attn simultaneously.

    5. Launch Command Example

    1. ./build/bin/llama-server \
    2. -m ./models/model_file.gguf \
    3. -ngl 99 \
    4. --n-cpu-moe 30 \
    5. -c 32768 \
    6. -t 8 \
    7. --flash-attn on \
    8. --cache-type-k q8_0 \
    9. --cache-type-v q8_0 \
    10. --host 127.0.0.1 --port 8080

    The functions of each parameter are as follows:

    • -ngl 99: Attempts to place all possible layers onto the GPU. If the number exceeds the model’s total layers, it equates to placing all layers on the GPU.
    • --n-cpu-moe 30: The expert weights of the first 30 layers remain in memory and are computed by the CPU. “30” is just an example; the appropriate value depends on the model’s layer count.
    • -c 32768: The context length. This directly affects the KV Cache size.
    • -t 8: The number of CPU threads. It is recommended to set this to the number of physical cores; hyper-threading usually offers little benefit and may cause resource contention.
    • --host 127.0.0.1: Only allows access from the local machine.

    When adjusting --n-cpu-moe, first set a larger value to ensure the program can start. Then gradually decrease this value until the VRAM is near capacity but not overflowing. This will yield the highest speed.

    6. Testing Performance

    You can test the speed using the built-in benchmarking tool:

    1. ./build/bin/llama-bench -m ./models/model_file.gguf -ngl 99 --n-cpu-moe 30 -t 8 -p 512 -n 128

    -p specifies the number of input tokens, used to test the pre-fill speed. -n specifies the number of tokens generated, and the tg value in the output represents the generation speed. In long-context scenarios, generation speed decreases as the context grows, so it is also necessary to test with real conversations. The logs of llama-server record the time taken for each request, from which you can calculate the generation speed.

    When publishing test results, it is recommended to include the following information: CPU and GPU models, memory capacity and frequency, driver and CUDA versions, llama.cpp commit hash, quantization file name, context length, output length, and number of threads. Since speed is highly dependent on hardware, numbers without this information cannot be directly compared with those from other machines.

    7. Common Issues

    • Out of VRAM at startup: Increase --n-cpu-moe or decrease -c.
    • Out of memory at startup or process terminated by the system: Close background programs. If still insufficient, use a smaller quantization file.
    • Sudden drop in generation speed: Use the system monitor to observe disk reads. If the read volume continuously rises, it indicates insufficient memory and frequent system paging.
    • High CPU usage but no speed improvement: The thread count may be too high. Try lowering -t.
    • Errors or slowdowns after context growth: The KV Cache has filled the VRAM. Decrease -c or enable KV Cache quantization.

    8. Scope of Application and Precautions

    This method is suitable for MoE models with relatively small activated parameters. Dense models use all weights for every token; applying the same split would route every step through the CPU, resulting in generally unacceptable speeds. Disk and memory bandwidth must also be sufficient. On-demand reads on a mechanical hard drive will be very slow; a solid-state drive is more appropriate.

    Long periods of high-load operation will keep the GPU and CPU at full capacity. Pay attention to cooling and power supply; laptops should be particularly mindful of temperatures. Frequent reading of large files will also cause some wear on the SSD, though the impact for general use is limited.

    The benefit of local deployment is that data stays on your machine. The service only listens to the local address by default. If you want to expose it to a local area network, you need to configure access control yourself.

    Object storage is not suitable for storing weights during inference. The inference process requires frequent reading of weights, and the access latency of object storage is much higher than that of local disks, which will significantly slow down generation speed.