@@ -286,3 +286,39 @@ def test_moe_permute_reuses_scratch_buffers(dtype: torch.dtype):
286286 permuted_idx_1 .untyped_storage ().data_ptr ()
287287 == scratch .permuted_idx .untyped_storage ().data_ptr ()
288288 )
289+
290+
291+ def test_moe_permute_ignores_invalid_expert_ids_with_scratch () -> None :
292+ if not moe_permute_unpermute_supported ():
293+ pytest .skip ("moe_permute_unpermute is not supported on this platform." )
294+
295+ hidden_states = torch .arange (5 * 16 , dtype = torch .bfloat16 , device = "cuda" ).view (
296+ 5 , 16
297+ )
298+ topk_ids = torch .tensor ([[0 ], [- 1 ], [1 ], [4 ], [2 ]], device = "cuda" )
299+ expert_map = torch .tensor ([0 , 1 , - 1 , - 1 ], dtype = torch .int32 , device = "cuda" )
300+ scratch = MoEPermuteScratch (
301+ max_num_tokens = 5 ,
302+ topk = 1 ,
303+ num_experts = 4 ,
304+ num_local_experts = 2 ,
305+ device = hidden_states .device ,
306+ hidden_size = 16 ,
307+ hidden_dtype = hidden_states .dtype ,
308+ )
309+
310+ permuted , _ , expert_offsets , _ , _ = moe_permute (
311+ hidden_states = hidden_states ,
312+ a1q_scale = None ,
313+ topk_ids = topk_ids ,
314+ n_expert = 4 ,
315+ n_local_expert = 2 ,
316+ expert_map = expert_map ,
317+ scratch = scratch ,
318+ )
319+
320+ torch .testing .assert_close (
321+ expert_offsets ,
322+ torch .tensor ([0 , 1 , 2 ], dtype = torch .int64 , device = "cuda" ),
323+ )
324+ torch .testing .assert_close (permuted [:2 ], hidden_states [[0 , 2 ]])
0 commit comments