Skip to main content

lk_moe

lk_moe is a highly optimized MOE hybrid inference engine that serves as the computational core for MOE layer execution. It is designed to maximize resource utilization across CPU, memory, and GPU, enabling large-scale MOE models to run efficiently beyond GPU memory constraints.

Key Capabilities

  • Hybrid Compute Backend: Each MOE layer can dynamically choose between the original GPU computation path or lk_moe's hybrid inference path, offering flexible deployment strategies.
  • CPU-GPU Collaborative Inference: Distributes expert computation across CPU (via NUMA-optimized threading) and GPU, reducing GPU memory requirements while maintaining high throughput.
  • NUMA-Aware Parallelism: Optimized thread binding and memory allocation across NUMA nodes, achieving cross-node communication as low as 3% and L3 cache hit rates above 50%.
  • Super Mix Prefill: GPU-path prefill with super-chunk sizing — the GPU chunk is decoupled from the token budget, keeping the GPU near 100% utilization while decode is served by the CPU. Always recommended whenever VRAM has headroom.
  • GPU Pool (expert cache): A background DMA pump keeps hot experts resident in VRAM (2nd-touch window LRU, off the critical path). Pool-resident experts are computed on the GPU while the rest stay on the CPU — both in decode and prefill — the split is decided by one shared snapshot word, so every expert is computed exactly once. Works for both NVFP4 and MXFP4 experts. Fully fail-closed: an empty or disabled pool is bit-identical to the plain hybrid path.
  • Quantization Kernel Support: Native support for multiple quantization formats including BF16, FP8, NVFP4, MXFP4, and AWQ 4-bit, with efficient kernel implementations.
  • Memory + VRAM Load Balancing: Total model footprint spans both VRAM and system memory, allowing models larger than GPU memory to run without performance collapse.

Configuration

All parameters are read once at startup and are completely inert when the master switch is off. The only path choice made at runtime is the prefill batch gate (LK_GPU_PREFILL_MIN_TOKENS).

Policy fields (pool, prefill, mailbox, verify) are owned by MOEConfigV2 — the library takes them from cfg, not the environment; the LK_* names below are accepted by the sglang integration and bridged into the config. Read directly by the library: bootstrap env (LK_THREADS, LK_THREAD_BINDING, LK_NUMA_HUGE, LK_NUMA_ILP, LK_POWER_SAVING) and the direct-read knobs (LK_DECODE_TS, LK_TS_SKIPGEMM, LK_MBOX_STOPFILE). The pooled H2D staging ring is not a knob: it is the only staging path, and the geometry checks turn it off by themselves when the expert blocks do not tile the slab. On-demand pool byte verification is the pool_verify_sample(layer, max_experts) binding, not an env knob.

Switch linkage (one master gate)

LK_MOE_HYBRID_ENABLED is the single master switch: with it off (the default) lk_moe is never imported and every LK_* below is inert — every MOE layer runs the framework-native path, bit-for-bit. Switches only link to switches; perf knobs never appear in a linkage:

LK_MOE_HYBRID_ENABLED=1                     master
 ├─ pool on            LK_POOL_SLOTS (e.g. 64)      (dual knob: value itself is the switch, 0 = off)
 │   └─ pool decode    LK_POOL_DECODE=1     (unset = follows pool on; explicit `1`/`0` wins)
 ├─ GPU prefill on     LK_GPU_PREFILL_MIN_TOKENS (e.g. 1024)   (dual knob, same rule)
 │   ├─ engine         LK_GPU_PREFILL_ENGINE=cutlass|triton|flashinfer (default cutlass; triton = opt-out;
 │   │                                             flashinfer = SM120/SM121 only)
 │   ├─ precision      LK_GPU_PREFILL_QUANT=w4a16|w4a4      (framework-read; default w4a16; unsupported
 │   │                                             device x engine x mode pair aborts the boot)
 │   ├─ wave           LK_GPU_PREFILL_WAVE_EXPERTS (cutlass only; -1 auto / 0 single-shot / >0 cap)
 │   └─ super mix      (framework env, not read here) LK_GPU_PREFILL_SUB_M - the framework max()es it with
 │                                             its chunk size and passes the result in as the width of one forward
 ├─ nvme filler on    LK_NVME_DIRECT=1          (needs the feature's own backend flag: --ple-offload-backend nvme / engram host table;
 │                                             the LK master only gates the lk_moe path)
 └─ resident layers   LK_GPU_RESIDENT_MOE_LAYERS*   (complementary: a resident layer never pools)
LK_MOE_HYBRID_ENABLED=0  →  every branch above unreachable = original sglang
( LK_NVME_DIRECT with the engram/PLE nvme backends is the one knob that also works without the LK master )

Dual-knob rule (switch + perf in one variable)

Two variables are both a switch and a perf knob. The rule: default 0 = feature not enabled; to use a tier you must explicitly give a value (e.g. 64 / 1024 - one value both switches the tier on and sets its parameter).

Variable Switch meaning Perf meaning Default Recommended when on
LK_POOL_SLOTS value itself is the switch (e.g. 64 powers the pool tier on); unset / 0 = off, all LK_POOL_* inert resident expert slots per MOE layer; VRAM cost = slots × layers × expert bytes. Auto-extended to what one prefill pass needs when it is smaller (those rows are already inside the same allocation, so it is free; the boot log prints auto extended LK_POOL_SLOTS X to Y). A larger value is never shrunk. 0 e.g. 64
LK_GPU_PREFILL_MIN_TOKENS value itself is the switch (e.g. 1024 powers the GPU-prefill tier on); 0 = pure CPU prefill value = minimum token batch for the GPU path 1024 (on by default) e.g. 1024 (set 0 on 16 GB cards)

Tuning parameters

Group Variable Default Description
Master LK_MOE_HYBRID_ENABLED 0 Engine master switch; 0 = every MOE layer runs the framework-native path.
Resident LK_GPU_RESIDENT_MOE_LAYERS unset Listed layer ids/ranges (e.g. 0, 9-11) stay on the native GPU path instead of the hybrid path; unset = none resident.
Resident LK_GPU_RESIDENT_MOE_LAYERS_MTP / LK_GPU_RESIDENT_MOE_LAYERS_SPEC / LK_GPU_RESIDENT_MOE_LAYERS_DSPARK unset Same grammar; for draft roles _SPEC wins when set, _MTP/_DSPARK apply only when _SPEC is unset.
Pool LK_POOL_SLOTS 0 Dual knob, see above (e.g. 64 when on).
Pool LK_POOL_DECODE follows pool Decode GPU half: 1 on / 0 off explicitly; unset follows LK_POOL_SLOTS > 0.
Pool LK_POOL_WINDOW 32 Perf only: expected-reuse window in steps — an evicted expert is pumped back only if seen again within the window. Illegal values clamp to min 8; clamping never flips a switch — only LK_POOL_SLOTS disables the pool.
Pool LK_POOL_INFLIGHT 16 Perf only: in-flight DMA jobs / event-ring depth (backpressure scales from this).
Pool LK_POOL_NO_STAGE 1 Fill path. 1 (default): DMA each NUMA fragment straight from the pinned host pages into the slot -- on an 8-node box that is ~16 async copies, no host copy. 0: the coalesced slab assembly, which memcpys the whole expert into pinned scratch first; measured 1.1 ms per admission against 0.13 ms here.
Debug LK_POOL_LOG 0 Diagnostic: windowed [pool] stats line every N decode steps.
Debug LK_POOL_DET_SPLIT 0 Diagnostic, sglang side: deterministic split — publish the claimed batch and make the GPU half stream-wait on that batch's copy fence before reading slots. Inert without the pool.
Debug LK_POOL_SPLIT_PROBE 0 Diagnostic, sglang side: log the frozen split (claim/ready/snapshot counts) per pool layer for batches of ≤32 routed ids; skipped inside CUDA-graph capture. Inert without the pool.
Pool LK_POOL_MBOX_SPLIT 0 Perf, sglang side: signal the decode mailbox before joining the CPU half instead of in one step. Measured no gain (7.43 vs 7.07-7.35 ms/step at one row), so the shipped recipes no longer set it. Read by the framework, inert without the pool.
Prefill LK_GPU_PREFILL_MIN_TOKENS 1024 Dual knob, see above. On by default; 0 forces pure CPU prefill.
Prefill LK_GPU_PREFILL_SUB_M 0 Framework-owned: lk_moe never reads this env. It is the MoE big-segment width, and the framework turns it into the token width of one forward as max(--chunked-prefill-size, SUB_M) - which is what arrives here as cfg.max_batch_size, the one number every pass is cut against. It therefore only ever RAISES that width (it is CAP= in the Super-chunk prefill wrapper active boot line), and a bigger one moves more of each expert's weights per token (faster) at the price of the scratch that scales with the width. Inside lk_moe that peak comes down with LK_GPU_PREFILL_WAVE_EXPERTS and LK_GPU_PREFILL_D_SLOTS, never by re-reading this knob.
Prefill LK_GPU_PREFILL_ENGINE cutlass Which GPU prefill path runs above the token gate. cutlass: fastest on long prompts, but rounds activations to bf16 — long-context logits can shift and borderline EOS can flip; triton: output bit-matches the CPU reference, slightly slower; flashinfer (SM120/SM121 only): pays off with LK_GPU_PREFILL_QUANT=w4a4. On a pool every engine stages through the pool's VRAM, so GPU prefill adds no extra VRAM. Framework-read and passed via cfg; the C++ library itself does not read this env. Repeatability: cutlass and triton are bitwise reproducible run to run; flashinfer is not — its combine sums each token's expert contributions with fp32 atomics and picks split-K from the token count (moe_nvfp4_w4a16.py:772, _plan), so a re-run differs in a handful of last-bit bf16 elements (~5e-4 of peak, 15 of 2.1M on the field shape). Same magnitude whether you re-run the same input or change the prompt's tail, i.e. no evidence of a lost dependency, but a bitwise causality gate cannot certify it. Use cutlass wherever run-to-run identical logprobs are required.

| Prefill | LK_GPU_PREFILL_WAVE_EXPERTS | -1 auto (frameworks) | Wave width for all three engines, applied inside each pass (triton/flashinfer have no per-wave gemm loop, so a value >0 aborts the boot instead of being ignored): -1 = largest expert wave whose deq blocks + whole tail staging layers fit the borrow slab (clamped to E, adapts to E=256/384/512); 0 = single-shot (C++ default for direct cfg users); >0 = explicit cap. Waves are bit-exact with single-shot. | | Prefill | LK_GPU_PREFILL_D_SLOTS | 0 = off | Slot rows per prefill pass, shared by all three engines. cutlass: splits each prefill into narrower passes so it holds less VRAM, at the cost of extra launches (result unchanged). triton/flashinfer: it also sizes their prefill work area (which lives in the pool) and how wide each pass walks, so it is the one parameter that decides how much VRAM a staging engine uses. The value counts routed entries (tokens × top_k); size it by tokens with tokens × top_k. 0 keeps the single-pass behaviour. Row slicing no longer changes the result on the cutlass path (see LK_MOE_ORDER_FREE_SUM): a narrow window costs ~2%, it used to cost a 2.3x-74x pass shrink to stay exact. | | Numerics | LK_MOE_SHAPE_INVARIANT | 1 | Prompt-logprob causality switch, CPU expert gemm. With 1 (default) an expert segment takes the same numeric path whatever its row count is, so an edit at the END of a prompt cannot move the rows BEFORE it; 0 restores the old row-count dispatch (LK_BIGM_M_THRESH + single-row / 3..4-row special cases), which made each row depend on how many rows the OTHER tokens handed to the same expert. Prefill turns it on for its whole call; decode keeps the row-count-specialised kernels (there the row count IS the batch). | | Numerics | LK_MOE_ORDER_FREE_SUM | 1 | Prompt-logprob causality switch, cutlass GPU prefill. With 1 (default) each top_k summand is quantized on its own value and added into an int64 fixed-point total, so the sum is independent of how the summands were grouped into windows/waves/passes (integer addition commutes and associates); 0 restores the fp32 read-modify-write combine, which summed in WINDOW order - i.e. according to the whole batch's routing histogram. Measured cost of the total: +2% at the field's D_SLOTS=16384, versus 2.3x for shrinking the pass to one window. Summands of |v| >= 2^23 are counted and reported (lk_moe.sum_range_hits()), never clamped. | | Numerics | LK_MOE_ONE_WINDOW_PER_PASS | derived | Not a deployment knob: with the int64 total on it changes nothing, and with it off the default already forces one window per pass. It exists so a gate can put the fp32 combine back under window slicing and prove the int64 total is what makes a row's sum order-independent (tests/test_sum_order_invariance.py case 2). | | Prefill | LK_GPU_RESERVE_GB | 0 | Framework-side fallback: reserve this many GB of KV budget for lk_moe staging when get_device_mem_usage() reports 0; ignored once the pool/arena/ring report is non-zero. | | NVMe | LK_ENGRAM_NVME | 0 | DeepSeek-V4.1 Engram on the lk_moe N1 async filler: table stays in the safetensors shard, rows fetched by pread/O_DIRECT; the sglang integration exposes it as LK_ENGRAM_NVME. | | NVMe | LK_ENGRAM_NVME_CACHE_MB / LK_ENGRAM_NVME_STAGING_MB | 1024 / 128 | Perf only: Engram NVMe store cache / staging budgets. | | NVMe | LK_NVME_CACHE_MB | 1024 | Perf only: pinned direct-map row cache (MiB) for the NVMe filler with LK_NVME_DIRECT=1, shared by PLE and other non-Engram consumers (Engram has its own LK_ENGRAM_NVME_CACHE_MB). Inert unless the feature's backend is on. | | NUMA | LK_NUMA_INTERLEAVE | 1 | Interleave expert weights across NUMA nodes (required for the pump's per-node copy streams; default-on via the sglang integration, 0 opts out). | | CPU | LK_THREADS | auto | CPU worker threads per GPU (physical cores / #GPUs). | | CPU | LK_THREAD_BINDING | CPU_CORE | Thread binding mode across NUMA nodes. | | Power | LK_POWER_SAVING | 0 | Standby only: an idle worker yield()s instead of spinning on its status word (and sleeps 4 s instead of 2 s once it has been idle for 120 s), handing CPU time back to the scheduler; trades wake-up latency for lower idle package power. Nothing in the compute path reads it, so under saturating decode the only difference is a yield in the sub-50 ms inter-step window — it does not lower power while inferring. | | Spec | LK_VERIFY_RESIDENT | 1 | Ride-share: verify batches let the DRAFT rows read the residency the real tokens built -- a resident expert is computed on the GPU half, a miss on the CPU. The draft ids never enter the admission ledger unless LK_VERIFY_PUMP is set. 0 = the old behaviour (draft rows always CPU). cfg field verify_resident. | | Debug | LK_VERIFY_PUMP | 0 | 1 also feeds the draft rows' ids to the admission ledger. Only sensible when the cache can hold a whole verify batch; on a small cache it evicts what it just brought in. cfg field verify_pump. | | Decode | LK_HF_MBOX | 1 | Mailbox early-start of the host-side decode (non-0 on, 0 off; saves the ~50 µs graph host-node wake-up latency). cfg field hf_mbox. | | Debug | LK_PP_DEBUG | off | Extra tracing inside the prefill staging tier. | | Debug | LK_ROUTE_PROBE | off | Per-step [RP] routing traces for offline calibration (requires the pool on). |

VRAM ledger (cutlass vs triton)

get_device_mem_usage() returns the persistent device bytes owned by lk_moe: pool rows (or the one per-type slab), the cutlass prefill arena, and the Triton staging ring (window × E × per-expert bytes). Borrowed cutlass blocks are aliases inside the slab and are not counted twice; a few lazily allocated KB-sized tables are excluded. Cutlass prefill also books its combine total: one int64 per output element of one forward, so one forward's token width × hidden × 8 bytes per rank (measured 0.62 GiB at 32768 x 2560, 0.50 GiB at 16384 x 4096). It is a slice of the prefill line, which rides inside the pool region whenever the cache line is the longer of the two, so it costs KV bytes only with LK_POOL_SLOTS=0. It is included here, so the KV budget already reflects it. The sglang integration reads this only to decide whether an extra KV reservation is needed — KV sizing itself uses free device memory.

With a pool, every prefill engine's working set lands in the pool slab, so GPU prefill adds no VRAM beyond it: cutlass plans its blocks and leaves the tail layers as staging rows; the staging engines stage into pool rows (startup logs [pool] wave width auto: W ..., [pool] block plan: X of Y GiB pool (Z GiB staging reserve), [pool] staging rows: pool VRAM via borrow). Only a pool-less GPU prefill still carries a private staging ring, logged as [pool] staging ring: ....

Framework Integration

lk_moe integrates with popular LLM serving frameworks as a drop-in MOE computation backend:

Framework Integration Description
vLLM LvLLM lk_moe as MOE layer backend for vLLM serving
sglang Lsglang lk_moe as MOE layer backend for sglang serving
DeepSeek V4 Lvllmds4 Specialized integration for DeepSeek V4 (SM120)
DeepSeek V4 Lvllmds4-x Specialized integration for DeepSeek V4 (SM80+)

Installation

Prerequisite: CUDA 13.2.1 (driver + toolkit, sm80+).

pip install lk-moe

License

lk_moe is provided under a proprietary software license agreement. See LICENSE for terms and conditions. Third-party open-source components and their respective licenses are listed in THIRD_PARTY_LICENSES.

Metadata

Release files for lk-moe 2.9.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Built distribution (wheel)

Table of built distributions (wheels) for lk-moe 2.9.1
File Interpreter ABI Platform Actions
lk_moe-2.9.1-cp312-cp312-manylinux_2_34_x86_64.whl CPython 3.12 CPython 3.12 Linux glibc 2.34+ x86-64 Details for lk_moe-2.9.1-cp312-cp312-manylinux_2_34_x86_64.whl

Release files / lk_moe-2.9.1-cp312-cp312-manylinux_2_34_x86_64.whl

Download URL lk_moe-2.9.1-cp312-cp312-manylinux_2_34_x86_64.whl
Size 26.9 MB
Tags CPython 3.12 Linux glibc 2.34+ x86-64
SHA-256 checksum
How to use checksums
f543e43cf5e373cda5740cc0e82e94101bf333266840ce51692a4df6dc474eed
BLAKE2b-256 checksum
How to use checksums
ef9eadb197d97514d84d36c46e848a1dcc4f58ae26cb7176d2b32ac7b3daac2a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.11

Security for lk-moe 2.9.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

2.9.1 This release

1 release file No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page