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
30 changes: 21 additions & 9 deletions python/freetoken/engine/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -851,10 +851,10 @@ def _init_offload_moe_cache(self, config: EngineConfig) -> OffloadMoeCache:
layer_methods = offload_layer_methods(self.model)
if not is_mixed(layer_methods):
layer_methods = None
elif config.moe_strategy == "cpu" or config.moe_cpu_layers:
elif config.moe_cpu_layers:
raise ValueError(
"this model's experts come in several formats, which are served from per-format GPU slot pools; "
"they do not combine with --moe-strategy cpu or --moe-cpu-layers (use offload or hybrid)"
"they do not combine with --moe-cpu-layers (use offload, hybrid or cpu)"
)
# Fast path: an FTW checkpoint loads its repacked banks directly.
# Slow path: load_expert_banks auto-picks parallel vs serial baseline by
Expand All @@ -875,7 +875,9 @@ def _init_offload_moe_cache(self, config: EngineConfig) -> OffloadMoeCache:
reserved = self._host_tables_bytes + staging_reserve(config, lambda: _bank_bytes(config, method, layer_methods))
cpu_layer_ids = _resolve_cpu_layers(config, num_moe_layers, reserved=reserved, method=method)
_check_pin_budget(config, reserved=reserved, method=method, layer_methods=layer_methods)
decode_target, split_residency = self._residency_split(config, cpu_layer_ids, method, capped=_pin_budget_bytes(reserved) is not None)
decode_target, split_residency = self._residency_split(
config, cpu_layer_ids, method, capped=_pin_budget_bytes(reserved) is not None, layer_methods=layer_methods
)
requested_residency = None
if split_residency:
from freetoken.moe.host_banks import HostResidency
Expand Down Expand Up @@ -918,7 +920,9 @@ def _init_offload_moe_cache(self, config: EngineConfig) -> OffloadMoeCache:
if locked_fetch:
# a locked refill costs a staged copy: place the locked pools after the pinned ones, which hold the prefill staging when they are big enough
self._moe_pool_groups.sort(key=lambda layers: layers[0] in cpu_layer_ids)
if len(self._moe_pool_groups) > 1 and cpu_layer_ids and not locked_fetch:
# --moe-strategy cpu decodes no layer from the slots, which only back the prefill staging (sized below)
staging_only = config.moe_strategy == "cpu" and config.moe_cache_scope == "unified"
if len(self._moe_pool_groups) > 1 and cpu_layer_ids and not locked_fetch and not staging_only:
raise ValueError(
"several MoE slot pools (--moe-cache-scope per-layer, or experts in several quant formats) need every MoE "
"layer to decode from the GPU slot cache; they combine with --moe-cpu-layers only for locked layers under "
Expand Down Expand Up @@ -966,6 +970,11 @@ def _init_offload_moe_cache(self, config: EngineConfig) -> OffloadMoeCache:
f"--moe-cache-mem {mem_GB(config.moe_cache_mem)} resolved moe_cache_size={size} "
f"({per_slot / 2**20:.2f} MiB per slot, prefill_overlap={overlap})"
)
if staging_only and len(pools) > 1:
# 2 * num_experts slots split over the pools leave a bank short of two layers of its widest format
size = stage_floor(layer_bank_bytes(banks.sources), pools, config.model_config.num_experts, self._moe_expert_counts, buffers=2)
object.__setattr__(config, "moe_cache_size", max(config.moe_cache_size, size))
logger.info_rank0(f"MoE backend 'cpu': {len(pools)} slot pools, prefill double buffer of moe_cache_size={config.moe_cache_size}")
_require_offload_cache_size(config.moe_cache_size, config.model_config.num_experts)
pool_sizes = split_slots(config.moe_cache_size, pools, self._moe_expert_counts)
if len(pools) > 1:
Expand Down Expand Up @@ -1034,7 +1043,7 @@ def _init_offload_moe_cache(self, config: EngineConfig) -> OffloadMoeCache:
self.moe_offload_cache = cache
return cache

def _residency_split(self, config: EngineConfig, cpu_layer_ids, method, *, capped: bool):
def _residency_split(self, config: EngineConfig, cpu_layer_ids, method, *, capped: bool, layer_methods=None):
"""(decode_target, split_residency) for a CPU-layer set; turns prefill overlap off when some layers stay unpinned."""
# the kernels were picked for model_config.decode_target; --moe-cpu-layers auto may still find that every bank fits the pin budget
decode_target = config.model_config.decode_target
Expand All @@ -1050,13 +1059,16 @@ def _residency_split(self, config: EngineConfig, cpu_layer_ids, method, *, cappe
)
if config.moe_strategy == "cpu" and not split_residency:
# cpu mode pins every bank for the prefill double buffer; over the pin cap that dies in cudaHostRegister, so lock everything instead
from freetoken.moe.expert_banks import bank_bytes_estimate, ftw_bank_bytes

budget = _pin_budget_bytes(self._host_tables_bytes)
bank_bytes = None
if budget is not None:
bank_bytes = ftw_bank_bytes(config.model_path) or bank_bytes_estimate(config.model_config, method)
bank_bytes = _bank_bytes(config, method, layer_methods)
if bank_bytes and bank_bytes > budget:
if layer_methods is not None:
raise ValueError(
f"--moe-strategy cpu: the expert banks ({bank_bytes / 2**30:.2f} GiB) exceed this host's pin budget, and "
"experts of several formats cannot be OS-locked instead"
)
split_residency = True
logger.info_rank0(
f"--moe-strategy cpu: banks {bank_bytes / 2**30:.2f} GiB exceed the "
Expand Down Expand Up @@ -1764,7 +1776,7 @@ def _decode_target(config: EngineConfig) -> str:
# expert activations the CPU MoE executor supports (csrc ActKind)
_CPU_MOE_ACTS = (
"silu", "swish", "gelu", "gelu_tanh", "gelu_pytorch_tanh", "swigluoai",
"swiglu_clamp",
"swiglu_clamp", "softcap_swiglu",
)


Expand Down
3 changes: 3 additions & 0 deletions python/freetoken/kernel/csrc/cpu_moe/common.h
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,15 @@ inline bf16_t f32_to_bf16(float f) {
// the mxfp4 kernel additionally fuses its own copy of the same math).
// ACT_SWIGLU_CLAMP (GLM-5.3 "swiglu_limit") is the same clamped form WITHOUT
// the (up + 1) bias: clamp(gate, max=lim) * sigmoid(alpha*gate) * clamp(up, +-lim).
// ACT_SOFTCAP_SWIGLU (Inkling 2) caps with tanh instead and the sigmoid sees the raw gate:
// alpha*tanh(gate/alpha) * sigmoid(gate) * lim*tanh(up/lim).
enum ActKind {
ACT_SILU = 0,
ACT_GELU = 1,
ACT_GELU_TANH = 2,
ACT_SWIGLUOAI = 3,
ACT_SWIGLU_CLAMP = 4,
ACT_SOFTCAP_SWIGLU = 5,
};

inline float act_apply(int act, float x) {
Expand Down
2 changes: 1 addition & 1 deletion python/freetoken/kernel/csrc/cpu_moe/cpu_moe_ext.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -645,7 +645,7 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
// accepts id 3 without error and silently computes the wrong activation
// (act_apply falls through to gelu_tanh); the probe turns a stale extension
// into a loud rebuild instruction instead of wrong model outputs.
m.def("max_generic_act_id", []() { return static_cast<int>(freetoken::cpu_moe::ACT_SWIGLU_CLAMP); });
m.def("max_generic_act_id", []() { return static_cast<int>(freetoken::cpu_moe::ACT_SOFTCAP_SWIGLU); });
// The ggml-cpu variant the gguf format calls: the kernel table address that freetoken.kernel.ggml_cpu.select() returns.
m.def("set_ggml_cpu", &freetoken::cpu_moe::set_ggml_cpu, py::arg("api"));
m.def("weight_formats", []() {
Expand Down
7 changes: 5 additions & 2 deletions python/freetoken/kernel/csrc/cpu_moe/format.h
Original file line number Diff line number Diff line change
Expand Up @@ -76,17 +76,20 @@ struct DownRoute {
};

// g[i] for i in [i0, i1) from the gate row i and the up row I + i; dot(row) is the row's GEMV.
// ACT_SWIGLUOAI and ACT_SWIGLU_CLAMP clamp both inputs; the other kinds go through act_apply.
// ACT_SWIGLUOAI and ACT_SWIGLU_CLAMP clamp both inputs, ACT_SOFTCAP_SWIGLU tanh-caps them; the other kinds go through act_apply.
template <class RowDot>
inline void gated_rows(const MoeParams& p, int i0, int i1, float w_in, bf16_t* g, RowDot dot) {
const bool softcap = p.act == ACT_SOFTCAP_SWIGLU;
const bool clamped = p.act == ACT_SWIGLUOAI || p.act == ACT_SWIGLU_CLAMP;
const float up_bias = p.act == ACT_SWIGLUOAI ? 1.0f : 0.0f;
const float lim = p.swiglu_limit, alpha = p.swiglu_alpha;
for (int i = i0; i < i1; ++i) {
// gate = row i, up = row I+i
float gate = dot(i) * w_in;
float up = dot(p.I + i) * w_in;
if (clamped) {
if (softcap) {
g[i] = f32_to_bf16(alpha * std::tanh(gate / alpha) / (1.0f + std::exp(-gate)) * (lim * std::tanh(up / lim)));
} else if (clamped) {
// clamp(gate, max=lim) * sigmoid(alpha * gate) * (clamp(up, +-lim) + up_bias)
// -- swigluoai carries the +1 up bias (gpt-oss/MiniMax); swiglu_clamp
// (GLM-5.3) does not. lim == +inf: no clamp.
Expand Down
1 change: 1 addition & 0 deletions python/freetoken/moe/cpu_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
"gpt_oss_swiglu": 3,
"swigluoai": 3,
"swiglu_clamp": 4,
"softcap_swiglu": 5,
}


Expand Down
13 changes: 8 additions & 5 deletions python/freetoken/moe/pool_policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,11 +80,14 @@ def split_slots(total: int, pools: list[PoolSpec], counts: torch.Tensor | None =
return _split_equal(total, pools) if counts is None else _split_hot(total, pools, counts)


def stage_floor(layer_rows: list[list[int]], pools: list[PoolSpec], num_experts: int, counts: torch.Tensor | None = None) -> int:
"""Fewest slots whose split gives every bank the bytes to stage one whole layer of its widest rows, as the offload
cache's shared bank bytes must (``layer_rows[l][k]``: one expert's bytes of bank k in layer l); the pools' room when
no size does. Row padding is left out: the cache adds the largest pad to both sides of that check."""
widest = [num_experts * max(rows[k] for rows in layer_rows) for k in range(len(layer_rows[0]))]
def stage_floor(
layer_rows: list[list[int]], pools: list[PoolSpec], num_experts: int, counts: torch.Tensor | None = None, buffers: int = 1,
) -> int:
"""Fewest slots whose split gives every bank the bytes to stage ``buffers`` whole layers of its widest rows, as the
offload cache's shared bank bytes must (``layer_rows[l][k]``: one expert's bytes of bank k in layer l); the pools'
room when no size does. Row padding is left out: a bank also holds each pool's pad and the largest one, which
covers the pads of one or two buffers."""
widest = [buffers * num_experts * max(rows[k] for rows in layer_rows) for k in range(len(layer_rows[0]))]

def fits(total: int) -> bool:
sizes = split_slots(total, pools, counts)
Expand Down
70 changes: 46 additions & 24 deletions tests/moe/test_mixed_expert_formats.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
E, H, I, TOPK = 8, 256, 128, 2
FORMATS = ["bf16", "nvfp4", "nvfp4", "nvfp4", "bf16", "mxfp8"]
L = len(FORMATS)
# (alpha, limit) per expert activation; softcap_swiglu's caps are ones the test inputs reach
ACTS = {"silu": (1.0, None), "softcap_swiglu": (1.5, 6.0)}

_E2M1 = torch.tensor([0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0])

Expand All @@ -29,7 +31,7 @@ def _init_tp():
set_tp_info(rank=0, size=1)


def _layer(layer_id: int, fmt: str):
def _layer(layer_id: int, fmt: str, act: str = "silu"):
from freetoken.layers.moe import OffloadMoELayer
from freetoken.layers.quantization import NoQuantConfig, QuantBackend, QuantConfig, set_quant_backend

Expand All @@ -41,7 +43,10 @@ def _layer(layer_id: int, fmt: str):
else:
set_quant_backend(QuantBackend.parse("moe.nvfp4=triton"))
quant = QuantConfig.from_hf({"quantization_config": {"quant_method": "modelopt", "quant_algo": "NVFP4", "ignore": ["lm_head"]}})
return OffloadMoELayer(layer_id, E, TOPK, H, I, quant_config=quant, prefix=f"model.layers.{layer_id}.mlp.experts")
alpha, limit = ACTS[act]
return OffloadMoELayer(
layer_id, E, TOPK, H, I, activation=act, alpha=alpha, limit=limit, quant_config=quant, prefix=f"model.layers.{layer_id}.mlp.experts"
)


def _dequant(packed, scale, row_global):
Expand Down Expand Up @@ -102,39 +107,46 @@ def _weights(pieces, layer):
return gu, dn


def _reference(pieces, layer, hidden, weights, ids):
def _gated(h, act):
gate, up = h[:I], h[I:]
if act == "silu":
return torch.nn.functional.silu(gate) * up
alpha, limit = ACTS[act]
return alpha * torch.tanh(gate / alpha) * torch.sigmoid(gate) * limit * torch.tanh(up / limit)


def _reference(pieces, layer, hidden, weights, ids, act="silu"):
gu, dn = _weights(pieces, layer)
out = torch.zeros(hidden.shape, dtype=torch.float32)
x = hidden.float().cpu()
for t in range(hidden.shape[0]):
for k in range(ids.shape[1]):
e = int(ids[t, k])
h = gu[e] @ x[t]
out[t] += float(weights[t, k]) * (dn[e] @ (torch.nn.functional.silu(h[:I]) * h[I:]))
out[t] += float(weights[t, k]) * (dn[e] @ _gated(gu[e] @ x[t], act))
return out


def _assert_close(out, ref):
torch.testing.assert_close(out.float().cpu(), ref, rtol=3e-2, atol=0.03 * float(ref.abs().max()))


def _mixed_banks(pieces, device, layer_sink=None):
def _mixed_banks(pieces, device, layer_sink=None, act="silu"):
from freetoken.moe.expert_banks import build_expert_banks, merge_expert_banks, method_groups

methods = [_layer(layer, fmt).quant_method for layer, fmt in enumerate(FORMATS)]
methods = [_layer(layer, fmt, act).quant_method for layer, fmt in enumerate(FORMATS)]
parts = [
build_expert_banks(method, L, _reader(pieces, method.kind), device=device, layer_sink=layer_sink, layers=layers)
for method, layers in method_groups(methods)
]
return merge_expert_banks(parts, methods, E), methods


def _mixed_cache(device, pieces, *, decode_target="gpu", prefill_overlap=False):
def _mixed_cache(device, pieces, *, decode_target="gpu", prefill_overlap=False, act="silu"):
from freetoken.moe.offload_cache import OffloadMoeCache, bank_layouts
from freetoken.moe.pool_policy import group_layers, make_pools, pool_of_layer, split_slots
from freetoken.engine.cache_budget import layer_slot_bytes

banks, methods = _mixed_banks(pieces, device)
banks, methods = _mixed_banks(pieces, device, act=act)
slot_bytes = layer_slot_bytes(banks.sources)
groups = group_layers("unified", bank_layouts(banks.sources, banks.layer_tags), slot_bytes)
pools = make_pools(groups, E, TOPK, None)
Expand All @@ -146,7 +158,7 @@ def _mixed_cache(device, pieces, *, decode_target="gpu", prefill_overlap=False):
)
cache.set_bank_sources(banks.sources, layer_tags=banks.layer_tags)
cache.reset()
layers = [_layer(layer, fmt) for layer, fmt in enumerate(FORMATS)]
layers = [_layer(layer, fmt, act) for layer, fmt in enumerate(FORMATS)]
for layer in layers:
layer.offload_cache = cache
return cache, layers, banks
Expand Down Expand Up @@ -253,8 +265,10 @@ def test_mixed_layers_decode_and_prefill_through_their_pools():


@cuda
def test_the_planned_floor_is_the_fewest_slots_that_stage_a_layer():
# the nvfp4 scale banks hold bytes that cannot stage bf16 weight rows, so the floor is per bank, not per slot
@pytest.mark.parametrize("buffers", [1, 2])
def test_the_planned_floor_is_the_fewest_slots_that_stage_a_layer(buffers):
# the nvfp4 scale banks hold bytes that cannot stage bf16 weight rows, so the floor is per bank, not per slot;
# two buffers are --moe-strategy cpu's prefill double buffer
from freetoken.engine.cache_budget import layer_bank_bytes, layer_slot_bytes
from freetoken.moe.offload_cache import OffloadMoeCache, bank_layouts
from freetoken.moe.pool_policy import group_layers, make_pools, pool_of_layer, split_slots, stage_floor
Expand All @@ -265,47 +279,55 @@ def test_the_planned_floor_is_the_fewest_slots_that_stage_a_layer():
rows = layer_bank_bytes(banks.sources)
# expert use that sends every slot past the minimums to the nvfp4 pool
counts = torch.tensor([[0.0 if fmt == "bf16" else 1.0] * E for fmt in FORMATS])
floor = stage_floor(rows, pools, E, counts)
floor = stage_floor(rows, pools, E, counts, buffers=buffers)

def build(size):
cache = OffloadMoeCache(
num_layers=L, num_experts=E, cache_size=size, device=device, quant_format=banks.quant_format,
decode_target="gpu", hybrid_max_fetch=1, prefill_overlap=False,
decode_target="gpu", hybrid_max_fetch=1, prefill_overlap=buffers == 2,
layer_layouts=[m.layout() for m in methods], pool_of_layer=pool_of_layer(pools, L), pool_sizes=split_slots(size, pools, counts),
)
cache.set_bank_sources(banks.sources, layer_tags=banks.layer_tags)
return cache

build(floor)
with pytest.raises(ValueError, match="cannot stage one whole layer"):
build(floor - 1)
if buffers == 1:
build(floor)
with pytest.raises(ValueError, match="cannot stage one whole layer"):
build(floor - 1)
else:
# one slot short of the floor, the cache turns the overlap off
assert build(floor).prefill_overlap and not build(floor - 1).prefill_overlap


@cuda
def test_cpu_executor_computes_each_layer_in_its_format():
@pytest.mark.parametrize("act", list(ACTS))
def test_cpu_executor_computes_each_layer_in_its_format(act):
pytest.importorskip("freetoken.kernel._cpu_moe")
from freetoken.moe.cpu_executor import CpuMoeExecutor

torch.manual_seed(1)
device = torch.device("cuda")
pieces = _pieces(seed=1)
cache, layers, _ = _mixed_cache(device, pieces, decode_target="hybrid")
cache, layers, _ = _mixed_cache(device, pieces, decode_target="hybrid", act=act)
alpha, limit = ACTS[act]
ex = CpuMoeExecutor(
cache, top_k=TOPK, activation="silu", apply_router_weight_on_input=False, num_threads=2,
max_tokens=4, device=device, layer_formats=[(f, {}) for f in FORMATS],
cache, top_k=TOPK, activation=act, apply_router_weight_on_input=False, num_threads=2,
max_tokens=4, device=device, swiglu_alpha=alpha, swiglu_limit=limit, layer_formats=[(f, {}) for f in FORMATS],
)
cache.set_cpu_executor(ex)
bs = 3
hidden = torch.randn(bs, H, dtype=torch.bfloat16, device=device) / 4
# softcap_swiglu: large enough that the gate and up rows reach past the caps
hidden = torch.randn(bs, H, dtype=torch.bfloat16, device=device) * (4 if act == "softcap_swiglu" else 0.25)
weights = torch.rand(bs, TOPK, device=device)
for layer in range(L):
ids = torch.stack([torch.randperm(E)[:TOPK] for _ in range(bs)]).to(torch.int32)
_assert_close(ex.decode(layer, hidden, weights, ids.to(device)), _reference(pieces, layer, hidden, weights, ids))
_assert_close(ex.decode(layer, hidden, weights, ids.to(device)), _reference(pieces, layer, hidden, weights, ids, act))
# hybrid: capped PCIe fetch on the GPU, the overflow misses on the CPU, per layer format
for _ in range(3):
for layer in layers:
ids = torch.stack([torch.randperm(E)[:TOPK] for _ in range(bs)]).to(torch.int32)
out = layer._decode_routed(hidden, weights, ids.clone().to(device))
_assert_close(out, _reference(pieces, layer.layer_id, hidden, weights, ids))
_assert_close(out, _reference(pieces, layer.layer_id, hidden, weights, ids, act))


@cuda
Expand Down