Skip to content

cuda: page MoE experts for 2-8 token calls, and keep a VRAM reserve for the page slabs - #417

Merged
TheTom merged 3 commits into
TheTom:feature/turboquant-kv-cachefrom
jasstrong:pr/moe-page-batched
Nov 22, 2026
Merged

TheTom merged 3 commits into
TheTom:feature/turboquant-kv-cachefrom
jasstrong:pr/moe-page-batched

Conversation

@jasstrong

Copy link
Copy Markdown

Two follow-ups to the expert paging from #364. Both only matter with GGML_MOE_PAGE_IN set; with paging off nothing changes.

1. Page for batched calls too (correctness). Paging ran only when n_tokens == 1, but the kernels read the expert table at every batch size up to MMVQ_MAX_BATCH_SIZE. A table entry is only repointed for the experts a call routes. So a 2-8 token call read the table as the last single-token call left it, and an expert evicted since then still pointed at a slot that now holds another expert. Short prompt tails and speculative verify steps are batches of that size.

The residency plan now runs for every batch size. The bookkeeping is sized for n_expert_used * MMVQ_MAX_BATCH_SIZE routed entries, and when several tokens route the same expert it is copied once and every token reads the copy.

2. Keep a VRAM reserve for the slabs. The slabs are allocated at the first decode, after the compute buffers, so they took everything that was left, and flash-attention scratch then had no room to grow at long context. Each slab allocation now checks free memory and leaves GGML_MOE_PAGE_RESERVE_MB (default 1024) free; a tensor that does not get a slab reads in place, as before. Measured on our fleet build with Mistral Small 4 TQ4_1S at 256k context, 7 expert layers on host, MI210: VRAM 63.96 -> 63.20 GiB, and a 201k-token prompt that used to fail with out-of-memory now completes.

Testing (MI210 gfx90a, ROCm 7.2.3). A standalone harness runs 400 seeded MUL_MAT_ID calls of 1-8 tokens on a TQ4_1S expert stack in pinned host memory (32 experts, 4 routed per token, GGML_MOE_HOST_EXPERTS=1 GGML_MOE_EXPERT_TABLE=1), once with paging and once without, and compares every output:

feature/turboquant-kv-cache this PR
paging, 8 slots, vs paging off 338 of 400 calls differ, all of them 2-8 token calls 0 differ
paging, 64 slots (no evictions), vs paging off 0 0
paging off, this PR vs base 0 (bit-identical)

test-backend-ops MUL_MAT_ID: tq4_1s 44/44, tq3_1s 44/44. Perplexity with paging off is unchanged.

Harness (pagecheck.cpp)
// pagecheck.cpp: seeded sequence of MUL_MAT_ID calls (1..8 tokens) on the GPU backend with the TQ4_1S
// expert stack in pinned host memory. Writes every output to a file; run once with GGML_MOE_PAGE_IN and
// once without, then compare the two files. Correct paging gives bit-identical outputs.
// usage: pagecheck <out.bin> [n_calls]
#include "ggml.h"
#include "ggml-alloc.h"
#include "ggml-backend.h"

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <random>
#include <vector>
#include <algorithm>

int main(int argc, char ** argv) {
    if (argc < 2) { fprintf(stderr, "usage: %s out.bin [n_calls]\n", argv[0]); return 1; }
    const int n_calls  = argc > 2 ? atoi(argv[2]) : 400;
    const int K        = 512, N = 256, n_expert = 32, n_used = 4, max_tok = 8;
    const ggml_type wt = GGML_TYPE_TQ4_1S;

    ggml_backend_load_all();
    ggml_backend_dev_t dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_GPU);
    if (!dev) { fprintf(stderr, "no GPU device\n"); return 1; }
    ggml_backend_t be = ggml_backend_dev_init(dev, nullptr);
    ggml_backend_buffer_type_t host_bt = ggml_backend_dev_host_buffer_type(dev);
    if (!host_bt) { fprintf(stderr, "no host buffer type\n"); return 1; }
    fprintf(stderr, "device %s, host buffer type %s\n", ggml_backend_dev_name(dev), ggml_backend_buft_name(host_bt));

    // weights: [K, N, n_expert] in pinned host memory
    ggml_init_params wp = { ggml_tensor_overhead() * 4, nullptr, true };
    ggml_context * wctx = ggml_init(wp);
    ggml_tensor * as = ggml_new_tensor_3d(wctx, wt, K, N, n_expert);
    ggml_backend_buffer_t wbuf = ggml_backend_alloc_ctx_tensors_from_buft(wctx, host_bt);
    {
        std::mt19937 rng(42);
        std::normal_distribution<float> nd(0.0f, 1.0f);
        std::vector<float> f((size_t) K * N * n_expert);
        for (auto & v : f) v = nd(rng);
        std::vector<uint8_t> q(ggml_nbytes(as));
        ggml_quantize_chunk(wt, f.data(), q.data(), 0, (int64_t) N * n_expert, K, nullptr);
        ggml_backend_tensor_set(as, q.data(), 0, q.size());
    }

    // one graph per token count
    struct G { ggml_context * ctx; ggml_cgraph * gf; ggml_tensor * b, * ids, * out; ggml_backend_buffer_t buf; };
    std::vector<G> gs(max_tok + 1);
    for (int t = 1; t <= max_tok; ++t) {
        ggml_init_params p = { ggml_tensor_overhead() * 8 + ggml_graph_overhead(), nullptr, true };
        G & g = gs[t];
        g.ctx = ggml_init(p);
        g.b   = ggml_new_tensor_3d(g.ctx, GGML_TYPE_F32, K, 1, t);
        g.ids = ggml_new_tensor_2d(g.ctx, GGML_TYPE_I32, n_used, t);
        g.out = ggml_mul_mat_id(g.ctx, as, g.b, g.ids);
        g.gf  = ggml_new_graph(g.ctx);
        ggml_build_forward_expand(g.gf, g.out);
        g.buf = ggml_backend_alloc_ctx_tensors(g.ctx, be);
    }

    FILE * fo = fopen(argv[1], "wb");
    std::mt19937 rng(1234);
    std::uniform_real_distribution<float> ud(-1.0f, 1.0f);
    std::vector<int> perm(n_expert);
    for (int c = 0; c < n_calls; ++c) {
        const int t = 1 + (int) (rng() % max_tok);
        G & g = gs[t];
        std::vector<float> b((size_t) K * t);
        for (auto & v : b) v = ud(rng);
        std::vector<int32_t> ids((size_t) n_used * t);
        for (int j = 0; j < t; ++j) {
            for (int e = 0; e < n_expert; ++e) perm[e] = e;
            std::shuffle(perm.begin(), perm.end(), rng);
            for (int k = 0; k < n_used; ++k) ids[(size_t) j * n_used + k] = perm[k];
        }
        ggml_backend_tensor_set(g.b, b.data(), 0, b.size() * sizeof(float));
        ggml_backend_tensor_set(g.ids, ids.data(), 0, ids.size() * sizeof(int32_t));
        if (ggml_backend_graph_compute(be, g.gf) != GGML_STATUS_SUCCESS) { fprintf(stderr, "compute failed at call %d\n", c); return 1; }
        std::vector<float> out(ggml_nelements(g.out));
        ggml_backend_tensor_get(g.out, out.data(), 0, out.size() * sizeof(float));
        fwrite(&t, sizeof(int), 1, fo);
        fwrite(out.data(), sizeof(float), out.size(), fo);
    }
    fclose(fo);
    fprintf(stderr, "wrote %d calls\n", n_calls);
    return 0;
}

Build against a ROCm or CUDA build: g++ -O2 -std=c++17 -Iggml/include pagecheck.cpp -Lbuild/bin -lggml -lggml-base -Wl,-rpath,build/bin -o pagecheck, then run it with and without GGML_MOE_PAGE_IN=1 GGML_MOE_PAGE_SLOTS=8 and compare the two output files.

🤖 Generated with Claude Code

jas and others added 2 commits November 7, 2026 23:41
The expert page slabs are allocated lazily at the first decode, after the compute buffers are
reserved, so they took every byte that was left. Flash-attention scratch then had no room to grow
at long context and the next deep prompt failed with out-of-memory.

Check free memory before allocating a slab and keep GGML_MOE_PAGE_RESERVE_MB (default 1024) free.
A tensor that does not get a slab reads its experts from host memory, as before.

Mistral Small 4 TQ4_1S, 256k context, 7 expert layers on host, MI210: VRAM after the first
requests 63.96 -> 63.20 GiB; a 201k-token prompt now completes with VRAM flat at 63.20 GiB.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The expert address table keeps an entry per expert, and a call only repoints
the entries for the experts it routes. Expert paging ran only for single-token
calls, so a call of 2 to 8 tokens read the table as the last single-token call
left it. If an expert had been evicted from its slot since then, its entry still
named that slot, and the batch read another expert's weights. Short prompt
tails and speculative verify steps are batches of this size.

Run the residency plan for every batch size up to MMVQ_MAX_BATCH_SIZE. When
several tokens route the same expert, it is copied once and every token reads
the copy.

Checked with a seeded sequence of 400 calls of 1 to 8 tokens against the same
sequence with paging off: 20% of outputs differed before, none after, at 8, 64
and 512 slots. MUL_MAT_ID 979/979 on gfx90a.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@TheTom TheTom left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ran the pagecheck harness from the description on a GB10 (sm_121) with 8 slots: base has 338 of 400 calls that differ from paging off, this PR has 0, and the paging kernels run on every call. -o MUL_MAT_ID for tq3_1s and tq4_1s passes. The harness needed a fallback for GB10 reporting as an integrated GPU.

Comment thread ggml/src/ggml-cuda/mmvq-tq.cu Outdated
// repointed for the experts a call routes, so an expert evicted from its slot by an earlier call
// still has an entry naming that slot, which now holds a different expert. Skipping the plan for
// batches of more than one token, as this once did, made those batches read the wrong weights.
const int ids_stride_tbl = ids->nb[1] / ggml_type_size(ids->type);

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ids_stride_tbl is the same expression as ids_stride, computed at the top of ggml_cuda_mul_mat_id_tq. Drop it and pass ids_stride to the four paging kernels.

Comment thread ggml/src/ggml-cuda/mmvq-tq.cu Outdated
static const bool page_in_on = getenv("GGML_MOE_PAGE_IN") != nullptr;
#endif
if (page_in_on && expert_tab && n_tokens == 1 && nb_expert % (int64_t) sizeof(uint4) == 0) {
// Every call that reads the table must page, whatever its batch size. Table entries are only

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This block tells the history of the bug ("as this once did"). AGENTS.md asks for 1-2 lines on the invariant, for example: every call that reads the table must run the plan, since only routed experts get their entries repointed.

@TheTom

TheTom commented Nov 11, 2026

Copy link
Copy Markdown
Owner

Thanks @jasstrong. The harness is the right way to show the paging bug, and it reproduces on a GB10 here too. Two small comments inline.

Review follow-up. ids_stride_tbl duplicated ids_stride, which is
computed at the top of ggml_cuda_mul_mat_id_tq. The comment now states
the invariant only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@jasstrong

Copy link
Copy Markdown
Author

Thanks. Both are done in 61fb6f3: ids_stride_tbl is gone, and the comment states the invariant only. pagecheck on the MI210 after the change: 0/400 calls differ from paging off, at 8 and 64 slots.

@superbudvar

Copy link
Copy Markdown

The head of this PR is on the old base (643956891). I rebased the three commits onto the current fork base (4185b90a0); the result is content-identical (git range-diff reports all 3 commits as =).

The rebased branch is on my fork, so it can be pushed as-is:

git fetch https://github.com/superbudvar/llama-cpp-turboquant.git pr/moe-page-batched
git push origin FETCH_HEAD:pr/moe-page-batched --force-with-lease

head: ae9ea5634

It picks up #414 (src1 column count in the TQ fused and cuBLAS paths), #412 (null src[0] in the graph compat check) and #406 (conditional subgroup size for the TurboQuant SET_ROWS on wave64-only GPUs), plus turbo5/turbo6 KV types and the Spark2_5 model.

@TheTom
TheTom merged commit e5b7b05 into TheTom:feature/turboquant-kv-cache Nov 22, 2026
superbudvar added a commit to superbudvar/llama-cpp-turboquant that referenced this pull request Nov 22, 2026
…heTom#417, TheTom#371, TheTom#401, TheTom#419)

# Conflicts:
#	AGENTS.md
#	docs/KV-cache-quantization.md
#	tests/CMakeLists.txt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants