Skip to content
13 changes: 10 additions & 3 deletions batchgen/attention/mla/paged_decode.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,9 @@ def mla_paged_decode(
head_dim_v: int,
softmax_scale: float,
schedule: Optional[DecodeSchedule] = None,
) -> torch.Tensor:
*,
return_lse: bool = False,
):
batch, q_len, num_heads, head_dim = query.shape
assert q_len == 1, "dense paged MLA decode takes one query token per sequence"
if schedule is None:
Expand All @@ -158,13 +160,18 @@ def mla_paged_decode(
if _backend() == "flashmla":
from flash_mla import flash_mla_with_kvcache

out, _ = flash_mla_with_kvcache(
out, lse = flash_mla_with_kvcache(
query, blocked_k, block_table, cache_seqlens, head_dim_v,
schedule.tile_scheduler_metadata, schedule.num_splits, softmax_scale,
True, **flashmla_dense_kwargs(),
)
return out
return (out, lse) if return_lse else out

if return_lse:
raise NotImplementedError(
"mla_paged_decode(return_lse=True) is not implemented for backend "
f"{_backend()!r}"
)
return _trtllm_gen_dense(
query, blocked_k, block_table, cache_seqlens, head_dim_v, softmax_scale
)
53 changes: 45 additions & 8 deletions batchgen/attention/mla/sparse_dispatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,9 +117,20 @@ def _fa3_num_splits() -> int:
return GLM5_SPARSE_FA3_NUM_SPLITS


def _fa3_sparse(q_pe, q_latent, flat_kv, token_rows, lengths, softmax_scale):
def _fa3_sparse(
q_pe,
q_latent,
flat_kv,
token_rows,
lengths,
softmax_scale,
*,
return_lse: bool = False,
num_splits: Optional[int] = None,
):
lora = q_latent.shape[-1]
return _fa3_with_kvcache()(
resolved_splits = _fa3_num_splits() if num_splits is None else int(num_splits)
res = _fa3_with_kvcache()(
q=q_pe,
k_cache=flat_kv[..., lora:],
v_cache=flat_kv[..., :lora],
Expand All @@ -128,9 +139,13 @@ def _fa3_sparse(q_pe, q_latent, flat_kv, token_rows, lengths, softmax_scale):
cache_seqlens=lengths,
softmax_scale=float(softmax_scale),
causal=True,
num_splits=_fa3_num_splits(),
return_softmax_lse=False,
num_splits=resolved_splits,
return_softmax_lse=return_lse,
)
if return_lse:
# Upstream FA3 flash_attn_with_kvcache returns (out, softmax_lse, *rest).
return res[0], res[1]
return res


# --------------------------------------------------------------------------- #
Expand Down Expand Up @@ -220,12 +235,24 @@ def sparse_mla_decode(
token_rows: torch.Tensor,
lengths: torch.Tensor,
softmax_scale: float,
) -> torch.Tensor:
*,
return_lse: bool = False,
num_splits: Optional[int] = None,
):
"""Decode: one query token per row over the paged latent cache."""
_announce("decode", q_latent, token_rows)
if _backend() == "fa3":
flat_kv = blocked_k.view(-1, 1, 1, blocked_k.shape[-1])
return _fa3_sparse(q_pe, q_latent, flat_kv, token_rows, lengths, softmax_scale)
return _fa3_sparse(
q_pe, q_latent, flat_kv, token_rows, lengths, softmax_scale,
return_lse=return_lse,
num_splits=num_splits,
)
if return_lse:
raise NotImplementedError(
"sparse_mla_decode(return_lse=True) is not implemented for backend "
f"{_backend()!r}"
)
return _trtllm_sparse_decode(q_pe, q_latent, blocked_k, token_rows, lengths, softmax_scale)


Expand All @@ -236,10 +263,20 @@ def sparse_mla_prefill(
token_rows: torch.Tensor,
lengths: torch.Tensor,
softmax_scale: float,
) -> torch.Tensor:
*,
return_lse: bool = False,
):
"""Prefill: every query token its own row over flat latent rows."""
_announce("prefill", q_latent, token_rows)
if _backend() == "fa3":
flat_kv = kv_rows.view(-1, 1, 1, kv_rows.shape[-1])
return _fa3_sparse(q_pe, q_latent, flat_kv, token_rows, lengths, softmax_scale)
return _fa3_sparse(
q_pe, q_latent, flat_kv, token_rows, lengths, softmax_scale,
return_lse=return_lse,
)
if return_lse:
raise NotImplementedError(
"sparse_mla_prefill(return_lse=True) is not implemented for backend "
f"{_backend()!r}"
)
return _flashmla_sparse_prefill(q_pe, q_latent, kv_rows, token_rows, lengths, softmax_scale)
128 changes: 79 additions & 49 deletions batchgen/moe/fused_moe_bf16_resident.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,23 +72,26 @@ def layer_shard_nbytes(num_local, hidden_size, intermediate_size,
)


def fill_layer_shard(w13, w2, get_tensor, layer_idx, expert_start):
def fill_layer_shard(w13, w2, get_tensor, layer_idx, expert_start,
weight_keys=("w1.weight", "w3.weight", "w2.weight")):
"""Copy one layer's local experts host->GPU into the stacked rows in place.

The build and every refill of a kept shard write the same host tensors
(``core_engine.get_tensor``, address-stable) to the same rows.
"""
gate_key, up_key, down_key = weight_keys
I = w2.shape[2]
for i in range(w13.shape[0]):
tensors = get_tensor(f"routed_expert_{layer_idx}_{expert_start + i}")
w13[i, :I].copy_(tensors["w1.weight"])
w13[i, I:].copy_(tensors["w3.weight"])
w2[i].copy_(tensors["w2.weight"])
w13[i, :I].copy_(tensors[gate_key])
w13[i, I:].copy_(tensors[up_key])
w2[i].copy_(tensors[down_key])


def build_layer_shard(get_tensor, layer_idx, expert_start, num_local,
hidden_size, intermediate_size, device,
dtype=torch.bfloat16, arena=None):
dtype=torch.bfloat16, arena=None,
weight_keys=("w1.weight", "w3.weight", "w2.weight")):
"""Materialize one MoE layer's local expert shard as stacked GPU tensors.

Copies each local expert's BF16 weights host->GPU exactly once, straight
Expand Down Expand Up @@ -125,10 +128,16 @@ def build_layer_shard(get_tensor, layer_idx, expert_start, num_local,
else:
w13 = torch.empty(w13_shape, dtype=dtype, device=device)
w2 = torch.empty(w2_shape, dtype=dtype, device=device)
fill_layer_shard(w13, w2, get_tensor, layer_idx, expert_start)
fill_layer_shard(w13, w2, get_tensor, layer_idx, expert_start,
weight_keys=weight_keys)
return w13, w2


# Cap the global all_gather/reduce_scatter buffer to avoid OOM on large
# prepacked prefill micro-batches while leaving decode single-shot.
_MAX_GLOBAL_TOKENS = 32768


class ResidentEPMoELayer:
"""Per-layer resident-EP decode MoE forward (thin: kernel + collectives).

Expand All @@ -144,7 +153,7 @@ class ResidentEPMoELayer:
num_tokens_per_rank = None

def __init__(self, layer_idx, w13, w2, comm, world_size, rank,
expert_start, arena=None):
expert_start, arena=None, swiglu_limit=None):
self.layer_idx = layer_idx
self.w13 = w13
self.w2 = w2
Expand All @@ -155,6 +164,7 @@ def __init__(self, layer_idx, w13, w2, comm, world_size, rank,
self.num_local_experts = w13.shape[0]
# The fixed-address arena the stacks are carved from, or None.
self.arena = arena
self.swiglu_limit = swiglu_limit

@classmethod
def set_num_tokens_per_rank(cls, num_tokens_per_rank):
Expand All @@ -169,18 +179,57 @@ def require_resident(self, context):
"access, so the decode activation must map and refill it first"
)

def _forward_chunk(self, padded, gate):
"""Run one all_gather -> gate -> fused_moe_bf16 -> reduce_scatter chunk."""
chunk_ntp, H = padded.shape
num_global = self.world_size * chunk_ntp
if self.world_size == 1:
all_tokens = padded
else:
all_tokens = padded.new_empty((num_global, H))
with self.comm.change_state(enable=True):
self.comm.all_gather(all_tokens, padded)

# Router on the global tokens (identical on every rank).
gate_out = gate(all_tokens.view(num_global, 1, H))
topk_idx, topk_weight = gate_out[0], gate_out[1]

# Mask routing to the local shard: non-local slots carry sentinel -1
# and weight 0 so fused_moe_bf16 skips them completely (zero wasted
# GEMM tiles on expert 0 under high EP such as EP-32).
local_ids = topk_idx - self.expert_start
local_mask = (local_ids >= 0) & (local_ids < self.num_local_experts)
local_ids = torch.where(local_mask, local_ids,
torch.full_like(local_ids, -1))
masked_weight = topk_weight * local_mask.to(topk_weight.dtype)

if self.swiglu_limit is not None:
partial = fused_moe_bf16(all_tokens, self.w13, self.w2,
masked_weight, local_ids,
swiglu_limit=self.swiglu_limit)
else:
partial = fused_moe_bf16(all_tokens, self.w13, self.w2,
masked_weight, local_ids)

if self.world_size > 1:
my_slice = partial.new_empty((chunk_ntp, H))
with self.comm.change_state(enable=True):
self.comm.reduce_scatter(my_slice, partial, op=ReduceOp.SUM)
return my_slice
return partial

def forward(self, x_local, gate):
"""Resident-EP decode MoE over DP-sharded tokens.
"""Resident-EP MoE over DP-sharded tokens (decode and resident-EP prefill).

Args:
x_local: (num_local_tokens, H) this rank's decode rows; may be
x_local: (num_local_tokens, H) this rank's rows; may be
(0, H) on an empty rank — the collectives still run.
gate: router module; called on the gathered (num_global, 1, H)
tokens, returns (topk_idx, topk_weight[, ...]).

Returns:
(num_local_tokens, H) summed routed-expert output for the local
rows (all 256 experts, combined across ranks).
rows (all experts, combined across ranks).
"""
self.require_resident(
f"resident-EP BF16 MoE forward (layer {self.layer_idx})"
Expand All @@ -196,45 +245,26 @@ def forward(self, x_local, gate):
)
num_global = self.world_size * ntp

# Fixed per-rank layout: zero-pad local rows to ntp, gather globally.
padded = x_local.new_zeros((ntp, H))
if num_tokens > 0:
padded[:num_tokens].copy_(x_local)
if self.world_size == 1:
# Degenerate collective schedule: the gather of one rank is the
# padded local rows themselves.
all_tokens = padded
else:
all_tokens = x_local.new_empty((num_global, H))
with self.comm.change_state(enable=True):
self.comm.all_gather(all_tokens, padded)

# Router on the global tokens (identical on every rank).
gate_out = gate(all_tokens.view(num_global, 1, H))
topk_idx, topk_weight = gate_out[0], gate_out[1]

# Mask routing to the local shard: non-local slots keep weight 0 and
# are pointed at local expert 0 — they contribute exactly 0 through
# the weighted top-k reduction, and the extra rows cost no additional
# weight traffic in the BW-bound decode regime (same experts read).
local_ids = topk_idx - self.expert_start
local_mask = (local_ids >= 0) & (local_ids < self.num_local_experts)
local_ids = torch.where(local_mask, local_ids,
torch.zeros_like(local_ids))
masked_weight = topk_weight * local_mask.to(topk_weight.dtype)

partial = fused_moe_bf16(all_tokens, self.w13, self.w2,
masked_weight, local_ids)

# Combine expert shards: SUM over ranks in the global layout (BF16
# over NCCL, K2.5-class numerics; per-rank top-k accumulation above
# is fp32 inside moe_weighted_sum).
if self.world_size > 1:
with self.comm.change_state(enable=True):
self.comm.all_reduce(partial, op=ReduceOp.SUM)

start = self.rank * ntp
return partial[start:start + num_tokens]
if num_global <= _MAX_GLOBAL_TOKENS:
padded = x_local.new_zeros((ntp, H))
if num_tokens > 0:
padded[:num_tokens].copy_(x_local)
out_padded = self._forward_chunk(padded, gate)
return out_padded[:num_tokens]

chunk_ntp = max(1, _MAX_GLOBAL_TOKENS // self.world_size)
out = x_local.new_empty((num_tokens, H))
for start in range(0, ntp, chunk_ntp):
end = min(start + chunk_ntp, ntp)
cur_ntp = end - start
padded = x_local.new_zeros((cur_ntp, H))
valid_end = min(end, num_tokens)
if valid_end > start:
padded[:valid_end - start].copy_(x_local[start:valid_end])
chunk_out = self._forward_chunk(padded, gate)
if valid_end > start:
out[start:valid_end].copy_(chunk_out[:valid_end - start])
return out


def _resident_moe_layers(model_layers):
Expand Down
Loading
Loading