Hugging Face Transformers Expert Streaming for MoE Models

Overview

Hugging Face has implemented a new expert streaming mechanism for Mixture-of-Experts (MoE) models within the transformers library, allowing models that exceed local memory capacity to run by streaming only the required experts from SSD to a preallocated device cache. This approach achieves performance within 6% of specialized inference engines like Strata, enabling the execution of massive models like Qwen3.8-Flash-Next on consumer hardware with 32GB of RAM.

Technical Implementation: The Slot Pool

The core innovation of this implementation is the transition from individual expert loading to a slot pool architecture. Instead of loading experts dynamically, the system uses a preallocated device tensor shared across all layers. A per-layer table maps expert IDs to these slots. By remapping the router's expert IDs to these slots, the model's existing grouped_mm kernels can operate on the cache as if it were a standard expert bank, eliminating the need for custom expert matmul kernels.

Key Components

  • experts_offload API: Introduced in PR #50717, this allows developers to define a device_map that offloads experts to disk while keeping dense layers in memory.
  • Quantization: Experts can be quantized offline (e.g., to 3 bits) to reduce the I/O bottleneck during streaming.
  • Prefetching: The system runs the routers for upcoming layers early on current hidden states to predict and prefetch necessary experts, hiding disk latency.
  • Metal Kernels: For Apple Silicon environments, the system utilizes runtime-compiled Metal kernels to handle operations not natively optimized in PyTorch, such as Gated DeltaNet and hyper-connections.

Performance and Benchmarks

On a 32GB Mac M5, this implementation successfully runs Qwen3.8-Flash-Next (180B parameters). The following table compares the optimized Transformers implementation against the Strata inference engine:

Metric Transformers Strata Gap
Decode (200 tokens) 13.9 tok/s 14.8 tok/s 1.06x
Prefill (4K prompt) 228 tok/s 220 tok/s 1.0x
Decode (after 6K doc) 12.4 tok/s 13.7 tok/s 1.1x

Implications for Local Inference

This work demonstrates that high-performance MoE inference is achievable within the standard transformers stack without requiring complex C++ extensions. By utilizing a bounded cache and efficient I/O threading, the system minimizes the performance penalty of offloading.

Remaining performance gaps are primarily attributed to host-device synchronization overheads in PyTorch. While specialized engines like Strata currently hold a slight lead by queuing token work more aggressively, the Transformers implementation provides a flexible, Python-native framework for experimenting with sparse model execution and memory-constrained inference.

Sources