diff --git a/agent-flow/agent_flow/workflows/trtllm_modeling_v2/agents/skills/trtllm-modeling-v2-features/SKILL.md b/agent-flow/agent_flow/workflows/trtllm_modeling_v2/agents/skills/trtllm-modeling-v2-features/SKILL.md index a20aca3e2765..e684add27a10 100644 --- a/agent-flow/agent_flow/workflows/trtllm_modeling_v2/agents/skills/trtllm-modeling-v2-features/SKILL.md +++ b/agent-flow/agent_flow/workflows/trtllm_modeling_v2/agents/skills/trtllm-modeling-v2-features/SKILL.md @@ -95,7 +95,7 @@ Climb only as far as the claim needs. Each rung says what it cannot see. | disaggregation | feature `disagg` + `accuracy.disagg` (`config`/`context`/`generation`, or `test`) | a benchmark scored through `trtllm-serve disaggregated` | the flow's own serving of the stated deployment, or the tree's disaggregated-serving test | | multimodal | feature `multimodal` | an image prompt answered | boot image, image benchmark | | speculative | features `mtp`, `eagle3`, `dflash`, `dspark` | accepted tokens per iteration | acceptance gate | -| EPLB | a variant setting `llm_api_options.moe_config.load_balancer` at a `dep` member, `modeling_v2: require` | the engine builds the target (a mode missing from its `EPLB_MODES` refuses it) | variant accuracy | +| EPLB | a variant setting `llm_api_options.moe_config.load_balancer` at a `dep` member (`layer_updates_per_iter` > 0 for online), `modeling_v2: require` | the engine builds the target (a mode missing from its `EPLB_MODES` refuses it) | variant accuracy | ## Rules that save hours diff --git a/agent-flow/agent_flow/workflows/trtllm_modeling_v2/agents/skills/trtllm-modeling-v2-features/references/features.md b/agent-flow/agent_flow/workflows/trtllm_modeling_v2/agents/skills/trtllm-modeling-v2-features/references/features.md index 7285ba0e1aeb..c0379c789db5 100644 --- a/agent-flow/agent_flow/workflows/trtllm_modeling_v2/agents/skills/trtllm-modeling-v2-features/references/features.md +++ b/agent-flow/agent_flow/workflows/trtllm_modeling_v2/agents/skills/trtllm-modeling-v2-features/references/features.md @@ -552,25 +552,43 @@ an EPLB deployment only if its class lists the mode in `EPLB_MODES`. - A target that gathers tokens before routing routes on every rank and must get the same slots on every rank: `eplb_call` does (`offset_by_ep_rank=False`). +- Online EPLB adds three duties, all through `EplbLayer`: + - While loading, `share_experts` hands the balancer host copies of this + rank's share of every routed layer's experts (`host_experts`), each slot + weight in the slot layout. + - After loading, `bind_slots` moves the slot weights to memory the balancer + writes, before any view of them is taken. Every per-slot scalar the + expert kernel reads is a bound slot weight, not a value recomputed in the + forward. + - Per forward, `eplb_call(eplb, ids, rows=..., last=...)` records the router's + expert ids without the padding rows, and `close()` hands each layer back + once, after its last expert kernel and before the next layer routes. A draft + layer is closed after the worker's last draft step, also when the worker + drafts nothing. **Grep.** `EPLB_MODES`, `moe_eplb_mode`, `eplb_slots`, `EplbLayer`, -`eplb_call`, `eplb_route`, `moe_load_balancer_mode`, `maybe_create_moe_load_balancer`, -`MoeLoadBalancerConfig`, `initial_global_assignments`, `num_slots`. +`eplb_call`, `eplb_route`, `share_experts`, `bind_slots`, `close_draft_eplb`, +`moe_load_balancer_mode`, `maybe_create_moe_load_balancer`, +`MoeLoadBalancerConfig`, `initial_global_assignments`, `num_slots`, +`layer_updates_per_iter`. **Tests to imitate.** - `tests/unittest/_torch/modeling_v2/moe/ops/test_modeling_v2_eplb.py`: the slots, - registration and each expert call's routing (`eplb_call`) on the CPU; the - route op's cells, where every EP rank must - route the same ids to the same slots; and a slot-routed layer whose windows - sum to the layer without EPLB. -- `tests/unittest/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_modeling_v2_deepseek_default_shards.py` - (`test_eplb_*`): slots and `load` under a placement drawn per layer, with - copies of an expert across ranks and twice on one rank, against the - world-size-1 table without EPLB. + registration and each expert call's routing (`eplb_call`) on the CPU; the online protocol a layer follows with the + balancer, its host copies and its binding, on the CPU; the route op's + cells, where every EP rank must route the same ids to the same slots; a + slot-routed layer whose windows sum to the layer without EPLB; and a real + online balancer moving experts into bound slots. +- `tests/unittest/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_modeling_v2_deepseek_eplb_shards.py` + (`test_eplb_*`, `test_online_eplb_*`): slots and `load` under a placement + drawn per layer, with copies of an expert across ranks and twice on one + rank, and the host copies online EPLB hands over, against the world-size-1 + table without EPLB. - `tests/unittest/_torch/modeling_v2/test_modeling_v2_routing.py` (`test_eplb_*`, `test_r1_*eplb*`): the resolver's decisions per mode and layout. -- `accuracy/modeling_v2/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_accuracy.py::TestModelingV2DeepseekR10528Nvfp4Sm10xDefault::test_gsm8k_static_eplb`. +- `accuracy/modeling_v2/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_accuracy.py::TestModelingV2DeepseekR10528Nvfp4Sm10xDefault::test_gsm8k_static_eplb` + and `::test_gsm8k_online_eplb`. **Fast check.** quickstart or `trtllm-serve` at a dep layout with `moe_config.load_balancer` set and `modeling_v2: require`: the engine must @@ -587,8 +605,16 @@ not report the registered layers, so the target's own tests carry that. - A slot loaded with the wrong expert, or an id routed to a slot that holds another expert, still produces fluent text. Use a placement that differs from the default in every layer, with an expert held twice on one rank. -- Padding rows and attention-DP dummy requests count in the routing like - real tokens. +- Attention-DP dummy requests count in the statistic like real tokens; + only the padding rows a target names with `eplb_call(..., rows=...)` are left out. - A layer that is registered but never runs, for example after the loader builds the model twice, changes nothing under static EPLB. Under online - EPLB the balancer waits for it. + EPLB the balancer waits for it, and so does every later forward: a missed + `close` hangs the engine rather than failing it. +- Under online EPLB, a view of a slot weight taken before `bind_slots`, or a + per-slot scalar recomputed in the forward, reads stale values after the + first move -- the score drops only once the balancer has moved experts, so + the run has to be long enough for that. +- Online EPLB needs host-accessible device memory: Grace's, or GDRCopy on x86 + with a library that matches the node's `gdrdrv` driver. Without it the + balancer fails at creation. diff --git a/examples/wide_ep/ep_load_balancer/README.md b/examples/wide_ep/ep_load_balancer/README.md index 183eca69b213..0ef9c5eef899 100644 --- a/examples/wide_ep/ep_load_balancer/README.md +++ b/examples/wide_ep/ep_load_balancer/README.md @@ -321,6 +321,149 @@ A [Modeling V2](../../../tensorrt_llm/_torch/modeling_v2/README.md) target runs | Target | EPLB modes | Layouts | |---|---|---| -| DeepSeek-R1-0528 NVFP4 (`deepseek_v3/r1_0528_nvfp4__sm_10x__default`, SM100 and SM103) | static | attention DP with pure expert parallelism over 4 or 8 GPUs (dep4, dep8) | +| DeepSeek-R1-0528 NVFP4 (`deepseek_v3/r1_0528_nvfp4__sm_10x__default`, SM100 and SM103) | static, online | attention DP with pure expert parallelism over 4 or 8 GPUs (dep4, dep8) | -Every other target declines EPLB, so those deployments run the built-in model. To collect the expert statistics for `generate_eplb_config.py`, run the statistics pass with `modeling_v2: off`. The built-in model uses the same router, so its statistics describe the same load. +Every other target declines EPLB, so those deployments run the built-in model. + +### Run EPLB on the Modeling V2 target + +The steps below run the DeepSeek-R1-0528 NVFP4 target with EPLB at dep8: attention DP with 8-way expert parallelism, on two GB200 or GB300 trays. They follow the steps above at the scale the target runs EPLB. `modeling_v2: require` builds the target or fails with the reason it does not fit; with `auto`, a deployment the target does not fit runs the built-in model instead. + +Set up the environment: + +```bash +export MODEL_NAME=nvidia/DeepSeek-R1-0528-FP4 +export MODEL_PATH= +``` + +Prepare a dataset following the [benchmarking documentation](https://github.com/NVIDIA/TensorRT-LLM/blob/main/docs/source/developer-guide/perf-benchmarking.md#preparing-a-dataset), for example: + +```bash +trtllm-bench --model ${MODEL_PATH} prepare-dataset \ + --output ./dataset.json \ + token-norm-dist \ + --num-requests 4096 \ + --input-mean 1024 --output-mean 1024 \ + --input-stdev 0 --output-stdev 0 +``` + +#### Static EPLB + +1. Collect the expert statistics on the built-in model. The Modeling V2 target does not record them, and the built-in model routes with the same router, so its statistics describe the same load. Quote `"off"`: YAML reads a bare `off` as `false`. + + ```bash + export EXPERT_STATISTIC_PATH=./expert_statistic + export EXPERT_STATISTIC_ITER_RANGE=100-200 + + cat > ./config_stats.yaml < ./config_v2_static.yaml < ./moe_load_balancer_online.yaml < ./config_v2_online.yaml < 0`) moves experts between slots while +the engine serves. Each forward, every routed layer's statistic records which +experts the tokens chose. Between forwards the balancer recomputes the +placement of a few layers, copies the moved experts' weights from host memory +into their new slots and reroutes to them. On top of the four static steps a +target does three more, and lists `"online"` in `EPLB_MODES`: + +5. **Host copies.** While loading, call + `EplbLayer.share_experts(slot_weights, expert_weight)` once per routed + layer. `slot_weights` names every per-slot weight -- the operands, their + block scales and any per-slot scalar the expert kernel takes -- and + `expert_weight(name, expert)` reads one expert's weight in the slot layout, + through the same cut and transform as a slot. It is called for the experts + in `EplbLayer.host_experts`, this rank's share of its node, so the node + holds every expert once. Those experts' checkpoint tensors are then read, + which the target's coverage accounting has to expect. +6. **Binding.** After loading, call `EplbLayer.bind_slots(slot_weights)` + before taking any view of those weights. Binding moves them to memory the + balancer can write and registers every slot, and a view taken earlier + keeps reading the old storage. Binding the same weights again does + nothing, as when the model loader runs a post-load hook twice. Every + per-slot value the expert kernel reads has to be a bound slot weight: a + value derived once from the slot's expert, such as an output scale + computed while taking the views, keeps the old expert's value after a + move. The balancer needs host-accessible device memory, which Grace + systems have and x86 systems get from GDRCopy. +7. **The forward.** `eplb_call(eplb, ids, rows=..., last=...)` takes the layer + from the balancer on its first call of a forward and records the router's + expert ids; its plan stays None, since the slots change only between + forwards. `rows` names the rows that are tokens when the rest are padding, + such as the rows an attention-DP gather pads, and `last` marks the last + call of a pass over the layer: the forward's last call of a layer that + runs once. Without `last`, `close` completes the statistic. + `EplbLayer.close()` hands the layer back after its last expert kernel of + the forward. The balancer takes the layers in their registration order + every forward and waits for each to come back, so call `close` once per + forward per layer, before the next layer routes. A layer the forward did + not run is closed as well, such as a draft layer when the worker drafts + nothing. A layer that runs once per draft step is closed after the last + draft step. + ### Testing EPLB A target that implements EPLB adds: * **CPU:** its slots and weight manifest under a placement unlike the default one, with copies of an expert on several ranks and twice on one rank, and - its routing decisions for each EPLB mode and layout. + its routing decisions for each EPLB mode and layout. Under online EPLB, + also the host copies its load hands over, against what a slot holding the + same expert loads. * **GPU:** the cells of the catalog EPLB entry and of its expert kernel at - the shapes and slot windows the target calls them with (`TARGET_CELLS`). + the shapes and slot windows the target calls them with (`TARGET_CELLS`), + and its registrations against a real balancer in each mode it implements. * **Accuracy:** its benchmark with EPLB at every layout it admits, with `modeling_v2="require"`. A slot loaded with the wrong expert still produces fluent text, so use a placement that differs from the default one in every - layer. + layer. Under online EPLB, a run long enough for the balancer to move + experts in every layer, the draft layer included. ## Writing operations diff --git a/tensorrt_llm/_torch/modeling_v2/catalog/moe/eplb.py b/tensorrt_llm/_torch/modeling_v2/catalog/moe/eplb.py index c4401ac9de28..7f38a97851e0 100644 --- a/tensorrt_llm/_torch/modeling_v2/catalog/moe/eplb.py +++ b/tensorrt_llm/_torch/modeling_v2/catalog/moe/eplb.py @@ -1,6 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Expert-parallel load balancing (EPLB): slot layouts, layer registration and routing. +"""Expert-parallel load balancing (EPLB): slot layouts, layer registration, routing and, +under online EPLB, the layer's share of moving experts between slots. The engine owns the load balancer: the model loader creates it around the model (`maybe_create_moe_load_balancer`) and finalizes it after the weights load, and @@ -20,8 +21,22 @@ `eplb_call` is a context rather than a function so that a mode which places replicas per call can hold that call's plan until the expert kernels are -enqueued. Static EPLB has no such plan: its slots are fixed at load, and the -plan it yields is None. +enqueued. Static and online EPLB have no such plan: their slots change only +between forwards, and the plan they yield is None. + +Online EPLB (`layer_updates_per_iter > 0`) moves experts between slots while the +engine serves: between two forwards the balancer copies an expert's weights from +host memory into a slot and points the routing at it. A target takes part in +three more steps: + +4. `EplbLayer.share_experts`, while loading: host copies of this rank's share of + the layer's experts, every per-slot weight of each in the slot layout. +5. `EplbLayer.bind_slots`, after loading and before any view of the slot weights + is taken: move them to memory the balancer can write, and register each slot. +6. `EplbLayer.close`, after the layer's last expert GEMM of a forward: hand the + layer back to the balancer. `eplb_call` takes it on the forward's first call + and records which experts the tokens chose, the statistic the balancer places + by. `eplb_mode` says whether the engine runs EPLB for a deployment and in which mode. A target lists the modes it implements in `EPLB_MODES`, and the resolver @@ -32,9 +47,10 @@ import contextlib from dataclasses import dataclass -from typing import Iterator, Optional, Sequence +from typing import Callable, Iterator, Mapping, Optional, Sequence import torch +from torch import nn import tensorrt_llm._torch.custom_ops # noqa: F401 — registers torch.ops.trtllm.* from tensorrt_llm._torch.modeling_v2._router_index import moe_eplb_mode @@ -233,21 +249,69 @@ def reference( eplb_route = EplbRoute() +#: Row ranges `(start, stop)` of a routed batch; see `EplbLayer.call`. +Rows = Sequence[tuple[int, int]] + + +def rows_within( + rows: Optional[Rows], start: int, stop: int +) -> Optional[tuple[tuple[int, int], ...]]: + """The parts of `rows` inside `[start, stop)`, relative to `start`: the token rows of + one chunk of a batch whose token rows are `rows`. None stays None (every row a token).""" + if rows is None: + return None + return tuple( + (max(a, start) - start, min(b, stop) - start) for a, b in rows if a < stop and b > start + ) + + +def _token_rows(ids: torch.Tensor, rows: Optional[Rows]) -> Optional[torch.Tensor]: + """The rows of `ids` that `rows` names, or None when it names none.""" + if rows is None: + return ids + parts = [ids[a:b] for a, b in rows if b > a] + if not parts: + return None + return parts[0] if len(parts) == 1 else torch.cat(parts) + + class EplbLayer: - """A MoE layer registered with the engine's load balancer, and its routing. + """A MoE layer registered with the engine's load balancer: its routing and, under + online EPLB, its part in moving experts between slots. Built with `register` while the target is constructed, inside the model loader's load-balancer context, once per MoE layer and in the order the layers run. + Under online EPLB the balancer takes the layers in that order on every + forward: it hands a layer to the GPU, waits for the GPU to hand it back, and + may then rewrite the layer's slots before the next forward. The layer is + taken on its first `call` of a forward and handed back by `close`, so a + target calls `close` once per forward per layer: after the layer's last + expert GEMM, before the next layer's first `call`, and also on a forward + that ran no tokens through the layer. A layer the forward leaves open stalls + the balancer and, with it, the next forward. + Attributes: balancer_layer: The layer's handle in the engine's load balancer. - slots: The layer's slots on this rank. + slots: The layer's slots on this rank, as loaded; under online EPLB the + balancer moves experts between them afterwards. + online: Whether the balancer moves experts between slots while serving. """ def __init__(self, balancer_layer: SingleLayerMoeLoadBalancer, slots: EplbSlots): self.balancer_layer = balancer_layer self.slots = slots + self.online = balancer_layer.is_dynamic_routing() + self._taken = False + self._counted = False + self._count_closed = False + self._no_tokens: Optional[torch.Tensor] = None + # The ids each statistic of this forward read. The balancer may count them on its + # own stream, which joins the forward's stream only in `close`, so they must + # outlive the caller's references until then. + self._counted_ids: list[torch.Tensor] = [] + self._bound: Optional[dict[str, int]] = None @classmethod def register(cls, slots: EplbSlots, top_k: int, repeat_count: int = 1) -> "EplbLayer": @@ -277,20 +341,153 @@ def register(cls, slots: EplbSlots, top_k: int, repeat_count: int = 1) -> "EplbL return cls(balancer_layer, slots) @contextlib.contextmanager - def call(self, token_selected_experts: torch.Tensor) -> Iterator[tuple[torch.Tensor, None]]: + def call( + self, + token_selected_experts: torch.Tensor, + *, + rows: Optional[Rows] = None, + last: bool = False, + ) -> Iterator[tuple[torch.Tensor, None]]: """The routing of one expert call; see `eplb_call`, which a target calls instead. Yields `(slot_ids, plan)`: global expert ids `[T, top_k]` int32 routed to global slot ids `[T, top_k]` int32 under the layer's placement, with `offset_by_ep_rank=False`, so every rank that routes the same tokens gets the - same slots. `plan` is None: the slots are fixed at load. + same slots. `plan` is None: the slots change only between forwards. + + Under online EPLB the first call of a forward takes the layer from the + balancer, and every call records the experts its tokens chose. A target + that gathers its tokens before routing records the same ids on every rank, + which is the statistic of the whole batch. + + Args: + token_selected_experts: The router's expert ids. + rows: Under online EPLB, the rows of `token_selected_experts` that are + tokens, as `(start, stop)` ranges, when the others are padding; the + statistic leaves padding out. None means every row is a token. + last: Under online EPLB, no token of this forward follows these, which + completes the statistic here rather than in `close`. """ + if self.online: + self._take() + ids = _token_rows(token_selected_experts, rows) + if ids is not None: + self.balancer_layer.update_statistic_with_global_ids(ids, not self._counted, last) + self._counted_ids.append(ids) + self._counted = True + self._count_closed = last + if self._no_tokens is None: + # One row of ids no expert has: counts nothing, and lets `close` + # complete a statistic that `last` did not. + self._no_tokens = torch.full_like(ids[:1], self.slots.num_experts) yield eplb_route(token_selected_experts, self.balancer_layer, False), None + def close(self) -> None: + """Hand the layer back to the balancer for this forward, after its last expert + GEMM; the balancer may rewrite its slots from then until the next forward takes + it. A no-op without online EPLB.""" + if not self.online: + return + self._take() + if self._counted and not self._count_closed: + self.balancer_layer.update_statistic_with_global_ids(self._no_tokens, False, True) + self.balancer_layer.start_set_cpu_stage() + self.balancer_layer.done_set_cpu_stage() + self._taken = self._counted = self._count_closed = False + self._counted_ids.clear() + + def _take(self) -> None: + """Wait, once per forward, until the balancer hands the layer to the GPU.""" + if not self._taken: + self.balancer_layer.start_wait_gpu_stage() + self.balancer_layer.done_wait_gpu_stage() + self._taken = True + + @property + def host_experts(self) -> tuple[int, ...]: + """The experts this rank keeps host copies of for the balancer under online EPLB: + its share of the ranks on its node, so the node holds every expert once. Empty + without online EPLB.""" + if not self.online: + return () + return tuple(self.balancer_layer.get_load_expert_ids()) + + def share_experts( + self, + slot_weights: Mapping[str, torch.Tensor], + expert_weight: Callable[[str, int], torch.Tensor], + ) -> None: + """Hand the balancer this rank's host copies of the layer's experts, under online + EPLB, while loading. A no-op otherwise. + + Args: + slot_weights: Every per-slot weight of the layer by name, `[local_slots, ...]`; + an expert's copy has the shape and dtype of one slot. + expert_weight: `(name, expert) -> tensor`: expert `expert`'s `name` weight in + the slot layout, on any device. Called for the experts in `host_experts`. + + The copies move to memory the ranks of the node share before this returns, so + the private ones go with each layer rather than piling up over the model. + """ + if not self.online: + return + sharer = self.balancer_layer.host_tensor_sharer + mine = set(self.host_experts) + for name, slot_weight in slot_weights.items(): + shape, dtype = slot_weight.shape[1:], slot_weight.dtype + for expert in range(self.slots.num_experts): + if expert not in mine: + sharer.pre_register_host_tensor_with_shape(expert, name, dtype, shape) + continue + t = expert_weight(name, expert).to("cpu").contiguous() + assert t.shape == shape and t.dtype == dtype, ( + f"expert {expert}'s {name} is {tuple(t.shape)} {t.dtype}, a slot is " + f"{tuple(shape)} {dtype}" + ) + sharer.share_host_tensor_with_shape(expert, name, t) + sharer.finalize_layer_weights() + + def bind_slots(self, slot_weights: Mapping[str, torch.Tensor]) -> None: + """Move the layer's per-slot weights to memory the balancer can write and register + every slot of each, under online EPLB, after loading. A no-op otherwise. + + Args: + slot_weights: Every per-slot weight of the layer by name, `[local_slots, ...]` + and contiguous -- the names `share_experts` was given. A parameter + keeps its identity and takes the new storage as its data. + + A view taken before this call keeps reading the old storage, which the + balancer never writes: bind first, then take the views the forward reads. + The slots stay registered: binding the same weights again does nothing, as + when the model loader runs a target's post-load hook more than once. + """ + if not self.online: + return + if self._bound is not None: + assert {name: w.data_ptr() for name, w in slot_weights.items()} == self._bound, ( + "the layer's slot weights moved after the balancer registered them" + ) + return + for name, weight in slot_weights.items(): + data = weight.detach() if isinstance(weight, nn.Parameter) else weight + assert data.is_contiguous() and data.shape[0] == self.slots.local_slots, ( + f"{name} {tuple(data.shape)} is not {self.slots.local_slots} contiguous slots" + ) + self.balancer_layer.make_tensor_host_accessible(data) + if isinstance(weight, nn.Parameter): + weight.data = data + for local in range(self.slots.local_slots): + self.balancer_layer.register_weight_slot(local, name, data[local]) + self._bound = {name: w.data_ptr() for name, w in slot_weights.items()} + @contextlib.contextmanager def eplb_call( - eplb: Optional[EplbLayer], token_selected_experts: torch.Tensor + eplb: Optional[EplbLayer], + token_selected_experts: torch.Tensor, + *, + rows: Optional[Rows] = None, + last: bool = False, ) -> Iterator[tuple[torch.Tensor, None]]: """The routing of one expert call, with or without EPLB. @@ -298,11 +495,12 @@ def eplb_call( `token_selected_experts`, the router's `[T, top_k]` int32 expert ids, routed to the global slot ids `[T, top_k]` int32 the kernels take, and the call's plan. Without EPLB (`eplb` None) every expert has one slot, so the slot ids are the - expert ids. The plan is None: static EPLB's slots are fixed at load. Enqueue the - call's expert kernels inside the context (see the module docstring). + expert ids. The plan is None: static and online EPLB change slots only between + forwards. Enqueue the call's expert kernels inside the context (see the module + docstring). `rows` and `last` feed online EPLB's statistic (`EplbLayer.call`). """ if eplb is None: yield token_selected_experts, None return - with eplb.call(token_selected_experts) as routed: + with eplb.call(token_selected_experts, rows=rows, last=last) as routed: yield routed diff --git a/tensorrt_llm/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/modeling.py b/tensorrt_llm/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/modeling.py index 1d486efa06d1..24f3251200c3 100644 --- a/tensorrt_llm/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/modeling.py +++ b/tensorrt_llm/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/modeling.py @@ -26,10 +26,14 @@ group's largest token count, `comm/allgather`, route and run this rank's experts over the gathered set, `comm/reducescatter` back. -Under static EPLB (`moe_config.load_balancer`, attention DP at dep4 and dep8) every routed -MoE layer registers with the engine's load balancer, its experts are loaded by slot rather than -by a contiguous expert window (weights.py), and `_experts` routes the router's expert ids to -slot ids before the runner, which then works in slots. See `catalog/moe/eplb.py`. +Under EPLB (`moe_config.load_balancer`, attention DP at dep4 and dep8) every routed MoE layer +registers with the engine's load balancer, its experts are loaded by slot rather than by a +contiguous expert window (weights.py), and `_experts` routes the router's expert ids to slot ids +before the runner, which then works in slots. Under online EPLB the balancer also moves experts +between slots while serving: the layers' slot weights are bound to it before the targets take +their views (`post_load_weights`), each routed call records which experts its tokens chose, and +each layer is handed back to the balancer once per forward -- a trunk layer after its experts +run, the MTP layer after the last draft step (`close_draft_eplb`). See `catalog/moe/eplb.py`. The MTP layer (one-model MTP-Eagle) is one more decoder layer, cut per rank like the others, and runs through the same two layout-dependent blocks: its two residual-norm slots are the @@ -79,7 +83,7 @@ from tensorrt_llm._torch.modeling_v2.catalog.gemm.bmm_out import bmm_out from tensorrt_llm._torch.modeling_v2.catalog.gemm.cublas_mm import cublas_mm from tensorrt_llm._torch.modeling_v2.catalog.gemm.nvfp4_gemm import nvfp4_gemm -from tensorrt_llm._torch.modeling_v2.catalog.moe.eplb import EplbLayer, eplb_call +from tensorrt_llm._torch.modeling_v2.catalog.moe.eplb import EplbLayer, Rows, eplb_call, rows_within from tensorrt_llm._torch.modeling_v2.catalog.moe.fp4_block_scale_moe_runner import ( # noqa: E501 fp4_block_scale_moe_runner, ) @@ -349,7 +353,9 @@ def __init__(self, model_config: ModelConfig): # Under EPLB every routed MoE layer registers with the engine's load # balancer, in the order the layers run: the trunk's, then the MTP # layer's, which runs once per draft step. - assert self.dims.eplb in (None, "static"), f"{self.dims.eplb} EPLB is not implemented" + assert self.dims.eplb in (None, "static", "online"), ( + f"{self.dims.eplb} EPLB is not implemented" + ) self.eplb_layers: dict[int, EplbLayer] = {} if self.dims.eplb is not None: for i, slots in self.dims.slots.items(): @@ -416,6 +422,10 @@ def post_load_weights(self) -> None: Named for the shell hook that drives it. Not an override: that hook lives on DecoderModelForCausalLM, and a core derives from DecoderModel, which has none. + Under online EPLB it first binds every MoE layer's slot weights to the engine's + load balancer, which gives them new storage: every view the targets take is + taken after that. + The side stream is made here, once: a CUDA stream created inside a graph capture is not capturable. The residual-norm op is chosen here, once, for both targets and the MTP layer: under attention TP choosing it builds a communicator, which is @@ -424,6 +434,10 @@ def post_load_weights(self) -> None: """ cfg = self.model_config.pretrained_config device = self.w["final_norm"].device + # Under online EPLB the slot weights move to storage the load balancer writes; the + # views below have to be taken of that storage, so this comes first. + for i, eplb in self.eplb_layers.items(): + eplb.bind_slots(_weights.MODEL_WEIGHTS.slot_weights(self, i)) self._rope_positions = cfg.max_position_embeddings self._rope = self._rope_tables(device, self._rope_positions) self._side_stream = torch.cuda.Stream(device=device) @@ -477,19 +491,20 @@ def forward( **kwargs, ) - def _dp_pad_rows(self, md, num_tokens: int) -> int: - """Rows this rank pads its block with before the MoE round trip: up to the largest - per-rank token count in the group, so both collectives run in their uniform form. - Zero without attention DP.""" + def _dp_rows(self, md, num_tokens: int) -> "_DpRows": + """Where this rank's rows sit in the MoE round trip (`_DpRows`): the rows it pads + its block with, up to the largest per-rank token count in the group, so both + collectives run in their uniform form, and the gathered rows that are tokens. + Nothing is padded without attention DP.""" if self.dp_size == 1: - return 0 + return _NO_DP counts = [int(n) for n in md.all_rank_num_tokens] assert len(counts) == self.dp_size, (counts, self.dp_size) assert counts[self.rank] == num_tokens, ( f"rank {self.rank} holds {num_tokens} rows but all_rank_num_tokens " f"says {counts[self.rank]} ({counts}); the collectives would gather the wrong split" ) - return max(counts) - num_tokens + return _DpRows.of(counts, num_tokens) def _mtp_kv_layer(self, md) -> int: """The MTP layer's index in the KV pool `md` addresses on this call. @@ -508,20 +523,55 @@ def _mtp_kv_layer(self, md) -> int: """ return int(md.kv_cache_manager.layer_offsets[self.dims.num_layers]) - def _mtp_pad_rows(self, all_rank_num_tokens, rows: int) -> int: - """The MTP layer's `_dp_pad_rows`, on the count list the spec worker hands it. + def _mtp_dp_rows(self, all_rank_num_tokens, rows: int) -> "_DpRows": + """The MTP layer's `_dp_rows`, on the count list the spec worker hands it. Callers must pass the worker's own basis, never `attn_metadata.all_rank_num_tokens`, which from draft step 1 onwards is still the trunk's list: at equal byte counts the - collectives diverge silently on every rank, with no hang. Zero without attention DP. + collectives diverge silently on every rank, with no hang. Nothing is padded without + attention DP. """ if self.dp_size == 1: - return 0 + return _NO_DP counts = [int(n) for n in all_rank_num_tokens] assert len(counts) == self.dp_size, (counts, self.dp_size) - pad = max(counts) - rows - assert pad >= 0, f"rank {self.rank} holds {rows} MTP rows, more than any rank in {counts}" - return pad + assert max(counts) >= rows, ( + f"rank {self.rank} holds {rows} MTP rows, more than any rank in {counts}" + ) + return _DpRows.of(counts, rows) + + def close_draft_eplb(self) -> None: + """Hand the MTP layer back to the engine's load balancer for this forward, under + online EPLB (`EplbLayer.close`): after the last draft step, also when the spec + worker drafted none. The trunk's layers hand themselves back in `_experts`.""" + eplb = self.eplb_layers.get(self.dims.num_layers) + if eplb is not None: + eplb.close() + + +class _DpRows(NamedTuple): + """Where a rank's rows sit in the attention-DP round trip of the routed experts. + + `pad`: the rows this rank pads its block with, up to the largest per-rank count, so + the collectives run in their uniform form. `tokens`: the rows of the gathered set + that are tokens, as `(start, stop)` ranges, or None when no rank pads -- what an + online EPLB statistic counts, padding left out. + """ + + pad: int + tokens: Rows | None + + @classmethod + def of(cls, counts: list[int], rows: int) -> "_DpRows": + """This rank holding `rows` of a group whose ranks hold `counts`.""" + block = max(counts) + if min(counts) == block: + return cls(0, None) + return cls(block - rows, tuple((r * block, r * block + n) for r, n in enumerate(counts))) + + +#: Without attention DP: every rank holds every token and nothing is padded. +_NO_DP = _DpRows(0, None) class _LayerWeights(NamedTuple): @@ -599,11 +649,8 @@ def _layer_views(core: DeepseekV3DefaultModelingV2) -> list[_LayerWeights]: # routed FC1 activation scale has to be a single value and the same value on all # ranks, or the expert slots and intermediate slices no longer sum to the whole # layer; the shared expert's `input_scale` is the max over all routed ones, so it - # is the safe one. The per-expert scalars are held for every expert on every - # rank; each slot reads its own expert's. - held = torch.tensor(d.slots[i].slot_experts, device=isc1.device) - e_isc2 = w[f"l{i}_e_isc2"][held] - gate1 = (isc1[0] * w[f"l{i}_e_ws2_1"][held]).contiguous() + # is the safe one. The three output scales are slot weights, each slot's from its + # expert's scalars (weights.py), so they move with the expert under online EPLB. moe = dict( router=w[f"l{i}_router"].t(), router_bias=w[f"l{i}_router_bias"], @@ -612,9 +659,9 @@ def _layer_views(core: DeepseekV3DefaultModelingV2) -> list[_LayerWeights]: fc1_s=w[f"l{i}_fc1_s"].view(torch.float8_e4m3fn), fc2_w=w[f"l{i}_fc2_w"], fc2_s=w[f"l{i}_fc2_s"].view(torch.float8_e4m3fn), - out1_scale=(gate1 / e_isc2).contiguous(), - out1_gate_scale=gate1, - out2_scale=(e_isc2 * w[f"l{i}_e_ws2_2"][held]).contiguous(), + out1_scale=w[f"l{i}_out1_scale"], + out1_gate_scale=w[f"l{i}_out1_gate_scale"], + out2_scale=w[f"l{i}_out2_scale"], eplb=core.eplb_layers.get(i), ) layers.append( @@ -655,7 +702,12 @@ def _dense_mlp(x: torch.Tensor, L: _LayerWeights, dt) -> torch.Tensor: return nvfp4_gemm(aq, L.mlp_dn_w, asf, L.mlp_dn_s, L.mlp_dn_alpha, dt) -def _experts(core: DeepseekV3DefaultModelingV2, L: _LayerWeights, x: torch.Tensor) -> torch.Tensor: +def _experts( + core: DeepseekV3DefaultModelingV2, + L: _LayerWeights, + x: torch.Tensor, + tokens: Rows | None = None, +) -> torch.Tensor: """Route, quantize and run this rank's experts -- its expert slots at its moe_tp slice of the intermediate -- over `x`, at most `_MOE_MAX_T` rows a call. The result is this rank's partial sum. @@ -663,11 +715,14 @@ def _experts(core: DeepseekV3DefaultModelingV2, L: _LayerWeights, x: torch.Tenso Under EPLB the router's expert ids are routed to slot ids first, and the runner works in slots: `num_slots` routing ids, of which this rank answers for its own window. Every rank routes the same gathered rows, so every rank picks the same slot for each - of a token's experts, and the slots' partial sums add up to the layer.""" + of a token's experts, and the slots' partial sums add up to the layer. Under online + EPLB the routing also records the experts of the rows `tokens` names (None: every + row), and the layer goes back to the balancer once its last chunk has run.""" cfg = core.model_config.pretrained_config d = core.dims + chunks = torch.split(x, _MOE_MAX_T, 0) parts = [] - for chunk in torch.split(x, _MOE_MAX_T, 0): + for k, chunk in enumerate(chunks): logits = cublas_mm(chunk, L.router) topk_w, topk_ids = noaux_tc_op( logits, @@ -677,7 +732,10 @@ def _experts(core: DeepseekV3DefaultModelingV2, L: _LayerWeights, x: torch.Tenso cfg.num_experts_per_tok, float(cfg.routed_scaling_factor), ) - with eplb_call(L.eplb, topk_ids) as (slot_ids, _): + start = k * _MOE_MAX_T + rows = rows_within(tokens, start, start + chunk.shape[0]) + last = k == len(chunks) - 1 + with eplb_call(L.eplb, topk_ids, rows=rows, last=last) as (slot_ids, _): xq, xsf = fp4_quantize(chunk, L.moe_gscale, _SF_VEC, False, _SF_LINEAR) parts.append( fp4_block_scale_moe_runner( @@ -712,6 +770,8 @@ def _experts(core: DeepseekV3DefaultModelingV2, L: _LayerWeights, x: torch.Tenso topk_ids=slot_ids, )[0] ) + if L.eplb is not None: + L.eplb.close() return parts[0] if len(parts) == 1 else torch.cat(parts, 0) @@ -790,12 +850,16 @@ def _mtp_shared(x: torch.Tensor, M: _MtpWeights) -> torch.Tensor: def _mtp_experts( - core: DeepseekV3DefaultModelingV2, M: _MtpWeights, x: torch.Tensor + core: DeepseekV3DefaultModelingV2, + M: _MtpWeights, + x: torch.Tensor, + tokens: Rows | None = None, ) -> torch.Tensor: """Route and run this rank's bf16 MTP experts -- its expert slots at its moe_tp slice of the intermediate -- over `x`, at most `_MOE_MAX_T` rows a call. The result is this rank's partial sum, the trunk's `_experts` at a different dtype, and under EPLB routed - to slots the same way. + to slots the same way. It runs once per draft step, so under online EPLB the layer + goes back to the balancer after the last of them, in `close_draft_eplb`, not here. `fused_moe` rather than the trtllm-gen runner: the checkpoint excludes `model.layers.61*` from NVFP4, and the runner takes NVFP4 operands only. It wants fp32 @@ -807,7 +871,7 @@ def _mtp_experts( cfg = core.model_config.pretrained_config d = core.dims parts = [] - for chunk in torch.split(x, _MOE_MAX_T, 0): + for k, chunk in enumerate(torch.split(x, _MOE_MAX_T, 0)): topk_w, topk_ids = noaux_tc_op( cublas_mm(chunk, M.router, None, torch.float32), M.router_bias, @@ -816,7 +880,9 @@ def _mtp_experts( cfg.num_experts_per_tok, float(cfg.routed_scaling_factor), ) - with eplb_call(M.eplb, topk_ids) as (slot_ids, _): + start = k * _MOE_MAX_T + rows = rows_within(tokens, start, start + chunk.shape[0]) + with eplb_call(M.eplb, topk_ids, rows=rows) as (slot_ids, _): parts.append( fused_moe( input=chunk, @@ -838,9 +904,10 @@ def _mtp_experts( return parts[0] if len(parts) == 1 else torch.cat(parts, 0) -#: The expert call a routed block wraps: `(core, weights, x) -> this rank's partial sum`. -#: `_experts` for a trunk layer, `_mtp_experts` for the MTP layer. -Experts = Callable[[DeepseekV3DefaultModelingV2, tuple, torch.Tensor], torch.Tensor] +#: The expert call a routed block wraps: `(core, weights, x, tokens) -> this rank's partial +#: sum`, `tokens` the rows of `x` that are tokens (None: every row). `_experts` for a trunk +#: layer, `_mtp_experts` for the MTP layer. +Experts = Callable[[DeepseekV3DefaultModelingV2, tuple, torch.Tensor, Rows | None], torch.Tensor] def _routed_on_every_token( @@ -848,11 +915,11 @@ def _routed_on_every_token( experts: Experts, weights: tuple, o: torch.Tensor, - pad_rows: int, + dp_rows: _DpRows, ) -> torch.Tensor: """Every rank holds every token (attention TP): the result is this rank's partial sum for the allreduce in the next residual-norm slot to complete.""" - return experts(core, weights, o) + return experts(core, weights, o, None) def _routed_attention_dp( @@ -860,7 +927,7 @@ def _routed_attention_dp( experts: Experts, weights: tuple, o: torch.Tensor, - pad_rows: int, + dp_rows: _DpRows, ) -> torch.Tensor: """Each rank holds its own tokens: gather them, run this rank's experts over the whole set, and sum back to the rows this rank owns. @@ -869,17 +936,18 @@ def _routed_attention_dp( top-8 ids fall in exactly one rank's slot window per moe_tp slice, and the reduce-scatter sums each contribution once.""" num_tokens = o.shape[0] + pad_rows = dp_rows.pad o_pad = o if not pad_rows else nn.functional.pad(o, [0, 0, 0, pad_rows]) group, pg = core.dp_group, core.dp_process_group routed_pad = reducescatter( - experts(core, weights, allgather(o_pad, None, group, pg)), None, group, pg + experts(core, weights, allgather(o_pad, None, group, pg), dp_rows.tokens), None, group, pg ) return routed_pad if not pad_rows else routed_pad[:num_tokens] -#: A routed-expert block: `(core, experts, weights, o, pad_rows) -> routed`. +#: A routed-expert block: `(core, experts, weights, o, dp_rows) -> routed`. RoutedBlock = Callable[ - [DeepseekV3DefaultModelingV2, Experts, tuple, torch.Tensor, int], torch.Tensor + [DeepseekV3DefaultModelingV2, Experts, tuple, torch.Tensor, _DpRows], torch.Tensor ] @@ -980,7 +1048,7 @@ def forward( gen_seqs = md.num_seqs - num_ctx gen_p = gen // gen_seqs if gen_seqs else 1 ctx_kv_tokens = int(md.host_total_kv_lens[0]) - pad_rows = core._dp_pad_rows(md, num_tokens) + dp_rows = core._dp_rows(md, num_tokens) cached_ctx = core._cached_ctx attn_out = torch.empty([num_tokens, heads * v_dim], dtype=dt, device=dev) @@ -1193,7 +1261,7 @@ def forward( side.wait_stream(main) with torch.cuda.stream(side): shared = _dense_mlp(o, L, dt) - routed = self._routed(core, _experts, L, o, pad_rows) + routed = self._routed(core, _experts, L, o, dp_rows) main.wait_stream(side) mlp_out = torch.add(routed, shared) mlp_out, residual = self._residual_norm(mlp_out, residual, L.norm_next) @@ -1253,7 +1321,7 @@ def mtp_forward( pool_map = md.host_kv_cache_pool_mapping window = md.max_seq_len ctx_kv_tokens = int(md.host_total_kv_lens[0]) - pad_rows = core._mtp_pad_rows(all_rank_num_tokens, rows) + dp_rows = core._mtp_dp_rows(all_rank_num_tokens, rows) e = nn.functional.embedding(input_ids, embed_tokens) en = flashinfer_rmsnorm(e, M.enorm, eps) @@ -1451,7 +1519,7 @@ def mtp_forward( attn_gen_t = torch.transpose(torch.reshape(attn_gen, [gen, heads, v_dim]), 0, 1) attn_gen_t = bmm_out(a=lat_out_t, b=M.v_b_t, out=attn_gen_t) - return _mtp_tail(self, M, attn_out, residual, pad_rows) + return _mtp_tail(self, M, attn_out, residual, dp_rows) class DecodeTarget: @@ -1552,7 +1620,7 @@ def forward( # query block is taller, and what aligns the bottom-right within-block causal mask. gen_seqs = md.num_seqs gen_p = gen // gen_seqs if gen_seqs else 1 - pad_rows = core._dp_pad_rows(md, num_tokens) + dp_rows = core._dp_rows(md, num_tokens) attn_out = torch.empty([num_tokens, heads * v_dim], dtype=dt, device=dev) attn_gen = attn_out @@ -1671,7 +1739,7 @@ def forward( side.wait_stream(main) with torch.cuda.stream(side): shared = _dense_mlp(o, L, dt) - routed = self._routed(core, _experts, L, o, pad_rows) + routed = self._routed(core, _experts, L, o, dp_rows) main.wait_stream(side) mlp_out = torch.add(routed, shared) mlp_out, residual = self._residual_norm(mlp_out, residual, L.norm_next) @@ -1723,7 +1791,7 @@ def mtp_forward( pool_ptrs = md.host_kv_cache_pool_pointers pool_map = md.host_kv_cache_pool_mapping window = md.max_seq_len - pad_rows = core._mtp_pad_rows(all_rank_num_tokens, rows) + dp_rows = core._mtp_dp_rows(all_rank_num_tokens, rows) e = nn.functional.embedding(input_ids, embed_tokens) en = flashinfer_rmsnorm(e, M.enorm, eps) @@ -1831,7 +1899,7 @@ def mtp_forward( attn_gen_t = torch.transpose(torch.reshape(attn_gen, [gen, heads, v_dim]), 0, 1) attn_gen_t = bmm_out(a=lat_out_t, b=M.v_b_t, out=attn_gen_t) - return _mtp_tail(self, M, attn_out, residual, pad_rows) + return _mtp_tail(self, M, attn_out, residual, dp_rows) def _mtp_tail( @@ -1839,7 +1907,7 @@ def _mtp_tail( M: _MtpWeights, attn_out: torch.Tensor, residual: torch.Tensor, - pad_rows: int, + dp_rows: _DpRows, ) -> torch.Tensor: """The MTP layer from its attention output on: o_proj, the two residual-norm slots and the MLP between them, through the target's layout-dependent blocks. @@ -1854,7 +1922,7 @@ def _mtp_tail( o = cublas_mm(attn_out, M.o) o, residual = target._residual_norm(o, residual, M.norm2) shared = _mtp_shared(o, M) - routed = target._routed(core, _mtp_experts, M, o, pad_rows) + routed = target._routed(core, _mtp_experts, M, o, dp_rows) _, residual = target._residual_norm(torch.add(routed, shared), residual, M.head_norm) return residual @@ -1936,9 +2004,11 @@ def embed_tokens(self) -> torch.Tensor: class ModelingV2DeepseekR10528Nvfp4Sm10xDefault( DecoderModelForCausalLM[DeepseekV3DefaultModelingV2, PretrainedConfig] ): - #: Static EPLB: the core registers its MoE layers with the engine's load balancer, loads - #: its experts by slot and routes expert ids to slots (`catalog/moe/eplb.py`). - EPLB_MODES = frozenset({"static"}) + #: The core registers its MoE layers with the engine's load balancer, loads its experts + #: by slot and routes expert ids to slots; under online EPLB it also hands the balancer + #: host copies of its experts, binds its slot weights and hands every layer back once + #: per forward (`catalog/moe/eplb.py`). + EPLB_MODES = frozenset({"static", "online"}) def __init__(self, model_config: ModelConfig): cfg = model_config.pretrained_config @@ -2003,7 +2073,7 @@ def forward( attn_metadata, True, ) - return self.spec_worker( + outputs = self.spec_worker( input_ids=input_ids, position_ids=position_ids, hidden_states=hidden, @@ -2013,6 +2083,9 @@ def forward( draft_model=self.draft_model, resource_manager=kwargs.get("resource_manager"), ) + # The worker decides how many draft steps this forward takes, none included. + self.model.close_draft_eplb() + return outputs def load_weights(self, weights, *args, **kwargs): _weights.MODEL_WEIGHTS.load(self, weights) diff --git a/tensorrt_llm/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/weights.py b/tensorrt_llm/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/weights.py index 9d6bccf44113..92ab94e9d021 100644 --- a/tensorrt_llm/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/weights.py +++ b/tensorrt_llm/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/weights.py @@ -23,7 +23,10 @@ slot and a rank's slots are the contiguous window of experts `[slot_offset, slot_offset + local_slots)`; under EPLB (`moe_config.load_balancer`) the placement is the load balancer's, and a - hot expert can sit in several slots, on one rank or on several. + hot expert can sit in several slots, on one rank or on several. Everything a + slot holds of its expert -- the NVFP4 operands, their block scales and the + three output scales the runner takes per slot -- is a slot weight, read from + that expert's checkpoint tensors (`_ExpertWindow`). * **The expert intermediate** is split over the MoE TP group, along the FC1 output rows and the FC2 input columns. At this geometry (I=2048, one e4m3 @@ -66,15 +69,22 @@ `embed_tokens` and `shared_head.head` are bitwise copies of the trunk's embedding and `lm_head`, which the draft model reads instead. +**Under online EPLB** the load balancer moves experts between slots while the +engine serves, copying them from host memory. `load` therefore also reads this +rank's share of every MoE layer's experts (`EplbLayer.host_experts`) through the +same cuts and transforms as a slot, and hands them to the balancer +(`EplbLayer.share_experts`), one layer at a time. + Loading contract: `load(model, weights)` consumes the engine-provided checkpoint dict, fills every declared parameter exactly once, and asserts bidirectional coverage -- every target parameter written, and every checkpoint key either consumed (a key read through a cut is consumed) or in the two -predicted non-load sets (the experts none of this rank's slots holds, and -what the MTP layer leaves: all of it without MTP, its two aliased keys with -it). +predicted non-load sets (the experts none of this rank's slots holds or, under +online EPLB, keeps a host copy of, and what the MTP layer leaves: all of it +without MTP, its two aliased keys with it). """ +from collections import Counter from dataclasses import dataclass from types import SimpleNamespace from typing import Any, Callable @@ -292,6 +302,33 @@ def _mtp_fc1(t: tuple[torch.Tensor, ...], core) -> torch.Tensor: return torch.cat(t, dim=0).contiguous() +# The runner's three per-slot output scales. The checkpoint stores reciprocals +# (`input_scale` = 1/g_act, `weight_scale_2` = 1/g_w), so each is a product of +# them. FC1's activation scale is the shared expert's `input_scale` -- one +# quantization of the hidden states feeds every expert on every rank, so it has +# to be a single value, and the shared expert's is the max over every routed +# one -- and FC2's is the slot's expert's own. + + +def _out1_gate_scale(t: tuple[torch.Tensor, ...], core) -> torch.Tensor: + """FC1's dequantization: (shared expert FC1 `input_scale`, expert gate `weight_scale_2`).""" + isc1, ws2_1 = t + return isc1 * ws2_1 + + +def _out1_scale(t: tuple[torch.Tensor, ...], core) -> torch.Tensor: + """FC1's dequantization and FC2's requantization: (shared expert FC1 `input_scale`, + expert gate `weight_scale_2`, expert FC2 `input_scale`).""" + isc1, ws2_1, isc2 = t + return isc1 * ws2_1 / isc2 + + +def _out2_scale(t: tuple[torch.Tensor, ...], core) -> torch.Tensor: + """FC2's dequantization: (expert FC2 `input_scale`, expert down `weight_scale_2`).""" + isc2, ws2_2 = t + return isc2 * ws2_2 + + # --- the shares, as (rank, span) in checkpoint rows or columns --- @@ -389,25 +426,49 @@ def _pair(a, b): return lambda d, i, x=a, y=b: [((x.format(i=i), y.format(i=i)), None)] -def _expert_window(suffix, *, pair_with=None): - """This rank's slots of the routed experts, one source per slot. +@dataclass(frozen=True) +class _ExpertWindow: + """The source of a slot weight: one source per slot of this rank, each the checkpoint + tensor(s) of the expert the slot holds. Slot `local` of layer `i` holds expert `d.slots[i].slot_experts[local]`. The checkpoint key depends on the rank and, under EPLB, on the layer, which is - why the source is computed rather than templated. + why the source is computed rather than templated. `keys(i, expert)` is the + key, or key tuple, of any expert, which is also how `load` reads the host + copies online EPLB keeps of experts no slot holds. """ - def build(d, i): - out = [] - for local, expert in enumerate(d.slots[i].slot_experts): - q = f"model.layers.{i}.mlp.experts.{expert}" - if pair_with is None: - out.append((f"{q}.{suffix}", (local,))) - else: - out.append(((f"{q}.{pair_with}", f"{q}.{suffix}"), (local,))) - return out + keys: Callable[[int, int], Any] + + def __call__(self, d, i): + return [ + (self.keys(i, expert), (local,)) for local, expert in enumerate(d.slots[i].slot_experts) + ] - return build + +def _expert_window(suffix, *, pair_with=None) -> _ExpertWindow: + """An expert's `suffix` tensor, or its `(pair_with, suffix)` pair.""" + + def keys(i, expert): + q = f"model.layers.{i}.mlp.experts.{expert}" + return f"{q}.{suffix}" if pair_with is None else (f"{q}.{pair_with}", f"{q}.{suffix}") + + return _ExpertWindow(keys) + + +def _expert_scale(*suffixes) -> _ExpertWindow: + """Per-tensor scalars combined into one per-slot scale: `shared_experts.` names the + layer's shared expert's scalar, `` alone the slot's expert's.""" + + def keys(i, expert): + return tuple( + f"model.layers.{i}.mlp.{x}" + if x.startswith("shared_experts.") + else f"model.layers.{i}.mlp.experts.{expert}.{x}" + for x in suffixes + ) + + return _ExpertWindow(keys) def _expert_scalars(suffix): @@ -637,7 +698,38 @@ class DeepseekV3DefaultWeights: transform=_expert_fc2_s, layers=_moe_layers, ), - # --- the routed experts' per-tensor scalars, over the whole routing space --- + # --- the runner's per-slot output scales, from the slot's expert's scalars --- + W( + "out1_scale", + shape=lambda d: (d.local_slots,), + dtype=torch.float32, + src=_expert_scale( + "shared_experts.gate_proj.input_scale", + "gate_proj.weight_scale_2", + "down_proj.input_scale", + ), + transform=_out1_scale, + layers=_moe_layers, + ), + W( + "out1_gate_scale", + shape=lambda d: (d.local_slots,), + dtype=torch.float32, + src=_expert_scale("shared_experts.gate_proj.input_scale", "gate_proj.weight_scale_2"), + transform=_out1_gate_scale, + layers=_moe_layers, + ), + W( + "out2_scale", + shape=lambda d: (d.local_slots,), + dtype=torch.float32, + src=_expert_scale("down_proj.input_scale", "down_proj.weight_scale_2"), + transform=_out2_scale, + layers=_moe_layers, + ), + # --- every routed expert's per-tensor scalars, on every rank: the values the slot + # output scales above are computed from, read whole so that every expert's scalars + # are consumed and `load`'s leftover keys are exactly the unheld experts' tensors --- *( W( f"e_{n}", @@ -783,10 +875,42 @@ def expected_unconsumed(self, core, weights) -> set: def load(self, model, weights) -> None: """Fill every declared weight from the checkpoint. Each source is read through its cut, multi-key rows feed their transform several tensors at once, and - coverage is asserted in both directions, not only checkpoint-side.""" + coverage is asserted in both directions, not only checkpoint-side. + + Keys leave the engine's dict (`mark_consumed_keys`) as early as they can, as + the built-in models release what they consume: the keys this rank never reads + at the start, every other key after its last read. The engine can back many + tensors with one read-ahead buffer, which is freed only when all of its keys + are gone; held to the end of the load, every rank would keep the checkpoint + files it touches in host memory, beside the host copies online EPLB keeps of + the experts.""" core = model.model manifest = self.manifest(core) consumed: set = set() + checkpoint_keys = set(weights.keys()) + expected = self.expected_unconsumed(core, weights) + reads = Counter( + key + for sources in manifest.values() + for ckpt_key, _, _, _ in sources + for key in (ckpt_key if isinstance(ckpt_key, tuple) else (ckpt_key,)) + ) + reads.update(self._host_copy_keys(core)) + reads["lm_head.weight"] += 1 + mark_consumed = getattr(weights, "mark_consumed_keys", None) + if mark_consumed is not None: + mark_consumed(sorted(expected)) + + def done(keys) -> None: + """Count one read of each of `keys`; release the ones read for the last time.""" + consumed.update(keys) + last = [] + for key in keys: + reads[key] -= 1 + if reads[key] == 0: + last.append(key) + if mark_consumed is not None and last: + mark_consumed(last) def fill(param: torch.nn.Parameter, ckpt_key, index, cut, transform) -> None: dst = param.data if index is None else param.data[index] @@ -794,7 +918,7 @@ def fill(param: torch.nn.Parameter, ckpt_key, index, cut, transform) -> None: assert dst.shape == src.shape, (ckpt_key, tuple(dst.shape), tuple(src.shape)) assert src.dtype == dst.dtype, (ckpt_key, src.dtype, dst.dtype) dst.copy_(src, non_blocking=True) - consumed.update(ckpt_key if isinstance(ckpt_key, tuple) else (ckpt_key,)) + done(ckpt_key if isinstance(ckpt_key, tuple) else (ckpt_key,)) assert set(manifest.keys()) == set(core.w.keys()), ( "manifest/parameter drift", @@ -809,6 +933,8 @@ def fill(param: torch.nn.Parameter, ckpt_key, index, cut, transform) -> None: if param_key.endswith(self.RELEASE_AFTER): torch.cuda.empty_cache() + self._share_experts(core, weights, done) + # The shell builds lm_head vocab-parallel under TP and whole under # attention DP; read the rows it built and nothing else. mapping = core.model_config.mapping @@ -821,14 +947,54 @@ def fill(param: torch.nn.Parameter, ckpt_key, index, cut, transform) -> None: assert shell == {"lm_head.weight"}, f"unfed shell parameters: {sorted(shell)}" torch.cuda.synchronize() - leftover = set(weights.keys()) - consumed - expected = self.expected_unconsumed(core, weights) + leftover = checkpoint_keys - consumed assert leftover == expected, ( "checkpoint coverage: leftover keys are not exactly this rank's " f"unheld experts plus what the MTP layer leaves; unexpected " f"{sorted(leftover - expected)[:8]}, missed {sorted(expected - leftover)[:8]}" ) + def slot_weights(self, core, i: int) -> dict[str, nn.Parameter]: + """MoE layer `i`'s slot weights by name: every weight with one source per slot.""" + d = core.dims + return { + entry.name: core.w[f"l{i}_{entry.name}"] + for entry in self.WEIGHTS + if isinstance(entry.src, _ExpertWindow) and i in entry.layer_indices(d) + } + + def _host_copy_keys(self, core): + """The checkpoint keys `_share_experts` reads, one per read.""" + d = core.dims + for i, eplb in getattr(core, "eplb_layers", {}).items(): + if not eplb.online: + continue + for entry in self.WEIGHTS: + if isinstance(entry.src, _ExpertWindow) and i in entry.layer_indices(d): + for expert in eplb.host_experts: + key = entry.src.keys(i, expert) + yield from key if isinstance(key, tuple) else (key,) + + def _share_experts(self, core, weights, done: Callable) -> None: + """Under online EPLB, hand each MoE layer's load-balancer handle this rank's host + copies of its share of the experts (`EplbLayer.share_experts`): every slot weight + of each, read through the same cut and transform as a slot's, on the slots' + device. A no-op otherwise.""" + d = core.dims + by_name = {entry.name: entry for entry in self.WEIGHTS} + for i, eplb in getattr(core, "eplb_layers", {}).items(): + slot_weights = self.slot_weights(core, i) + + def expert_weight(name, expert, i=i, device=next(iter(slot_weights.values())).device): + entry = by_name[name] + key = entry.src.keys(i, expert) + cut = entry.cut(d) if entry.cut is not None else None + t = self.read(weights, key, cut, entry.transform, core, device) + done(key if isinstance(key, tuple) else (key,)) + return t + + eplb.share_experts(slot_weights, expert_weight) + def dims(self, core) -> SimpleNamespace: """Every per-rank width, from the config and the engine's Mapping.""" cfg = core.model_config.pretrained_config @@ -927,17 +1093,21 @@ def pad(t: torch.Tensor, core) -> torch.Tensor: def _unheld_expert_keys(core) -> set: """The first predicted non-load: the weight/scale tensors of every routed - expert that none of this rank's slots holds. Their per-tensor scalars are - consumed on every rank, so nothing else of theirs is left over. + expert that none of this rank's slots holds and, under online EPLB, that + this rank keeps no host copy of. Their per-tensor scalars are consumed on + every rank, so nothing else of theirs is left over. The trunk's MoE layers store six such tensors per expert (NVFP4 data plus block scales); the MTP layer's are bf16, so when it is live its unheld experts leave three each and no `weight_scale`.""" d = core.dims + eplb_layers = getattr(core, "eplb_layers", {}) keys = set() for i in _router_layers(d): quantized = i < d.num_layers held = set(d.slots[i].slot_experts) + if i in eplb_layers: + held.update(eplb_layers[i].host_experts) for e in range(d.num_experts): if e in held: continue diff --git a/tensorrt_llm/_torch/moe/fused_moe/moe_load_balancer.py b/tensorrt_llm/_torch/moe/fused_moe/moe_load_balancer.py index 6bbefc9e0ccc..984b6285da84 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/moe_load_balancer.py +++ b/tensorrt_llm/_torch/moe/fused_moe/moe_load_balancer.py @@ -1173,7 +1173,9 @@ def moe_load_balancer_mode(model_config, return None mode = getattr(config, "mode", "standard") if mode == "standard": - return "online" if config.layer_updates_per_iter > 0 else "static" + # The balancer runs a static layer exactly when no layer updates + # (``MoeLoadBalancer.is_static_routing``); any other count is online. + return "static" if config.layer_updates_per_iter == 0 else "online" return mode diff --git a/tests/integration/defs/accuracy/modeling_v2/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_accuracy.py b/tests/integration/defs/accuracy/modeling_v2/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_accuracy.py index 9a5430695a04..a1d2e203c46f 100644 --- a/tests/integration/defs/accuracy/modeling_v2/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_accuracy.py +++ b/tests/integration/defs/accuracy/modeling_v2/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_accuracy.py @@ -110,7 +110,7 @@ def _layout(layout_id, world_size, moe_tp_size, moe_ep_size, attention_dp): _MTP_LAYOUTS = [p for i in _MTP_LAYOUT_IDS for p in _LAYOUTS if p.id == i] -# The layouts the target runs static EPLB at: attention DP over ranks holding whole experts. +# The layouts the target runs EPLB at: attention DP over ranks holding whole experts. _EPLB_LAYOUTS = [p for i in ("dep4", "dep8") for p in _LAYOUTS if p.id == i] @@ -376,3 +376,47 @@ def test_gsm8k_static_eplb(self, mocker, parallel, mtp): task.evaluate(llm) if mtp: assert_acceptance_length_for_llm(self.ACCEPTANCE_KEY, llm) + + @skip_not_sm10x + @pytest.mark.parametrize("mtp", [False, True], ids=["no_spec", "mtp3"]) + @pytest.mark.parametrize("parallel", _EPLB_LAYOUTS) + def test_gsm8k_online_eplb(self, mocker, parallel, mtp): + """Online EPLB from the built-in default placement, the MTP layer included. + + Two layers are rebalanced per forward. Every routed layer hands the engine's load + balancer host copies of its share of the experts and binds its slot weights to it, + every forward records which experts its tokens chose, and between forwards the + balancer copies experts into slots and reroutes to them. An expert copied wrong, a + statistic that stalls the balancer or a view left on the storage the balancer no + longer writes shows up here, against the same GSM8K reference as the identity cases. + With the MTP layer the acceptance length is read against the target's MTP minimum + too: a draft routed to the wrong slots is rejected without moving the score. + """ + mocker.patch.dict(GSM8K.EVALUATE_KWARGS, _SCORES_FILTER) + load_balancer = MoeLoadBalancerConfig(num_slots=288, layer_updates_per_iter=2) + spec = ( + dict( + speculative_config=self.MTP3, + kv_cache_config=self.MTP3_KV, + cuda_graph_config=CudaGraphConfig(), + enable_iter_perf_stats=True, + ) + if mtp + else {} + ) + + with ( + scoped_env_overrides({MODELING_V2_VALIDATE_ENV: "1"}) as rank_env, + LLM( + self.MODEL_PATH, + moe_config=MoeConfig(load_balancer=load_balancer), + modeling_v2="require", + env_overrides=rank_env, + **spec, + **parallel, + ) as llm, + ): + task = GSM8K(self.MODEL_NAME) + task.evaluate(llm) + if mtp: + assert_acceptance_length_for_llm(self.ACCEPTANCE_KEY, llm) diff --git a/tests/integration/test_lists/test-db/l0_gb300_multi_gpus.yml b/tests/integration/test_lists/test-db/l0_gb300_multi_gpus.yml index 60c3b1f4e9c8..cfa381b957d3 100644 --- a/tests/integration/test_lists/test-db/l0_gb300_multi_gpus.yml +++ b/tests/integration/test_lists/test-db/l0_gb300_multi_gpus.yml @@ -38,6 +38,8 @@ l0_gb300_multi_gpus: - accuracy/modeling_v2/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_accuracy.py::TestModelingV2DeepseekR10528Nvfp4Sm10xDefault::test_gsm8k_chunked_prefill[dep4] - accuracy/modeling_v2/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_accuracy.py::TestModelingV2DeepseekR10528Nvfp4Sm10xDefault::test_gsm8k_static_eplb[dep4-no_spec] - accuracy/modeling_v2/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_accuracy.py::TestModelingV2DeepseekR10528Nvfp4Sm10xDefault::test_gsm8k_static_eplb[dep4-mtp3] + - accuracy/modeling_v2/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_accuracy.py::TestModelingV2DeepseekR10528Nvfp4Sm10xDefault::test_gsm8k_online_eplb[dep4-no_spec] + - accuracy/modeling_v2/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_accuracy.py::TestModelingV2DeepseekR10528Nvfp4Sm10xDefault::test_gsm8k_online_eplb[dep4-mtp3] - accuracy/modeling_v2/minimax_m3/minimax_m3_nvfp4__sm_103__tp4/test_accuracy.py::TestModelingV2MiniMaxM3Nvfp4Sm103Tp4::test_gsm8k - accuracy/modeling_v2/minimax_m3/minimax_m3_nvfp4__sm_103__tp4/test_accuracy.py::TestModelingV2MiniMaxM3Nvfp4Sm103Tp4::test_eagle3_gsm8k_and_acceptance - unittest/_torch/modeling_v2/models/kimi_k3_vl/kernels/k3r_comm diff --git a/tests/integration/test_lists/test-db/l0_gb300_multi_nodes_node2_gpu8.yml b/tests/integration/test_lists/test-db/l0_gb300_multi_nodes_node2_gpu8.yml index 9632a007645e..609936c2c00f 100644 --- a/tests/integration/test_lists/test-db/l0_gb300_multi_nodes_node2_gpu8.yml +++ b/tests/integration/test_lists/test-db/l0_gb300_multi_nodes_node2_gpu8.yml @@ -30,6 +30,7 @@ l0_gb300_multi_nodes_node2_gpu8: - accuracy/modeling_v2/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_accuracy.py::TestModelingV2DeepseekR10528Nvfp4Sm10xDefault::test_gsm8k[tp8_moetp2_ep4] - accuracy/modeling_v2/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_accuracy.py::TestModelingV2DeepseekR10528Nvfp4Sm10xDefault::test_gsm8k[dep8] - accuracy/modeling_v2/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_accuracy.py::TestModelingV2DeepseekR10528Nvfp4Sm10xDefault::test_gsm8k_static_eplb[dep8-no_spec] + - accuracy/modeling_v2/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_accuracy.py::TestModelingV2DeepseekR10528Nvfp4Sm10xDefault::test_gsm8k_online_eplb[dep8-no_spec] # GLM-5.2 NVFP4 modeling_v2 sm_103 tp8 target, GSM8K under modeling_v2="require". # Measured 34 min on 2x4 GB300 (batch 1). - accuracy/modeling_v2/glm_moe_dsa/glm_5_2_nvfp4__sm_103__tp8/test_accuracy.py::TestModelingV2Glm52Nvfp4Sm103Tp8::test_gsm8k_tp8 TIMEOUT (90) diff --git a/tests/unittest/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_modeling_v2_deepseek_default_shards.py b/tests/unittest/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_modeling_v2_deepseek_default_shards.py index e7b95da80fe6..e67c1911ed93 100644 --- a/tests/unittest/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_modeling_v2_deepseek_default_shards.py +++ b/tests/unittest/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_modeling_v2_deepseek_default_shards.py @@ -255,6 +255,12 @@ def __getitem__(self, key): def full(self, key) -> torch.Tensor: return _full(key, self.cfg) + def mark_consumed_keys(self, keys) -> int: + """The engine dict's release: the keys are gone, so a later read of one fails.""" + for key in keys: + dict.pop(self, key) + return len(keys) + def _read_first(core, ckpt, param_key): """The tensor `load` copies into `param_key`'s first source, through the @@ -702,6 +708,9 @@ def test_load_reads_only_the_rank_share(layout, mtp, monkeypatch): ) ckpt = _Checkpoint(cfg, keys) D.MODEL_WEIGHTS.load(model, ckpt) + # Every key has left the dict: unread ones at the start, read ones after their last read. + assert not set(ckpt.keys()), sorted(ckpt.keys())[:4] + _assert_slot_scales_are_the_expert_products(core) seen = [k for k, _, _ in ckpt.reads] assert len(seen) == len(set(seen)), "a checkpoint key was read twice" @@ -728,3 +737,17 @@ def test_load_reads_only_the_rank_share(layout, mtp, monkeypatch): and not (".mlp.experts." in k and not lo <= int(k.split(".")[5]) < hi) } assert read_mtp == want, (sorted(want - read_mtp)[:4], sorted(read_mtp - want)[:4]) + + +def _assert_slot_scales_are_the_expert_products(core) -> None: + """Each trunk layer's per-slot output scales are bitwise what the forward used to derive + from the per-expert scalars: the same products of the same fp32 values, in the same + order.""" + d, w = core.dims, core.w + for i in range(d.dense_layers, d.num_layers): + held = torch.tensor(d.slots[i].slot_experts) + isc1, e_isc2 = w[f"l{i}_mlp_isc1"], w[f"l{i}_e_isc2"][held] + gate1 = isc1[0] * w[f"l{i}_e_ws2_1"][held] + assert torch.equal(w[f"l{i}_out1_gate_scale"], gate1), i + assert torch.equal(w[f"l{i}_out1_scale"], gate1 / e_isc2), i + assert torch.equal(w[f"l{i}_out2_scale"], e_isc2 * w[f"l{i}_e_ws2_2"][held]), i diff --git a/tests/unittest/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_modeling_v2_deepseek_eplb.py b/tests/unittest/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_modeling_v2_deepseek_eplb.py index 783f7bb6fba4..80b56c64ed8a 100644 --- a/tests/unittest/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_modeling_v2_deepseek_eplb.py +++ b/tests/unittest/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_modeling_v2_deepseek_eplb.py @@ -1,22 +1,24 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""What the default deepseek target registers with the engine's load balancer under static EPLB. +"""What the default deepseek target registers with the engine's load balancer under EPLB. -The target is built under meta init, so no weight is allocated, against a real static load -balancer at one rank of dep4. The registrations are the target's half of the contract: the -loader finalizes the balancer and the executor drives it per forward, and both rely on every -routed MoE layer being registered once, in the order the layers run, with the placement the -target loads its weights by. +The target is built under meta init, so no weight is allocated, against a real load balancer, +static or online, at one rank of dep4. The registrations are the target's half of the +contract: the loader finalizes the balancer and the executor drives it per forward, and both +rely on every routed MoE layer being registered once, in the order the layers run, with the +placement the target loads its weights by. """ from __future__ import annotations +import os import random import pytest import torch from transformers import DeepseekV3Config +import tensorrt_llm.bindings.internal.runtime as _tbr from tensorrt_llm._torch.model_config import ModelConfig from tensorrt_llm._torch.modeling_v2.models.deepseek_v3.r1_0528_nvfp4__sm_10x__default.modeling import ( # noqa: E501 DeepseekV3DefaultModelingV2, @@ -83,11 +85,28 @@ def _placement(layer: int) -> list: return out +@pytest.mark.parametrize( + "updates", + [ + 0, + pytest.param( + 2, + marks=pytest.mark.skipif( + not torch.cuda.is_available() + or not _tbr.is_host_accessible_device_memory_supported(), + reason="online EPLB needs host-accessible device memory", + ), + ), + ], + ids=["static", "online"], +) @pytest.mark.parametrize("mtp", [False, True], ids=["no_spec", "mtp3"]) -def test_static_eplb_registers_every_routed_layer(mtp): +def test_eplb_registers_every_routed_layer(mtp, updates): layers = range(3, 61 + int(mtp)) assignments = {i: _placement(i) for i in layers} - load_balancer = MoeLoadBalancerConfig(num_slots=_SLOTS, initial_global_assignments=assignments) + load_balancer = MoeLoadBalancerConfig( + num_slots=_SLOTS, initial_global_assignments=assignments, layer_updates_per_iter=updates + ) load_balancer.setup(ep_rank=_RANK, ep_size=_EP) model_config = ModelConfig( pretrained_config=DeepseekV3Config(**_R1), @@ -104,7 +123,12 @@ def test_static_eplb_registers_every_routed_layer(mtp): spec_config=MTPDecodingConfig(max_draft_len=3) if mtp else None, ) - balancer = MoeLoadBalancer(ep_rank=_RANK, ep_size=_EP, layer_updates_per_iter=0) + balancer = MoeLoadBalancer( + ep_rank=_RANK, + ep_size=_EP, + layer_updates_per_iter=updates, + shared_memory_base_name=f"mv2_ds_eplb_{os.getpid()}", + ) try: with balancer, MetaInitMode(): core = DeepseekV3DefaultModelingV2(model_config) @@ -118,8 +142,10 @@ def test_static_eplb_registers_every_routed_layer(mtp): placement = layer.single_layer_load_balancer_impl.get_old_rank_expert_ids() assert sum(placement, []) == assignments[i], i + mode = "online" if updates else "static" + assert [eplb.online for eplb in core.eplb_layers.values()] == [bool(updates)] * len(layers) d = core.dims - assert (d.eplb, d.num_slots, d.local_slots, d.slot_offset) == ("static", 288, 72, 72) + assert (d.eplb, d.num_slots, d.local_slots, d.slot_offset) == (mode, 288, 72, 72) for i in layers: mine = tuple(assignments[i][72:144]) assert d.slots[i].slot_experts == mine diff --git a/tests/unittest/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_modeling_v2_deepseek_eplb_shards.py b/tests/unittest/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_modeling_v2_deepseek_eplb_shards.py index d342fda07b6f..475fae599c06 100644 --- a/tests/unittest/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_modeling_v2_deepseek_eplb_shards.py +++ b/tests/unittest/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_modeling_v2_deepseek_eplb_shards.py @@ -7,7 +7,8 @@ The checks reuse the shares test's synthetic checkpoint and its world-size-1 oracle (``test_modeling_v2_deepseek_default_shards``): the slots tile every expert of every routed layer, and ``load`` fills each slot with exactly the oracle's tensors for its expert, reading -each expert once per slot that holds it. +each expert once per slot that holds it. Under online EPLB ``load`` also hands each layer's +balancer handle this rank's share of the experts. """ from __future__ import annotations @@ -20,6 +21,7 @@ from test_modeling_v2_deepseek_default_shards import ( _TINY, _WS1, + _assert_slot_scales_are_the_expert_products, _Checkpoint, _default_core, _layout_id, @@ -32,6 +34,9 @@ from tensorrt_llm._torch.modeling_v2.models.deepseek_v3.r1_0528_nvfp4__sm_10x__default import ( # noqa: E501 weights as D, ) +from tensorrt_llm._torch.modeling_v2.models.deepseek_v3.r1_0528_nvfp4__sm_10x__default.modeling import ( # noqa: E501 + ModelingV2DeepseekR10528Nvfp4Sm10xDefault, +) from tensorrt_llm.llmapi.llm_args import MoeLoadBalancerConfig pytestmark = pytest.mark.cpu_only @@ -55,9 +60,10 @@ def _placement(layer: int, num_experts: int, ep_size: int, spare: int) -> list[i return out -def _eplb_core(layout, rank: int, cfg, mtp: bool, spare: int = 2): - """`_default_core` under static EPLB: the config names the architecture the engine - balances, and the load balancer config places the experts of every routed layer.""" +def _eplb_core(layout, rank: int, cfg, mtp: bool, spare: int = 2, updates: int = 0): + """`_default_core` under EPLB, static unless `updates` layers move per forward: the + config names the architecture the engine balances, and the load balancer config places + the experts of every routed layer.""" ep = layout[3] layers = range(cfg.first_k_dense_replace, cfg.num_hidden_layers + int(mtp)) assignments = {i: _placement(i, cfg.n_routed_experts, ep, spare) for i in layers} @@ -71,6 +77,7 @@ def _eplb_core(layout, rank: int, cfg, mtp: bool, spare: int = 2): moe_load_balancer=MoeLoadBalancerConfig( num_slots=cfg.n_routed_experts + ep * spare, initial_global_assignments=assignments, + layer_updates_per_iter=updates, ), ) ) @@ -127,20 +134,140 @@ def test_eplb_load_fills_every_slot_with_its_expert(layout, mtp, monkeypatch): ) ckpt = _Checkpoint(cfg, keys) D.MODEL_WEIGHTS.load(model, ckpt) + # Every key has left the dict: unread ones at the start, read ones after their last read. + assert not set(ckpt.keys()), sorted(ckpt.keys())[:4] + _assert_slot_scales_are_the_expert_products(core) reads = Counter(k for k, _, _ in ckpt.reads) for i in assignments: mine = d.slots[i].slot_experts - names = ( - ("fc1_w", "fc1_s", "fc2_w", "fc2_s") - if i < cfg.num_hidden_layers - else ("fc1", "fc2") - ) + names = _slot_names(i, cfg) + assert tuple(D.MODEL_WEIGHTS.slot_weights(core, i)) == names, i for e in range(cfg.n_routed_experts): key = f"model.layers.{i}.mlp.experts.{e}.down_proj.weight" assert reads[key] == mine.count(e), (layout, rank, i, e) for slot, e in enumerate(mine): for name in names: - ckpt_key, _, cut, transform = oracle.manifest[f"l{i}_{name}"][e] - want = D.MODEL_WEIGHTS.read(_Checkpoint(cfg), ckpt_key, cut, transform, oracle) + want = _ws1_expert(oracle, cfg, i, name, e) assert torch.equal(core.w[f"l{i}_{name}"][slot], want), (rank, i, slot, name) + + +def _slot_names(layer: int, cfg) -> tuple[str, ...]: + """A routed layer's slot weights: the trunk's NVFP4 operands and output scales, the MTP + layer's bf16 operands.""" + if layer < cfg.num_hidden_layers: + return ("fc1_w", "fc1_s", "fc2_w", "fc2_s", "out1_scale", "out1_gate_scale", "out2_scale") + return ("fc1", "fc2") + + +def _ws1_expert(oracle, cfg, layer: int, name: str, expert: int) -> torch.Tensor: + """What the world-size-1 table, which has no EPLB, loads into expert `expert`'s slot.""" + ckpt_key, _, cut, transform = oracle.manifest[f"l{layer}_{name}"][expert] + return D.MODEL_WEIGHTS.read(_Checkpoint(cfg), ckpt_key, cut, transform, oracle) + + +class _Hosting: + """An online EPLB layer handle that keeps the host copies `load` hands it.""" + + online = True + + def __init__(self, experts): + self.host_experts = tuple(experts) + self.copies: dict = {} + self.names: tuple = () + + def share_experts(self, slot_weights, expert_weight): + self.names = tuple(slot_weights) + for name, slot_weight in slot_weights.items(): + for e in self.host_experts: + self.copies[(name, e)] = expert_weight(name, e) + assert self.copies[(name, e)].shape == slot_weight.shape[1:], (name, e) + + +@pytest.mark.parametrize("mtp", [False, True], ids=["no_mtp", "mtp"]) +@pytest.mark.parametrize("layout", _EPLB_LAYOUTS, ids=_layout_id) +def test_online_eplb_load_hands_over_this_ranks_experts(layout, mtp, monkeypatch): + """`load` under online EPLB, with the ranks on one node: each rank hands each routed + layer's balancer handle every slot weight of its share of the experts -- each one what + the world-size-1 table loads for that expert -- reads each of those experts' tensors once + more, whether or not a slot already did, and coverage still holds both ways.""" + monkeypatch.setattr(torch.cuda, "synchronize", lambda *a, **k: None) + monkeypatch.setattr(torch.cuda, "empty_cache", lambda *a, **k: None) + cfg = SimpleNamespace(**_TINY) + keys = _tiny_keys(cfg) + oracle = _default_core(_WS1, 0, cfg, mtp) + oracle.manifest = D.MODEL_WEIGHTS.manifest(oracle) + experts, ranks = cfg.n_routed_experts, layout[0] + for rank in range(ranks): + core, assignments = _eplb_core(layout, rank, cfg, mtp, updates=2) + d = core.dims + assert d.eplb == "online" + share = range(rank * experts // ranks, (rank + 1) * experts // ranks) + core.eplb_layers = {i: _Hosting(share) for i in assignments} + core.w = D.MODEL_WEIGHTS.declare(d) + lm_head = nn.Parameter(torch.empty(cfg.vocab_size, cfg.hidden_size, dtype=torch.bfloat16)) + params = [("lm_head.weight", lm_head)] + [(f"model.w.{k}", p) for k, p in core.w.items()] + model = SimpleNamespace( + model=core, lm_head=SimpleNamespace(weight=lm_head), named_parameters=lambda: params + ) + ckpt = _Checkpoint(cfg, keys) + D.MODEL_WEIGHTS.load(model, ckpt) + # Every key has left the dict: unread ones at the start, read ones after their last read. + assert not set(ckpt.keys()), sorted(ckpt.keys())[:4] + + reads = Counter(k for k, _, _ in ckpt.reads) + for i, hosting in core.eplb_layers.items(): + names = _slot_names(i, cfg) + assert hosting.names == names, i + mine = d.slots[i].slot_experts + for e in range(experts): + key = f"model.layers.{i}.mlp.experts.{e}.down_proj.weight" + assert reads[key] == mine.count(e) + (e in share), (layout, rank, i, e) + for e in share: + for name in names: + want = _ws1_expert(oracle, cfg, i, name, e) + assert torch.equal(hosting.copies[(name, e)], want), (rank, i, e, name) + + +class _Core: + """The shell's core, recording the trunk forward and the MTP layer's hand-back.""" + + def __init__(self, events: list): + self.events = events + + def __call__(self, **kwargs) -> torch.Tensor: + self.events.append("trunk") + return torch.zeros(4, 8) + + def close_draft_eplb(self) -> None: + self.events.append("close") + + +@pytest.mark.parametrize("draft_steps", [0, 3], ids=["no_draft", "three_drafts"]) +def test_the_shell_hands_the_mtp_layer_back_once_after_the_worker(draft_steps): + """With a spec worker the shell's forward closes the MTP layer's EPLB once per forward, + after the worker returns: also when the worker drafts nothing, and never between draft + steps. A layer left open stalls the balancer and the next forward under online EPLB.""" + events: list = [] + + def worker(**kwargs): + for _ in range(draft_steps): + events.append("draft") + return "outputs" + + shell = SimpleNamespace( + spec_worker=worker, + model=_Core(events), + logits_processor=SimpleNamespace(forward=lambda *a: events.append("logits")), + lm_head=object(), + draft_model=object(), + ) + out = ModelingV2DeepseekR10528Nvfp4Sm10xDefault.forward( + shell, + attn_metadata=None, + input_ids=torch.zeros(4, dtype=torch.int32), + position_ids=torch.zeros(1, 4, dtype=torch.int32), + spec_metadata=SimpleNamespace(gather_ids=torch.tensor([3])), + ) + assert out == "outputs" + assert events == ["trunk", "logits", *["draft"] * draft_steps, "close"] diff --git a/tests/unittest/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_modeling_v2_deepseek_weight_table.py b/tests/unittest/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_modeling_v2_deepseek_weight_table.py index 770fef744520..40f311b75c26 100644 --- a/tests/unittest/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_modeling_v2_deepseek_weight_table.py +++ b/tests/unittest/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_modeling_v2_deepseek_weight_table.py @@ -11,7 +11,9 @@ -- green in CI job 1081689 -- and both the function and that test were deleted together. One renaming was deliberate: the hand-written manifest called the MTP module's rows `mtp_*`; the table addresses it as layer `num_hidden_layers`, which is -what the checkpoint calls it, so they are `l61_*`. +what the checkpoint calls it, so they are `l61_*`. And one addition: the runner's three +per-slot output scales, which the block left to the forward to derive, are slot weights +in the table, read per slot like the experts' other operands. No GPU: nothing here allocates, and `dims` reads `model_config` alone. """ @@ -160,6 +162,8 @@ def P(*shape, dtype=torch.bfloat16): w[f"l{i}_fc1_s"] = P(local, 2 * mi, hidden // sf_vec, dtype=u8) w[f"l{i}_fc2_w"] = P(local, hidden, mi // 2, dtype=u8) w[f"l{i}_fc2_s"] = P(local, hidden, mi // sf_vec, dtype=u8) + for name in ("out1_scale", "out1_gate_scale", "out2_scale"): + w[f"l{i}_{name}"] = P(local, dtype=f32) for name in ("isc1", "isc1_up", "ws2_1", "ws2_1_up", "isc2", "ws2_2"): w[f"l{i}_e_{name}"] = P(c.n_routed_experts, dtype=f32) w["final_norm"] = P(hidden) diff --git a/tests/unittest/_torch/modeling_v2/moe/ops/test_modeling_v2_eplb.py b/tests/unittest/_torch/modeling_v2/moe/ops/test_modeling_v2_eplb.py index e7119ec94bbb..43d3de68cf4b 100644 --- a/tests/unittest/_torch/modeling_v2/moe/ops/test_modeling_v2_eplb.py +++ b/tests/unittest/_torch/modeling_v2/moe/ops/test_modeling_v2_eplb.py @@ -1,26 +1,38 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""The eplb catalog entry: slot layouts, layer registration and the routing op. +"""The eplb catalog entry: slot layouts, layer registration, each expert call's routing, +the routing op and, under online EPLB, the layer's part in moving experts between slots. -Slot layouts and registration are plain Python and run on the CPU. The routing op -and the sum over EP ranks of a slot-routed MoE layer need a GPU. +Slot layouts, registration, the routing of an expert call (`eplb_call`) and the online +protocol a layer follows with the balancer are plain Python and run on the CPU. The +routing op, the sum over EP ranks of a slot-routed MoE layer and a real online balancer +moving experts need a GPU. """ from __future__ import annotations +import os import zlib from collections.abc import Iterator from unittest.mock import MagicMock, patch import pytest import torch +from torch import nn +import tensorrt_llm.bindings.internal.runtime as _tbr from tensorrt_llm._torch.modeling_v2.catalog._op import Cell from tensorrt_llm._torch.modeling_v2.catalog.moe import eplb as eplb_module -from tensorrt_llm._torch.modeling_v2.catalog.moe.eplb import EplbLayer, EplbSlots, eplb_call +from tensorrt_llm._torch.modeling_v2.catalog.moe.eplb import ( + EplbLayer, + EplbSlots, + eplb_call, + rows_within, +) from tensorrt_llm._torch.modeling_v2.catalog.moe.eplb import eplb_route as op from tensorrt_llm._torch.moe.fused_moe.moe_load_balancer import ( MoeLoadBalancer, + MoeLoadBalancerIterContext, get_moe_load_balancer, ) from tensorrt_llm._utils import get_sm_version @@ -31,6 +43,10 @@ from _validating import validating # noqa: E402 — needs the path declared above requires_gpu = pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a CUDA device") +requires_host_accessible = pytest.mark.skipif( + not torch.cuda.is_available() or not _tbr.is_host_accessible_device_memory_supported(), + reason="online EPLB needs host-accessible device memory", +) # The NVFP4 MoE runner the numerical test drives is certified on sm_100 and sm_103 only. requires_sm10x = pytest.mark.skipif( not torch.cuda.is_available() or get_sm_version() not in (100, 103), @@ -138,6 +154,231 @@ def test_registering_adds_the_layer_with_its_placement(mocked_runtime): assert get_moe_load_balancer() is None +# --- online EPLB: what a layer tells the balancer (CPU) ----------------------------------------- + + +class _Layer: + """A balancer layer that records what `EplbLayer` asks of it, in order.""" + + def __init__(self, online: bool, load_expert_ids=()): + self.online = online + self.load_expert_ids = list(load_expert_ids) + self.calls: list = [] + self.host_tensor_sharer = MagicMock() + self.slots: dict = {} + + def is_dynamic_routing(self): + return self.online + + def get_load_expert_ids(self): + return self.load_expert_ids + + def start_wait_gpu_stage(self): + self.calls.append("wait") + + def done_wait_gpu_stage(self): + self.calls.append("waited") + + def update_statistic_with_global_ids(self, ids, is_first_stage, is_last_stage): + self.calls.append(("count", ids.tolist(), is_first_stage, is_last_stage)) + + def start_set_cpu_stage(self): + self.calls.append("set") + + def done_set_cpu_stage(self): + self.calls.append("done") + + def make_tensor_host_accessible(self, t): + # New storage with the same contents, as the engine's migration gives. + t.set_(t.clone()) + self.calls.append(("migrate", t.data_ptr())) + + def register_weight_slot(self, local, name, t): + self.slots[(local, name)] = t + + +@pytest.fixture +def no_route(monkeypatch): + """The routing op returns the ids it is given: the protocol is the subject here.""" + monkeypatch.setattr(eplb_module, "eplb_route", lambda ids, layer, offset: ids) + + +def _ids(*rows): + return torch.tensor(rows, dtype=torch.int32) + + +def _route(eplb, ids, **kwargs): + """One expert call's routing, as a target runs it: the slot ids `eplb_call` yields. + Static and online EPLB hold no plan.""" + with eplb_call(eplb, ids, **kwargs) as (slot_ids, plan): + assert plan is None + return slot_ids + + +def _online(**kwargs) -> tuple[EplbLayer, _Layer]: + layer = _Layer(online=True, **kwargs) + return EplbLayer(layer, EplbSlots.without_eplb(8, 2, 0)), layer + + +@pytest.mark.cpu_only +def test_a_layer_run_once_a_forward_counts_and_hands_back_once(no_route): + """A trunk layer: taken on its first chunk, every chunk counted, the statistic complete on + the last chunk, then handed back -- and the next forward takes it again.""" + eplb, layer = _online() + _route(eplb, _ids([0, 1], [2, 3])) + _route(eplb, _ids([4, 5]), last=True) + eplb.close() + assert layer.calls == [ + "wait", + "waited", + ("count", [[0, 1], [2, 3]], True, False), + ("count", [[4, 5]], False, True), + "set", + "done", + ] + layer.calls.clear() + _route(eplb, _ids([6, 7]), last=True) + eplb.close() + assert layer.calls == ["wait", "waited", ("count", [[6, 7]], True, True), "set", "done"] + + +@pytest.mark.cpu_only +def test_a_layer_run_once_a_draft_step_completes_its_count_when_handed_back(no_route): + """The MTP layer runs once per draft step and does not know which step is the last, so + `close` completes the statistic with a row of ids no expert has.""" + eplb, layer = _online() + for step in range(3): + _route(eplb, _ids([step, 7])) + eplb.close() + assert layer.calls == [ + "wait", + "waited", + ("count", [[0, 7]], True, False), + ("count", [[1, 7]], False, False), + ("count", [[2, 7]], False, False), + ("count", [[8, 8]], False, True), + "set", + "done", + ] + + +@pytest.mark.cpu_only +def test_a_layer_that_ran_no_tokens_is_still_taken_and_handed_back(no_route): + """A forward that drafted nothing: the balancer waits for every layer every forward.""" + eplb, layer = _online() + eplb.close() + assert layer.calls == ["wait", "waited", "set", "done"] + + +@pytest.mark.cpu_only +def test_padding_rows_are_left_out_of_the_count(no_route): + """Rows `rows` does not name are padding: counted out, whatever their ids; a chunk of + padding alone is routed but not counted.""" + eplb, layer = _online() + ids = _ids([0, 1], [2, 3], [7, 7], [4, 5], [7, 7]) + assert torch.equal(_route(eplb, ids, rows=((0, 2), (3, 4))), ids) + _route(eplb, _ids([7, 7]), rows=(), last=True) + eplb.close() + assert layer.calls == [ + "wait", + "waited", + ("count", [[0, 1], [2, 3], [4, 5]], True, False), + ("count", [[8, 8]], False, True), + "set", + "done", + ] + + +@pytest.mark.cpu_only +def test_rows_within_a_chunk(): + tokens = ((0, 5), (8, 13), (16, 18)) + assert rows_within(None, 0, 4) is None + assert rows_within(tokens, 0, 4) == ((0, 4),) + assert rows_within(tokens, 4, 12) == ((0, 1), (4, 8)) + assert rows_within(tokens, 13, 16) == () + assert rows_within(tokens, 12, 20) == ((0, 1), (4, 6)) + + +@pytest.mark.cpu_only +def test_without_online_eplb_a_layer_only_routes(no_route): + """Static EPLB: no statistic, no hand-over, no host copies, no binding.""" + layer = _Layer(online=False, load_expert_ids=range(8)) + eplb = EplbLayer(layer, EplbSlots.without_eplb(8, 2, 0)) + weight = nn.Parameter(torch.arange(8.0).reshape(4, 2), requires_grad=False) + before = weight.data_ptr() + _route(eplb, _ids([0, 1]), last=True) + eplb.close() + eplb.share_experts({"w": weight}, lambda name, expert: pytest.fail("read an expert")) + eplb.bind_slots({"w": weight}) + assert layer.calls == [] and layer.slots == {} and eplb.host_experts == () + assert weight.data_ptr() == before + assert not layer.host_tensor_sharer.method_calls + + +@pytest.mark.cpu_only +def test_host_copies_are_this_ranks_share_of_the_experts(): + """Each name: this rank's share of the experts handed over in the slot layout, every + other expert announced with a slot's shape and dtype; then the layer's copies go to + shared memory, once.""" + eplb, layer = _online(load_expert_ids=(2, 3)) + slot_weights = {"w": torch.zeros(4, 3, 2, dtype=torch.uint8), "s": torch.zeros(4)} + read = [] + + def expert_weight(name, expert): + read.append((name, expert)) + return torch.full((3, 2), expert, dtype=torch.uint8) if name == "w" else torch.tensor(1.0) + + eplb.share_experts(slot_weights, expert_weight) + assert eplb.host_experts == (2, 3) + assert read == [("w", 2), ("w", 3), ("s", 2), ("s", 3)] + calls = layer.host_tensor_sharer.method_calls + shared = [c.args[:2] for c in calls if c[0] == "share_host_tensor_with_shape"] + announced = [c.args for c in calls if c[0] == "pre_register_host_tensor_with_shape"] + assert shared == [(2, "w"), (3, "w"), (2, "s"), (3, "s")] + assert [a[:2] for a in announced] == [ + (e, n) for n in ("w", "s") for e in range(8) if e not in (2, 3) + ] + assert {(a[1], a[2], tuple(a[3])) for a in announced} == { + ("w", torch.uint8, (3, 2)), + ("s", torch.float32, ()), + } + assert calls[-1][0] == "finalize_layer_weights" + assert [c[0] for c in calls].count("finalize_layer_weights") == 1 + + +@pytest.mark.cpu_only +def test_a_copy_unlike_a_slot_is_refused(): + eplb, _ = _online(load_expert_ids=(0,)) + with pytest.raises(AssertionError, match="a slot is"): + eplb.share_experts({"w": torch.zeros(4, 3)}, lambda name, expert: torch.zeros(2)) + + +@pytest.mark.cpu_only +def test_binding_moves_every_slot_weight_and_registers_each_slot(): + """A parameter keeps its identity and takes the new storage; a plain tensor moves in + place; each slot is registered as a view of the new storage.""" + eplb, layer = _online() + param = nn.Parameter(torch.arange(24.0).reshape(4, 6), requires_grad=False) + scale = torch.arange(4.0) + old = param.data_ptr(), scale.data_ptr() + eplb.bind_slots({"w": param, "s": scale}) + assert (param.data_ptr(), scale.data_ptr()) != old + assert [c[1] for c in layer.calls] == [param.data_ptr(), scale.data_ptr()] + assert torch.equal(param, torch.arange(24.0).reshape(4, 6)) + assert torch.equal(scale, torch.arange(4.0)) + for local in range(4): + assert layer.slots[(local, "w")].data_ptr() == param[local].data_ptr() + assert layer.slots[(local, "s")].data_ptr() == scale[local].data_ptr() + assert len(layer.slots) == 8 + + # The loader may run a target's post-load hook twice: the slots stay as registered. + calls, ptrs = len(layer.calls), (param.data_ptr(), scale.data_ptr()) + eplb.bind_slots({"w": param, "s": scale}) + assert len(layer.calls) == calls and (param.data_ptr(), scale.data_ptr()) == ptrs + with pytest.raises(AssertionError, match="moved after the balancer registered them"): + eplb.bind_slots({"w": param, "s": torch.arange(4.0)}) + + # --- the routing of one expert call (CPU) --------------------------------------------------- @@ -399,3 +640,60 @@ def test_slot_windows_sum_to_the_layer() -> None: ) summed = sum(p.float() for p in parts).to(torch.bfloat16) _assert_moe_close(summed, want) + + +# --- a real online balancer moves experts into slots (GPU) ----------------------------------- + + +@requires_host_accessible +def test_an_online_balancer_moves_experts_into_slots() -> None: + """Rank 0 of two under online EPLB, through `EplbLayer` alone: host copies, binding, one + forward whose every token picks experts 6 and 7, then a forward without updates, which + waits for the move. + + The default placement holds 6 and 7 only on rank 1. After the move rank 0 holds some of + their replicas, every one of its slots holds exactly the host copy of the expert the + balancer placed there -- the bytes and the scalar -- and the route sends each id to a + slot that holds it. + """ + experts, ep_size, top_k = 8, 2, 2 + config = MoeLoadBalancerConfig(num_slots=12, layer_updates_per_iter=1) + slots = EplbSlots.from_config(config, 3, experts, ep_size, 0) + + def expert_weight(name: str, expert: int) -> torch.Tensor: + if name == "w": + return torch.full((4, 16), 10 + expert, dtype=torch.uint8, device="cuda") + return torch.tensor(0.5 + expert, dtype=torch.float32, device="cuda") + + weights = { + "w": torch.stack([expert_weight("w", e) for e in slots.slot_experts]).contiguous(), + "s": torch.stack([expert_weight("s", e) for e in slots.slot_experts]).contiguous(), + } + balancer = MoeLoadBalancer(0, ep_size, 1, shared_memory_base_name=f"mv2_eplb_{os.getpid()}") + try: + with balancer: + eplb = EplbLayer.register(slots, top_k) + assert eplb.online and eplb.host_experts == tuple(range(experts)) + eplb.share_experts(weights, expert_weight) + eplb.bind_slots(weights) + balancer.register_weight_slots_after_to_cuda() + balancer.finalize_model() + + hot = torch.tensor([[6, 7]] * 64, dtype=torch.int32, device="cuda") + for updates in (True, False): + balancer.set_iter_info(enable_statistic=True, enable_update_weights=updates) + with MoeLoadBalancerIterContext(balancer): + routed = _route(eplb, hot, last=True) + eplb.close() + torch.cuda.synchronize() + + placement = eplb.balancer_layer.get_old_rank_expert_ids() + mine = list(placement[0]) + assert {6, 7} & set(mine), placement + for local, expert in enumerate(mine): + assert torch.equal(weights["w"][local], expert_weight("w", expert)), (local, expert) + assert torch.equal(weights["s"][local], expert_weight("s", expert)), (local, expert) + slot_expert = torch.tensor(sum(placement, []), dtype=torch.int32, device="cuda") + assert torch.equal(slot_expert[routed.long()], hot) + finally: + balancer.shutdown() diff --git a/tests/unittest/_torch/modeling_v2/test_modeling_v2_routing.py b/tests/unittest/_torch/modeling_v2/test_modeling_v2_routing.py index fba2ac5342f0..8db27862e7a3 100644 --- a/tests/unittest/_torch/modeling_v2/test_modeling_v2_routing.py +++ b/tests/unittest/_torch/modeling_v2/test_modeling_v2_routing.py @@ -1715,24 +1715,24 @@ def test_eplb_at_dep4_keeps_the_builtin_gpt_oss(eplb_mode): _R1_EPLB_LAYOUTS = {"dep4": _layout(4, True, 1, 4), "dep8": _layout(8, True, 1, 8)} +@pytest.mark.parametrize("eplb_mode", ["static", "online"]) @pytest.mark.parametrize("spec_config", [None, _MTP3], ids=["no_spec", "mtp3"]) @pytest.mark.parametrize( "mapping_kwargs", list(_R1_EPLB_LAYOUTS.values()), ids=list(_R1_EPLB_LAYOUTS) ) -def test_r1_static_eplb_matches_at_dep4_and_dep8(mapping_kwargs, spec_config): - """The default target implements static EPLB, measured at dep4 and dep8, with and - without its MTP layer.""" +def test_r1_eplb_matches_at_dep4_and_dep8(mapping_kwargs, spec_config, eplb_mode): + """The default target implements static and online EPLB, measured at dep4 and dep8, + with and without its MTP layer.""" config = _balanced( - _model_config(_r1_config(), spec_config=spec_config, **mapping_kwargs), "static" + _model_config(_r1_config(), spec_config=spec_config, **mapping_kwargs), eplb_mode ) assert _qualified(modeling_v2_resolve(config, _llm_args("require"))) == _R1_DEFAULT_TARGET -@pytest.mark.parametrize("eplb_mode", ["online", "per_layer_dynamic"]) -def test_r1_eplb_beyond_static_keeps_the_builtin_model(eplb_mode): - config = _balanced(_model_config(_r1_config(), **_DEP4), eplb_mode) +def test_r1_per_layer_dynamic_eplb_keeps_the_builtin_model(): + config = _balanced(_model_config(_r1_config(), **_DEP4), "per_layer_dynamic") assert modeling_v2_resolve(config, _llm_args("auto")) is None - with pytest.raises(ValueError, match=f"{eplb_mode} EPLB .* implements static"): + with pytest.raises(ValueError, match="per_layer_dynamic EPLB .* implements online, static"): modeling_v2_resolve(config, _llm_args("require")) @@ -1745,12 +1745,13 @@ def test_r1_eplb_beyond_static_keeps_the_builtin_model(eplb_mode): pytest.param(_layout(16, True, 1, 16), id="dep16"), ], ) -def test_r1_static_eplb_is_refused_where_it_was_not_measured(mapping_kwargs): +@pytest.mark.parametrize("eplb_mode", ["static", "online"]) +def test_r1_eplb_is_refused_where_it_was_not_measured(mapping_kwargs, eplb_mode): """EPLB balances attention DP over ranks that hold whole experts; the target runs it at the layouts it was measured at and declines the rest, which keep the built-in model.""" - config = _balanced(_model_config(_r1_config(), **mapping_kwargs), "static") + config = _balanced(_model_config(_r1_config(), **mapping_kwargs), eplb_mode) assert modeling_v2_resolve(config, _llm_args("auto")) is None - with pytest.raises(ValueError, match="static EPLB at parallel layout"): + with pytest.raises(ValueError, match=f"{eplb_mode} EPLB at parallel layout"): modeling_v2_resolve(config, _llm_args("require")) diff --git a/tests/unittest/_torch/moe/test_moe_load_balancer.py b/tests/unittest/_torch/moe/test_moe_load_balancer.py index 71fedf94d56f..316e2013eb68 100644 --- a/tests/unittest/_torch/moe/test_moe_load_balancer.py +++ b/tests/unittest/_torch/moe/test_moe_load_balancer.py @@ -602,6 +602,14 @@ def create_decoder(decoder_config: ModelConfig) -> torch.nn.Module: MoeLoadBalancerConfig(num_slots=288, layer_updates_per_iter=2), "online", id="online"), + # The balancer is static only at zero updates; the resolver must agree for any other + # count, or it would build a static target for an online balancer. + pytest.param("DeepseekV3ForCausalLM", + _EP4, + MoeLoadBalancerConfig(num_slots=288, + layer_updates_per_iter=-1), + "online", + id="nonzero-updates-are-online"), pytest.param("DeepseekV3ForCausalLM", _EP4, None,