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
39 changes: 39 additions & 0 deletions docs/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,45 @@ tests require TileLang on an SM90+ NVIDIA GPU, and the `cann` parity tests requi
with `cann_ops_transformer`. Its mHC kernel parity is covered by `tests/ops/mhc/test_mhc.py` and
requires TileKernels on an SM90+ NVIDIA GPU or CANN on an Ascend NPU.

DeepSeek-V4 expert-parallel training is exercised separately by
`tests/e2e/test_e2e_parallel.py::test_deepseek_v4_expert_parallel_alignment`:
four-rank FSDP2, SP=1, EP=1 versus EP=2, and two optimizer steps. This uses
eager DSA/mHC with fused routed experts, so it does not qualify the SM90+
kernel paths. The CPU duplicate-hash-route regression verifies that EP split
counts match unique token/expert dispatch pairs; repeated routing weights are
summed when combining outputs.
The GPU CI also runs `test_deepseek_v4_expert_parallel_fixed_route_vjp_matches_fp32_reference`
in `tests/models/transformers/deepseek_v4/test_deepseek_v4.py`: four-rank EP=4, unequal token
payloads, ordinary and duplicate expert slots, and three held-out seeds. Output,
input/routing gradients and expert-weight gradients are compared with a global
FP32 mathematical VJP using the same BF16 bit patterns and the rounding budget
described below. This isolates expert transport/kernel numerics, not FSDP2
gradient averaging or whole-model optimizer trajectories.

Controlled two-step BF16 FSDP2 runs matched initial FP32 master weights,
buffers, optimizer settings and every rank's micro-batches. Aggregate execution
gates passed, but whole-model pre-clipping gradient relative L2 differed by
about 4.61% for EP2 versus EP1 before aligning routing-weight placement. Non-EP
Triton experts now weight the down-projection output, matching EP and the eager
reference, instead of weighting the BF16 activation before that projection.
Both split/merged weights and shared/independent LoRA use this order; for LoRA,
the routing weight scales the complete base-plus-adapter output.

On the same four-rank fixture, this reduced first-step whole-model gradient
relative L2 to 0.0751%, with bit-identical non-expert gradients. Expert weight
gradients still differ across EP reduction layouts. First-step update relative
L2 was 2.62%; after that update, second-step gradient relative L2 was 4.24% and
update relative L2 was 5.21%. These measurements do not establish whole-model
update parity or convergence. First-step AdamW replay and clipping passed their
separate oracles in the earlier diagnostic runs.

`tests/ops/moe_experts/test_moe_experts_ep.py` checks output and all VJPs against
the single-expert EP projection order without relaxing split/merged parity.
`tests/ops/moe_experts_lora/test_moe_experts_lora.py` checks that zero-B adapters preserve base
output, input/routing and base-weight gradients, while retaining trainable
B-gradients. Both files run in GPU CI. Duplicate routes still have distinct
EP/non-EP reduction layouts; no bitwise guarantee is made for arbitrary routes.

---

### 2. VLM Trainer Test (`tests/trainer/test_vlm_trainer.py`)
Expand Down
26 changes: 26 additions & 0 deletions tests/e2e/test_e2e_parallel.py
Original file line number Diff line number Diff line change
Expand Up @@ -504,6 +504,32 @@ def test_text_parallel_smoke(
)


def test_deepseek_v4_expert_parallel_alignment(dummy_deepseek_v4_dense_packed_text_dataset):
"""Compare two optimizer steps with EP=1/2 on the same four-rank FSDP2 job.

Keep SP disabled so this explicitly validates expert sharding and token
dispatch rather than conflating it with the existing SP-only smoke test.
Eager DSA/mHC work on the SM89 CI fleet; routed MoE stays fused.
"""
main(
task_name="train_text_test",
model_name="deepseek_v4",
config_path="./tests/toy_config/deepseek_v4_toy",
is_moe=True,
rtol=_DEFAULT_RTOL,
atol=_DEFAULT_ATOL,
train_path=dummy_deepseek_v4_dense_packed_text_dataset,
max_sp_size=1,
max_ep_size=2,
compare_alignment=True,
extra_args=[
"--model.ops_implementation.dsa_indexer_implementation=eager",
"--model.ops_implementation.dsa_attention_implementation=eager",
"--model.ops_implementation.mhc_implementation=eager",
],
)


@_deepseek_v4_tilelang_skip
@pytest.mark.parametrize("dataset_fixture, case_args", deepseek_v4_tilelang_dyn_bsz_test_cases)
def test_deepseek_v4_tilelang_dyn_bsz_smoke(
Expand Down
194 changes: 194 additions & 0 deletions tests/models/transformers/deepseek_v4/test_deepseek_v4.py
Original file line number Diff line number Diff line change
Expand Up @@ -398,3 +398,197 @@ def counting(cu_seqlens):
use_cache=False,
)
assert calls["from_cu"] == 0


def test_deepseek_v4_duplicate_hash_routes_match_ep_dispatch_splits(monkeypatch):
import veomni.distributed.moe.moe_layer as moe

selected = torch.tensor([[0, 0], [0, 2], [3, 3]])
mask = F.one_hot(selected, num_classes=4).permute(2, 1, 0)
group = SimpleNamespace(size=lambda: 2)
monkeypatch.setattr(moe.dist, "get_rank", lambda _group: 0)

def gather(output, counts, group):
output.copy_(counts.expand(2, -1))

monkeypatch.setattr(moe.dist, "all_gather_into_tensor", gather)
inputs, outputs, counts, totals = moe.preprocess(mask, 4, group)
dispatched, _ = moe.permute(torch.ones(3, 2), mask.sum(dim=1))
assert inputs == [2, 2]
assert outputs == [2, 2]
assert sum(inputs) == dispatched.shape[0] == 4
torch.testing.assert_close(counts, torch.tensor([[2, 0], [2, 0]]))
torch.testing.assert_close(totals, torch.tensor([4, 0]))


def _deepseek_v4_experts_reference(
num_experts: int,
routing_weights: torch.Tensor,
selected_experts: torch.Tensor,
hidden_states: torch.Tensor,
gate_up_proj: torch.Tensor,
down_proj: torch.Tensor,
swiglu_limit: float | None,
) -> torch.Tensor:
output = torch.zeros_like(hidden_states)
expert_mask = F.one_hot(selected_experts, num_classes=num_experts).permute(2, 1, 0)
expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
for expert_idx in expert_hit:
idx = int(expert_idx[0].item())
top_k_pos, token_idx = torch.where(expert_mask[idx])
current_state = hidden_states[token_idx]
gate, up = F.linear(current_state, gate_up_proj[idx]).chunk(2, dim=-1)
if swiglu_limit is not None:
gate = gate.clamp(min=None, max=swiglu_limit)
up = up.clamp(min=-swiglu_limit, max=swiglu_limit)
current_hidden_states = F.silu(gate) * up
current_hidden_states = F.linear(current_hidden_states, down_proj[idx])
current_hidden_states = current_hidden_states * routing_weights[token_idx, top_k_pos, None]
output.index_add_(0, token_idx, current_hidden_states.to(output.dtype))
return output


def _run_deepseek_v4_ep_fixed_route_vjp(rank, world_size, init_file, seed):
import torch.distributed as dist

from tests.tools.training_utils import make_eager_ops_config
from veomni.distributed.parallel_state import ParallelState, _init_parallel_state, use_parallel_state
from veomni.models import build_foundation_model
from veomni.ops.kernels.moe_experts.standard.triton import group_gemm_fused_moe_forward
from veomni.utils.device import get_device_type, get_dist_comm_backend, get_torch_device

device_type = get_device_type()
get_torch_device().set_device(rank)
dist.init_process_group(
get_dist_comm_backend(), init_method=f"file://{init_file}", rank=rank, world_size=world_size
)
torch.manual_seed(seed)
torch.set_float32_matmul_precision("highest")
with use_parallel_state(ParallelState(dp_size=world_size, dp_shard_size=world_size)):
model = build_foundation_model(
config_path="tests/toy_config/deepseek_v4_toy",
weights_path=None,
torch_dtype="bfloat16",
init_device=device_type,
ops_implementation=make_eager_ops_config(moe_implementation="fused_triton"),
).train()
with torch.no_grad():
for module in model.modules():
if hasattr(module, "tid2eid"):
table = module.tid2eid
table.copy_(
(
torch.arange(table.shape[0], device=table.device)[:, None]
+ torch.arange(table.shape[1], device=table.device)[None, :]
)
% module.num_experts
)
expert = model.model.layers[3].mlp.experts
captured = {}

def capture(_module, args, kwargs, output):
for i, name in enumerate(("hidden_states", "top_k_index", "top_k_weights")):
captured[name] = (args[i] if len(args) > i else kwargs[name]).detach().clone()
output.register_hook(lambda grad: captured.update(cotangent=grad.detach().clone()))

handle = expert.register_forward_hook(capture, with_kwargs=True)
ids = torch.arange(64, device=device_type).view(1, 64)
model(input_ids=ids, labels=ids, use_cache=False).loss.backward()
handle.remove()
full_gate_up = expert.gate_up_proj.detach().clone()
full_down = expert.down_proj.detach().clone()
limit = expert.limit
del model
for value in (*captured.values(), full_gate_up, full_down):
dist.broadcast(value, src=0)
state = _init_parallel_state(
dp_size=world_size,
dp_shard_size=world_size,
device_type=device_type,
extra_parallel_sizes=(world_size,),
name=None,
)
local_experts = full_gate_up.shape[0] // world_size
expert_slice = slice(state.ep_rank * local_experts, (state.ep_rank + 1) * local_experts)
offsets = (0, 9, 24, 41, 64)
token_slice = slice(offsets[rank], offsets[rank + 1])
for duplicate_slots in (False, True):
indices = captured["top_k_index"].clone()
if duplicate_slots:
indices[::8, 1] = indices[::8, 0]
route_bits = captured["top_k_weights"].to(torch.bfloat16)
hidden = captured["hidden_states"][token_slice].detach().clone().requires_grad_()
route = route_bits[token_slice].detach().clone().requires_grad_()
gate_up = full_gate_up[expert_slice].detach().clone().requires_grad_()
down = full_down[expert_slice].detach().clone().requires_grad_()
with use_parallel_state(state):
output = group_gemm_fused_moe_forward(
num_experts=full_gate_up.shape[0],
routing_weights=route,
selected_experts=indices[token_slice],
hidden_states=hidden,
fc1_1_weight=None,
fc1_2_weight=None,
fc1_1_2_weight=gate_up,
fc2_weight=down,
swiglu_limit=limit,
)
output.backward(captured["cotangent"][token_slice])
ref_hidden = captured["hidden_states"].float().detach().requires_grad_()
ref_route = route_bits.float().detach().requires_grad_()
ref_gate_up = full_gate_up.float().detach().requires_grad_()
ref_down = full_down.float().detach().requires_grad_()
ref_output = _deepseek_v4_experts_reference(
num_experts=full_gate_up.shape[0],
routing_weights=ref_route,
selected_experts=indices,
hidden_states=ref_hidden,
gate_up_proj=ref_gate_up,
down_proj=ref_down,
swiglu_limit=limit,
)
ref_output.backward(captured["cotangent"].float())
pairs = {
"output": (output, ref_output[token_slice]),
"hidden_grad": (hidden.grad, ref_hidden.grad[token_slice]),
"route_grad": (route.grad, ref_route.grad[token_slice]),
# Global reference VJP sums cotangents from EVERY source rank.
# Direct EP has no FSDP gradient averaging to undo here.
"gate_up_grad": (gate_up.grad, ref_gate_up.grad[expert_slice]),
"down_grad": (down.grad, ref_down.grad[expert_slice]),
}
for name, (actual, expected) in pairs.items():
context = (seed, rank, duplicate_slots, name)
assert actual is not None and expected is not None, context
assert actual.shape == expected.shape, context
assert torch.isfinite(actual).all() and torch.isfinite(expected).all(), context
delta = actual.double() - expected.double()
relative_l2 = delta.norm() / expected.double().norm().clamp_min(1e-30)
# Same multi-stage BF16 rounding budget as the non-EP oracle;
# discovery seed0 is excluded from these held-out cases.
eps = torch.finfo(torch.bfloat16).eps
assert relative_l2 <= 2 * eps, (context, relative_l2.item())
assert delta.abs().max() <= 4 * eps * expected.double().abs().max(), context
dist.barrier()
dist.destroy_process_group()


def _has_four_nvidia_gpus() -> bool:
from veomni.utils.device import IS_CUDA_AVAILABLE, get_torch_device

return bool(IS_CUDA_AVAILABLE and torch.version.hip is None and get_torch_device().device_count() >= 4)


@pytest.mark.skipif(
not _has_four_nvidia_gpus(),
reason="DeepSeek V4 EP expert oracle requires four NVIDIA CUDA devices",
)
@pytest.mark.parametrize("seed", [1, 2, 3])
def test_deepseek_v4_expert_parallel_fixed_route_vjp_matches_fp32_reference(seed, tmp_path):
"""Check all-to-all output and four VJPs, unequal splits and duplicate slots."""
torch.multiprocessing.spawn(
_run_deepseek_v4_ep_fixed_route_vjp,
args=(4, str(tmp_path / "rendezvous"), seed),
nprocs=4,
join=True,
)
7 changes: 4 additions & 3 deletions tests/ops/moe_experts/reference.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,11 @@ def standard_fused_reference(
num_experts: int,
swiglu_limit: float | None = None,
) -> Tensor:
"""Evaluate standard MoE with github/main fused-kernel order.
"""Evaluate standard MoE with pre-fc2 routing-weight order.

Non-EP Triton and Quack multiply routing onto the SwiGLU intermediate,
then apply ``fc2``. Use this only for fused-kernel tests.
Non-EP Quack multiplies routing onto the SwiGLU intermediate, then
applies ``fc2``. Non-EP Triton uses ``standard_ep_reference`` (post-``fc2``
routing order) to match EP combine and Hugging Face eager.
"""
return _standard_expert_loop(
hidden,
Expand Down
11 changes: 6 additions & 5 deletions tests/ops/moe_experts/test_moe_experts.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
from transformers.models.gpt_oss.modeling_gpt_oss import GptOssExperts
from transformers.models.qwen3_moe.modeling_qwen3_moe import Qwen3MoeExperts

from tests.ops.moe_experts.reference import standard_fused_reference
from tests.ops.moe_experts.reference import standard_ep_reference, standard_fused_reference
from tests.ops.tol import (
EAGER_ATOL,
EAGER_GRAD_ATOL,
Expand Down Expand Up @@ -485,9 +485,9 @@ def _run_fused_three_way(
):
"""Compare one fused implementation's split and merged layouts with eager math.

The reference is ``standard_fused_reference``: eager math in the fused
rows' routing order. The production eager row uses Hugging Face order,
which drifts from it by BF16 rounding at production shapes.
Non-EP Triton uses ``standard_ep_reference`` (post-``fc2`` routing-weight
order matching EP and Hugging Face eager), while Quack uses
``standard_fused_reference`` (pre-``fc2`` routing-weight order).
"""
torch.manual_seed(seed)
if device is None:
Expand Down Expand Up @@ -519,7 +519,8 @@ def _run_fused_three_way(
out_m = fused(hidden_m, routing_m, selected, empty, empty, fc2_m, fc1_12_m, **kwargs)
if impl == "fused_triton":
assert len(out_m.grad_fn.saved_tensors) == 11
out_e = standard_fused_reference(hidden_e, routing_e, selected, fc1_1_e, fc1_2_e, fc2_e, **kwargs)
reference_fn = standard_ep_reference if impl == "fused_triton" else standard_fused_reference
out_e = reference_fn(hidden_e, routing_e, selected, fc1_1_e, fc1_2_e, fc2_e, **kwargs)
torch.testing.assert_close(out_s, out_m, rtol=0, atol=0)

go = torch.randn_like(out_s)
Expand Down
Loading
Loading