Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
9 changes: 6 additions & 3 deletions aiter/ops/flydsl/kernels/moe_sorting_kernel.py
Original file line number Diff line number Diff line change
Expand Up @@ -384,14 +384,16 @@ def moe_sorting_oneshot_kernel(

global_idx = token_id * c_topk + topk_slot
eid = _gld(topk_ids_it, global_idx)
valid_eid = (eid >= c_zero_i32) & (eid < c_E)
should_store = is_valid & valid_eid

# mesh[token_id, eid] = topk_slot + 1 (valid threads only).
# Invalid threads must NOT write to mesh[0] — that would race
# with a valid write to (token=0, expert=0).
mesh_addr = token_id * c_smem_cols + eid
last_mesh_idx = fx.Int32(sub_tokens * smem_cols - 1)
safe_mesh_addr = is_valid.select(mesh_addr, last_mesh_idx)
val = is_valid.select(topk_slot + c_one_i32, c_zero_i32)
safe_mesh_addr = should_store.select(mesh_addr, last_mesh_idx)
val = should_store.select(topk_slot + c_one_i32, c_zero_i32)
_lds_store_raw(mesh_mr, val, safe_mesh_addr)
gpu.barrier()

Expand Down Expand Up @@ -1030,9 +1032,10 @@ def p0_scatter_kernel(
token_id = safe_flat // c_topk
topk_slot = safe_flat % c_topk
eid = _gld(topk_it, safe_flat)
valid_eid = (eid >= c_zero) & (eid < fx.Int32(E))
byte_offset = eid * i32_mesh_stride + token_id
val_i8 = fx.Int32(topk_slot + c_one).to(fx.Int8)
if valid:
if valid & valid_eid:
ws_i8[byte_offset] = val_i8

@flyc.jit
Expand Down
32 changes: 20 additions & 12 deletions csrc/include/moe_sorting_opus.h
Original file line number Diff line number Diff line change
Expand Up @@ -793,10 +793,13 @@ struct MoeSortingKernel
{
int eid = topk_id[i_t * topk + curr_topk_id];

if constexpr(Problem::SubTokenOneShot)
smem_tokens(curr_token_id, eid) = curr_topk_id + 1;
else
smem_tokens(curr_token_id, eid)++;
if(eid >= 0 && eid < num_experts)
{
if constexpr(Problem::SubTokenOneShot)
smem_tokens(curr_token_id, eid) = curr_topk_id + 1;
else
smem_tokens(curr_token_id, eid)++;
}
}
#if defined(__gfx1250__)
opus::s_wait_dscnt(opus::number<0>{});
Expand Down Expand Up @@ -950,7 +953,9 @@ struct MoeSortingKernel
int local_id = eid;
if constexpr(Problem::LocalExpertMasking)
{
local_id = local_expert_mask[eid] != 0 ? smem_cumdup(eid) : -1;
bool valid_eid = eid >= 0 && eid < num_experts;
local_id = valid_eid && local_expert_mask[eid] != 0 ? smem_cumdup(eid)
: -1;
}
p_local_topk_ids[i] = local_id;
}
Expand Down Expand Up @@ -1019,7 +1024,8 @@ struct MoeSortingKernel
if(i_t < tokens)
{
int eid = topk_id[i_t * topk + curr_topk_id];
smem_tokens(curr_token_id, eid) = curr_topk_id + 1; // at least 1
if(eid >= 0 && eid < num_experts)
smem_tokens(curr_token_id, eid) = curr_topk_id + 1; // at least 1
}
}
__syncthreads();
Expand Down Expand Up @@ -2158,16 +2164,18 @@ struct MoeSortingMultiPhaseKernel_P01
uint32_t curr_token_id, curr_topk_id;
kargs.topk_mdiv.divmod(
i * Problem::SubTokenTile + j, curr_token_id, curr_topk_id);
// p_expert_mesh[eid * kargs.mesh_stride + curr_token_id] = curr_topk_id + 1;
if constexpr(Problem::LocalToken)
if(eid >= 0 && eid < kargs.num_experts)
{
if(static_cast<opus::index_t>(curr_token_id) < tokens)
if constexpr(Problem::LocalToken)
{
if(static_cast<opus::index_t>(curr_token_id) < tokens)
p_expert_mesh[eid * kargs.mesh_stride + curr_token_id] =
(curr_topk_id + 1) & 0xffff;
}
else
p_expert_mesh[eid * kargs.mesh_stride + curr_token_id] =
(curr_topk_id + 1) & 0xffff;
}
else
p_expert_mesh[eid * kargs.mesh_stride + curr_token_id] =
(curr_topk_id + 1) & 0xffff;
});
}
if(static_cast<opus::index_t>(blockIdx.x) < wg_count)
Expand Down
151 changes: 148 additions & 3 deletions op_tests/test_moe_sorting.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,25 @@ def _build_moe_sorting_inputs(
return topk_ids, topk_weights, expert_mask, num_local_tokens


def _apply_routing_case(topk_ids, topk_weights, routing_case):
token, topk = topk_weights.shape
if routing_case == "all-empty":
topk_ids[:token].fill_(-1)
topk_weights.zero_()
elif routing_case == "mixed":
invalid = (
torch.arange(token * topk, device=topk_ids.device, dtype=torch.int64).view(
token, topk
)
% 2
== 1
)
topk_ids[:token].masked_fill_(invalid, -1)
topk_weights.masked_fill_(invalid, 0)
elif routing_case != "valid":
raise ValueError(f"unknown routing case: {routing_case}")


@benchmark()
def test_moe_sorting(
dtype,
Expand All @@ -197,6 +216,7 @@ def test_moe_sorting(
padding_extra=0,
dispatch_policy=0,
accumulate=True,
routing_case="valid",
):
"""accumulate=False (with has_expert_mask=False) makes moe_sorting allocate
a (0,0) moe_buf placeholder instead of the full [M, model_dim] buffer --
Expand All @@ -213,6 +233,7 @@ def test_moe_sorting(
has_expert_mask,
padding_extra,
)
_apply_routing_case(topk_ids, topk_weights, routing_case)

ref = run_torch_moe_sorting(
topk_ids,
Expand Down Expand Up @@ -265,7 +286,7 @@ def test_moe_sorting(
)

flops, nbytes = _moe_sorting_roofline(token, topk, E, model_dim, dtype)
ret = {"gfx": get_gfx()}
ret = {"gfx": get_gfx(), "routing case": routing_case}
failures = {}

for name, fn in candidates.items():
Expand All @@ -290,7 +311,8 @@ def test_moe_sorting(
raise AssertionError(
f"moe_sorting mismatch vs CPU reference at token={token}, E={E}, "
f"topk={topk}, has_expert_mask={has_expert_mask}, "
f"padding_extra={padding_extra}, dispatch_policy={dispatch_policy}: "
f"padding_extra={padding_extra}, dispatch_policy={dispatch_policy}, "
f"routing_case={routing_case}: "
f"{failures}"
)
return ret
Expand All @@ -303,6 +325,7 @@ def test_moe_sorting_flydsl_cuda_graph_capture(
E,
topk,
has_expert_mask=False,
routing_case="valid",
):
"""Capture moe_sorting (FlyDSL backend) under a real torch.cuda.graph(),
then replay with a DIFFERENT num_local_tokens tensor value than was
Expand All @@ -327,6 +350,7 @@ def test_moe_sorting_flydsl_cuda_graph_capture(
has_expert_mask,
padding_extra,
)
_apply_routing_case(topk_ids, topk_weights, routing_case)
assert isinstance(num_local_tokens, torch.Tensor)

def run():
Expand Down Expand Up @@ -381,7 +405,85 @@ def run():
assert not bad, (
f"moe_sorting cuda-graph replay mismatch (captured token={capture_tokens}, "
f"replayed token={replay_tokens}, E={E}, topk={topk}, "
f"has_expert_mask={has_expert_mask}): {bad}"
f"has_expert_mask={has_expert_mask}, routing_case={routing_case}): {bad}"
)


def test_moe_sorting_invalid_topk_ids():
"""Exercise every invalid-ID sorting path against the torch reference."""
if get_gfx() not in SUPPORTED_GFX:
aiter.logger.warning("moe_sorting unsupported on %s; skipping", get_gfx())
return

dtype = dtypes.bf16
model_dim = 4096
E = 256
topk = 6

direct_cases = (
# Automatic large-token Opus path; P0_v1 is guarded by #4839.
("opus", 16384, 0, False),
# Remaining single-kernel mesh and local-expert-mask accesses.
("opus", 8, 1, False),
("opus", 8, 1, True),
# Forced large-token multi-phase regression (P0_v1 -> P1 -> P23).
("opus", 2048, 2, False),
# FlyDSL LDS oneshot and HBM multiphase mesh stores.
("flydsl", 8, 0, False),
("flydsl", 2048, 0, False),
)

for backend, token, dispatch_policy, has_expert_mask in direct_cases:
for routing_case in ("all-empty", "mixed"):
topk_ids, topk_weights, expert_mask, _ = _build_moe_sorting_inputs(
token,
model_dim,
E,
topk,
dtype,
has_expert_mask,
padding_extra=0,
)
_apply_routing_case(topk_ids, topk_weights, routing_case)
ref = run_torch_moe_sorting(
topk_ids,
topk_weights,
E,
BLOCK_SIZE_M,
expert_mask,
)

set_moe_sorting_backend(backend)
out = moe_sorting(
topk_ids,
topk_weights,
E,
model_dim,
dtype,
BLOCK_SIZE_M,
expert_mask,
None,
dispatch_policy,
accumulate=True,
)
torch.cuda.synchronize()
errs = _compare_moe_sorting_outputs(ref, out, topk, token)
bad = {name: value for name, value in errs.items() if value}
assert not bad, (
f"{backend} moe_sorting mismatch for token={token}, "
f"dispatch_policy={dispatch_policy}, "
f"has_expert_mask={has_expert_mask}, "
f"routing_case={routing_case}: {bad}"
)

test_moe_sorting_flydsl_cuda_graph_capture(
dtype,
token=2048,
model_dim=model_dim,
E=E,
topk=topk,
has_expert_mask=True,
routing_case="mixed",
)


Expand Down Expand Up @@ -483,6 +585,27 @@ def run():
return ret


def run_invalid_routing_regressions(dtype, model_dim, inter_dim):
rows = []
for routing_case in ("all-empty", "mixed"):
rows.append(
test_moe_sorting(
dtype,
token=2048,
model_dim=model_dim,
inter_dim=inter_dim,
E=256,
topk=6,
has_expert_mask=False,
padding_extra=0,
dispatch_policy=0,
accumulate=True,
routing_case=routing_case,
)
)
return rows


def main():
if get_gfx() not in SUPPORTED_GFX:
aiter.logger.warning("moe_sorting unsupported on %s; skipping", get_gfx())
Expand Down Expand Up @@ -573,6 +696,16 @@ def main():
"moe_buf placeholder instead of the full [M, model_dim] buffer -- "
"isolates moe_buf-zeroing cost from mesh-scan work).\n e.g.: -accum f",
)
parser.add_argument(
"-rc",
"--routing_case",
choices=["valid", "all-empty", "mixed"],
nargs="*",
default=None,
help="Routing inputs, including invalid -1 sentinel coverage.\n"
" e.g.: -rc all-empty mixed\n"
" default: valid matrix plus focused all-empty/mixed regressions",
)
parser.add_argument(
"-dg",
"--decode_graph",
Expand All @@ -591,6 +724,7 @@ def main():
parser.error("-e/--expert and -t/--topk must have the same length")

model_configs = list(zip(args.expert, args.topk))
routing_cases = args.routing_case if args.routing_case is not None else ["valid"]

for dtype in args.dtype:
df = []
Expand All @@ -599,12 +733,14 @@ def main():
expert_mask,
dispatch_policy,
accumulate,
routing_case,
m,
) in itertools.product(
args.padding,
args.expert_mask,
args.dispatch_policy,
args.accumulate,
routing_cases,
args.m,
):
for E, topk in model_configs:
Expand All @@ -620,8 +756,17 @@ def main():
padding_extra=padding_extra,
dispatch_policy=dispatch_policy,
accumulate=accumulate,
routing_case=routing_case,
)
)
if args.routing_case is None:
df.extend(
run_invalid_routing_regressions(
dtype,
args.model_dim,
args.inter_dim,
)
)
df = pd.DataFrame(df)
aiter.logger.info(
"moe_sorting summary (markdown):\n%s", df.to_markdown(index=False)
Expand Down
Loading