Local Deployment of Lightweight MoE Models: From Compilation to Quantization and Tuning

    Learn how to deploy lightweight MoE (Mixture of Experts) models locally with llama.cpp. This guide covers environment setup, engine compilation, GGUF weight conversion, quantization selection, inference, and performance tuning, with a focus on the key distinction between total and activated parameters.

    1. First Things First: MoE Saves Compute, Not Memory

    An MoE (Mixture of Experts) model contains multiple expert sub-networks. For each incoming token, a routing mechanism selects only a few experts to participate in the computation. This means there are two numbers you need to distinguish:

    • Total parameters: the sum of all expert parameters plus shared layers, which determines how much memory or VRAM the model occupies;
    • Activated parameters: the parameters actually involved in computing each token, which determines the per-inference compute load and the amount of data that must be read per token.

    Take a model with 30B total parameters and 3B activated parameters as an example. Its per-token compute is close to that of a 3B dense model, but all expert weights must reside in memory or VRAM, because routing decides which expert to use at runtime. So when deploying an MoE model, budget memory based on total parameters, and set speed expectations based on activated parameters. This is a point many people overlook.

    2. Preparing the Environment

    Compiling and converting require the following tools:

    • Git, for pulling the source code;
    • CMake 3.14 or later, plus a C++17-capable compiler (GCC 11+, Clang, or MSVC);
    • Python 3.10 or later, for the weight conversion scripts;
    • If you use an NVIDIA GPU, a CUDA Toolkit matching your driver.

    Check the versions first:

    1. git --version
    2. cmake --version
    3. g++ --version
    4. python3 --version
    5. nvidia-smi # NVIDIA GPUs only
    6. nvcc --version # only needed for building the CUDA version

    3. Compiling the Inference Engine

    This article uses llama.cpp as an example. Its core operators are implemented in C/C++, it has few dependencies, supports multiple hardware backends, and already supports several MoE architectures. Refer to the project’s README for the exact list of supported models.

    Clone the source code and build the CPU version:

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

    The build artifacts are located in the build/bin/ directory. Set the number after -j to your CPU’s logical core count, or slightly fewer.

    If you use an NVIDIA GPU, add the CUDA flag at the configuration stage:

    1. cmake -B build -DGGML_CUDA=ON
    2. cmake --build build --config Release -j 8

    Build flag names may change between versions. If an option is not found, check the current README first. On macOS, the Metal backend is enabled by default with no extra flags needed.

    It is recommended to build new versions in a separate directory, such as build-new, while keeping the old build directory. If the new version has problems, you can switch back to the old one immediately without recompiling.

    After compilation, run a smoke test with a small model to confirm the engine produces output:

    1. ./build/bin/llama-cli -m ./models/small-test.gguf -p "Hello" -n 32

    If text is generated, both compilation and the runtime environment are working. If you get errors, refer to section 9 of this article for troubleshooting.

    4. Obtaining Weights and Converting to GGUF

    Step 1: Download the original weights. Most models are hosted on platforms such as Hugging Face, and the weights are usually in safetensors format. The following command uses huggingface-cli (the newer tool is named hf) to download:

    1. huggingface-cli download <org/model-name> --local-dir ./hf-model

    After downloading, find the SHA256 value of each file on the model page and verify locally:

    1. sha256sum ./hf-model/*.safetensors

    If the checksums do not match, do not proceed with conversion—download the files again.

    Step 2: Convert to GGUF. The conversion script is located in the root of the llama.cpp source tree and is named convert_hf_to_gguf.py. Install the dependencies first:

    1. pip install -r requirements.txt

    Then run the conversion, producing a GGUF file in F16 precision:

    1. python convert_hf_to_gguf.py ./hf-model \
    2. --outfile ./models/model-f16.gguf \
    3. --outtype f16

    If the script reports an unsupported architecture, it means the current source version does not recognize this model. In that case, update the source code, or switch to a model on the supported list.

    5. Choosing a Quantization Type

    F16 files are large and demanding on memory. Quantization reduces the number of bits used to store each weight, thereby shrinking the file. Use the llama-quantize tool:

    1. ./build/bin/llama-quantize ./models/model-f16.gguf \
    2. ./models/model-Q4_K_M.gguf Q4_K_M

    Reference data for common quantization types is shown below. Size ratios are estimates relative to the F16 file:

    Quantization type Size vs. F16 Approx. bits per weight Accuracy impact Use case
    Q8_0 ~53% 8.5 Very small Ample memory, quality-focused
    Q5_K_M ~36% 5.7 Small Balance of quality and size
    Q4_K_M ~30% 4.8 Acceptable The default choice for most local deployments
    Q3_K_M ~24% 3.9 Noticeable Tight memory budgets
    Q2_K ~21% 3.4 Large Testing only

    File size can be estimated with the following formula:

    File size (bytes) ≈ total parameters × bits per weight ÷ 8

    For example, a 30B total-parameter model quantized to Q4_K_M is roughly 30×10⁹×4.8÷8 ≈ 18 GB. Note that total parameters include all experts—you cannot calculate using only the activated parameters.

    Accuracy loss must be measured, not just read from a table. llama.cpp provides the llama-perplexity tool, which compares the perplexity of different quantized versions on the same text. Lower perplexity generally means the model predicts text better. The following command requires a plain-text test file:

    1. ./build/bin/llama-perplexity -m ./models/model-Q4_K_M.gguf -f ./test.txt -c 2048

    For MoE models, different layers may have different sensitivity to quantization. Some versions of llama-quantize support specifying quantization types per tensor; check the output of ./build/bin/llama-quantize --help for the exact options. Without a specific requirement, Q4_K_M or Q5_K_M is a safe choice.

    6. Running Inference

    The following command starts an interactive session in the terminal:

    1. ./build/bin/llama-cli -m ./models/model-Q4_K_M.gguf \
    2. -p "Hello, please introduce yourself" \
    3. -n 512 -c 4096 -t 8 -ngl 99

    Key parameters:

    • -c: context length. The longer it is, the more memory the KV cache occupies—set it based on actual needs;
    • -t: number of CPU threads;
    • -ngl: number of layers offloaded to the GPU. A large value means offloading as many layers as possible. If VRAM is insufficient, reduce this value and the remaining layers stay in RAM for CPU computation;
    • -n: maximum number of tokens to generate.

    If other applications need to call the model, you can start the built-in HTTP server:

    1. ./build/bin/llama-server -m ./models/model-Q4_K_M.gguf \
    2. --host 127.0.0.1 --port 8080 -c 4096 -ngl 99

    The server is compatible with the OpenAI API. Example call:

    1. curl http://127.0.0.1:8080/v1/chat/completions \
    2. -H "Content-Type: application/json" \
    3. -d '{"messages":[{"role":"user","content":"Explain MoE in one sentence"}]}'

    Note: setting --host to 127.0.0.1 allows access only from the local machine. By default the server has no authentication. If you change it to 0.0.0.0 to expose it on the LAN, put an authenticated gateway in front of it first.

    7. Performance Testing and Tuning

    Measure a baseline before tuning. llama.cpp provides llama-bench, which can compare multiple parameter sets in one run:

    1. ./build/bin/llama-bench -m ./models/model-Q4_K_M.gguf \
    2. -t 4,8 -ngl 0,99 -p 512 -n 128

    The output includes two key metrics:

    • pp (prompt processing): the speed of processing the input prompt, in tokens/s;
    • tg (token generation): the speed of generating the response token by token, in tokens/s. The fluency users perceive depends mainly on this value.

    There is a rough theoretical upper bound for generation speed, which you can use to judge whether your test results are reasonable:

    Generation speed upper bound ≈ memory or VRAM bandwidth ÷ bytes of weights actually read per token

    Take 3B activated parameters with Q4_K_M quantization as an example: each token reads roughly 3×10⁹×4.8÷8 ≈ 1.8 GB of data. With a memory bandwidth of 50 GB/s, the theoretical upper bound is about 28 tokens/s. Real-world speed will be lower due to attention computation, scheduling, and other overhead.

    Keep the following in mind when tuning:

    • Thread count: usually set to the number of physical cores. Hyper-threading may reduce speed due to resource contention—use the -t parameter of llama-bench to test and compare;
    • Context length: