Skip to content
sanmaiPublic

About

ClassLRU, the MoE expert cache eviction policy

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

ClassLRU, the MoE expert cache eviction policy of llama.cpp, in Python

A model of struct moe_cache_lru in src/llama-moe-cache.cpp (branch feat/moe-cache-classlru), with tests, a key-level specification of the same policy, and a replay tool for LLAMA_MOE_CACHE_TRACE files. Standard library only.

The problem

A MoE model keeps the experts of its layers in host memory. The device has a cache of n_slots expert copies, shared by a group of layers. For each layer of each ubatch the router selects a few experts per token; those not in the cache are uploaded over PCIe into a slot, and each upload needs a free slot. During generation the upload time dominates the step, so the policy that picks the slots to free decides the decode speed.

The policy

  • Every expert (layer, index) has a CRF: a count of its uses that decays with a half-life of 128 tokens. An expert used every token settles near 185, one used every 24 tokens near 8, one used every 128 near 2.
  • Its class is floor(log2 CRF): 1-2 is class 0, 2-4 class 1, ..., 128 and up class 7. The largest CRF is 1 / (1 - 2^(-1/128)) = 185.165, so the half-life gives 8 classes (n_classes()). With fewer classes the top class is a plain LRU list: at 4 classes, experts used on 50% and on 5% of the tokens share class 3.
  • Each slot sits in the LRU list of the class its expert had at its last use. A use moves the slot to the most recently used end of the list of the new class; without a use the slot keeps its class.
  • A miss takes an empty slot if there is one. Else the victim is the least recently used slot of the class whose list head has the largest age / 2^class: a class-7 slot must be 128 times as old as a class-0 slot before it goes. Age is counted in tokens on the clock of the slot's layer.
  • Uses are recorded for misses too, so an expert evicted and selected again keeps its history and lands in its old class at once. The experts a request selects are never evicted by the fills of that request.

plan(il, ids, n_tokens) handles one layer of one ubatch: it deduplicates ids, records a use of each expert, promotes the hits, then gives the misses victims in ascending expert order (consecutive experts tend to get consecutive slots, so the C++ merges their uploads), and advances the layer clock by n_tokens.

Files

file content
moe_cache_lru.py MoeCacheLru: the slot-level model (same arrays and float32 arithmetic as the C++); HeadOnly: an equivalent victim() that reads one head per class; cache_enabled(): the gate that skips large batches
reference.py ClassLruSpec: the policy over keys and ordered dicts, no slots; what the model must mean
tracefile.py reader of LLAMA_MOE_CACHE_TRACE files (versions 1 and 2)
replay.py replays a trace and compares every record with the hits and fills the C++ cache recorded
tests/ python -m pytest -q tests

Tests

  • test_plan.py: one behaviour per test. Deduplication and sort order of the fills, protection of the hits and earlier fills, a rejected request changes nothing, the half-life and the class boundaries, log2f rounding at the class-3 boundary, the class count, a hot expert idle for a few tokens outliving a warm one (and losing with 4 classes), class staleness without a use, history surviving eviction, the victim score and its tie-break, multi-token ubatches (one use per ubatch, the clock advances by the tokens), slots shared by a group of layers, seen_gen wrap, the get_slot_map() gate.
  • test_equivalence.py: on random workloads (1-4 layers, 4-24 experts, ubatches of 1-32 tokens) the model and the specification agree on hits, misses, evicted keys and the content and order of every list, for 2, 4, 6 and 8 classes; HeadOnly makes the same decisions with the same list state as the walking victim(); with one layer the list heads hold the largest scores; with several layers and varying ubatch sizes they need not (the list order is call order, the score is token age on the key's layer), shown on a 6-call example.
  • test_replay.py: on traces the C++ ClassLRU recorded itself the model gives the same hits and fills on every record (12,335 and 32,295 records, both from a 4-class build). Skipped if the traces are not at ../../tmp/moe-split/traces or $MOE_CACHE_TRACES.

MoeCacheLru.check() asserts the structural invariants after every plan() in the tests: each slot is in exactly one list, prev/next/head/tail agree, key_of and slot_map agree, a slot is in the list of the class of its key, and the empty slots lead list 0 (which is why victim() may return the first empty slot it meets).

Replay

python replay.py TRACE                  # traced slot counts, compared with the C++ record by record
python replay.py TRACE --ubatch-clock   # a trace of a build whose clock counted ubatches, not tokens
python replay.py TRACE --classes 4      # a trace of a build with 4 classes
python replay.py TRACE --slots 860 20 80  # other slot counts per group: hit rate and uploads per token only

Notes on the implementation

  • Float32: f32() rounds after every operation as the C++ float arithmetic does; exp2/log2 are the double functions rounded to float, which matched exp2f/log2f on every record of the traces. One visible effect: log2f(8 - 1 ulp) rounds to 3.0, so that CRF is class 3; threshold comparisons would say 2.
  • HeadOnly is equivalent because plan() moves every hit to a tail before it picks a victim and appends every fill to a tail, while no other slot moves during the call: a protected head means a list with no candidate. It removes the inner loop; it is not faster in practice (the walk visits under four slots per fill on traces).
  • The per-layer token clock makes every expert used within the last token age 1 at every layer, so with one-token ubatches the class weights alone pick among the list heads. This is why ClassLRU loses a few points to plain LRU when the cache holds about one token's experts and wins from 1.2x up.
  • One use per ubatch per expert, with the clock in tokens, is the better of the alternatives on replays (per-token use counts are a wash at large caches and lose at small ones; an ubatch clock loses with multi-token ubatches).
  • 8 classes against 4: on the replays of the older traces, more classes help only when the cache holds fewer than about five tokens' experts (5 classes = 6 = 8 there). On a gemma model they help much further. The replays of its C++ trace give hit rates of 37.4% against 35.3% at 232 slots, 48.7% against 40.2% at 330, 59.9% against 54.8% at 464, and 98.47% for both at 2320. The C++ builds measured 4-13% faster decode with 8 classes from 661 to 3287 slots, and were within about 2% of each other (one run per point) from 3944 to 6571 slots.

Producing a trace

The traces come from an instrumented llama_moe_cache (trace-instrumentation.patch, commit 917001b35 on the bench branch bench/30966-classlru-trace; it replaces the MCT1 writer of PR 30966, so on a tree without that writer only its additions apply). The pieces:

  • LLAMA_MOE_CACHE_TRACE=<file>: read in the constructor after the groups are sized (the header needs the slot count of each group). The file is opened with "wb", so one file per server start. fflush once per second: a killed server loses at most one second.
  • Header, int32 words: magic 0x54454F4D ("MOET"), version 2, n_layer, n_expert_used, n_group, the n_slots of each group, then for each layer ig (-1 if not cached), n_expert (0 for a dense layer) and the bytes of one expert (all its tensors).
  • One record per copy() call, written after plan() and the stats: kind = 0, il, n_used, n_tokens, n_hit, n_fill, n_cpu (0 without the CPU-miss PR), the ggml_time_us() stamp as two words (low, high), then the ids as the cache saw them. The ids tensor is the 1-D reshape of the router output, so take n_used and n_tokens from sel->src[0]->ne[0] and ne[1]; the patch wrote sel->ne[1], which is 1 for the 1-D tensor, so tracefile.requests() recovers the tokens as len(ids) / n_used and replay.py --ubatch-clock replays the builds whose clock counted ubatches for the same reason.
  • One record per large batch (kind = 1, the n_hit/n_fill/n_cpu words -1), written from llama_context::sched_copy_experts through llama_moe_cache::trace_large() after it has read the ids from the device. These batches only read the cache; the replay skips them, a policy study can use them to seed.

Size: about 2 KB per decode token for a 48-layer model with 10 experts per token. tracefile.read_trace() reads versions 1 (no time stamps, 7-word records) and 2.

About

ClassLRU, the MoE expert cache eviction policy

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages