Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 101 additions & 0 deletions docs/moe-streaming.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
<!--
Copyright 2026 bong-water-water-bong
SPDX-License-Identifier: Apache-2.0

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

# MoE streaming from NVMe

The goal: run mixture-of-experts models larger than Strix Halo's 128 GB. Only the experts a
token routes to are needed. The hot ones stay in RAM, and the rest come from the NVMe drive
as the router asks for them. The work splits three ways:
- the dense layers (attention, shared experts, embeddings) on the GPU (HRX or Vulkan);
- the routed experts wherever they run fastest: NPU (native int8 x int4) or GPU;
- the NVMe feeding the cache.

This page holds the measurements the design rests on. The engine code comes next.

## What one token needs

Qwen3.8-Flash-Next (`qwen4exp`) UD-Q4_K_XL, from its GGUF metadata:

| | |
|---|---|
| layers | 48 |
| experts per layer / routed per token | 512 / 10 (+ 1 shared) |
| routed expert weights | 71.7 GiB, 3.06 MiB per expert per layer |
| per-layer token embeddings | 26.8 GiB (llama.cpp's `--lazy-mode` already reads their rows on demand) |
| everything else | 4.9 GiB |

A token reads 48 × 10 × 3.06 MiB = 1.47 GB of routed experts. The shared weights stay
resident.

## The drive

Strix Halo's NVMe (YMTC PC41Q 2 TB), `O_DIRECT` reads from a model file:

| read | throughput |
|---|---|
| sequential, 16 MiB | 4.91 GB/s |
| random, 3 MiB (one expert), one at a time | 3.62 GB/s (0.87 ms each) |
| random, 3 MiB, 8 in flight | 3.87 GB/s |

With nothing cached, 1.47 GB per token at about 3.7 GB/s caps decode at about 2.5 tok/s. So
the cache decides the speed.

## How often experts repeat

`tools/moe_trace.cpp` records each token's routed experts per layer, then replays them
through an LRU cache per layer. The cache is warmed by the prompt, and the hit rate counts
decode tokens only. Greedy decode, 300 tokens (Qwen3.6: 400), on Vulkan:

| experts cached per layer | Flash-Next, prose | Flash-Next, code | Qwen3.6-35B-A3B, code (of 256) |
|---|---|---|---|
| 64 | 68.1% | 69.6% | 82.5% |
| 128 | 85.7% | 84.5% | 93.8% |
| 192 | 92.2% | 91.4% | 97.4% |
| 256 | 94.5% | 94.5% | all |
| 384 | 96.5% | 97.7% | |

For Flash-Next, the per-token read from the drive and the ceiling that sets are:

| cache | RAM for experts | misses | read per token | NVMe ceiling |
|---|---|---|---|---|
| 128 / layer | 18.4 GiB | ~15% | ~0.22 GB | ~17 tok/s |
| 192 / layer | 27.5 GiB | ~8% | ~0.12 GB | ~31 tok/s |
| 256 / layer | 36.7 GiB | ~5.5% | ~0.08 GB | ~46 tok/s |

These are ceilings from the drive alone, before compute, and from two prompts. LRU per
layer is the simplest policy. The traces are kept, so better policies (frequency, a budget
shared across layers, prefetching the next layer's experts while this one runs) can be
compared on the same data.

## Running these measurements safely

A model larger than free memory must never be loaded blind. llama.cpp's CPU backend copies
quantized weights into anonymous memory (repacking), so `n_gpu_layers=0` doesn't stream from
the file. On 2026-09-25 that OOM-killed other services on the box. On Strix Halo, GPU
allocations also escape cgroup memory limits. So every big run goes through
`scripts/mem-guard.sh <floor GB> <cmd>`, which kills the run itself when `MemAvailable` falls
below the floor.

## Next

1. More traces: long context, chat, other MoE families. Then cache policies, replayed on
those traces.
2. The expert cache in the engine: pinned RAM slots, `O_DIRECT` reads with several in flight,
and the next layer's experts prefetched while this layer computes.
3. The three-way split. Dense on HRX or Vulkan, experts on the NPU or the GPU, measured
both ways.
4. The sweet spot per model: quantization × split × cache size × MTP, on tok/s and quality.
27 changes: 27 additions & 0 deletions scripts/mem-guard.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#!/usr/bin/env bash
# Copyright 2026 bong-water-water-bong
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# mem-guard.sh <min_available_gb> <cmd...>: run cmd and kill it if MemAvailable drops below
# the floor, before the kernel's OOM killer picks other processes (GPU allocations on Strix
# Halo's unified memory escape cgroup limits, so MemoryMax alone does not protect the box).
floor=$1; shift
"$@" & pid=$!
while kill -0 $pid 2>/dev/null; do
avail=$(awk '/MemAvailable/ {print int($2/1048576)}' /proc/meminfo)
if [ "$avail" -lt "$floor" ]; then echo "GUARD: MemAvailable ${avail} GB < ${floor} GB, killing $pid" >&2; kill -9 $pid; fi
sleep 0.5
done
wait $pid
114 changes: 114 additions & 0 deletions tools/moe_trace.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
// Copyright 2026 bong-water-water-bong
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// moe_trace: records every token's routed experts per layer (llama.cpp's ffn_moe_topk
// tensor, through the eval callback) and simulates a per-layer LRU expert cache: the
// decode hit rate for several cache sizes (docs/moe-streaming.md). Env: MOE_NGL (layers
// on the GPU, default all), MOE_BATCH (prompt batch, default 2048).
// Build against a libllama: g++ -std=c++17 -O2 -I<llama.cpp>/include -I<llama.cpp>/ggml/include
// tools/moe_trace.cpp -L<build>/bin -lllama -lggml -lggml-base -Wl,-rpath,<build>/bin
#include "llama.h"
#include "ggml.h"
#include "ggml-backend.h"
#include <cstdio>
#include <cstring>
#include <fstream>
#include <list>
#include <map>
#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>
#include <chrono>
#include <cstdlib>

struct Trace { std::vector<std::vector<std::vector<int>>> steps; }; // step -> layer -> experts (per token rows flattened)
static std::map<int, std::vector<std::vector<int>>> g_cur; // layer -> tokens -> experts

static bool cb(struct ggml_tensor* t, bool ask, void*) {
if (strncmp(t->name, "ffn_moe_topk", 12) != 0) return ask ? false : true;
if (ask) return true;
const int il = atoi(strrchr(t->name, '-') + 1);
const int k = t->ne[0], n = t->ne[1];
std::vector<int32_t> v(size_t(k) * n);
ggml_backend_tensor_get(t, v.data(), 0, v.size() * 4);
auto& rows = g_cur[il];
for (int j = 0; j < n; j++) rows.emplace_back(v.begin() + j * k, v.begin() + (j + 1) * k);
return true;
}

int main(int argc, char** argv) {
if (argc < 4) { fprintf(stderr, "moe_trace model.gguf prompt.txt n_gen [out.tsv]\n"); return 2; }
std::ifstream pf(argv[2]); std::stringstream ss; ss << pf.rdbuf(); const std::string prompt = ss.str();
const int n_gen = atoi(argv[3]);
llama_backend_init();
auto mp = llama_model_default_params(); mp.n_gpu_layers = getenv("MOE_NGL") ? atoi(getenv("MOE_NGL")) : 999;
llama_model* model = llama_model_load_from_file(argv[1], mp);
if (!model) return 1;
auto cp = llama_context_default_params(); cp.n_ctx = 8192; cp.n_batch = getenv("MOE_BATCH") ? atoi(getenv("MOE_BATCH")) : 2048; cp.n_ubatch = std::min<int>(cp.n_batch, 512); cp.cb_eval = cb; cp.cb_eval_user_data = nullptr;
llama_context* ctx = llama_init_from_model(model, cp);
const llama_vocab* vocab = llama_model_get_vocab(model);
std::vector<llama_token> toks(prompt.size() + 16);
int n = llama_tokenize(vocab, prompt.c_str(), prompt.size(), toks.data(), toks.size(), true, true);
toks.resize(n);
auto* smpl = llama_sampler_init_greedy();
std::vector<std::map<int, std::vector<std::vector<int>>>> per_step; // step: layer -> token rows
for (size_t i = 0; i < toks.size(); i += cp.n_batch) { // the prompt, one batch at a time
llama_batch b = llama_batch_get_one(toks.data() + i, std::min<size_t>(cp.n_batch, toks.size() - i));
if (llama_decode(ctx, b)) return 1;
}
per_step.push_back(g_cur); g_cur.clear();
auto t0 = std::chrono::steady_clock::now();
for (int i = 0; i < n_gen; i++) {
llama_token t = llama_sampler_sample(smpl, ctx, -1);
if (llama_vocab_is_eog(vocab, t)) break;
llama_batch bb = llama_batch_get_one(&t, 1);
if (llama_decode(ctx, bb)) return 1;
per_step.push_back(g_cur); g_cur.clear();
}
const double dt = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
printf("decode %.2f tok/s (%zu tokens in %.1f s)\n", (per_step.size() - 1) / dt, per_step.size() - 1, dt);
const int n_layer = per_step[0].size();
int n_exp = 0; for (auto& [l, rows] : per_step[0]) for (auto& r : rows) for (int e : r) n_exp = std::max(n_exp, e + 1);
printf("prompt %d tokens, decoded %zu, layers %d, experts seen up to %d\n", n, per_step.size() - 1, n_layer, n_exp);
if (argc > 4) { // token-level trace: step \t layer \t e1,e2,...
FILE* f = fopen(argv[4], "w");
for (size_t s = 0; s < per_step.size(); s++)
for (auto& [l, rows] : per_step[s])
for (auto& r : rows) { fprintf(f, "%zu\t%d\t", s, l); for (size_t i = 0; i < r.size(); i++) fprintf(f, i ? ",%d" : "%d", r[i]); fprintf(f, "\n"); }
fclose(f);
}
// decode-only LRU per layer, cache warmed by the prompt
for (int cap : {16, 32, 64, 96, 128, 192, 256, 384}) {
long hit = 0, tot = 0;
for (int l = 0; l < n_layer; l++) {
std::list<int> lru; std::unordered_map<int, std::list<int>::iterator> pos;
auto touch = [&](int e, bool count) {
auto it = pos.find(e);
if (it != pos.end()) { if (count) hit++; lru.erase(it->second); }
else if ((int)lru.size() >= cap) { pos.erase(lru.back()); lru.pop_back(); }
lru.push_front(e); pos[e] = lru.begin();
if (count) tot++;
};
for (size_t s = 0; s < per_step.size(); s++) {
auto it = per_step[s].find(l); if (it == per_step[s].end()) continue;
for (auto& r : it->second) for (int e : r) touch(e, s > 0);
}
}
printf("LRU %3d experts/layer: decode hit rate %.1f%%\n", cap, 100.0 * hit / std::max(1L, tot));
}
llama_sampler_free(smpl); llama_free(ctx); llama_model_free(model);
return 0;
}
2 changes: 1 addition & 1 deletion tools/site.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@
("Start", [("serve", "1bit serve"), ("lemonade", "Lemonade")]),
("Devices", [("npu", "NPU"), ("hrx", "HRX + Vulkan"), ("vulkan", "Vulkan (upstream)"), ("lean", "Lean (ROCmFP4, ROCmI4)"),
("zinc", "ZINC"), ("apple", "Apple Silicon")]),
("Components", [("laya", "Laya router"), ("comfyui", "ComfyUI.cpp"), ("tokenizers", "Tokenizers"), ("kernel", "Linux kernel")]),
("Components", [("moe-streaming", "MoE streaming"), ("laya", "Laya router"), ("comfyui", "ComfyUI.cpp"), ("tokenizers", "Tokenizers"), ("kernel", "Linux kernel")]),
("Project", [("PORTING", "Porting map")]),
]

Expand Down
Loading