From e604e13461d1a05c8c357e9b6ddaef34d86a8e83 Mon Sep 17 00:00:00 2001 From: Ruocheng Jia Date: Sat, 14 Nov 2026 03:38:40 -0800 Subject: [PATCH 01/16] [TRTLLM-17824][fix] Decline EPLB in modeling_v2 targets that do not implement it The loader creates the MoE load balancer around whichever class it builds, but a modeling_v2 target takes part only by registering its MoE layers with it. No target does, so a deployment that sets modeling_v2 together with EPLB ran on fixed expert windows: static EPLB lost its replicas silently, and online EPLB gave the balancer no layer to update. - moe_load_balancer.py: moe_load_balancer_mode() reports the EPLB mode the engine runs (static, online or per_layer_dynamic) or None, and maybe_create_moe_load_balancer creates a balancer exactly when it returns a mode. - modeling_v2 resolver: after route returns a target, a deployment that runs EPLB in a mode the target does not list in EPLB_MODES is NoTarget, so auto keeps Modeling V1 and require says why. An unknown name in EPLB_MODES is an error. - README: document EPLB_MODES. Signed-off-by: Ruocheng Jia --- .../_experimental/modeling_v2/README.md | 15 ++- .../modeling_v2/_router_index.py | 42 +++++- .../_torch/moe/fused_moe/moe_load_balancer.py | 42 +++++- .../modeling_v2/test_modeling_v2_routing.py | 123 +++++++++++++++++- .../_torch/moe/test_moe_load_balancer.py | 91 ++++++++++++- 5 files changed, 300 insertions(+), 13 deletions(-) diff --git a/tensorrt_llm/_torch/_experimental/modeling_v2/README.md b/tensorrt_llm/_torch/_experimental/modeling_v2/README.md index 144eded94204..f80a0aeaa707 100644 --- a/tensorrt_llm/_torch/_experimental/modeling_v2/README.md +++ b/tensorrt_llm/_torch/_experimental/modeling_v2/README.md @@ -157,7 +157,9 @@ example that uses no Modeling V1 model code. for switches to it as soon as the target lands. To keep a target opt-in until it is validated, decorate its class with `@disable_v2_by_default` (from `tensorrt_llm._torch._experimental.modeling_v2`). Deployments then use - it only when they set `modeling_v2` to `auto` or `require` explicitly. + it only when they set `modeling_v2` to `auto` or `require` explicitly. A + target that implements expert load balancing lists its modes in + `EPLB_MODES`; see [Routing](#routing). 4. Use catalog operations where they fit. Add new operations as `OpWrapper`s with tests. See [Writing operations](#writing-operations). 5. For C++/CUDA code, follow the [native code guide](../../../../cpp/tensorrt_llm/modeling_v2/README.md). @@ -207,6 +209,17 @@ Check in `route` every requirement the target has, not only in the target's constructor. A configuration that `route` declines falls back to Modeling V1 under `auto`; one that the constructor rejects with an assertion fails. +Expert load balancing (EPLB) is checked for every target. When a deployment +runs EPLB (`moe_config.load_balancer` is set, the architecture is in +`moe_model_arch_list` and the experts are split over more than one EP rank), +the loader creates the load balancer whichever class it builds, but only a +target that registers its MoE layers with it balances anything. After `route` +returns a target, the resolver compares the deployment's EPLB mode (`static`, +`online` or `per_layer_dynamic`) with the target class's `EPLB_MODES` and +treats a target that does not list it as `NoTarget`: `auto` keeps Modeling V1 +for that deployment and `require` raises with the reason. `EPLB_MODES` is empty +unless the target sets it. + How the model loader resolves a target: ```text diff --git a/tensorrt_llm/_torch/_experimental/modeling_v2/_router_index.py b/tensorrt_llm/_torch/_experimental/modeling_v2/_router_index.py index 328bc4a535ad..618e88bf1da8 100644 --- a/tensorrt_llm/_torch/_experimental/modeling_v2/_router_index.py +++ b/tensorrt_llm/_torch/_experimental/modeling_v2/_router_index.py @@ -215,15 +215,47 @@ def engine_kv_cache_quant_algo(config: "ModelConfig", llm_args: "TorchLlmArgs"): return {"fp8": QuantAlgo.FP8, "nvfp4": QuantAlgo.NVFP4}.get(dtype, dtype) +def _check_eplb_mode(target: type, config: "ModelConfig") -> None: + """Raise ``NoTarget`` unless ``target`` implements the EPLB mode this deployment runs. + + The loader creates the MoE load balancer around whichever class it builds + (``maybe_create_moe_load_balancer``). A target takes part only by + registering its MoE layers with it, so a target that does not would run an + EPLB deployment on fixed expert windows: no replicas under static EPLB and + no layer to update under online EPLB. A target lists the modes it + implements in the class attribute ``EPLB_MODES``; without it, none. + """ + from tensorrt_llm._torch.moe.fused_moe.moe_load_balancer import ( + MOE_LOAD_BALANCER_MODES, + moe_load_balancer_mode, + ) + + implemented = frozenset(getattr(target, "EPLB_MODES", ())) + unknown = implemented - MOE_LOAD_BALANCER_MODES + if unknown: + raise ValueError( + f"{target.__qualname__}.EPLB_MODES names {sorted(unknown)}; the EPLB modes are " + f"{sorted(MOE_LOAD_BALANCER_MODES)}" + ) + eplb = moe_load_balancer_mode(config, config.mapping) + if eplb is not None and eplb not in implemented: + raise NoTarget( + f"{eplb} EPLB (moe_config.load_balancer at moe_ep_size={config.mapping.moe_ep_size}); " + f"{target.__name__} implements {', '.join(sorted(implemented)) or 'no EPLB mode'}" + ) + + def modeling_v2_resolve(config: "ModelConfig", llm_args: "TorchLlmArgs") -> Optional[type]: """Decide which modeling_v2 target, if any, this deployment builds. Returns the target class, or None for the built-in implementation: when ``llm_args.modeling_v2`` is ``off``, when no ``route`` is registered - for the architecture, or when that ``route`` raises ``NoTarget``. - In ``require`` every one of those but ``off`` raises ``ValueError`` instead. - It also returns None for a ``@disable_v2_by_default`` target when - ``modeling_v2`` was left at its default. + for the architecture, when that ``route`` raises ``NoTarget``, or when + the deployment runs EPLB in a mode the target does not list in + ``EPLB_MODES``. In ``require`` every one of those but ``off`` raises + ``ValueError`` instead. It also returns None for a + ``@disable_v2_by_default`` target when ``modeling_v2`` was left at its + default. """ mode = ModelingV2Mode.of(llm_args) @@ -241,6 +273,8 @@ def modeling_v2_resolve(config: "ModelConfig", llm_args: "TorchLlmArgs") -> Opti known = ", ".join(sorted(registered_routes())) or "(none)" raise NoTarget(f"no route for this architecture; routed architectures: {known}") target = route(config, llm_args, _device_compute_capability()) + if target is not None: + _check_eplb_mode(target, config) except NoTarget as why: if mode is ModelingV2Mode.REQUIRE: raise ValueError(f"modeling_v2='require', but no target fits {arch!r}: {why}") from None 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 4b3ac2c3b189..689ef070ff41 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/moe_load_balancer.py +++ b/tensorrt_llm/_torch/moe/fused_moe/moe_load_balancer.py @@ -1107,6 +1107,45 @@ def __repr__(self): 'Qwen3_5MoeForConditionalGeneration', ] +#: The EPLB modes ``moe_load_balancer_mode`` reports. +MOE_LOAD_BALANCER_MODES = frozenset({"static", "online", "per_layer_dynamic"}) + + +def moe_load_balancer_mode(model_config, + mapping: Optional[Mapping]) -> Optional[str]: + """Return the EPLB mode the engine runs this model with, or None. + + ``maybe_create_moe_load_balancer`` creates a balancer exactly when this + returns a mode, so code that decides before the model is built, such as + the modeling_v2 resolver, agrees with the loader on whether EPLB runs. + + Args: + model_config: The model's ``ModelConfig``. Its ``moe_load_balancer`` + and the first of ``pretrained_config.architectures`` are read. + mapping: The mapping the model is built with. + + Returns: + ``"static"`` for standard EPLB that keeps its initial placement + (``layer_updates_per_iter == 0``), ``"online"`` for standard EPLB + that updates layers, ``"per_layer_dynamic"`` for per-layer dynamic + EPLB, and None when no balancer is created: no ``moe_load_balancer`` + config, an architecture outside ``moe_model_arch_list``, a single EP + rank, or smart routing (``moe_cluster_size > 1``). + """ + config = model_config.moe_load_balancer + if config is None or mapping is None: + return None + architectures = getattr(model_config.pretrained_config, "architectures", + None) or [None] + if architectures[0] not in moe_model_arch_list: + return None + if mapping.moe_ep_size <= 1 or mapping.moe_cluster_size > 1: + return None + mode = getattr(config, "mode", "standard") + if mode == "standard": + return "online" if config.layer_updates_per_iter > 0 else "static" + return mode + def maybe_create_moe_load_balancer( model_config, mapping: Optional[Mapping] @@ -1134,8 +1173,7 @@ def maybe_create_moe_load_balancer( "per-layer dynamic EPLB is incompatible with smart routing " "(moe_cluster_size > 1)") - if (in_supported_model_arch and using_ep and not using_smart_router - and config is not None): + if moe_load_balancer_mode(model_config, mapping) is not None: config.setup(ep_rank=ep_rank, ep_size=ep_size) if mode == "per_layer_dynamic": from .per_layer_dynamic_eplb import PerLayerDynamicMoeLoadBalancer 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 3ba909c278e3..61ab1e992c67 100644 --- a/tests/unittest/_torch/modeling_v2/test_modeling_v2_routing.py +++ b/tests/unittest/_torch/modeling_v2/test_modeling_v2_routing.py @@ -46,9 +46,13 @@ from tensorrt_llm._torch.distributed.ops import MNNVLAllReduce from tensorrt_llm._torch.model_config import ModelConfig from tensorrt_llm._torch.models.modeling_auto import AutoModelForCausalLM +from tensorrt_llm._torch.moe.fused_moe import moe_load_balancer +from tensorrt_llm._torch.moe.fused_moe.moe_load_balancer import MOE_LOAD_BALANCER_MODES from tensorrt_llm.llmapi.llm_args import ( CacheTransceiverConfig, KvCacheConfig, + MoeLoadBalancerConfig, + MoePerLayerDynamicLoadBalancerConfig, MTPDecodingConfig, NGramDecodingConfig, TorchLlmArgs, @@ -234,11 +238,13 @@ class _TargetDisabledByDefault: """A target the default mode declines.""" -def _claimed_by(monkeypatch, target): +_CLAIMED_ARCH = "ModelingV2TestForCausalLM" + + +def _claimed_by(monkeypatch, target, **mapping_kwargs): """A config whose architecture's ``route`` claims every deployment for ``target``.""" - arch = "ModelingV2TestForCausalLM" - monkeypatch.setitem(_ROUTES, arch, lambda *_: target) - return _model_config(PretrainedConfig(architectures=[arch])) + monkeypatch.setitem(_ROUTES, _CLAIMED_ARCH, lambda *_: target) + return _model_config(PretrainedConfig(architectures=[_CLAIMED_ARCH]), **mapping_kwargs) def test_the_default_mode_builds_a_claiming_target(monkeypatch): @@ -258,6 +264,89 @@ def test_a_set_mode_builds_a_target_disabled_by_default(monkeypatch, mode): assert modeling_v2_resolve(config, _llm_args(mode)) is _TargetDisabledByDefault +# --- Expert load balancing: a target runs only the EPLB modes it lists ----------------------- + + +class _TargetWithStaticEplb: + """A target that implements static EPLB and no other mode.""" + + EPLB_MODES = frozenset({"static"}) + + +def _eplb_config(eplb_mode, num_slots=288): + """A ``moe_config.load_balancer`` that runs ``eplb_mode``.""" + if eplb_mode == "per_layer_dynamic": + return MoePerLayerDynamicLoadBalancerConfig(num_slots=num_slots) + updates = 2 if eplb_mode == "online" else 0 + return MoeLoadBalancerConfig(num_slots=num_slots, layer_updates_per_iter=updates) + + +def _balanced(config, eplb_mode, num_slots=288): + """``config`` deployed with ``eplb_mode``, as the loader hands it to routing.""" + return replace(config, moe_load_balancer=_eplb_config(eplb_mode, num_slots)) + + +def _balance_the_claimed_arch(monkeypatch): + """Have the engine balance ``_CLAIMED_ARCH``, as it balances the architectures in moe_model_arch_list.""" + monkeypatch.setattr( + moe_load_balancer, + "moe_model_arch_list", + [*moe_load_balancer.moe_model_arch_list, _CLAIMED_ARCH], + ) + + +@pytest.mark.parametrize("eplb_mode", sorted(MOE_LOAD_BALANCER_MODES)) +def test_eplb_declines_a_target_that_lists_no_mode(monkeypatch, eplb_mode): + """The loader creates the load balancer around whatever class it builds. A target that registers no + layer with it would serve the deployment on fixed expert windows, so ``auto`` keeps the built-in + model and ``require`` says why.""" + _balance_the_claimed_arch(monkeypatch) + config = _balanced(_claimed_by(monkeypatch, _TargetUsedByDefault, **_DEP4), eplb_mode) + assert modeling_v2_resolve(config, _llm_args("auto")) is None + with pytest.raises(ValueError, match=f"{eplb_mode} EPLB .* implements no EPLB mode"): + modeling_v2_resolve(config, _llm_args("require")) + + +@pytest.mark.parametrize("eplb_mode", sorted(MOE_LOAD_BALANCER_MODES)) +def test_eplb_builds_a_target_for_the_modes_it_lists(monkeypatch, eplb_mode): + _balance_the_claimed_arch(monkeypatch) + config = _balanced(_claimed_by(monkeypatch, _TargetWithStaticEplb, **_DEP4), eplb_mode) + expected = _TargetWithStaticEplb if eplb_mode == "static" else None + assert modeling_v2_resolve(config, _llm_args("auto")) is expected + + +@pytest.mark.parametrize( + "arch_balanced, mapping_kwargs, eplb_mode", + [ + pytest.param(True, _DEP4, None, id="no-load-balancer-config"), + pytest.param(True, {}, "static", id="one-ep-rank"), + pytest.param(False, _DEP4, "static", id="architecture-not-balanced"), + ], +) +def test_eplb_config_without_a_balancer_changes_nothing( + monkeypatch, arch_balanced, mapping_kwargs, eplb_mode +): + """Where the engine creates no balancer, the load-balancer config is inert, and a target that lists no + EPLB mode is built as before.""" + if arch_balanced: + _balance_the_claimed_arch(monkeypatch) + config = _claimed_by(monkeypatch, _TargetUsedByDefault, **mapping_kwargs) + if eplb_mode is not None: + config = _balanced(config, eplb_mode) + assert modeling_v2_resolve(config, _llm_args("require")) is _TargetUsedByDefault + + +def test_an_unknown_eplb_mode_name_is_an_error(monkeypatch): + """A misspelled mode never matches, so the target would decline every EPLB deployment without a word.""" + + class _TargetWithMisspelledMode: + EPLB_MODES = frozenset({"Static"}) + + config = _claimed_by(monkeypatch, _TargetWithMisspelledMode) + with pytest.raises(ValueError, match=r"EPLB_MODES names \['Static'\]"): + modeling_v2_resolve(config, _llm_args("auto")) + + @pytest.mark.parametrize( "pretrained_config, expected", [(_gpt_oss_config, _GPT_OSS_DEFAULT_TARGET), (_r1_config, _R1_DEFAULT_TARGET)], @@ -1568,3 +1657,29 @@ def test_glm52_without_an_fp8_kv_cache_does_not_match(): assert modeling_v2_resolve(config, _llm_args("auto")) is None with pytest.raises(ValueError, match="KV cache bf16"): modeling_v2_resolve(config, _llm_args("require")) + + +# --- EPLB on the targets that do not implement it ------------------------------------------- + + +@pytest.mark.parametrize("eplb_mode", ["static", "online"]) +@pytest.mark.parametrize( + "pretrained_config, num_slots", + [pytest.param(_r1_config, 288, id="r1"), pytest.param(_gpt_oss_config, 160, id="gpt_oss")], +) +def test_eplb_at_dep4_keeps_the_builtin_r1_and_gpt_oss(pretrained_config, num_slots, eplb_mode): + """The built-in DeepSeek-R1 and gpt-oss models balance their experts; the default targets register no + MoE layer with the balancer, so an EPLB deployment that sets modeling_v2 keeps the built-in model.""" + config = _balanced(_model_config(pretrained_config(), **_DEP4), eplb_mode, num_slots) + assert modeling_v2_resolve(config, _llm_args("auto")) is None + with pytest.raises(ValueError, match=f"{eplb_mode} EPLB .* implements no EPLB mode"): + modeling_v2_resolve(config, _llm_args("require")) + + +@pytest.mark.usefixtures("_glm52_sm") +def test_glm52_tep4_with_eplb_keeps_the_builtin_model(): + """The tep4 target is built by default; it must not serve an EPLB deployment on fixed expert windows.""" + config = _balanced(_model_config(_glm52_config(), **_TEP4), "static") + assert modeling_v2_resolve(config, TorchLlmArgs(model=_DUMMY_MODEL)) is None + with pytest.raises(ValueError, match="static EPLB .* implements no EPLB mode"): + 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 33ae4828e268..51a79403a683 100644 --- a/tests/unittest/_torch/moe/test_moe_load_balancer.py +++ b/tests/unittest/_torch/moe/test_moe_load_balancer.py @@ -15,8 +15,9 @@ from tensorrt_llm._torch.moe.fused_moe.moe_load_balancer import ( MoeLoadBalancer, MoeLoadBalancerIterContext, SingleLayerMoeLoadBalancer, get_moe_load_balancer, maybe_create_moe_load_balancer, - moe_load_balancer_add_single_layer) -from tensorrt_llm.llmapi.llm_args import MoeLoadBalancerConfig + moe_load_balancer_add_single_layer, moe_load_balancer_mode) +from tensorrt_llm.llmapi.llm_args import (MoeLoadBalancerConfig, + MoePerLayerDynamicLoadBalancerConfig) from tensorrt_llm.mapping import Mapping from tensorrt_llm.models.modeling_utils import QuantAlgo, QuantConfig @@ -563,5 +564,91 @@ def create_decoder(decoder_config: ModelConfig) -> torch.nn.Module: assert get_moe_load_balancer() is None +_EP4 = dict(world_size=4, rank=1, tp_size=4, moe_ep_size=4) + +# (architecture, mapping kwargs, load-balancer config, the mode the engine +# runs). The standard-mode and no-balancer cases, which +# maybe_create_moe_load_balancer can build here with the runtime mocked. +_STANDARD_MODE_CASES = [ + pytest.param("DeepseekV3ForCausalLM", + _EP4, + MoeLoadBalancerConfig(num_slots=288), + "static", + id="static"), + pytest.param("DeepseekV3ForCausalLM", + _EP4, + MoeLoadBalancerConfig(num_slots=288, layer_updates_per_iter=2), + "online", + id="online"), + pytest.param("DeepseekV3ForCausalLM", + _EP4, + None, + None, + id="no-load-balancer-config"), + pytest.param("DeepseekV3ForCausalLM", + dict(world_size=4, + rank=1, + tp_size=4, + moe_tp_size=4, + moe_ep_size=1), + MoeLoadBalancerConfig(num_slots=256), + None, + id="one-ep-rank"), + pytest.param("LlamaForCausalLM", + _EP4, + MoeLoadBalancerConfig(num_slots=288), + None, + id="architecture-not-balanced"), +] + + +def _balancer_model_config(arch, mapping, load_balancer): + pretrained_config = PretrainedConfig() + pretrained_config.architectures = [arch] + return ModelConfig(pretrained_config=pretrained_config, + mapping=mapping, + moe_load_balancer=load_balancer) + + +@pytest.mark.cpu_only +@pytest.mark.parametrize( + "arch, mapping_kwargs, load_balancer, expected", _STANDARD_MODE_CASES + [ + pytest.param("DeepseekV3ForCausalLM", + _EP4, + MoePerLayerDynamicLoadBalancerConfig(num_slots=288), + "per_layer_dynamic", + id="per-layer-dynamic"), + ]) +def test_moe_load_balancer_mode(arch, mapping_kwargs, load_balancer, + expected) -> None: + mapping = Mapping(**mapping_kwargs) + model_config = _balancer_model_config(arch, mapping, load_balancer) + + assert moe_load_balancer_mode(model_config, mapping) == expected + assert moe_load_balancer_mode(model_config, None) is None + + +@pytest.mark.cpu_only +@pytest.mark.parametrize("arch, mapping_kwargs, load_balancer, expected", + _STANDARD_MODE_CASES) +def test_maybe_create_moe_load_balancer_follows_the_mode( + arch, mapping_kwargs, load_balancer, expected, + mock_runtime: MagicMock) -> None: + """The loader creates a balancer exactly where the mode says EPLB runs.""" + mapping = Mapping(**mapping_kwargs) + model_config = _balancer_model_config(arch, mapping, load_balancer) + + with maybe_create_moe_load_balancer(model_config, mapping) as balancer: + if expected is None: + assert balancer is None + else: + try: + assert isinstance(balancer, MoeLoadBalancer) + assert balancer.is_static_routing() == (expected == "static") + finally: + balancer.shutdown() + assert get_moe_load_balancer() is None + + if __name__ == '__main__': unittest.main() From 7386ca95c729beabef574339c0b2ffe091e84620 Mon Sep 17 00:00:00 2001 From: Ruocheng Jia Date: Sat, 14 Nov 2026 04:03:37 -0800 Subject: [PATCH 02/16] [TRTLLM-17824][feat] Static EPLB for the DeepSeek-R1 modeling_v2 target Make the DeepSeek-R1-0528 NVFP4 default target the Modeling V2 example of expert-parallel load balancing, and give other targets the shared pieces and the documentation to follow it. - catalog/moe/eplb.py: a MoE layer's slots on a rank (EplbSlots, eplb_slots), its registration with the engine's load balancer (EplbLayer) and the routing op (eplb_route). This module is the one place Modeling V2 reaches the balancer. - _router_index: moe_eplb_mode(), the EPLB mode a deployment runs, for routes to gate layouts on. - DeepSeek-R1 target: under static EPLB every routed MoE layer, the MTP layer included, registers with the balancer, loads its experts and per-expert scales by slot, and routes the router's expert ids to slot ids before the expert kernels, which then work in slots. EPLB_MODES is {"static"}, and routing admits EPLB at dep4 and dep8. Without EPLB a rank's slots are its expert window and the forward is unchanged. - Docs: an EPLB section in the Modeling V2 README, an EPLB section in the agent features skill, and a Modeling V2 note in the wide-EP EPLB example. - Tests: slot layouts, registration and the routing op of the catalog entry, slot windows that sum to the layer, runner cells at 288 slots, the target's slots and load under a per-layer placement, its routing decisions, and a static EPLB GSM8K test at dep4 and dep8. Signed-off-by: Ruocheng Jia --- .../trtllm-modeling-v2-features/SKILL.md | 3 +- .../references/features.md | 71 ++++ examples/wide_ep/ep_load_balancer/README.md | 10 + .../_experimental/modeling_v2/README.md | 69 ++++ .../modeling_v2/_router_index.py | 20 +- .../modeling_v2/catalog/moe/eplb.py | 279 ++++++++++++++ .../modeling.py | 76 +++- .../r1_0528_nvfp4__sm_10x__default/weights.py | 74 ++-- .../modeling_v2/models/deepseek_v3/routing.py | 27 +- .../test_accuracy.py | 67 +++- .../integration/test_lists/test-db/l0_cpu.yml | 1 + .../test-db/l0_gb300_multi_gpus.yml | 2 + .../l0_gb300_multi_nodes_node2_gpu8.yml | 1 + ...est_modeling_v2_deepseek_default_shards.py | 130 ++++++- .../test_modeling_v2_deepseek_eplb.py | 129 +++++++ .../test_modeling_v2_deepseek_weight_table.py | 5 +- .../modeling_v2/moe/test_modeling_v2_eplb.py | 348 ++++++++++++++++++ ..._modeling_v2_fp4_block_scale_moe_runner.py | 46 ++- .../modeling_v2/test_modeling_v2_routing.py | 53 ++- 19 files changed, 1338 insertions(+), 73 deletions(-) create mode 100644 tensorrt_llm/_torch/_experimental/modeling_v2/catalog/moe/eplb.py create mode 100644 tests/unittest/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_modeling_v2_deepseek_eplb.py create mode 100644 tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py 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 51381619ada6..8a7cf7345633 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 @@ -1,6 +1,6 @@ --- name: trtllm-modeling-v2-features -description: Load when working on, testing or debugging a TensorRT-LLM engine feature around a ModelingV2 target -- KV-cache block (prefix) reuse, disaggregated serving, chunked prefill, KV-cache dtype (fp8/nvfp4 and their scales), CUDA graphs and the overlap scheduler, multimodal inputs, speculative decoding, or attention-DP/TP/EP where it changes one of those -- including a check that fails on a feature field, or a number that moves only with a feature on. Says which engine stage owns the feature and what the target must honour, where its code and tests are in the tree, and how to prove it from a CPU check up to the flow's accuracy, disagg or acceptance gate. Not needed to write or certify one catalog entry (trtllm-modeling-v2-entry) or to debug core accuracy with every feature at its default. +description: Load when working on, testing or debugging a TensorRT-LLM engine feature around a ModelingV2 target -- KV-cache block (prefix) reuse, disaggregated serving, chunked prefill, KV-cache dtype (fp8/nvfp4 and their scales), CUDA graphs and the overlap scheduler, multimodal inputs, speculative decoding, expert-parallel load balancing (EPLB), or attention-DP/TP/EP where it changes one of those -- including a check that fails on a feature field, or a number that moves only with a feature on. Says which engine stage owns the feature and what the target must honour, where its code and tests are in the tree, and how to prove it from a CPU check up to the flow's accuracy, disagg or acceptance gate. Not needed to write or certify one catalog entry (trtllm-modeling-v2-entry) or to debug core accuracy with every feature at its default. --- @@ -94,6 +94,7 @@ Climb only as far as the claim needs. Each rung says what it cannot see. | disaggregation | feature `disagg` + `accuracy.disagg.test` | a benchmark scored through `trtllm-serve disaggregated` | the tree's disaggregated-serving test | | multimodal | feature `multimodal` | an image prompt answered | boot image, image benchmark | | speculative | features `mtp`, `eagle3`, `dflash`, `dspark` | each rank's algorithm and depth; 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 | ## 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 79a18d93cef6..b39272903858 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 @@ -545,3 +545,74 @@ run declares. - **Blind spots.** The reuse probe covers attention-DP rank 0 only. With `benchmark_members: ` the benchmark runs at that member alone; the other members rest on their boots (`task.example.yaml`). + +## 9. Expert-parallel load balancing (EPLB) + +**What.** A MoE layer's experts sit in slots split evenly over the EP ranks, +with spare slots holding more copies of hot experts, so each rank's load +follows its share of the slots (`examples/wide_ep/ep_load_balancer/README.md`). +`moe_config.load_balancer` sets `num_slots`, and either a fixed placement +(static EPLB, `layer_updates_per_iter: 0`, `initial_global_assignments`) or +one that the engine updates while serving (online EPLB). + +**Engine owns.** Creating the load balancer around the model when the +deployment runs EPLB (`maybe_create_moe_load_balancer`, +`moe_load_balancer_mode`), registering weight slots and finalizing it after +loading (`_torch/pyexecutor/model_loader.py`), a balancer iteration around +every forward with statistics and updates off in warmup (`model_engine.py`, +`MoeLoadBalancerIterContext`), and shutdown. The resolver builds a target for +an EPLB deployment only if its class lists the mode in `EPLB_MODES`. + +**Target must honour.** +- Implement the modes it lists in `EPLB_MODES`, through + `catalog/moe/eplb.py`: `eplb_slots` for each routed layer's slots, + `EplbLayer.register` for each routed layer at construction in run order + (a one-model draft layer with `repeat_count=max_draft_len`), expert weights + and per-expert scales sized and loaded by slot, and `EplbLayer.route` after + the router's top-k. The expert kernel then takes `num_slots` as its expert + count and this rank's slot window. +- `route` admits EPLB only at the layouts it was measured at + (`moe_eplb_mode`). EPLB needs attention DP over ranks that hold whole + experts (moe_tp 1), as the built-in MoE does. +- A target that gathers tokens before routing routes on every rank and must + get the same slots on every rank: `EplbLayer.route` does + (`offset_by_ep_rank=False`). + +**Grep.** `EPLB_MODES`, `moe_eplb_mode`, `eplb_slots`, `EplbLayer`, +`eplb_route`, `moe_load_balancer_mode`, `maybe_create_moe_load_balancer`, +`MoeLoadBalancerConfig`, `initial_global_assignments`, `num_slots`. + +**Tests to imitate.** +- `tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py`: the slots + and registration 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. +- `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`. + +**Fast check.** quickstart or `trtllm-serve` at a dep layout with +`moe_config.load_balancer` set and `modeling_v2: require`: the engine must +build the target (a mode it does not implement fails with the reason), and the +load log shows the balancer created before the model and finalized after the +weights load. + +**Flow proof.** The flow has no `eplb` feature yet. Prove it as a variant that +sets `llm_api_options.moe_config.load_balancer` at a `dep` member, with +`modeling_v2: require`, and read the accuracy gate. The engine read-back does +not report the registered layers, so the target's own tests carry that. + +**Blind spots.** +- 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. +- 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. diff --git a/examples/wide_ep/ep_load_balancer/README.md b/examples/wide_ep/ep_load_balancer/README.md index 0f1883ea4b62..defc46f3ca7f 100644 --- a/examples/wide_ep/ep_load_balancer/README.md +++ b/examples/wide_ep/ep_load_balancer/README.md @@ -314,3 +314,13 @@ Per-layer dynamic EPLB has the following constraints: * **Speculative decoding**: a one-model draft's MoE layers follow the same rule as the target's: every MoE layer that runs on `MEGAMOE_CUTEDSL` registers as one more per-layer dynamic layer after the target layers, is planned and load-balanced like them, and, with `per_layer_resident`, gets its own helper slots. DSpark drafters shipped inside an NVFP4 target checkpoint, such as `DeepSeek-V4-Pro-nvfp4-DSpark`, do so with NVFP4 draft experts. A draft layer only computes correctly if its checkpoint experts are NVFP4: the `mtp.*` routed experts of the `DeepSeek-V4-Pro-NVFP4` checkpoint are MXFP4, which `MEGAMOE_CUTEDSL` does not serve, so MTP on that checkpoint is not supported with or without this load balancer. * **DWDP**: not supported; `dwdp_config` must keep `dwdp_size` at 1. * **Fields**: only `mode`, `num_slots`, `auxiliary_sms` and `helper_slot_mode`. `num_slots` is required, must be greater than the expert count, and must be divisible by the EP size. `layer_updates_per_iter` and `initial_global_assignments` are `standard`-only and rejected in this mode. + +## Modeling V2 targets + +A [Modeling V2](../../../tensorrt_llm/_torch/_experimental/modeling_v2/README.md) target runs only the EPLB modes it implements. When a deployment sets `modeling_v2` (`auto` or `require`) together with `moe_config.load_balancer`, the engine builds a target only if the target implements the deployment's EPLB mode. Otherwise `auto` builds the built-in model, which implements every mode above, and `require` fails with the reason. + +| 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) | + +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. diff --git a/tensorrt_llm/_torch/_experimental/modeling_v2/README.md b/tensorrt_llm/_torch/_experimental/modeling_v2/README.md index f80a0aeaa707..6a69236bfee2 100644 --- a/tensorrt_llm/_torch/_experimental/modeling_v2/README.md +++ b/tensorrt_llm/_torch/_experimental/modeling_v2/README.md @@ -363,6 +363,75 @@ mode the target uses. (batch size, number of context requests, draft length), so the whole step is captured in one CUDA graph with the target. +## Expert load balancing (EPLB) + +EPLB places a MoE layer's experts in slots split evenly over the EP ranks, +with spare slots holding more copies of the hot experts, so a rank's load +follows its share of the slots rather than of the experts. Deployments +configure it with `moe_config.load_balancer`; see the +[EPLB example](../../../../examples/wide_ep/ep_load_balancer/README.md). + +The engine owns the load balancer. A target that implements EPLB plugs its +MoE layers into it: + +| Owner | What it does | +|---|---| +| Model loader | Creates the balancer around the model when the deployment runs EPLB (`moe_load_balancer_mode`), and registers weight slots and finalizes it after the weights load. | +| Executor | Wraps every forward in a balancer iteration, turns statistics and updates off during warmup, and shuts the balancer down. | +| Resolver | Builds a target for an EPLB deployment only if the target class lists the deployment's mode in `EPLB_MODES` (see [Routing](#routing)). | +| Target | Registers its MoE layers, loads its experts by slot, routes expert ids to slot ids, and declines in `route` the layouts it has not measured EPLB at. | + +A target reaches the balancer only through +[`catalog/moe/eplb.py`](catalog/moe/eplb.py). The balancer +(`_torch/moe/fused_moe/moe_load_balancer.py`) is engine runtime, like the KV +cache managers, not Modeling V1 model code. + +### Static EPLB in a target + +Static EPLB keeps the placement it starts with (`layer_updates_per_iter: 0`). +A target implements it in four steps. The +[DeepSeek R1 target](models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/) is +the example. + +1. **Slots.** `eplb_slots(model_config, layer_idx, num_experts)` returns a + routed MoE layer's slots on this rank: `num_slots`, this rank's + `slot_offset` and `local_slots`, and `slot_experts`, the expert each local + slot holds. The placement can differ by layer. Without EPLB every expert + has one slot and a rank's slots are its contiguous expert window, so one + code path serves both. +2. **Registration.** At construction, call + `EplbLayer.register(slots, top_k, repeat_count)` for every routed MoE + layer, in the order the layers run. That includes a draft layer from the + target's checkpoint, with `repeat_count` the number of times one forward + runs it (`max_draft_len` for one-model MTP). The loader builds the model + inside the balancer's context, so the registration reaches it. +3. **Weights.** Size every expert weight and per-expert scale by + `local_slots`, and fill slot `j` from checkpoint expert `slot_experts[j]`. + An expert in two slots is loaded twice, and a rank reads only the experts + its slots hold. +4. **Routing.** After the router's top-k, map the expert ids to slot ids + with `EplbLayer.route`, and call the expert kernels with `num_slots` as + the expert count and `[slot_offset, slot_offset + local_slots)` as this + rank's window. Every rank that routes the same tokens gets the same slots, + so a target that gathers its tokens before routing stays consistent. + +Then list the mode in the target class, `EPLB_MODES = frozenset({"static"})`, +and gate the layouts in `route` on `moe_eplb_mode(model_config)`. + +### 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. +* **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`). +* **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. + ## Writing operations Wrap each kernel call in a thin, stateless operation class that makes its diff --git a/tensorrt_llm/_torch/_experimental/modeling_v2/_router_index.py b/tensorrt_llm/_torch/_experimental/modeling_v2/_router_index.py index 618e88bf1da8..fe4c52f201bd 100644 --- a/tensorrt_llm/_torch/_experimental/modeling_v2/_router_index.py +++ b/tensorrt_llm/_torch/_experimental/modeling_v2/_router_index.py @@ -215,6 +215,19 @@ def engine_kv_cache_quant_algo(config: "ModelConfig", llm_args: "TorchLlmArgs"): return {"fp8": QuantAlgo.FP8, "nvfp4": QuantAlgo.NVFP4}.get(dtype, dtype) +def moe_eplb_mode(config: "ModelConfig") -> Optional[str]: + """The EPLB mode the engine runs this deployment with, for a route to gate layouts on. + + ``static``, ``online`` or ``per_layer_dynamic`` (see ``moe_load_balancer_mode``), + or None when the engine creates no MoE load balancer. Which modes a target + implements is not a route's check: the resolver compares this mode with the + target's ``EPLB_MODES``. + """ + from tensorrt_llm._torch.moe.fused_moe.moe_load_balancer import moe_load_balancer_mode + + return moe_load_balancer_mode(config, config.mapping) + + def _check_eplb_mode(target: type, config: "ModelConfig") -> None: """Raise ``NoTarget`` unless ``target`` implements the EPLB mode this deployment runs. @@ -225,10 +238,7 @@ def _check_eplb_mode(target: type, config: "ModelConfig") -> None: no layer to update under online EPLB. A target lists the modes it implements in the class attribute ``EPLB_MODES``; without it, none. """ - from tensorrt_llm._torch.moe.fused_moe.moe_load_balancer import ( - MOE_LOAD_BALANCER_MODES, - moe_load_balancer_mode, - ) + from tensorrt_llm._torch.moe.fused_moe.moe_load_balancer import MOE_LOAD_BALANCER_MODES implemented = frozenset(getattr(target, "EPLB_MODES", ())) unknown = implemented - MOE_LOAD_BALANCER_MODES @@ -237,7 +247,7 @@ def _check_eplb_mode(target: type, config: "ModelConfig") -> None: f"{target.__qualname__}.EPLB_MODES names {sorted(unknown)}; the EPLB modes are " f"{sorted(MOE_LOAD_BALANCER_MODES)}" ) - eplb = moe_load_balancer_mode(config, config.mapping) + eplb = moe_eplb_mode(config) if eplb is not None and eplb not in implemented: raise NoTarget( f"{eplb} EPLB (moe_config.load_balancer at moe_ep_size={config.mapping.moe_ep_size}); " diff --git a/tensorrt_llm/_torch/_experimental/modeling_v2/catalog/moe/eplb.py b/tensorrt_llm/_torch/_experimental/modeling_v2/catalog/moe/eplb.py new file mode 100644 index 000000000000..315bad7c9907 --- /dev/null +++ b/tensorrt_llm/_torch/_experimental/modeling_v2/catalog/moe/eplb.py @@ -0,0 +1,279 @@ +# 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. + +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 +the executor drives it on every forward. A target takes part in three steps, +and this module is what they share: + +1. `eplb_slots`: the slots of one MoE layer on this rank, that is which expert + each local slot holds. The target allocates and loads its expert weights by + slot. Without EPLB every expert has one slot and a rank holds a contiguous + window of them, so a target can read its experts through `EplbSlots` either + way. +2. `EplbLayer.register`: register the layer with the engine's balancer, at + construction and in the order the layers run. +3. `EplbLayer.route`: map the router's expert ids to slot ids before the expert + GEMMs, which then take `num_slots` as their expert count and this rank's + slot window as their local experts. + +`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 +declines EPLB deployments in any other mode (see the Modeling V2 README). +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Optional, Sequence + +import torch + +import tensorrt_llm._torch.custom_ops # noqa: F401 — registers torch.ops.trtllm.* +from tensorrt_llm._torch._experimental.modeling_v2._router_index import moe_eplb_mode +from tensorrt_llm._torch._experimental.modeling_v2.catalog._op import Arch, Cell, OpWrapper +from tensorrt_llm._torch.moe.fused_moe.moe_load_balancer import ( + SingleLayerMoeLoadBalancer, + get_moe_load_balancer, +) + + +def eplb_mode(model_config) -> Optional[str]: + """The EPLB mode the engine runs this deployment with: ``static``, ``online``, + ``per_layer_dynamic``, or None when it creates no load balancer.""" + if getattr(model_config, "moe_load_balancer", None) is None: + return None + return moe_eplb_mode(model_config) + + +@dataclass(frozen=True) +class EplbSlots: + """One MoE layer's expert slots on this rank. + + Attributes: + num_experts: The layer's experts. + num_slots: Slots over all EP ranks; ``num_experts`` without EPLB. + slot_offset: The global id of this rank's first slot. + slot_experts: The expert each of this rank's slots holds, in slot order. + global_assignments: The expert each global slot holds, in slot order. + """ + + num_experts: int + num_slots: int + slot_offset: int + slot_experts: tuple[int, ...] + global_assignments: tuple[int, ...] + + @property + def local_slots(self) -> int: + """Slots on this rank, ``num_slots / ep_size``.""" + return len(self.slot_experts) + + @classmethod + def from_assignments( + cls, assignments: Sequence[int], num_experts: int, ep_size: int, ep_rank: int + ) -> "EplbSlots": + """The slots of ``ep_rank`` when global slot ``j`` holds expert ``assignments[j]``. + + Raises: + ValueError: If the slots do not split evenly over the EP ranks, or do not + hold every expert at least once and nothing else. + """ + num_slots = len(assignments) + if num_slots % ep_size != 0: + raise ValueError(f"{num_slots} slots do not split evenly over {ep_size} EP ranks") + if sorted(set(assignments)) != list(range(num_experts)): + raise ValueError( + f"the {num_slots} slots must hold every one of the {num_experts} experts " + "at least once, and nothing else" + ) + local = num_slots // ep_size + offset = ep_rank * local + return cls( + num_experts=num_experts, + num_slots=num_slots, + slot_offset=offset, + slot_experts=tuple(assignments[offset : offset + local]), + global_assignments=tuple(assignments), + ) + + @classmethod + def without_eplb(cls, num_experts: int, ep_size: int, ep_rank: int) -> "EplbSlots": + """One slot per expert, each rank holding an equal contiguous window.""" + return cls.from_assignments(list(range(num_experts)), num_experts, ep_size, ep_rank) + + @classmethod + def from_config( + cls, config, layer_idx: int, num_experts: int, ep_size: int, ep_rank: int + ) -> "EplbSlots": + """The placement standard EPLB starts ``layer_idx`` with. + + ``config.initial_global_assignments[layer_idx]`` when the config gives + assignments, which then has to name the layer as the built-in MoE + requires; otherwise the built-in MoE's default, where rank ``r``'s slots + hold the experts from ``r * num_experts // ep_size`` on, wrapping. + """ + assignments = config.get_layer_initial_global_assignments(layer_idx) + if assignments is None: + if config.num_slots % ep_size != 0: + raise ValueError( + f"{config.num_slots} slots do not split evenly over {ep_size} EP ranks" + ) + local = config.num_slots // ep_size + assignments = [ + (rank * num_experts // ep_size + slot) % num_experts + for rank in range(ep_size) + for slot in range(local) + ] + return cls.from_assignments(assignments, num_experts, ep_size, ep_rank) + + +def eplb_slots(model_config, layer_idx: int, num_experts: int) -> EplbSlots: + """The slots of MoE layer ``layer_idx`` on this rank, with or without EPLB.""" + mapping = model_config.mapping + if eplb_mode(model_config) is None: + return EplbSlots.without_eplb(num_experts, mapping.moe_ep_size, mapping.moe_ep_rank) + return EplbSlots.from_config( + model_config.moe_load_balancer, + layer_idx, + num_experts, + mapping.moe_ep_size, + mapping.moe_ep_rank, + ) + + +class EplbRoute(OpWrapper): + """Map each token's expert ids to the global slots that hold those experts. + + `token_selected_experts` is `[T, top_k]` int32 global expert ids, and + `balancer_layer` the layer's handle in the engine's load balancer. The + result is `[T, top_k]` int32 global slot ids under the layer's current + placement. + + An expert held by one slot always maps to it. An expert with replicas maps + to one of them: the kernel spreads an expert's occurrences over its + replicas, and which replica it picks depends only on the input and, with + `offset_by_ep_rank`, on the rank. Ranks that route the same gathered tokens + with `offset_by_ep_rank=False` therefore agree on every slot, which a target + that gathers its tokens before routing needs. An id outside + `[0, num_experts)` maps to `num_slots`, a slot no rank holds. + """ + + ARCHS = frozenset({Arch.SM_100, Arch.SM_103}) + + CELLS: tuple[Cell, ...] = ( + Cell( + why="no replica: every expert held once, the kernel's direct lookup", + spec=dict(experts=256, slots=256, ep_size=4, top_k=8, tokens=64), + ), + Cell( + why="replicas: 288 slots over 256 experts at EP 4, 72 slots a rank", + spec=dict(experts=256, slots=288, ep_size=4, top_k=8, tokens=256), + ), + Cell( + why="more ids than one kernel block arbitrates (1024), so replicas are " + "spread per block", + spec=dict(experts=256, slots=288, ep_size=8, top_k=8, tokens=2048), + ), + Cell( + why="an expert held twice on the same rank, and a hot expert held four times", + spec=dict(experts=16, slots=32, ep_size=4, top_k=4, tokens=96, hot_replicas=4), + ), + ) + + def __call__( + self, + token_selected_experts: torch.Tensor, + balancer_layer: SingleLayerMoeLoadBalancer, + offset_by_ep_rank: bool = False, + ) -> torch.Tensor: + """Route `token_selected_experts` `[T, top_k]` to global slot ids `[T, top_k]`.""" + return torch.ops.trtllm.moe_load_balance_routing( + token_selected_experts, + offset_by_ep_rank, + balancer_layer.single_layer_load_balancer_ptr, + ) + + def reference( + self, + token_selected_experts: torch.Tensor, + balancer_layer: SingleLayerMoeLoadBalancer, + offset_by_ep_rank: bool = False, + ) -> torch.Tensor: + """The first slot that holds each expert, under the layer's current placement. + + Which replica the kernel picks is its own business (see the class + docstring), so the test holds the op to the reference's *expert*, and + holds the slot itself exactly only where an expert has one slot. + `offset_by_ep_rank` changes only the replica, so it is ignored here. + """ + placement = balancer_layer.single_layer_load_balancer_impl.get_old_rank_expert_ids() + slot_expert = torch.tensor( + [expert for rank in placement for expert in rank], dtype=torch.int64 + ) + num_slots = slot_expert.numel() + num_experts = balancer_layer.expert_count + first_slot = torch.full((num_experts,), num_slots, dtype=torch.int64) + for slot in range(num_slots - 1, -1, -1): + first_slot[slot_expert[slot]] = slot + ids = token_selected_experts.cpu().to(torch.int64) + out = torch.full_like(ids, num_slots) + valid = (ids >= 0) & (ids < num_experts) + out[valid] = first_slot[ids[valid]] + return out.to(torch.int32).to(token_selected_experts.device) + + +eplb_route = EplbRoute() + + +class EplbLayer: + """A MoE layer registered with the engine's load balancer, and its routing. + + 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. + + Attributes: + balancer_layer: The layer's handle in the engine's load balancer. + slots: The layer's slots on this rank. + """ + + def __init__(self, balancer_layer: SingleLayerMoeLoadBalancer, slots: EplbSlots): + self.balancer_layer = balancer_layer + self.slots = slots + + @classmethod + def register(cls, slots: EplbSlots, top_k: int, repeat_count: int = 1) -> "EplbLayer": + """Add the layer to the engine's load balancer with its initial placement. + + Args: + slots: The layer's slots on this rank; its `global_assignments` are the + initial placement. + top_k: Experts each token selects. + repeat_count: How many times one forward runs the layer, such as the + draft steps of a one-model MTP layer. + + Raises: + RuntimeError: If no load balancer is active, which means the layer is + built outside the model loader while the deployment runs EPLB. + """ + balancer = get_moe_load_balancer() + if balancer is None: + raise RuntimeError( + "this deployment runs EPLB, but no MoE load balancer is active: register " + "the MoE layers while the model loader builds the model" + ) + if repeat_count > 1: + balancer.set_repeated_for_next_layer(repeat_count) + balancer_layer = balancer.add_layer(slots.num_experts, top_k, slots.local_slots) + balancer_layer.set_initial_weight_assignments(list(slots.global_assignments)) + return cls(balancer_layer, slots) + + def route(self, token_selected_experts: torch.Tensor) -> torch.Tensor: + """Global expert ids `[T, top_k]` int32 -> global slot ids `[T, top_k]` int32. + + Routes with `offset_by_ep_rank=False`, so every rank that routes the same + tokens gets the same slots. + """ + return eplb_route(token_selected_experts, self.balancer_layer, False) diff --git a/tensorrt_llm/_torch/_experimental/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/modeling.py b/tensorrt_llm/_torch/_experimental/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/modeling.py index cafe194744ce..8257ffabacf1 100644 --- a/tensorrt_llm/_torch/_experimental/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/modeling.py +++ b/tensorrt_llm/_torch/_experimental/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/modeling.py @@ -26,6 +26,11 @@ 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`. + 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 same op, and its routed experts the same round trip around a bf16 expert call. Its @@ -73,6 +78,7 @@ from tensorrt_llm._torch._experimental.modeling_v2.catalog.gemm.bmm_out import bmm_out from tensorrt_llm._torch._experimental.modeling_v2.catalog.gemm.cublas_mm import cublas_mm from tensorrt_llm._torch._experimental.modeling_v2.catalog.gemm.nvfp4_gemm import nvfp4_gemm +from tensorrt_llm._torch._experimental.modeling_v2.catalog.moe.eplb import EplbLayer from tensorrt_llm._torch._experimental.modeling_v2.catalog.moe.fp4_block_scale_moe_runner import ( # noqa: E501 fp4_block_scale_moe_runner, ) @@ -346,6 +352,16 @@ def __init__(self, model_config: ModelConfig): self.dims = _weights.MODEL_WEIGHTS.dims(self) self.w = _weights.MODEL_WEIGHTS.declare(self.dims) + # 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" + self.eplb_layers: dict[int, EplbLayer] = {} + if self.dims.eplb is not None: + for i, slots in self.dims.slots.items(): + repeat = model_config.spec_config.max_draft_len if i == self.dims.num_layers else 1 + self.eplb_layers[i] = EplbLayer.register(slots, cfg.num_experts_per_tok, repeat) + self._rope: dict | None = None self._rope_positions = 0 self._side_stream: torch.cuda.Stream | None = None @@ -520,7 +536,8 @@ class _LayerWeights(NamedTuple): GEMM operands are `.t()` views; `k_b` / `v_b_t` are the two halves of this rank's `kv_b` in the shapes the absorbed-q and expand BMMs take; `norm_next` is the *next* layer's input norm (the final norm on the last layer). The MoE fields are None on the - dense layers. + dense layers. The per-expert scales are this rank's slots' (`dims.slots`), and `eplb` + is the layer's handle in the engine's load balancer under EPLB, None otherwise. """ qa: torch.Tensor @@ -552,6 +569,7 @@ class _LayerWeights(NamedTuple): out1_scale: torch.Tensor | None out1_gate_scale: torch.Tensor | None out2_scale: torch.Tensor | None + eplb: EplbLayer | None def _layer_views(core: DeepseekV3DefaultModelingV2) -> list[_LayerWeights]: @@ -559,7 +577,6 @@ def _layer_views(core: DeepseekV3DefaultModelingV2) -> list[_LayerWeights]: d = core.dims w = core.w hn = d.heads * d.nope - window = slice(d.expert_offset, d.expert_offset + d.local_experts) layers = [] for i in range(d.num_layers): @@ -581,15 +598,18 @@ def _layer_views(core: DeepseekV3DefaultModelingV2) -> list[_LayerWeights]: out1_scale=None, out1_gate_scale=None, out2_scale=None, + eplb=None, ) if i >= d.dense_layers: # One quantization of the hidden states feeds every expert on every rank, so the # routed FC1 activation scale has to be a single value and the same value on all - # ranks, or the expert windows and intermediate slices no longer sum to the whole + # 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. - e_isc2 = w[f"l{i}_e_isc2"][window] - gate1 = (isc1[0] * w[f"l{i}_e_ws2_1"][window]).contiguous() + # 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() moe = dict( router=w[f"l{i}_router"].t(), router_bias=w[f"l{i}_router_bias"], @@ -600,7 +620,8 @@ def _layer_views(core: DeepseekV3DefaultModelingV2) -> list[_LayerWeights]: 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"][window]).contiguous(), + out2_scale=(e_isc2 * w[f"l{i}_e_ws2_2"][held]).contiguous(), + eplb=core.eplb_layers.get(i), ) layers.append( _LayerWeights( @@ -641,9 +662,14 @@ def _dense_mlp(x: torch.Tensor, L: _LayerWeights, dt) -> torch.Tensor: def _experts(core: DeepseekV3DefaultModelingV2, L: _LayerWeights, x: torch.Tensor) -> torch.Tensor: - """Route, quantize and run this rank's experts -- its EP window 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.""" + """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. + + 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.""" cfg = core.model_config.pretrained_config d = core.dims parts = [] @@ -657,6 +683,8 @@ def _experts(core: DeepseekV3DefaultModelingV2, L: _LayerWeights, x: torch.Tenso cfg.num_experts_per_tok, float(cfg.routed_scaling_factor), ) + if L.eplb is not None: + topk_ids = L.eplb.route(topk_ids) xq, xsf = fp4_quantize(chunk, L.moe_gscale, _SF_VEC, False, _SF_LINEAR) parts.append( fp4_block_scale_moe_runner( @@ -676,13 +704,13 @@ def _experts(core: DeepseekV3DefaultModelingV2, L: _LayerWeights, x: torch.Tenso output1_scale_scalar=L.out1_scale, output1_scale_gate_scalar=L.out1_gate_scale, output2_scale_scalar=L.out2_scale, - num_experts=d.num_experts, + num_experts=d.num_slots, top_k=cfg.num_experts_per_tok, n_group=None, topk_group=None, intermediate_size=d.moe_inter, - local_expert_offset=d.expert_offset, - local_num_experts=d.local_experts, + local_expert_offset=d.slot_offset, + local_num_experts=d.local_slots, routed_scaling_factor=None, routing_method_type=_ROUTING_METHOD_INERT, do_finalize=True, @@ -699,7 +727,8 @@ class _MtpWeights(NamedTuple): The attention fields are a trunk layer's, at layer `num_hidden_layers`; the experts (`fc1`, `fc2`) and the shared expert (`sh_gu`, `sh_dn`) are bf16, `enorm`, `hnorm`, - `eh` and `head_norm` are the module's own. + `eh` and `head_norm` are the module's own. `eplb` is the layer's handle in the engine's + load balancer under EPLB, None otherwise. """ enorm: torch.Tensor @@ -723,6 +752,7 @@ class _MtpWeights(NamedTuple): sh_gu: torch.Tensor sh_dn: torch.Tensor head_norm: torch.Tensor + eplb: EplbLayer | None def _mtp_views(core: DeepseekV3DefaultModelingV2) -> _MtpWeights: @@ -755,6 +785,7 @@ def _mtp_views(core: DeepseekV3DefaultModelingV2) -> _MtpWeights: sh_gu=w[f"l{j}_sh_gu"].t(), sh_dn=w[f"l{j}_sh_dn"].t(), head_norm=w[f"l{j}_head_norm"], + eplb=core.eplb_layers.get(j), ) @@ -768,9 +799,10 @@ def _mtp_shared(x: torch.Tensor, M: _MtpWeights) -> torch.Tensor: def _mtp_experts( core: DeepseekV3DefaultModelingV2, M: _MtpWeights, x: torch.Tensor ) -> torch.Tensor: - """Route and run this rank's bf16 MTP experts -- its EP window 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. + """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. `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 @@ -791,6 +823,8 @@ def _mtp_experts( cfg.num_experts_per_tok, float(cfg.routed_scaling_factor), ) + if M.eplb is not None: + topk_ids = M.eplb.route(topk_ids) parts.append( fused_moe( input=chunk, @@ -840,8 +874,8 @@ def _routed_attention_dp( set, and sum back to the rows this rank owns. Gathering before the router keeps the routing identical on every rank, so each token's - top-8 ids fall in exactly one expert window per moe_tp slice, and the reduce-scatter - sums each contribution once.""" + 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] 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 @@ -1910,6 +1944,10 @@ 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"}) + def __init__(self, model_config: ModelConfig): cfg = model_config.pretrained_config super().__init__( diff --git a/tensorrt_llm/_torch/_experimental/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/weights.py b/tensorrt_llm/_torch/_experimental/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/weights.py index 0ae579bddcf4..b50d9d0b3272 100644 --- a/tensorrt_llm/_torch/_experimental/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/weights.py +++ b/tensorrt_llm/_torch/_experimental/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/weights.py @@ -17,8 +17,13 @@ same group along their intermediate: a rank holds a slice of the gate and up rows and the matching down columns, and its output is a partial sum. -* **Experts** are split over the MoE EP group: a rank holds the contiguous id - window `[expert_offset, expert_offset + local_experts)`. +* **Experts** sit in slots, split evenly over the MoE EP group: a rank holds + `local_slots` slots from global slot `slot_offset` on, and `slots[i]` names + the expert each of them holds at layer `i`. Without EPLB each expert has one + 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. * **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 @@ -65,8 +70,9 @@ 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 (this rank's off-window experts, 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, and +what the MTP layer leaves: all of it without MTP, its two aliased keys with +it). """ from dataclasses import dataclass @@ -76,6 +82,8 @@ import torch import torch.nn as nn +from tensorrt_llm._torch._experimental.modeling_v2.catalog.moe.eplb import eplb_mode, eplb_slots + #: `layers=ALL_LAYERS` is the common case and the default. A sentinel rather #: than a lambda so the table reads as data, and rather than `True` so the #: field has one type of answer: which layers. @@ -382,16 +390,17 @@ def _pair(a, b): def _expert_window(suffix, *, pair_with=None): - """This rank's EP window of the routed experts, one source per local expert. + """This rank's slots of the routed experts, one source per slot. - The checkpoint key depends on the rank -- `expert_offset` is this rank's first - expert -- which is why the source is computed rather than templated. + 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. """ def build(d, i): out = [] - for local in range(d.local_experts): - q = f"model.layers.{i}.mlp.experts.{d.expert_offset + local}" + 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: @@ -594,7 +603,7 @@ class DeepseekV3DefaultWeights: # --- this rank's routed experts, NVFP4, at its moe_tp slice --- W( "fc1_w", - shape=lambda d: (d.local_experts, 2 * d.moe_inter, d.hidden // 2), + shape=lambda d: (d.local_slots, 2 * d.moe_inter, d.hidden // 2), dtype=torch.uint8, src=_expert_window("gate_proj.weight", pair_with="up_proj.weight"), cut=_rows(_expert_rows), @@ -603,7 +612,7 @@ class DeepseekV3DefaultWeights: ), W( "fc1_s", - shape=lambda d: (d.local_experts, 2 * d.moe_inter, d.hidden // SF_BLOCK), + shape=lambda d: (d.local_slots, 2 * d.moe_inter, d.hidden // SF_BLOCK), dtype=torch.uint8, src=_expert_window("gate_proj.weight_scale", pair_with="up_proj.weight_scale"), cut=_rows(_expert_rows), @@ -612,7 +621,7 @@ class DeepseekV3DefaultWeights: ), W( "fc2_w", - shape=lambda d: (d.local_experts, d.hidden, d.moe_inter // 2), + shape=lambda d: (d.local_slots, d.hidden, d.moe_inter // 2), dtype=torch.uint8, src=_expert_window("down_proj.weight"), cut=_cols(_expert_cols_w), @@ -621,7 +630,7 @@ class DeepseekV3DefaultWeights: ), W( "fc2_s", - shape=lambda d: (d.local_experts, d.hidden, d.moe_inter // SF_BLOCK), + shape=lambda d: (d.local_slots, d.hidden, d.moe_inter // SF_BLOCK), dtype=torch.uint8, src=_expert_window("down_proj.weight_scale"), cut=_cols(_expert_cols_s), @@ -688,7 +697,7 @@ class DeepseekV3DefaultWeights: # This rank's EP window of the bf16 routed experts, at its moe_tp slice. W( "fc1", - shape=lambda d: (d.local_experts, 2 * d.moe_inter, d.hidden), + shape=lambda d: (d.local_slots, 2 * d.moe_inter, d.hidden), src=_expert_window("gate_proj.weight", pair_with="up_proj.weight"), cut=_rows(_expert_rows), transform=_mtp_fc1, @@ -696,7 +705,7 @@ class DeepseekV3DefaultWeights: ), W( "fc2", - shape=lambda d: (d.local_experts, d.hidden, d.moe_inter), + shape=lambda d: (d.local_slots, d.hidden, d.moe_inter), src=_expert_window("down_proj.weight"), cut=_cols(_expert_cols_bf16), layers=_mtp_only, @@ -769,7 +778,7 @@ def read(self, weights, ckpt_key, cut: Cut | None, transform, core, device=None) return src_all[0] def expected_unconsumed(self, core, weights) -> set: - return _offwindow_expert_keys(core) | _mtp_keys(core, weights) + return _unheld_expert_keys(core) | _mtp_keys(core, weights) def load(self, model, weights) -> None: """Fill every declared weight from the checkpoint. Each source is read through @@ -816,7 +825,7 @@ def fill(param: torch.nn.Parameter, ckpt_key, index, cut, transform) -> None: expected = self.expected_unconsumed(core, weights) assert leftover == expected, ( "checkpoint coverage: leftover keys are not exactly this rank's " - f"off-window experts plus what the MTP layer leaves; unexpected " + f"unheld experts plus what the MTP layer leaves; unexpected " f"{sorted(leftover - expected)[:8]}, missed {sorted(expected - leftover)[:8]}" ) @@ -833,8 +842,12 @@ def dims(self, core) -> SimpleNamespace: attn_tp_rank = 0 if attention_dp else m.tp_rank heads_total = cfg.num_attention_heads assert heads_total % attn_tp == 0, (heads_total, attn_tp) - assert cfg.n_routed_experts % m.moe_ep_size == 0, (cfg.n_routed_experts, m.moe_ep_size) - local_experts = cfg.n_routed_experts // m.moe_ep_size + # Each routed MoE layer's slots on this rank, in the order the layers run: + # the trunk's, then the MTP layer's. Every layer has the same number of + # slots; under EPLB the expert each slot holds differs by layer. + moe_layers = range(cfg.first_k_dense_replace, cfg.num_hidden_layers + int(mtp_enabled)) + slots = {i: eplb_slots(core.model_config, i, cfg.n_routed_experts) for i in moe_layers} + layout = slots[cfg.first_k_dense_replace] shared_full = cfg.moe_intermediate_size * cfg.n_shared_experts # The built-in model sizes the dense MLP's TP down when it would cross # nodes (`_compute_mlp_tp_size`); this target splits it over the whole @@ -877,8 +890,11 @@ def dims(self, core) -> SimpleNamespace: moe_inter=cfg.moe_intermediate_size // m.moe_tp_size, moe_ep=m.moe_ep_size, moe_ep_rank=m.moe_ep_rank, - local_experts=local_experts, - expert_offset=local_experts * m.moe_ep_rank, + eplb=eplb_mode(core.model_config), + slots=slots, + num_slots=layout.num_slots, + local_slots=layout.local_slots, + slot_offset=layout.slot_offset, mtp_enabled=mtp_enabled, dtype=core.model_config.torch_dtype, ) @@ -909,21 +925,21 @@ def pad(t: torch.Tensor, core) -> torch.Tensor: return (slice(start, stop),), pad -def _offwindow_expert_keys(core) -> set: +def _unheld_expert_keys(core) -> set: """The first predicted non-load: the weight/scale tensors of every routed - expert outside this rank's EP window. 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. 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 off-window + 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 - lo, hi = d.expert_offset, d.expert_offset + d.local_experts keys = set() for i in _router_layers(d): quantized = i < d.num_layers + held = set(d.slots[i].slot_experts) for e in range(d.num_experts): - if lo <= e < hi: + if e in held: continue q = f"model.layers.{i}.mlp.experts.{e}" for proj in ("gate_proj", "up_proj", "down_proj"): @@ -940,8 +956,8 @@ def _mtp_keys(core, weights) -> set: land here. Without MTP that is those layers whole -- on this checkpoint layer 61's 790 - keys. With MTP the table consumes all but two per rank (and this rank's - off-window experts, which the family above names): `embed_tokens` and + keys. With MTP the table consumes all but two per rank (and the experts + this rank's slots do not hold, which the family above names): `embed_tokens` and `shared_head.head` are bitwise copies of the trunk's embedding and `lm_head`, which the draft model reads instead of loading them twice.""" cfg = core.model_config.pretrained_config diff --git a/tensorrt_llm/_torch/_experimental/modeling_v2/models/deepseek_v3/routing.py b/tensorrt_llm/_torch/_experimental/modeling_v2/models/deepseek_v3/routing.py index aeaf7e8aa266..55b8fee1e882 100644 --- a/tensorrt_llm/_torch/_experimental/modeling_v2/models/deepseek_v3/routing.py +++ b/tensorrt_llm/_torch/_experimental/modeling_v2/models/deepseek_v3/routing.py @@ -16,7 +16,13 @@ from tensorrt_llm.llmapi.llm_args import MTPDecodingConfig from tensorrt_llm.quantization.mode import QuantAlgo -from ..._router_index import NoTarget, engine_kv_cache_quant_algo, routes, tp_reaches_across_nodes +from ..._router_index import ( + NoTarget, + engine_kv_cache_quant_algo, + moe_eplb_mode, + routes, + tp_reaches_across_nodes, +) # The GPUs the target is certified on: sm_100 (B200, GB200) and sm_103 (B300, # GB300). They run the same kernels. @@ -69,6 +75,16 @@ } ) +# The layouts at which static EPLB was measured. EPLB balances attention DP over +# expert-parallel ranks that each hold whole experts, which is the built-in +# model's requirement too, so only attention-DP layouts with moe_tp 1 qualify. +_EPLB_LAYOUTS = frozenset( + { + (4, True, 1, 4), # dep4 + (8, True, 1, 8), # dep8 + } +) + if TYPE_CHECKING: from tensorrt_llm._torch.model_config import ModelConfig from tensorrt_llm.llmapi.llm_args import TorchLlmArgs @@ -156,6 +172,15 @@ def route( "ep8, tp8 or tp2 x ep4, and dep16" ) + # Under EPLB the target loads its experts by slot and routes ids to slots. Which EPLB + # modes it implements is the resolver's check (`EPLB_MODES`); where it was measured + # is this one. + eplb = moe_eplb_mode(model_config) + if eplb is not None and layout not in _EPLB_LAYOUTS: + raise NoTarget( + f"{eplb} EPLB at parallel layout {split}; the default target runs EPLB at dep4 and dep8" + ) + # Attention TP across nodes reduces only over multi-node NVLink. if not tp_reaches_across_nodes(mapping): raise NoTarget( 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 584a77d9ae0b..2ba6e1176a0e 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 @@ -26,12 +26,15 @@ so it reaches the ranks the way the rest of the arguments do. """ +import random + import pytest from tensorrt_llm import LLM from tensorrt_llm._torch._experimental.modeling_v2 import MODELING_V2_VALIDATE_ENV from tensorrt_llm._utils import get_sm_version -from tensorrt_llm.llmapi import CudaGraphConfig, KvCacheConfig, MTPDecodingConfig +from tensorrt_llm.llmapi import CudaGraphConfig, KvCacheConfig, MoeConfig, MTPDecodingConfig +from tensorrt_llm.llmapi.llm_args import MoeLoadBalancerConfig from .....conftest import llm_models_root from ....accuracy_core import ( @@ -106,6 +109,31 @@ 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. +_EPLB_LAYOUTS = [p for i in ("dep4", "dep8") for p in _LAYOUTS if p.id == i] + + +def _eplb_placement(layer: int, experts: int, slots: int, ep_size: int) -> list: + """A static EPLB placement unlike the built-in default, drawn per layer. + + The experts shuffled by layer, each rank holding its share once; then each rank's + spare slots hold experts again: first one it already holds, then experts of the + ranks after it. A slot loaded with the wrong expert, or an id routed to a slot that + does not hold its expert, still produces fluent text, so only a placement this far + from the default shows up in the score. + """ + order = list(range(experts)) + random.Random(layer).shuffle(order) + per_rank, spare = experts // ep_size, (slots - experts) // ep_size + out = [] + for rank in range(ep_size): + own = order[rank * per_rank : (rank + 1) * per_rank] + extra = [order[(rank * per_rank + per_rank + k) % experts] for k in range(spare)] + extra[0] = own[0] + out += own + extra + return out + + class TestModelingV2DeepseekR10528Nvfp4Sm10xDefault(LlmapiAccuracyTestHarness): """deepseek-r1-0528-nvfp4 / sm_10x / default, identity and the mtp3 variant. @@ -297,3 +325,40 @@ def test_gsm8k_chunked_prefill(self, mocker, parallel): ): task = GSM8K(self.MODEL_NAME) task.evaluate(llm) + + @skip_not_sm10x + @pytest.mark.parametrize("mtp", [False, True], ids=["no_spec", "mtp3"]) + @pytest.mark.parametrize("parallel", _EPLB_LAYOUTS) + def test_gsm8k_static_eplb(self, mocker, parallel, mtp): + """Static EPLB at a placement drawn per layer, the MTP layer included. + + 288 slots hold the 256 experts of every routed layer. Every layer registers + with the engine's load balancer, loads its experts by slot and routes the + router's ids to slots, so this is the whole EPLB path of the target against + the same GSM8K reference as the identity cases. + """ + mocker.patch.dict(GSM8K.EVALUATE_KWARGS, _SCORES_FILTER) + cfg_layers, first_moe, num_slots = 61, 3, 288 + ep_size = parallel["moe_expert_parallel_size"] + assignments = { + i: _eplb_placement(i, 256, num_slots, ep_size) + for i in range(first_moe, cfg_layers + int(mtp)) + } + load_balancer = MoeLoadBalancerConfig( + num_slots=num_slots, initial_global_assignments=assignments + ) + spec = dict(speculative_config=self.MTP3, kv_cache_config=self.MTP3_KV) 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) diff --git a/tests/integration/test_lists/test-db/l0_cpu.yml b/tests/integration/test_lists/test-db/l0_cpu.yml index 6d3c9b44f063..f1491b833827 100644 --- a/tests/integration/test_lists/test-db/l0_cpu.yml +++ b/tests/integration/test_lists/test-db/l0_cpu.yml @@ -136,6 +136,7 @@ l0_cpu: - unittest/_torch/modeling_v2/test_modeling_v2_reference_precision.py - unittest/_torch/modeling_v2/test_modeling_v2_fp4_test_helpers.py - unittest/_torch/modeling_v2/test_modeling_v2_routing.py + - unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py - unittest/_torch/modeling_v2/comm/test_modeling_v2_rank_equality.py - unittest/_torch/modeling_v2/comm/test_modeling_v2_rank_job.py # The GPU stages run with -m "not cpu_only", so this entry is what runs it. 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 6283d4b80a49..66a63c313f7f 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 @@ -31,6 +31,8 @@ l0_gb300_multi_gpus: - accuracy/modeling_v2/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_accuracy.py::TestModelingV2DeepseekR10528Nvfp4Sm10xDefault::test_gsm8k[dep4_moetp4] - accuracy/modeling_v2/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_accuracy.py::TestModelingV2DeepseekR10528Nvfp4Sm10xDefault::test_gsm8k_chunked_prefill[tp4_ep4] - 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/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 # qwen4_exp target, post-merge: three drafts over quantized KV -- NVFP4 KV at tp4 with the 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 543dfa95bcd4..f96a9da59404 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 @@ -24,6 +24,7 @@ l0_gb300_multi_nodes_node2_gpu8: - accuracy/modeling_v2/gpt_oss/gpt_oss_120b__sm_10x__default/test_accuracy.py::TestModelingV2GptOss120bSm10xDefault::test_gsm8k[dep8] - 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] # 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 618556d413eb..077e051673e2 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 @@ -36,6 +36,7 @@ import math import zlib +from collections import Counter from types import SimpleNamespace import pytest @@ -46,6 +47,7 @@ from tensorrt_llm._torch._experimental.modeling_v2.models.deepseek_v3.r1_0528_nvfp4__sm_10x__default import ( # noqa: E501 weights as D, ) +from tensorrt_llm.llmapi.llm_args import MoeLoadBalancerConfig from tensorrt_llm.mapping import Mapping pytestmark = pytest.mark.cpu_only @@ -343,8 +345,12 @@ def test_shares_tile_intermediates_and_experts(layout): for tp_slot in range(layout[2]): slot = [d for d in dims if d.moe_tp_rank == tp_slot] - experts = sorted(e for d in slot for e in _blocks(d.expert_offset, d.local_experts)) + experts = sorted(e for d in slot for e in _blocks(d.slot_offset, d.local_slots)) assert experts == list(range(cfg.n_routed_experts)), (tp_slot, experts[:8]) + # Without EPLB every expert has one slot, so a rank's slots are its window. + for d in slot: + for slots in d.slots.values(): + assert slots.slot_experts == tuple(_blocks(d.slot_offset, d.local_slots)) @pytest.mark.parametrize("layout", _ATTN_LAYOUTS, ids=_layout_id) @@ -446,7 +452,7 @@ def test_expert_operands_are_the_ws1_operands_of_the_rank_share(layout): d = core.dims share = _cfg(hidden_size=256, moe_intermediate_size=d.moe_inter) rows, cols2, cols16 = _intermediate_index(d.moe_tp_rank * d.moe_inter, d.moe_inter, True) - for local in (0, d.local_experts - 1): + for local in (0, d.local_slots - 1): ckpt = _Checkpoint(cfg) for name, index in ( ("fc1_w", (rows,)), @@ -500,7 +506,7 @@ def test_mtp_expert_operands_are_the_ws1_operands_of_the_rank_share(layout): d = core.dims share = _cfg(hidden_size=256, moe_intermediate_size=d.moe_inter) rows, cols, _ = _intermediate_index(d.moe_tp_rank * d.moe_inter, d.moe_inter, False) - for local in (0, d.local_experts - 1): + for local in (0, d.local_slots - 1): ckpt = _Checkpoint(cfg) for name, index in (("fc1", (rows,)), ("fc2", (slice(None), cols))): param = f"l{layer}_{name}" @@ -514,7 +520,7 @@ def test_mtp_expert_operands_are_the_ws1_operands_of_the_rank_share(layout): ) # FC1 is [up ; gate], the order fused_moe reads, opposite to the dense # gate_up linear's. - q = f"model.layers.{layer}.mlp.experts.{d.expert_offset + local}" + q = f"model.layers.{layer}.mlp.experts.{d.slot_offset + local}" fc1, _, _ = _read_source(core, _Checkpoint(cfg), f"l{layer}_fc1", local) up, gate = _full(f"{q}.up_proj.weight", cfg), _full(f"{q}.gate_proj.weight", cfg) assert torch.equal(fc1, torch.cat([up[rows], gate[rows]])), (layout, rank, local) @@ -713,8 +719,8 @@ def test_load_reads_only_the_rank_share(layout, mtp, monkeypatch): assert not read_mtp, sorted(read_mtp)[:4] continue # Every lazy key of the layer (the 0-dim KV scales are not reads) but the two - # aliased ones and the off-window experts. - lo, hi = d.expert_offset, d.expert_offset + d.local_experts + # aliased ones and the experts this rank's slots do not hold. + lo, hi = d.slot_offset, d.slot_offset + d.local_slots want = { k for k in keys @@ -724,3 +730,115 @@ 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]) + + +# --- static EPLB: a rank's slots hold the experts the placement gives them --- + +_EPLB_LAYOUTS = sorted(routing._EPLB_LAYOUTS) + + +def _placement(layer: int, num_experts: int, ep_size: int, spare: int) -> list[int]: + """A placement unlike the default one: the experts shuffled per layer, then `spare` + more slots a rank holding other experts again -- on rank 0 a second copy of an expert + it already holds.""" + order = torch.randperm(num_experts, generator=torch.Generator().manual_seed(layer)).tolist() + per_rank = num_experts // ep_size + out = [] + for rank in range(ep_size): + own = order[rank * per_rank : (rank + 1) * per_rank] + extra = [order[(rank * per_rank + per_rank + k) % num_experts] for k in range(spare)] + if rank == 0: + extra[0] = own[0] + out += own + extra + 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.""" + 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} + pretrained = SimpleNamespace(**vars(cfg), architectures=["DeepseekV3ForCausalLM"]) + core = SimpleNamespace( + model_config=SimpleNamespace( + pretrained_config=pretrained, + mapping=_mapping(layout, rank), + torch_dtype=torch.bfloat16, + spec_config=object() if mtp else None, + moe_load_balancer=MoeLoadBalancerConfig( + num_slots=cfg.n_routed_experts + ep * spare, + initial_global_assignments=assignments, + ), + ) + ) + core.dims = D.MODEL_WEIGHTS.dims(core) + return core, assignments + + +@pytest.mark.parametrize("layout", _EPLB_LAYOUTS, ids=_layout_id) +def test_eplb_slots_hold_the_placed_experts(layout): + """Rank r holds slots [r * S, (r + 1) * S) of every routed layer, S = num_slots / ep, + and each slot the expert the placement puts there; together the ranks hold every + expert of every layer, the MTP layer's included.""" + cfg = SimpleNamespace(**_TINY) + ep = layout[3] + held: dict = {} + for rank in range(layout[0]): + core, assignments = _eplb_core(layout, rank, cfg, mtp=True) + d = core.dims + local = (cfg.n_routed_experts + 2 * ep) // ep + assert (d.eplb, d.num_slots, d.local_slots, d.slot_offset) == ( + "static", + local * ep, + local, + rank * local, + ) + for i, placement in assignments.items(): + mine = tuple(placement[rank * local : (rank + 1) * local]) + assert d.slots[i].slot_experts == mine, (layout, rank, i) + held.setdefault(i, set()).update(mine) + assert all(experts == set(range(cfg.n_routed_experts)) for experts in held.values()) + + +@pytest.mark.parametrize("mtp", [False, True], ids=["no_mtp", "mtp"]) +@pytest.mark.parametrize("layout", _EPLB_LAYOUTS, ids=_layout_id) +def test_eplb_load_fills_every_slot_with_its_expert(layout, mtp, monkeypatch): + """`load` under static EPLB: coverage holds both ways, a rank reads each expert's + tensors once per slot that holds it and no expert it does not hold, and every slot + holds exactly what the world-size-1 table, which has no EPLB, loads for that slot's + expert.""" + 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) + for rank in range(layout[0]): + core, assignments = _eplb_core(layout, rank, cfg, mtp) + d = core.dims + 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) + + 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") + ) + 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) + assert torch.equal(core.w[f"l{i}_{name}"][slot], want), (rank, i, slot, name) 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 new file mode 100644 index 000000000000..1a0301ead26f --- /dev/null +++ b/tests/unittest/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_modeling_v2_deepseek_eplb.py @@ -0,0 +1,129 @@ +# 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. + +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. +""" + +from __future__ import annotations + +import random + +import pytest +import torch +from transformers import DeepseekV3Config + +from tensorrt_llm._torch._experimental.modeling_v2.models.deepseek_v3.r1_0528_nvfp4__sm_10x__default.modeling import ( # noqa: E501 + DeepseekV3DefaultModelingV2, +) +from tensorrt_llm._torch.model_config import ModelConfig +from tensorrt_llm._torch.models.modeling_utils import MetaInitMode +from tensorrt_llm._torch.moe.fused_moe.moe_load_balancer import MoeLoadBalancer +from tensorrt_llm.llmapi.llm_args import MoeLoadBalancerConfig, MTPDecodingConfig +from tensorrt_llm.mapping import Mapping +from tensorrt_llm.models.modeling_utils import QuantConfig +from tensorrt_llm.quantization.mode import QuantAlgo + +pytestmark = pytest.mark.skipif( + not torch.cuda.is_available() or torch.cuda.get_device_capability() not in ((10, 0), (10, 3)), + reason="the target is certified on sm_100 and sm_103", +) + +# DeepSeek-R1-0528's config.json, the fields the target reads. +_R1 = dict( + architectures=["DeepseekV3ForCausalLM"], + num_hidden_layers=61, + hidden_size=7168, + num_attention_heads=128, + qk_nope_head_dim=128, + qk_rope_head_dim=64, + v_head_dim=128, + kv_lora_rank=512, + q_lora_rank=1536, + vocab_size=129280, + first_k_dense_replace=3, + n_routed_experts=256, + num_experts_per_tok=8, + n_group=8, + topk_group=4, + routed_scaling_factor=2.5, + moe_intermediate_size=2048, + n_shared_experts=1, + intermediate_size=18432, + num_nextn_predict_layers=1, + max_position_embeddings=163840, + rms_norm_eps=1e-6, + rope_theta=10000, + rope_scaling=dict( + type="yarn", + factor=40, + original_max_position_embeddings=4096, + beta_fast=32, + beta_slow=1, + mscale=1.0, + mscale_all_dim=1.0, + ), + dtype=torch.bfloat16, +) +_EP, _RANK, _SLOTS = 4, 1, 288 + + +def _placement(layer: int) -> list: + """A per-layer placement of 288 slots: the experts shuffled, then 8 spare slots a rank.""" + order = list(range(256)) + random.Random(layer).shuffle(order) + out = [] + for rank in range(_EP): + own = order[rank * 64 : (rank + 1) * 64] + out += own + [own[0]] + order[(rank + 1) * 64 % 256 :][:7] + return out + + +@pytest.mark.parametrize("mtp", [False, True], ids=["no_spec", "mtp3"]) +def test_static_eplb_registers_every_routed_layer(mtp): + 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.setup(ep_rank=_RANK, ep_size=_EP) + model_config = ModelConfig( + pretrained_config=DeepseekV3Config(**_R1), + mapping=Mapping( + world_size=_EP, + rank=_RANK, + tp_size=_EP, + moe_tp_size=1, + moe_ep_size=_EP, + enable_attention_dp=True, + ), + quant_config=QuantConfig(quant_algo=QuantAlgo.NVFP4, kv_cache_quant_algo=QuantAlgo.FP8), + moe_load_balancer=load_balancer, + spec_config=MTPDecodingConfig(max_draft_len=3) if mtp else None, + ) + + balancer = MoeLoadBalancer(ep_rank=_RANK, ep_size=_EP, layer_updates_per_iter=0) + try: + with balancer, MetaInitMode(): + core = DeepseekV3DefaultModelingV2(model_config) + + registered = balancer.single_layer_load_balancers + assert list(core.eplb_layers) == list(layers) + assert [eplb.balancer_layer for eplb in core.eplb_layers.values()] == registered + repeats = [layer.get_repeat_count() for layer in registered] + assert repeats == [1] * 58 + ([3] if mtp else []) + for i, layer in zip(layers, registered): + placement = layer.single_layer_load_balancer_impl.get_old_rank_expert_ids() + assert sum(placement, []) == assignments[i], i + + d = core.dims + assert (d.eplb, d.num_slots, d.local_slots, d.slot_offset) == ("static", 288, 72, 72) + for i in layers: + mine = tuple(assignments[i][72:144]) + assert d.slots[i].slot_experts == mine + name = "fc1_w" if i < 61 else "fc1" + assert core.w[f"l{i}_{name}"].shape[0] == 72 + finally: + balancer.shutdown() 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 68bb49d54e35..50befa84e44d 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 @@ -55,8 +55,9 @@ def _core(mtp: bool): """The configuration surface the table reads, at the dep4 layout: attention DP over four ranks, the experts split four ways, this rank the second. - `dims` derives the expert window from the mapping; the reference below hard-codes - the hand-written `local_experts`, so the comparison also checks that the two agree. + `dims` derives the expert slots from the mapping; the reference below hard-codes + the hand-written expert count per rank, so the comparison also checks that the two + agree. """ cfg = SimpleNamespace(**_CFG) mapping = SimpleNamespace( diff --git a/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py b/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py new file mode 100644 index 000000000000..a0f72ab24fdd --- /dev/null +++ b/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py @@ -0,0 +1,348 @@ +# 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. + +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. +""" + +from __future__ import annotations + +import zlib +from collections.abc import Iterator +from unittest.mock import MagicMock, patch + +import pytest +import torch + +from tensorrt_llm._torch._experimental.modeling_v2.catalog._op import Cell +from tensorrt_llm._torch._experimental.modeling_v2.catalog.moe.eplb import EplbLayer, EplbSlots +from tensorrt_llm._torch._experimental.modeling_v2.catalog.moe.eplb import eplb_route as op +from tensorrt_llm._torch.moe.fused_moe.moe_load_balancer import ( + MoeLoadBalancer, + get_moe_load_balancer, +) +from tensorrt_llm.llmapi.llm_args import MoeLoadBalancerConfig + +__extra_import_path__ = [".."] +from _cells import certified_cells # noqa: E402 — needs the path declared above +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") + + +# --- slot layouts (CPU) --------------------------------------------------------------------- + + +@pytest.mark.cpu_only +@pytest.mark.parametrize("ep_rank", range(4)) +def test_without_eplb_a_rank_holds_a_contiguous_window(ep_rank): + slots = EplbSlots.without_eplb(256, 4, ep_rank) + assert (slots.num_slots, slots.local_slots, slots.slot_offset) == (256, 64, 64 * ep_rank) + assert slots.slot_experts == tuple(range(64 * ep_rank, 64 * ep_rank + 64)) + + +@pytest.mark.cpu_only +def test_the_default_placement_is_the_builtin_moes(): + """Without assignments, rank r's slots hold the experts from r * E / ep on, wrapping: + at 288 slots over 4 ranks each rank's 72 slots repeat the next rank's first 8 experts, + and the last rank's wrap to experts 0-7.""" + config = MoeLoadBalancerConfig(num_slots=288) + layouts = [EplbSlots.from_config(config, 3, 256, 4, rank) for rank in range(4)] + for rank, slots in enumerate(layouts): + assert (slots.num_slots, slots.local_slots, slots.slot_offset) == (288, 72, 72 * rank) + assert layouts[0].slot_experts == tuple(range(72)) + assert layouts[3].slot_experts == tuple(range(192, 256)) + tuple(range(8)) + assert layouts[0].global_assignments == sum((s.slot_experts for s in layouts), ()) + + +@pytest.mark.cpu_only +def test_given_assignments_place_each_layer(): + a3 = [3, 0, 1, 3, 2, 3, 1, 0] + a4 = [0, 1, 2, 3, 0, 1, 2, 3] + config = MoeLoadBalancerConfig(num_slots=8, initial_global_assignments={3: a3, 4: a4}) + assert EplbSlots.from_config(config, 3, 4, 2, 0).slot_experts == (3, 0, 1, 3) + assert EplbSlots.from_config(config, 3, 4, 2, 1).slot_experts == (2, 3, 1, 0) + assert EplbSlots.from_config(config, 4, 4, 2, 1).slot_experts == (0, 1, 2, 3) + with pytest.raises(KeyError): + EplbSlots.from_config(config, 5, 4, 2, 0) + + +@pytest.mark.cpu_only +@pytest.mark.parametrize( + "assignments, missed", + [ + ([0, 1, 2, 0, 1, 2], "every one of the 4 experts"), # expert 3 has no slot + ([0, 1, 2, 3, 4, 0], "every one of the 4 experts"), # an expert that does not exist + ([0, 1, 2, 3, 0], "do not split evenly"), + ], +) +def test_a_placement_that_loses_an_expert_is_refused(assignments, missed): + with pytest.raises(ValueError, match=missed): + EplbSlots.from_assignments(assignments, 4, 2, 0) + + +@pytest.fixture +def mocked_runtime() -> Iterator[MagicMock]: + """The C++ balancer and the node's MPI communicator, mocked: registration is the + Python side's contract.""" + shared_comm = MagicMock() + shared_comm.Get_rank.return_value = 1 + shared_comm.Get_size.return_value = 4 + with ( + patch("tensorrt_llm.bindings.internal.runtime.MoeLoadBalancer") as runtime, + patch.object( + MoeLoadBalancer, + "_setup_mpi_comm", + lambda self: setattr(self, "shared_mpi_comm", shared_comm), + ), + ): + yield runtime + + +@pytest.mark.cpu_only +def test_registering_without_the_engines_balancer_is_an_error(): + assert get_moe_load_balancer() is None + with pytest.raises(RuntimeError, match="no MoE load balancer is active"): + EplbLayer.register(EplbSlots.without_eplb(8, 2, 0), top_k=2) + + +@pytest.mark.cpu_only +def test_registering_adds_the_layer_with_its_placement(mocked_runtime): + """One `add_layer` per registration, sized by this rank's slots, then the global + placement; the MTP layer's repeat count reaches the balancer's layer.""" + config = MoeLoadBalancerConfig(num_slots=288) + slots = EplbSlots.from_config(config, 61, 256, 4, 1) + balancer = MoeLoadBalancer(ep_rank=1, ep_size=4, layer_updates_per_iter=0) + try: + with balancer: + layer = EplbLayer.register(slots, top_k=8, repeat_count=3) + impl = mocked_runtime.return_value + impl.add_layer.assert_called_once_with(256, 8, 72) + impl.add_layer.return_value.set_initial_weight_assignments.assert_called_once_with( + list(slots.global_assignments) + ) + assert balancer.single_layer_load_balancers == [layer.balancer_layer] + assert layer.balancer_layer.get_repeat_count() == 3 + assert layer.balancer_layer.is_static_routing() + assert layer.slots is slots + finally: + balancer.shutdown() + assert get_moe_load_balancer() is None + + +# --- the routing op (GPU) --------------------------------------------------------------------- + + +def _placement(experts: int, slots: int, ep_size: int, hot_replicas: int, seed: int) -> list: + """`slots` global slots over `ep_size` ranks, unlike the default placement. + + Every expert once, in a shuffled order; then the spare slots: the hottest expert + `hot_replicas` times in all, one more copy of others, and on rank 0 a second copy of + an expert rank 0 already holds. + """ + g = torch.Generator().manual_seed(seed) + order = torch.randperm(experts, generator=g).tolist() + per_rank, spare = experts // ep_size, (slots - experts) // ep_size + hot = order[-1] + extra = [hot] * min(hot_replicas - 1, ep_size * spare) + extra += [e for e in order if e != hot][: ep_size * spare - len(extra)] + out = [] + for rank in range(ep_size): + own = order[rank * per_rank : (rank + 1) * per_rank] + mine = extra[rank * spare : (rank + 1) * spare] + if rank == 0 and spare: + mine[0] = own[0] + out += own + mine + return out + + +def _expert_ids(tokens: int, experts: int, top_k: int, seed: int) -> torch.Tensor: + """`[tokens, top_k]` int32: each token's distinct experts, as a router emits them.""" + g = torch.Generator().manual_seed(seed) + rows = [torch.randperm(experts, generator=g)[:top_k] for _ in range(tokens)] + return torch.stack(rows).to(torch.int32).cuda() + + +class _Balancers: + """One static load balancer per EP rank, each holding the layer at `placement`: what + every rank of an EP group builds.""" + + def __init__(self, experts: int, top_k: int, placement: list, ep_size: int): + self.balancers = [MoeLoadBalancer(rank, ep_size, 0) for rank in range(ep_size)] + self.layers = [] + for balancer in self.balancers: + layer = balancer.add_layer(experts, top_k, len(placement) // ep_size) + layer.set_initial_weight_assignments(placement) + self.layers.append(layer) + + def shutdown(self) -> None: + for balancer in self.balancers: + balancer.shutdown() + + +# The shapes the default deepseek target routes, by target directory under `models/`: the +# 8192-row chunk its attention-DP gather fills, at the two layouts it runs EPLB at. +TARGET_CELLS: dict[str, tuple[Cell, ...]] = { + "deepseek_v3/r1_0528_nvfp4__sm_10x__default": ( + Cell( + why="deepseek default at dep4: 288 slots, an 8192-row chunk", + spec=dict(experts=256, slots=288, ep_size=4, top_k=8, tokens=8192), + ), + Cell( + why="deepseek default at dep8: 288 slots, 36 a rank, an 8192-row chunk", + spec=dict(experts=256, slots=288, ep_size=8, top_k=8, tokens=8192), + ), + ), +} + +CELLS = certified_cells(op, TARGET_CELLS) + + +@requires_gpu +@pytest.mark.parametrize("cell", CELLS, ids=[c.why[:44] for c in CELLS]) +def test_certified_cells(cell) -> None: + """Every rank routes the same ids to the same slots; each slot holds the token's expert; + an expert held once maps to its slot; and within each 1024-id block the kernel + arbitrates, an expert's occurrences are spread over its replicas round-robin.""" + spec = cell.spec + seed = zlib.crc32(cell.why.encode()) % 2**31 + placement = _placement( + spec["experts"], spec["slots"], spec["ep_size"], spec.get("hot_replicas", 2), seed + ) + ids = _expert_ids(spec["tokens"], spec["experts"], spec["top_k"], seed) + group = _Balancers(spec["experts"], spec["top_k"], placement, spec["ep_size"]) + try: + with validating(op): + routed = [op(ids, layer) for layer in group.layers] + ref = op.reference(ids, group.layers[0]) + finally: + group.shutdown() + + got = routed[0] + assert got.dtype is torch.int32 and got.shape == ids.shape + for other in routed[1:]: + assert torch.equal(other, got), "EP ranks routed the same ids to different slots" + slot_expert = torch.tensor(placement, dtype=torch.int32, device="cuda") + assert torch.equal(slot_expert[got.long()], ids), "a slot does not hold the token's expert" + assert torch.equal(slot_expert[ref.long()], ids), "the reference's slot does not either" + + replicas = torch.bincount(slot_expert.long(), minlength=spec["experts"]) + single = replicas[ids.long()] == 1 + assert torch.equal(got[single], ref[single]), "an expert held once left its slot" + + flat_ids, flat_slots = ids.flatten().tolist(), got.flatten().tolist() + for start in range(0, len(flat_ids), 1024): + block = list(zip(flat_ids[start : start + 1024], flat_slots[start : start + 1024])) + for expert in {e for e, _ in block if replicas[e] > 1}: + counts = [0] * len(placement) + for e, s in block: + if e == expert: + counts[s] += 1 + held = [counts[s] for s, e in enumerate(placement) if e == expert] + assert max(held) - min(held) <= 1, (expert, held) + + +@requires_gpu +def test_an_id_outside_the_experts_routes_to_no_slot() -> None: + placement = _placement(16, 24, 4, 2, seed=7) + ids = torch.tensor([[0, 15], [-1, 3], [16, 4]], dtype=torch.int32, device="cuda") + group = _Balancers(16, 2, placement, 4) + try: + got = op(ids, group.layers[0]) + ref = op.reference(ids, group.layers[0]) + finally: + group.shutdown() + assert got[1, 0].item() == got[2, 0].item() == ref[1, 0].item() == len(placement) + + +# --- a slot-routed layer sums to the layer (GPU) --------------------------------------------- + + +@requires_gpu +def test_slot_windows_sum_to_the_layer() -> None: + """Under EPLB each rank runs its slot window on slot-routed ids, and the windows add up + to the layer: the DeepSeek-V3-Lite routed geometry (72 experts, H 2560, I 1536, top-6) + at 80 slots over 4 ranks, with replicas across and within ranks, against the 72-expert + layer without EPLB. + + The slot weights are the expert stack's own rows, gathered by the placement, and the + route is the engine's kernel on one balancer per rank -- so this checks, independently + of any target, that slot ids, slot windows and replicated weights compose: a slot id + landing in the wrong window, or a window loaded with another slot's expert, moves the + sum by far more than the kernel's own error. + """ + from _fp4_moe_test_utils import ( + _assert_moe_close, + _build, + _calibrate_g2, + _call, + _rand_activation, + _ref_moe, + _routing, + _scalars, + ) + + experts, slots, ep_size, hidden, top_k = 72, 80, 4, 2560, 6 + args, ref = _build(experts, hidden, 1536, seed=7280) + placement = _placement(experts, slots, ep_size, hot_replicas=3, seed=80) + local = slots // ep_size + gen = torch.Generator(device="cuda").manual_seed(8072) + g1 = 137.0 + data, sf, x = _rand_activation(1024, hidden, g1, gen) + ids, wts = _routing(1024, experts, top_k, gen) + g2 = _calibrate_g2(x, ids, ref) + s1, sg, s2 = _scalars(experts, g1, g2) + + full = _call( + data, + sf, + args, + experts, + top_k, + topk_ids=ids, + topk_weights=wts, + output1_scale_scalar=s1, + output1_scale_gate_scalar=sg, + output2_scale_scalar=s2, + )[0] + want = _ref_moe(x, ids, wts, ref, g2).to(torch.bfloat16) + _assert_moe_close(full, want) + + group = _Balancers(experts, top_k, placement, ep_size) + try: + routed = [op(ids, layer) for layer in group.layers] + finally: + group.shutdown() + parts = [] + for rank in range(ep_size): + assert torch.equal(routed[rank], routed[0]) + held = torch.tensor(placement[rank * local : (rank + 1) * local], device="cuda") + window = { + k: args[k][held].contiguous() + for k in ( + "gemm1_weights", + "gemm1_weights_scale", + "gemm2_weights", + "gemm2_weights_scale", + ) + } + window["intermediate_size"] = args["intermediate_size"] + parts.append( + _call( + data, + sf, + window, + slots, + top_k, + local_expert_offset=rank * local, + local_num_experts=local, + topk_ids=routed[rank], + topk_weights=wts, + output1_scale_scalar=s1[held].contiguous(), + output1_scale_gate_scalar=sg[held].contiguous(), + output2_scale_scalar=s2[held].contiguous(), + )[0] + ) + summed = sum(p.float() for p in parts).to(torch.bfloat16) + _assert_moe_close(summed, want) diff --git a/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_fp4_block_scale_moe_runner.py b/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_fp4_block_scale_moe_runner.py index caaa881c800c..9810cd0e04a5 100644 --- a/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_fp4_block_scale_moe_runner.py +++ b/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_fp4_block_scale_moe_runner.py @@ -97,13 +97,35 @@ def _dsr1_at(inter: int): return _DSR1_SLICE[inter] +# DeepSeek-R1's routed experts in 288 slots, as static EPLB places them: every expert +# once and 32 of them again. The kernel sees a slot as an expert, so the slot stack is +# the 256-expert stack's own rows gathered by the placement. +_DSR1_SLOTS = None + + +def _dsr1_slots(): + global _DSR1_SLOTS + if _DSR1_SLOTS is None: + args, ref = _dsr1() + g = torch.Generator().manual_seed(288) + held = torch.cat([torch.arange(256), torch.randperm(256, generator=g)[:32]]).to(DEV) + slot_args = { + k: (v[held].contiguous() if torch.is_tensor(v) else v) for k, v in args.items() + } + slot_ref = dict(ref, num_experts=288) + for k in ("up", "gate", "down"): + slot_ref[k] = (ref[k][0][held].contiguous(), ref[k][1][held].contiguous()) + _DSR1_SLOTS = (slot_args, slot_ref) + return _DSR1_SLOTS + + @pytest.fixture(scope="module", autouse=True) def _release_reference_layers() -> Iterator[None]: - global _DSV3, _DSR1 + global _DSV3, _DSR1, _DSR1_SLOTS try: yield finally: - _DSV3 = _DSR1 = None + _DSV3 = _DSR1 = _DSR1_SLOTS = None _DSR1_SLICE.clear() @@ -1864,6 +1886,8 @@ def _cell_layer(spec: dict, layer_factory: Callable[[], tuple[dict, dict]]) -> t return layer_factory() if key == (256, 7168, 2048): return _dsr1() + if key == (288, 7168, 2048): + return _dsr1_slots() assert key[:2] == (256, 7168), f"no shared layer for cell geometry {key}" return _dsr1_at(key[2]) @@ -1933,6 +1957,24 @@ def _cell_layer(spec: dict, layer_factory: Callable[[], tuple[dict, dict]]) -> t **Fp4BlockScaleMoeRunner.R1, ), ), + Cell( + why="deepseek default under static EPLB at dep4: the last 72 of 288 slots", + spec=dict( + tokens=64, + local_expert_offset=216, + local_num_experts=72, + **dict(Fp4BlockScaleMoeRunner.R1, num_experts=288), + ), + ), + Cell( + why="deepseek default under static EPLB at dep8: a 36-slot window of 288", + spec=dict( + tokens=64, + local_expert_offset=108, + local_num_experts=36, + **dict(Fp4BlockScaleMoeRunner.R1, num_experts=288), + ), + ), ), "qwen4_exp/qwen3_8_flash_next_nvfp4__sm_103__default": ( Cell( 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 61ab1e992c67..cbbdfdf93724 100644 --- a/tests/unittest/_torch/modeling_v2/test_modeling_v2_routing.py +++ b/tests/unittest/_torch/modeling_v2/test_modeling_v2_routing.py @@ -1663,16 +1663,55 @@ def test_glm52_without_an_fp8_kv_cache_does_not_match(): @pytest.mark.parametrize("eplb_mode", ["static", "online"]) +def test_eplb_at_dep4_keeps_the_builtin_gpt_oss(eplb_mode): + """The built-in gpt-oss model balances its experts; the default target registers no MoE + layer with the balancer, so an EPLB deployment that sets modeling_v2 keeps the built-in + model.""" + config = _balanced(_model_config(_gpt_oss_config(), **_DEP4), eplb_mode, num_slots=160) + assert modeling_v2_resolve(config, _llm_args("auto")) is None + with pytest.raises(ValueError, match=f"{eplb_mode} EPLB .* implements no EPLB mode"): + modeling_v2_resolve(config, _llm_args("require")) + + +_R1_EPLB_LAYOUTS = {"dep4": _layout(4, True, 1, 4), "dep8": _layout(8, True, 1, 8)} + + +@pytest.mark.parametrize("spec_config", [None, _MTP3], ids=["no_spec", "mtp3"]) @pytest.mark.parametrize( - "pretrained_config, num_slots", - [pytest.param(_r1_config, 288, id="r1"), pytest.param(_gpt_oss_config, 160, id="gpt_oss")], + "mapping_kwargs", list(_R1_EPLB_LAYOUTS.values()), ids=list(_R1_EPLB_LAYOUTS) ) -def test_eplb_at_dep4_keeps_the_builtin_r1_and_gpt_oss(pretrained_config, num_slots, eplb_mode): - """The built-in DeepSeek-R1 and gpt-oss models balance their experts; the default targets register no - MoE layer with the balancer, so an EPLB deployment that sets modeling_v2 keeps the built-in model.""" - config = _balanced(_model_config(pretrained_config(), **_DEP4), eplb_mode, num_slots) +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.""" + config = _balanced( + _model_config(_r1_config(), spec_config=spec_config, **mapping_kwargs), "static" + ) + 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) assert modeling_v2_resolve(config, _llm_args("auto")) is None - with pytest.raises(ValueError, match=f"{eplb_mode} EPLB .* implements no EPLB mode"): + with pytest.raises(ValueError, match=f"{eplb_mode} EPLB .* implements static"): + modeling_v2_resolve(config, _llm_args("require")) + + +@pytest.mark.parametrize( + "mapping_kwargs", + [ + pytest.param(_layout(4, False, 1, 4), id="tp4_ep4"), + pytest.param(_layout(4, True, 2, 2), id="dep4_moetp2_ep2"), + pytest.param(_layout(2, True, 1, 2), id="dep2"), + pytest.param(_layout(16, True, 1, 16), id="dep16"), + ], +) +def test_r1_static_eplb_is_refused_where_it_was_not_measured(mapping_kwargs): + """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") + assert modeling_v2_resolve(config, _llm_args("auto")) is None + with pytest.raises(ValueError, match="static EPLB at parallel layout"): modeling_v2_resolve(config, _llm_args("require")) From 47865abc00edd4a7541479293b8a8b97124240fd Mon Sep 17 00:00:00 2001 From: Ruocheng Jia Date: Sat, 14 Nov 2026 04:33:53 -0800 Subject: [PATCH 03/16] [TRTLLM-17824][feat] Online EPLB for the DeepSeek-R1 modeling_v2 target Extend the DeepSeek-R1-0528 NVFP4 default target from static to online expert-parallel load balancing, where the engine's load balancer moves experts between slots while serving, the MTP layer included. - catalog/moe/eplb.py: the layer's part in online EPLB, on EplbLayer. share_experts hands the balancer host copies of this rank's share of the layer's experts while loading; bind_slots moves the slot weights to memory the balancer writes and registers each slot, before any view of them is taken; route takes the layer from the balancer on a forward's first call and records the routed ids, padding rows left out; close hands the layer back once per forward. All four are no-ops without online EPLB. - DeepSeek-R1 target: the runner's three per-slot output scales become slot weights in the weight table, read from the slot's expert's scalars, so they move with the expert. Under online EPLB, load hands over the host copies, post_load_weights binds the slots before the targets take their views, the attention-DP round trip passes the gathered rows that are tokens, a trunk layer closes after its experts run and the MTP layer after the worker's last draft step, also when it drafts nothing. EPLB_MODES is {"static", "online"}. - Docs: online EPLB in the Modeling V2 README, the agent features skill and the wide-EP EPLB example. - Tests: the online protocol, host copies and binding of the catalog entry on the CPU and a real online balancer moving experts into bound slots on the GPU; the target's registrations against an online balancer, its host copies against the world-size-1 table, its routing decisions, and an online EPLB GSM8K test at dep4 and dep8. Signed-off-by: Ruocheng Jia --- .../trtllm-modeling-v2-features/SKILL.md | 2 +- .../references/features.md | 50 ++- examples/wide_ep/ep_load_balancer/README.md | 2 +- .../_experimental/modeling_v2/README.md | 51 ++- .../modeling_v2/catalog/moe/eplb.py | 192 +++++++++++- .../modeling.py | 191 ++++++++---- .../r1_0528_nvfp4__sm_10x__default/weights.py | 165 ++++++++-- .../test_accuracy.py | 33 +- .../test-db/l0_gb300_multi_gpus.yml | 2 + .../l0_gb300_multi_nodes_node2_gpu8.yml | 1 + ...est_modeling_v2_deepseek_default_shards.py | 109 ++++++- .../test_modeling_v2_deepseek_eplb.py | 31 +- .../test_modeling_v2_deepseek_weight_table.py | 6 +- .../modeling_v2/moe/test_modeling_v2_eplb.py | 292 +++++++++++++++++- .../modeling_v2/test_modeling_v2_routing.py | 23 +- 15 files changed, 1012 insertions(+), 138 deletions(-) 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 8a7cf7345633..a4d2deca63a2 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 @@ -94,7 +94,7 @@ Climb only as far as the claim needs. Each rung says what it cannot see. | disaggregation | feature `disagg` + `accuracy.disagg.test` | a benchmark scored through `trtllm-serve disaggregated` | the tree's disaggregated-serving test | | multimodal | feature `multimodal` | an image prompt answered | boot image, image benchmark | | speculative | features `mtp`, `eagle3`, `dflash`, `dspark` | each rank's algorithm and depth; 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 b39272903858..abbfba392983 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 @@ -577,24 +577,42 @@ 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: `EplbLayer.route` 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, `route(ids, rows, last)` records the routed 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_route`, `moe_load_balancer_mode`, `maybe_create_moe_load_balancer`, -`MoeLoadBalancerConfig`, `initial_global_assignments`, `num_slots`. +`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/test_modeling_v2_eplb.py`: the slots - and registration 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. + and registration 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_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. + (`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 @@ -611,8 +629,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 in `route` 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 defc46f3ca7f..61e304c5733a 100644 --- a/examples/wide_ep/ep_load_balancer/README.md +++ b/examples/wide_ep/ep_load_balancer/README.md @@ -321,6 +321,6 @@ A [Modeling V2](../../../tensorrt_llm/_torch/_experimental/modeling_v2/README.md | 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. diff --git a/tensorrt_llm/_torch/_experimental/modeling_v2/README.md b/tensorrt_llm/_torch/_experimental/modeling_v2/README.md index 6a69236bfee2..1f8aea323493 100644 --- a/tensorrt_llm/_torch/_experimental/modeling_v2/README.md +++ b/tensorrt_llm/_torch/_experimental/modeling_v2/README.md @@ -379,7 +379,7 @@ MoE layers into it: | Model loader | Creates the balancer around the model when the deployment runs EPLB (`moe_load_balancer_mode`), and registers weight slots and finalizes it after the weights load. | | Executor | Wraps every forward in a balancer iteration, turns statistics and updates off during warmup, and shuts the balancer down. | | Resolver | Builds a target for an EPLB deployment only if the target class lists the deployment's mode in `EPLB_MODES` (see [Routing](#routing)). | -| Target | Registers its MoE layers, loads its experts by slot, routes expert ids to slot ids, and declines in `route` the layouts it has not measured EPLB at. | +| Target | Registers its MoE layers, loads its experts by slot, routes expert ids to slot ids, and declines in `route` the layouts it has not measured EPLB at. Under online EPLB it also hands the balancer host copies of its experts, binds its slot weights to it, and hands every layer back once per forward. | A target reaches the balancer only through [`catalog/moe/eplb.py`](catalog/moe/eplb.py). The balancer @@ -418,19 +418,62 @@ the example. Then list the mode in the target class, `EPLB_MODES = frozenset({"static"})`, and gate the layouts in `route` on `moe_eplb_mode(model_config)`. +### Online EPLB in a target + +Online EPLB (`layer_updates_per_iter > 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.** `EplbLayer.route(ids, rows, last)` takes the layer from + the balancer on its first call of a forward and records the routed ids. + `rows` names the rows that are tokens when the rest are padding, such as + the rows an attention-DP gather pads. `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/_experimental/modeling_v2/catalog/moe/eplb.py b/tensorrt_llm/_torch/_experimental/modeling_v2/catalog/moe/eplb.py index 315bad7c9907..6b84c3406cdb 100644 --- a/tensorrt_llm/_torch/_experimental/modeling_v2/catalog/moe/eplb.py +++ b/tensorrt_llm/_torch/_experimental/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 @@ -18,6 +19,19 @@ GEMMs, which then take `num_slots` as their expert count and this rank's slot window as their local experts. +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. `route` 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 declines EPLB deployments in any other mode (see the Modeling V2 README). @@ -26,9 +40,10 @@ from __future__ import annotations from dataclasses import dataclass -from typing import Optional, Sequence +from typing import Callable, 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._experimental.modeling_v2._router_index import moe_eplb_mode @@ -227,21 +242,65 @@ def reference( eplb_route = EplbRoute() +#: Row ranges `(start, stop)` of a routed batch; see `EplbLayer.route`. +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 `route` 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 `route`, 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 + self._bound: Optional[dict[str, int]] = None @classmethod def register(cls, slots: EplbSlots, top_k: int, repeat_count: int = 1) -> "EplbLayer": @@ -270,10 +329,133 @@ def register(cls, slots: EplbSlots, top_k: int, repeat_count: int = 1) -> "EplbL balancer_layer.set_initial_weight_assignments(list(slots.global_assignments)) return cls(balancer_layer, slots) - def route(self, token_selected_experts: torch.Tensor) -> torch.Tensor: + def route( + self, token_selected_experts: torch.Tensor, rows: Optional[Rows] = None, last: bool = False + ) -> torch.Tensor: """Global expert ids `[T, top_k]` int32 -> global slot ids `[T, top_k]` int32. Routes with `offset_by_ep_rank=False`, so every rank that routes the same tokens gets the same slots. + + 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 = 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) return eplb_route(token_selected_experts, self.balancer_layer, False) + + 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 + + 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()} diff --git a/tensorrt_llm/_torch/_experimental/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/modeling.py b/tensorrt_llm/_torch/_experimental/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/modeling.py index 8257ffabacf1..c44eadd1c8e4 100644 --- a/tensorrt_llm/_torch/_experimental/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/modeling.py +++ b/tensorrt_llm/_torch/_experimental/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 @@ -78,7 +82,11 @@ from tensorrt_llm._torch._experimental.modeling_v2.catalog.gemm.bmm_out import bmm_out from tensorrt_llm._torch._experimental.modeling_v2.catalog.gemm.cublas_mm import cublas_mm from tensorrt_llm._torch._experimental.modeling_v2.catalog.gemm.nvfp4_gemm import nvfp4_gemm -from tensorrt_llm._torch._experimental.modeling_v2.catalog.moe.eplb import EplbLayer +from tensorrt_llm._torch._experimental.modeling_v2.catalog.moe.eplb import ( + EplbLayer, + Rows, + rows_within, +) from tensorrt_llm._torch._experimental.modeling_v2.catalog.moe.fp4_block_scale_moe_runner import ( # noqa: E501 fp4_block_scale_moe_runner, ) @@ -355,7 +363,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(): @@ -422,6 +432,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 @@ -430,6 +444,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) @@ -483,19 +501,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. @@ -514,20 +533,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): @@ -605,11 +659,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"], @@ -618,9 +669,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( @@ -661,7 +712,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. @@ -669,11 +725,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, @@ -684,7 +743,9 @@ def _experts(core: DeepseekV3DefaultModelingV2, L: _LayerWeights, x: torch.Tenso float(cfg.routed_scaling_factor), ) if L.eplb is not None: - topk_ids = L.eplb.route(topk_ids) + start = k * _MOE_MAX_T + rows = rows_within(tokens, start, start + chunk.shape[0]) + topk_ids = L.eplb.route(topk_ids, rows, last=k == len(chunks) - 1) xq, xsf = fp4_quantize(chunk, L.moe_gscale, _SF_VEC, False, _SF_LINEAR) parts.append( fp4_block_scale_moe_runner( @@ -719,6 +780,8 @@ def _experts(core: DeepseekV3DefaultModelingV2, L: _LayerWeights, x: torch.Tenso topk_ids=topk_ids, )[0] ) + if L.eplb is not None: + L.eplb.close() return parts[0] if len(parts) == 1 else torch.cat(parts, 0) @@ -797,12 +860,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 @@ -814,7 +881,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, @@ -824,7 +891,8 @@ def _mtp_experts( float(cfg.routed_scaling_factor), ) if M.eplb is not None: - topk_ids = M.eplb.route(topk_ids) + start = k * _MOE_MAX_T + topk_ids = M.eplb.route(topk_ids, rows_within(tokens, start, start + chunk.shape[0])) parts.append( fused_moe( input=chunk, @@ -846,9 +914,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( @@ -856,11 +925,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( @@ -868,7 +937,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. @@ -877,17 +946,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 ] @@ -988,7 +1058,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) @@ -1201,7 +1271,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) @@ -1261,7 +1331,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) @@ -1459,7 +1529,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: @@ -1560,7 +1630,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 @@ -1679,7 +1749,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) @@ -1731,7 +1801,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) @@ -1839,7 +1909,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( @@ -1847,7 +1917,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. @@ -1862,7 +1932,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 @@ -1944,9 +2014,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 @@ -2011,7 +2083,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, @@ -2021,6 +2093,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/_experimental/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/weights.py b/tensorrt_llm/_torch/_experimental/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/weights.py index b50d9d0b3272..a3d95b8a4982 100644 --- a/tensorrt_llm/_torch/_experimental/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/weights.py +++ b/tensorrt_llm/_torch/_experimental/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,13 +69,19 @@ `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 dataclasses import dataclass @@ -292,6 +301,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 +425,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] - return build + def __call__(self, d, i): + return [ + (self.keys(i, expert), (local,)) for local, expert in enumerate(d.slots[i].slot_experts) + ] + + +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 +697,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}", @@ -809,6 +900,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, consumed) + # 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 @@ -829,6 +922,34 @@ def fill(param: torch.nn.Parameter, ckpt_key, index, cut, transform) -> None: 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 _share_experts(self, core, weights, consumed: set) -> 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 + consumed.update(key if isinstance(key, tuple) else (key,)) + return self.read(weights, key, cut, entry.transform, core, device) + + 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 +1048,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/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 2ba6e1176a0e..d1837b9d237f 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 @@ -109,7 +109,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] @@ -362,3 +362,34 @@ def test_gsm8k_static_eplb(self, mocker, parallel, mtp): ): task = GSM8K(self.MODEL_NAME) task.evaluate(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. + """ + 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) 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) 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 66a63c313f7f..5fb941d60755 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 @@ -33,6 +33,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 # qwen4_exp target, post-merge: three drafts over quantized KV -- NVFP4 KV at tp4 with the 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 f96a9da59404..d9fa7e1726c9 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 @@ -25,6 +25,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 077e051673e2..96137bc71673 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 @@ -704,6 +704,7 @@ def test_load_reads_only_the_rank_share(layout, mtp, monkeypatch): ) ckpt = _Checkpoint(cfg, keys) D.MODEL_WEIGHTS.load(model, ckpt) + _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" @@ -753,9 +754,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} @@ -769,6 +771,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, ), ) ) @@ -826,19 +829,105 @@ def test_eplb_load_fills_every_slot_with_its_expert(layout, mtp, monkeypatch): ckpt = _Checkpoint(cfg, keys) D.MODEL_WEIGHTS.load(model, ckpt) + _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 _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 + + +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 unless 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) + + 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) 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 1a0301ead26f..4ad247ee4bc8 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,16 +1,17 @@ # 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 @@ -83,11 +84,14 @@ def _placement(layer: int) -> list: return out +@pytest.mark.parametrize("updates", [0, 2], 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 +108,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 +127,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_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 50befa84e44d..c7e02e094228 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/test_modeling_v2_eplb.py b/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py index a0f72ab24fdd..28cd8a9cb379 100644 --- a/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py +++ b/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py @@ -1,25 +1,35 @@ # 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, 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 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 from tensorrt_llm._torch._experimental.modeling_v2.catalog._op import Cell -from tensorrt_llm._torch._experimental.modeling_v2.catalog.moe.eplb import EplbLayer, EplbSlots +from tensorrt_llm._torch._experimental.modeling_v2.catalog.moe import eplb as eplb_module +from tensorrt_llm._torch._experimental.modeling_v2.catalog.moe.eplb import ( + EplbLayer, + EplbSlots, + rows_within, +) from tensorrt_llm._torch._experimental.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.llmapi.llm_args import MoeLoadBalancerConfig @@ -131,6 +141,223 @@ 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 _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() + eplb.route(_ids([0, 1], [2, 3])) + eplb.route(_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() + eplb.route(_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): + eplb.route(_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(eplb.route(ids, rows=((0, 2), (3, 4))), ids) + eplb.route(_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() + eplb.route(_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 op (GPU) --------------------------------------------------------------------- @@ -346,3 +573,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_gpu +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 = eplb.route(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 cbbdfdf93724..a3aada2de36c 100644 --- a/tests/unittest/_torch/modeling_v2/test_modeling_v2_routing.py +++ b/tests/unittest/_torch/modeling_v2/test_modeling_v2_routing.py @@ -1676,24 +1676,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")) @@ -1706,12 +1706,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")) From 283c1314831a5e36816c47342304ac3264d2af6b Mon Sep 17 00:00:00 2001 From: Ruocheng Jia Date: Sat, 14 Nov 2026 09:52:24 -0800 Subject: [PATCH 04/16] [TRTLLM-17824][fix] Keep counted EPLB ids alive until close; skip online tests without host-accessible memory Under multi-stream the balancer counts the routed ids on its own stream, which joins the forward's stream only when the layer is handed back, so EplbLayer now holds the counted ids until close. The real online-balancer tests skip where host-accessible device memory is unavailable. Doc and docstring wording follow the code. Signed-off-by: Ruocheng Jia --- .../references/features.md | 4 ++-- .../_torch/_experimental/modeling_v2/README.md | 2 +- .../modeling_v2/catalog/moe/eplb.py | 6 ++++++ .../test_modeling_v2_deepseek_default_shards.py | 2 +- .../test_modeling_v2_deepseek_eplb.py | 17 ++++++++++++++++- .../modeling_v2/moe/test_modeling_v2_eplb.py | 7 ++++++- 6 files changed, 32 insertions(+), 6 deletions(-) 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 abbfba392983..b73baeb183ef 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 @@ -585,8 +585,8 @@ an EPLB deployment only if its class lists the mode in `EPLB_MODES`. 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, `route(ids, rows, last)` records the routed ids without the - padding rows, and `close()` hands each layer back once, after its last + - Per forward, `route(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. diff --git a/tensorrt_llm/_torch/_experimental/modeling_v2/README.md b/tensorrt_llm/_torch/_experimental/modeling_v2/README.md index 1f8aea323493..5ca9f76ee029 100644 --- a/tensorrt_llm/_torch/_experimental/modeling_v2/README.md +++ b/tensorrt_llm/_torch/_experimental/modeling_v2/README.md @@ -447,7 +447,7 @@ target does three more, and lists `"online"` in `EPLB_MODES`: move. The balancer needs host-accessible device memory, which Grace systems have and x86 systems get from GDRCopy. 7. **The forward.** `EplbLayer.route(ids, rows, last)` takes the layer from - the balancer on its first call of a forward and records the routed ids. + the balancer on its first call of a forward and records the router's expert ids. `rows` names the rows that are tokens when the rest are padding, such as the rows an attention-DP gather pads. `EplbLayer.close()` hands the layer back after its last expert kernel of the forward. The balancer takes the diff --git a/tensorrt_llm/_torch/_experimental/modeling_v2/catalog/moe/eplb.py b/tensorrt_llm/_torch/_experimental/modeling_v2/catalog/moe/eplb.py index 6b84c3406cdb..c439829941ab 100644 --- a/tensorrt_llm/_torch/_experimental/modeling_v2/catalog/moe/eplb.py +++ b/tensorrt_llm/_torch/_experimental/modeling_v2/catalog/moe/eplb.py @@ -300,6 +300,10 @@ def __init__(self, balancer_layer: SingleLayerMoeLoadBalancer, slots: EplbSlots) 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 @@ -355,6 +359,7 @@ def route( 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: @@ -375,6 +380,7 @@ def close(self) -> None: 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.""" 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 96137bc71673..426315d501f7 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 @@ -896,7 +896,7 @@ 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 unless a slot already did, and coverage still holds both ways.""" + 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) 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 4ad247ee4bc8..1cd19b65a0b8 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 @@ -18,6 +18,7 @@ import torch from transformers import DeepseekV3Config +import tensorrt_llm.bindings.internal.runtime as _tbr from tensorrt_llm._torch._experimental.modeling_v2.models.deepseek_v3.r1_0528_nvfp4__sm_10x__default.modeling import ( # noqa: E501 DeepseekV3DefaultModelingV2, ) @@ -84,7 +85,21 @@ def _placement(layer: int) -> list: return out -@pytest.mark.parametrize("updates", [0, 2], ids=["static", "online"]) +@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_eplb_registers_every_routed_layer(mtp, updates): layers = range(3, 61 + int(mtp)) diff --git a/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py b/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py index 28cd8a9cb379..ef3c2233156c 100644 --- a/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py +++ b/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py @@ -19,6 +19,7 @@ import torch from torch import nn +import tensorrt_llm.bindings.internal.runtime as _tbr from tensorrt_llm._torch._experimental.modeling_v2.catalog._op import Cell from tensorrt_llm._torch._experimental.modeling_v2.catalog.moe import eplb as eplb_module from tensorrt_llm._torch._experimental.modeling_v2.catalog.moe.eplb import ( @@ -39,6 +40,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", +) # --- slot layouts (CPU) --------------------------------------------------------------------- @@ -578,7 +583,7 @@ def test_slot_windows_sum_to_the_layer() -> None: # --- a real online balancer moves experts into slots (GPU) ----------------------------------- -@requires_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 From 7bdeb6466617627a50a9b697538db20422f213a7 Mon Sep 17 00:00:00 2001 From: Ruocheng Jia Date: Sun, 15 Nov 2026 03:07:53 -0800 Subject: [PATCH 05/16] [TRTLLM-17824][test] Run online EPLB GSM8K at dep4 only on GB300 Two GB300 trays do not hold the DeepSeek-R1 target's online EPLB load at dep8: each node keeps host copies of every expert (about 320 GB) while every rank holds about 70-80 GB of host memory through the target's weight load, with or without EPLB, and the node runs out of its 908 GB. Static EPLB at dep8 and online EPLB at dep4 fit and stay in the lists. Signed-off-by: Ruocheng Jia --- .../test_lists/test-db/l0_gb300_multi_nodes_node2_gpu8.yml | 1 - 1 file changed, 1 deletion(-) 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 d9fa7e1726c9..f96a9da59404 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 @@ -25,7 +25,6 @@ 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) From 80111be3f7a6c25fbf0234f1a9ad9b7c923da23e Mon Sep 17 00:00:00 2001 From: Ruocheng Jia Date: Sun, 15 Nov 2026 03:22:21 -0800 Subject: [PATCH 06/16] [TRTLLM-17824][fix] Release checkpoint keys as the DeepSeek-R1 target loads The target held every checkpoint tensor it touched until its load ended. The engine can back many tensors with one read-ahead buffer, freed only when all of its keys are released, so every rank kept about 70-80 GB of host memory through the load, with or without EPLB. With online EPLB's host copies of the experts on top, two GB300 trays ran out of memory at dep8. load now releases the keys this rank never reads at the start and every other key after its last read (mark_consumed_keys), as the built-in models release what they consume, and checks coverage against the keys it started with. Online EPLB at dep8 fits again and is back in the GB300 multi-node list. Signed-off-by: Ruocheng Jia --- .../r1_0528_nvfp4__sm_10x__default/weights.py | 61 ++++++++++++++++--- .../l0_gb300_multi_nodes_node2_gpu8.yml | 1 + ...est_modeling_v2_deepseek_default_shards.py | 12 ++++ 3 files changed, 66 insertions(+), 8 deletions(-) diff --git a/tensorrt_llm/_torch/_experimental/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/weights.py b/tensorrt_llm/_torch/_experimental/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/weights.py index a3d95b8a4982..b0b5c20d8245 100644 --- a/tensorrt_llm/_torch/_experimental/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/weights.py +++ b/tensorrt_llm/_torch/_experimental/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/weights.py @@ -84,6 +84,7 @@ 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 @@ -874,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] @@ -885,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", @@ -900,7 +933,7 @@ 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, consumed) + 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. @@ -914,8 +947,7 @@ 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 " @@ -931,7 +963,19 @@ def slot_weights(self, core, i: int) -> dict[str, nn.Parameter]: if isinstance(entry.src, _ExpertWindow) and i in entry.layer_indices(d) } - def _share_experts(self, core, weights, consumed: set) -> None: + 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' @@ -945,8 +989,9 @@ def expert_weight(name, expert, i=i, device=next(iter(slot_weights.values())).de entry = by_name[name] key = entry.src.keys(i, expert) cut = entry.cut(d) if entry.cut is not None else None - consumed.update(key if isinstance(key, tuple) else (key,)) - return self.read(weights, key, cut, entry.transform, core, device) + 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) 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 f96a9da59404..d9fa7e1726c9 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 @@ -25,6 +25,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 426315d501f7..377de8ab3e10 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 @@ -257,6 +257,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 @@ -704,6 +710,8 @@ 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] @@ -828,6 +836,8 @@ 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) @@ -918,6 +928,8 @@ def test_online_eplb_load_hands_over_this_ranks_experts(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] reads = Counter(k for k, _, _ in ckpt.reads) for i, hosting in core.eplb_layers.items(): From 98ee560b0206e5ed36e058bddb2921c635155b9b Mon Sep 17 00:00:00 2001 From: Ruocheng Jia Date: Sun, 15 Nov 2026 05:43:36 -0800 Subject: [PATCH 07/16] [TRTLLM-17824][fix] Sort the routing test's imports after the merge with main Signed-off-by: Ruocheng Jia --- tests/unittest/_torch/modeling_v2/test_modeling_v2_routing.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 aaac4dc6b60e..55a4c6ea24f2 100644 --- a/tests/unittest/_torch/modeling_v2/test_modeling_v2_routing.py +++ b/tests/unittest/_torch/modeling_v2/test_modeling_v2_routing.py @@ -53,8 +53,8 @@ from tensorrt_llm._torch.model_config import KIMI_K3_DEFAULT_ROUTED_QUANT_ALGO, ModelConfig from tensorrt_llm._torch.models.modeling_auto import AutoModelForCausalLM from tensorrt_llm._torch.moe.fused_moe import moe_load_balancer -from tensorrt_llm._torch.moe.fused_moe.moe_load_balancer import MOE_LOAD_BALANCER_MODES from tensorrt_llm._torch.moe.fused_moe.impl_identity import MoEImplId +from tensorrt_llm._torch.moe.fused_moe.moe_load_balancer import MOE_LOAD_BALANCER_MODES from tensorrt_llm.llmapi.llm_args import ( CacheTransceiverConfig, KvCacheConfig, From 10f2828c677850940258a4cd89c5da9cfa1e4f9c Mon Sep 17 00:00:00 2001 From: Ruocheng Jia Date: Mon, 16 Nov 2026 21:46:29 -0800 Subject: [PATCH 08/16] [TRTLLM-17824][feat] Use the tensorrt_llm._torch.modeling_v2 path for static EPLB modeling_v2 moved out of _torch/_experimental in #22286; move this PR's new files and references to the new location. Signed-off-by: Ruocheng Jia --- examples/wide_ep/ep_load_balancer/README.md | 2 +- tensorrt_llm/_torch/modeling_v2/catalog/moe/eplb.py | 4 ++-- .../deepseek_v3/r1_0528_nvfp4__sm_10x__default/weights.py | 2 +- .../test_modeling_v2_deepseek_eplb.py | 4 ++-- .../_torch/modeling_v2/moe/test_modeling_v2_eplb.py | 6 +++--- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/examples/wide_ep/ep_load_balancer/README.md b/examples/wide_ep/ep_load_balancer/README.md index defc46f3ca7f..183eca69b213 100644 --- a/examples/wide_ep/ep_load_balancer/README.md +++ b/examples/wide_ep/ep_load_balancer/README.md @@ -317,7 +317,7 @@ Per-layer dynamic EPLB has the following constraints: ## Modeling V2 targets -A [Modeling V2](../../../tensorrt_llm/_torch/_experimental/modeling_v2/README.md) target runs only the EPLB modes it implements. When a deployment sets `modeling_v2` (`auto` or `require`) together with `moe_config.load_balancer`, the engine builds a target only if the target implements the deployment's EPLB mode. Otherwise `auto` builds the built-in model, which implements every mode above, and `require` fails with the reason. +A [Modeling V2](../../../tensorrt_llm/_torch/modeling_v2/README.md) target runs only the EPLB modes it implements. When a deployment sets `modeling_v2` (`auto` or `require`) together with `moe_config.load_balancer`, the engine builds a target only if the target implements the deployment's EPLB mode. Otherwise `auto` builds the built-in model, which implements every mode above, and `require` fails with the reason. | Target | EPLB modes | Layouts | |---|---|---| diff --git a/tensorrt_llm/_torch/modeling_v2/catalog/moe/eplb.py b/tensorrt_llm/_torch/modeling_v2/catalog/moe/eplb.py index 315bad7c9907..b8b1c985ad8b 100644 --- a/tensorrt_llm/_torch/modeling_v2/catalog/moe/eplb.py +++ b/tensorrt_llm/_torch/modeling_v2/catalog/moe/eplb.py @@ -31,8 +31,8 @@ import torch import tensorrt_llm._torch.custom_ops # noqa: F401 — registers torch.ops.trtllm.* -from tensorrt_llm._torch._experimental.modeling_v2._router_index import moe_eplb_mode -from tensorrt_llm._torch._experimental.modeling_v2.catalog._op import Arch, Cell, OpWrapper +from tensorrt_llm._torch.modeling_v2._router_index import moe_eplb_mode +from tensorrt_llm._torch.modeling_v2.catalog._op import Arch, Cell, OpWrapper from tensorrt_llm._torch.moe.fused_moe.moe_load_balancer import ( SingleLayerMoeLoadBalancer, get_moe_load_balancer, 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 b50d9d0b3272..9d6bccf44113 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 @@ -82,7 +82,7 @@ import torch import torch.nn as nn -from tensorrt_llm._torch._experimental.modeling_v2.catalog.moe.eplb import eplb_mode, eplb_slots +from tensorrt_llm._torch.modeling_v2.catalog.moe.eplb import eplb_mode, eplb_slots #: `layers=ALL_LAYERS` is the common case and the default. A sentinel rather #: than a lambda so the table reads as data, and rather than `True` so the 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 1a0301ead26f..783f7bb6fba4 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 @@ -17,10 +17,10 @@ import torch from transformers import DeepseekV3Config -from tensorrt_llm._torch._experimental.modeling_v2.models.deepseek_v3.r1_0528_nvfp4__sm_10x__default.modeling import ( # noqa: E501 +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, ) -from tensorrt_llm._torch.model_config import ModelConfig from tensorrt_llm._torch.models.modeling_utils import MetaInitMode from tensorrt_llm._torch.moe.fused_moe.moe_load_balancer import MoeLoadBalancer from tensorrt_llm.llmapi.llm_args import MoeLoadBalancerConfig, MTPDecodingConfig diff --git a/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py b/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py index a0f72ab24fdd..19039acd3aec 100644 --- a/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py +++ b/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py @@ -15,9 +15,9 @@ import pytest import torch -from tensorrt_llm._torch._experimental.modeling_v2.catalog._op import Cell -from tensorrt_llm._torch._experimental.modeling_v2.catalog.moe.eplb import EplbLayer, EplbSlots -from tensorrt_llm._torch._experimental.modeling_v2.catalog.moe.eplb import eplb_route as op +from tensorrt_llm._torch.modeling_v2.catalog._op import Cell +from tensorrt_llm._torch.modeling_v2.catalog.moe.eplb import EplbLayer, EplbSlots +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, get_moe_load_balancer, From 4bc1efb0c52d70f0b0440d9f0a166fbdf8148915 Mon Sep 17 00:00:00 2001 From: Ruocheng Jia Date: Mon, 16 Nov 2026 21:46:29 -0800 Subject: [PATCH 09/16] [TRTLLM-17824][feat] Use the tensorrt_llm._torch.modeling_v2 path for static EPLB modeling_v2 moved out of _torch/_experimental in #22286; move this PR's new files and references to the new location. Signed-off-by: Ruocheng Jia --- examples/wide_ep/ep_load_balancer/README.md | 2 +- tensorrt_llm/_torch/modeling_v2/README.md | 2 +- tensorrt_llm/_torch/modeling_v2/catalog/moe/eplb.py | 4 ++-- .../deepseek_v3/r1_0528_nvfp4__sm_10x__default/weights.py | 2 +- .../test_modeling_v2_deepseek_eplb.py | 4 ++-- .../_torch/modeling_v2/moe/test_modeling_v2_eplb.py | 6 +++--- 6 files changed, 10 insertions(+), 10 deletions(-) diff --git a/examples/wide_ep/ep_load_balancer/README.md b/examples/wide_ep/ep_load_balancer/README.md index defc46f3ca7f..183eca69b213 100644 --- a/examples/wide_ep/ep_load_balancer/README.md +++ b/examples/wide_ep/ep_load_balancer/README.md @@ -317,7 +317,7 @@ Per-layer dynamic EPLB has the following constraints: ## Modeling V2 targets -A [Modeling V2](../../../tensorrt_llm/_torch/_experimental/modeling_v2/README.md) target runs only the EPLB modes it implements. When a deployment sets `modeling_v2` (`auto` or `require`) together with `moe_config.load_balancer`, the engine builds a target only if the target implements the deployment's EPLB mode. Otherwise `auto` builds the built-in model, which implements every mode above, and `require` fails with the reason. +A [Modeling V2](../../../tensorrt_llm/_torch/modeling_v2/README.md) target runs only the EPLB modes it implements. When a deployment sets `modeling_v2` (`auto` or `require`) together with `moe_config.load_balancer`, the engine builds a target only if the target implements the deployment's EPLB mode. Otherwise `auto` builds the built-in model, which implements every mode above, and `require` fails with the reason. | Target | EPLB modes | Layouts | |---|---|---| diff --git a/tensorrt_llm/_torch/modeling_v2/README.md b/tensorrt_llm/_torch/modeling_v2/README.md index 27fac0a71636..3f0c5ede8687 100644 --- a/tensorrt_llm/_torch/modeling_v2/README.md +++ b/tensorrt_llm/_torch/modeling_v2/README.md @@ -381,7 +381,7 @@ EPLB places a MoE layer's experts in slots split evenly over the EP ranks, with spare slots holding more copies of the hot experts, so a rank's load follows its share of the slots rather than of the experts. Deployments configure it with `moe_config.load_balancer`; see the -[EPLB example](../../../../examples/wide_ep/ep_load_balancer/README.md). +[EPLB example](../../../examples/wide_ep/ep_load_balancer/README.md). The engine owns the load balancer. A target that implements EPLB plugs its MoE layers into it: diff --git a/tensorrt_llm/_torch/modeling_v2/catalog/moe/eplb.py b/tensorrt_llm/_torch/modeling_v2/catalog/moe/eplb.py index 315bad7c9907..b8b1c985ad8b 100644 --- a/tensorrt_llm/_torch/modeling_v2/catalog/moe/eplb.py +++ b/tensorrt_llm/_torch/modeling_v2/catalog/moe/eplb.py @@ -31,8 +31,8 @@ import torch import tensorrt_llm._torch.custom_ops # noqa: F401 — registers torch.ops.trtllm.* -from tensorrt_llm._torch._experimental.modeling_v2._router_index import moe_eplb_mode -from tensorrt_llm._torch._experimental.modeling_v2.catalog._op import Arch, Cell, OpWrapper +from tensorrt_llm._torch.modeling_v2._router_index import moe_eplb_mode +from tensorrt_llm._torch.modeling_v2.catalog._op import Arch, Cell, OpWrapper from tensorrt_llm._torch.moe.fused_moe.moe_load_balancer import ( SingleLayerMoeLoadBalancer, get_moe_load_balancer, 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 b50d9d0b3272..9d6bccf44113 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 @@ -82,7 +82,7 @@ import torch import torch.nn as nn -from tensorrt_llm._torch._experimental.modeling_v2.catalog.moe.eplb import eplb_mode, eplb_slots +from tensorrt_llm._torch.modeling_v2.catalog.moe.eplb import eplb_mode, eplb_slots #: `layers=ALL_LAYERS` is the common case and the default. A sentinel rather #: than a lambda so the table reads as data, and rather than `True` so the 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 1a0301ead26f..783f7bb6fba4 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 @@ -17,10 +17,10 @@ import torch from transformers import DeepseekV3Config -from tensorrt_llm._torch._experimental.modeling_v2.models.deepseek_v3.r1_0528_nvfp4__sm_10x__default.modeling import ( # noqa: E501 +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, ) -from tensorrt_llm._torch.model_config import ModelConfig from tensorrt_llm._torch.models.modeling_utils import MetaInitMode from tensorrt_llm._torch.moe.fused_moe.moe_load_balancer import MoeLoadBalancer from tensorrt_llm.llmapi.llm_args import MoeLoadBalancerConfig, MTPDecodingConfig diff --git a/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py b/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py index a0f72ab24fdd..19039acd3aec 100644 --- a/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py +++ b/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py @@ -15,9 +15,9 @@ import pytest import torch -from tensorrt_llm._torch._experimental.modeling_v2.catalog._op import Cell -from tensorrt_llm._torch._experimental.modeling_v2.catalog.moe.eplb import EplbLayer, EplbSlots -from tensorrt_llm._torch._experimental.modeling_v2.catalog.moe.eplb import eplb_route as op +from tensorrt_llm._torch.modeling_v2.catalog._op import Cell +from tensorrt_llm._torch.modeling_v2.catalog.moe.eplb import EplbLayer, EplbSlots +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, get_moe_load_balancer, From 9c31e4255e306bc0f49721cde74bfd27e28a7371 Mon Sep 17 00:00:00 2001 From: Ruocheng Jia Date: Mon, 16 Nov 2026 21:51:14 -0800 Subject: [PATCH 10/16] [TRTLLM-17824][feat] Use the tensorrt_llm._torch.modeling_v2 path for online EPLB modeling_v2 moved out of _torch/_experimental in #22286; update this PR's references to the new location and restore the ModelConfig import the merge dropped. Signed-off-by: Ruocheng Jia --- tensorrt_llm/_torch/modeling_v2/README.md | 2 +- .../deepseek_v3/r1_0528_nvfp4__sm_10x__default/modeling.py | 6 +----- .../test_modeling_v2_deepseek_eplb.py | 1 + .../_torch/modeling_v2/moe/test_modeling_v2_eplb.py | 6 +----- 4 files changed, 4 insertions(+), 11 deletions(-) diff --git a/tensorrt_llm/_torch/modeling_v2/README.md b/tensorrt_llm/_torch/modeling_v2/README.md index ae517be170b2..acd01cce62c5 100644 --- a/tensorrt_llm/_torch/modeling_v2/README.md +++ b/tensorrt_llm/_torch/modeling_v2/README.md @@ -381,7 +381,7 @@ EPLB places a MoE layer's experts in slots split evenly over the EP ranks, with spare slots holding more copies of the hot experts, so a rank's load follows its share of the slots rather than of the experts. Deployments configure it with `moe_config.load_balancer`; see the -[EPLB example](../../../../examples/wide_ep/ep_load_balancer/README.md). +[EPLB example](../../../examples/wide_ep/ep_load_balancer/README.md). The engine owns the load balancer. A target that implements EPLB plugs its MoE layers into it: 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 6fd5b7126c4d..5a6782218947 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 @@ -83,11 +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, - Rows, - rows_within, -) +from tensorrt_llm._torch.modeling_v2.catalog.moe.eplb import EplbLayer, Rows, rows_within from tensorrt_llm._torch.modeling_v2.catalog.moe.fp4_block_scale_moe_runner import ( # noqa: E501 fp4_block_scale_moe_runner, ) 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 95e87f4cf018..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 @@ -19,6 +19,7 @@ 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, ) diff --git a/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py b/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py index b571c8ba9237..05f6efb25ffc 100644 --- a/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py +++ b/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py @@ -22,11 +22,7 @@ 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, - rows_within, -) +from tensorrt_llm._torch.modeling_v2.catalog.moe.eplb import EplbLayer, EplbSlots, 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, From 5186ddb3ae0814e73c0441e38558aa8c2c4d6607 Mon Sep 17 00:00:00 2001 From: Ruocheng Jia Date: Tue, 17 Nov 2026 09:40:44 -0800 Subject: [PATCH 11/16] [TRTLLM-17824][test] Move the static EPLB shard tests to their own file test_modeling_v2_deepseek_default_shards.py already runs for about half of the l0_cpu per-file timeout on main; the EPLB cases pushed it over on a loaded node. They now run from test_modeling_v2_deepseek_eplb_shards.py, which reuses the shares test's checkpoint and oracle. Signed-off-by: Ruocheng Jia --- .../integration/test_lists/test-db/l0_cpu.yml | 1 + ...est_modeling_v2_deepseek_default_shards.py | 114 -------------- .../test_modeling_v2_deepseek_eplb_shards.py | 146 ++++++++++++++++++ 3 files changed, 147 insertions(+), 114 deletions(-) create mode 100644 tests/unittest/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_modeling_v2_deepseek_eplb_shards.py diff --git a/tests/integration/test_lists/test-db/l0_cpu.yml b/tests/integration/test_lists/test-db/l0_cpu.yml index b3a777f345e0..61143b927c53 100644 --- a/tests/integration/test_lists/test-db/l0_cpu.yml +++ b/tests/integration/test_lists/test-db/l0_cpu.yml @@ -146,6 +146,7 @@ l0_cpu: - unittest/_torch/modeling_v2/models/kimi_k3_vl/kimi_k3_mxfp4__sm_100__tp16_moetp4ep4/test_tp16_moetp4ep4_uncertified_generic_calls.py - unittest/_torch/modeling_v2/models/kimi_k3_vl/kimi_k3_mxfp4__sm_100__tp16_moetp16ep1/test_tp16_moetp16ep1_uncertified_generic_calls.py - unittest/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_modeling_v2_deepseek_default_shards.py + - unittest/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_modeling_v2_deepseek_eplb_shards.py - unittest/_torch/modeling_v2/models/gpt_oss/gpt_oss_120b__sm_10x__default/test_modeling_v2_gpt_oss_default_shards.py - unittest/_torch/modeling_v2/models/gpt_oss/gpt_oss_120b__sm_10x__default/test_modeling_v2_weight_table.py # MiniMax-M3 sm_107 tp2 target: its device-free (cpu_only) tests. 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 f6d2b69d5bab..e7b95da80fe6 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 @@ -36,7 +36,6 @@ import math import zlib -from collections import Counter from types import SimpleNamespace import pytest @@ -47,7 +46,6 @@ from tensorrt_llm._torch.modeling_v2.models.deepseek_v3.r1_0528_nvfp4__sm_10x__default import ( # noqa: E501 weights as D, ) -from tensorrt_llm.llmapi.llm_args import MoeLoadBalancerConfig from tensorrt_llm.mapping import Mapping pytestmark = pytest.mark.cpu_only @@ -730,115 +728,3 @@ 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]) - - -# --- static EPLB: a rank's slots hold the experts the placement gives them --- - -_EPLB_LAYOUTS = sorted(routing._EPLB_LAYOUTS) - - -def _placement(layer: int, num_experts: int, ep_size: int, spare: int) -> list[int]: - """A placement unlike the default one: the experts shuffled per layer, then `spare` - more slots a rank holding other experts again -- on rank 0 a second copy of an expert - it already holds.""" - order = torch.randperm(num_experts, generator=torch.Generator().manual_seed(layer)).tolist() - per_rank = num_experts // ep_size - out = [] - for rank in range(ep_size): - own = order[rank * per_rank : (rank + 1) * per_rank] - extra = [order[(rank * per_rank + per_rank + k) % num_experts] for k in range(spare)] - if rank == 0: - extra[0] = own[0] - out += own + extra - 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.""" - 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} - pretrained = SimpleNamespace(**vars(cfg), architectures=["DeepseekV3ForCausalLM"]) - core = SimpleNamespace( - model_config=SimpleNamespace( - pretrained_config=pretrained, - mapping=_mapping(layout, rank), - torch_dtype=torch.bfloat16, - spec_config=object() if mtp else None, - moe_load_balancer=MoeLoadBalancerConfig( - num_slots=cfg.n_routed_experts + ep * spare, - initial_global_assignments=assignments, - ), - ) - ) - core.dims = D.MODEL_WEIGHTS.dims(core) - return core, assignments - - -@pytest.mark.parametrize("layout", _EPLB_LAYOUTS, ids=_layout_id) -def test_eplb_slots_hold_the_placed_experts(layout): - """Rank r holds slots [r * S, (r + 1) * S) of every routed layer, S = num_slots / ep, - and each slot the expert the placement puts there; together the ranks hold every - expert of every layer, the MTP layer's included.""" - cfg = SimpleNamespace(**_TINY) - ep = layout[3] - held: dict = {} - for rank in range(layout[0]): - core, assignments = _eplb_core(layout, rank, cfg, mtp=True) - d = core.dims - local = (cfg.n_routed_experts + 2 * ep) // ep - assert (d.eplb, d.num_slots, d.local_slots, d.slot_offset) == ( - "static", - local * ep, - local, - rank * local, - ) - for i, placement in assignments.items(): - mine = tuple(placement[rank * local : (rank + 1) * local]) - assert d.slots[i].slot_experts == mine, (layout, rank, i) - held.setdefault(i, set()).update(mine) - assert all(experts == set(range(cfg.n_routed_experts)) for experts in held.values()) - - -@pytest.mark.parametrize("mtp", [False, True], ids=["no_mtp", "mtp"]) -@pytest.mark.parametrize("layout", _EPLB_LAYOUTS, ids=_layout_id) -def test_eplb_load_fills_every_slot_with_its_expert(layout, mtp, monkeypatch): - """`load` under static EPLB: coverage holds both ways, a rank reads each expert's - tensors once per slot that holds it and no expert it does not hold, and every slot - holds exactly what the world-size-1 table, which has no EPLB, loads for that slot's - expert.""" - 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) - for rank in range(layout[0]): - core, assignments = _eplb_core(layout, rank, cfg, mtp) - d = core.dims - 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) - - 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") - ) - 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) - assert torch.equal(core.w[f"l{i}_{name}"][slot], want), (rank, i, slot, name) 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 new file mode 100644 index 000000000000..d342fda07b6f --- /dev/null +++ b/tests/unittest/_torch/modeling_v2/models/deepseek_v3/r1_0528_nvfp4__sm_10x__default/test_modeling_v2_deepseek_eplb_shards.py @@ -0,0 +1,146 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""The deepseek default target's per-rank weight shares under static EPLB, checked on the CPU. + +Under static EPLB a rank holds a contiguous range of expert slots, and each slot holds the +expert the load balancer's placement puts there, possibly an expert another slot also holds. +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. +""" + +from __future__ import annotations + +from collections import Counter +from types import SimpleNamespace + +import pytest +import torch +from test_modeling_v2_deepseek_default_shards import ( + _TINY, + _WS1, + _Checkpoint, + _default_core, + _layout_id, + _mapping, + _tiny_keys, +) +from torch import nn + +from tensorrt_llm._torch.modeling_v2.models.deepseek_v3 import routing +from tensorrt_llm._torch.modeling_v2.models.deepseek_v3.r1_0528_nvfp4__sm_10x__default import ( # noqa: E501 + weights as D, +) +from tensorrt_llm.llmapi.llm_args import MoeLoadBalancerConfig + +pytestmark = pytest.mark.cpu_only + +_EPLB_LAYOUTS = sorted(routing._EPLB_LAYOUTS) + + +def _placement(layer: int, num_experts: int, ep_size: int, spare: int) -> list[int]: + """A placement unlike the default one: the experts shuffled per layer, then `spare` + more slots a rank holding other experts again -- on rank 0 a second copy of an expert + it already holds.""" + order = torch.randperm(num_experts, generator=torch.Generator().manual_seed(layer)).tolist() + per_rank = num_experts // ep_size + out = [] + for rank in range(ep_size): + own = order[rank * per_rank : (rank + 1) * per_rank] + extra = [order[(rank * per_rank + per_rank + k) % num_experts] for k in range(spare)] + if rank == 0: + extra[0] = own[0] + out += own + extra + 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.""" + 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} + pretrained = SimpleNamespace(**vars(cfg), architectures=["DeepseekV3ForCausalLM"]) + core = SimpleNamespace( + model_config=SimpleNamespace( + pretrained_config=pretrained, + mapping=_mapping(layout, rank), + torch_dtype=torch.bfloat16, + spec_config=object() if mtp else None, + moe_load_balancer=MoeLoadBalancerConfig( + num_slots=cfg.n_routed_experts + ep * spare, + initial_global_assignments=assignments, + ), + ) + ) + core.dims = D.MODEL_WEIGHTS.dims(core) + return core, assignments + + +@pytest.mark.parametrize("layout", _EPLB_LAYOUTS, ids=_layout_id) +def test_eplb_slots_hold_the_placed_experts(layout): + """Rank r holds slots [r * S, (r + 1) * S) of every routed layer, S = num_slots / ep, + and each slot the expert the placement puts there; together the ranks hold every + expert of every layer, the MTP layer's included.""" + cfg = SimpleNamespace(**_TINY) + ep = layout[3] + held: dict = {} + for rank in range(layout[0]): + core, assignments = _eplb_core(layout, rank, cfg, mtp=True) + d = core.dims + local = (cfg.n_routed_experts + 2 * ep) // ep + assert (d.eplb, d.num_slots, d.local_slots, d.slot_offset) == ( + "static", + local * ep, + local, + rank * local, + ) + for i, placement in assignments.items(): + mine = tuple(placement[rank * local : (rank + 1) * local]) + assert d.slots[i].slot_experts == mine, (layout, rank, i) + held.setdefault(i, set()).update(mine) + assert all(experts == set(range(cfg.n_routed_experts)) for experts in held.values()) + + +@pytest.mark.parametrize("mtp", [False, True], ids=["no_mtp", "mtp"]) +@pytest.mark.parametrize("layout", _EPLB_LAYOUTS, ids=_layout_id) +def test_eplb_load_fills_every_slot_with_its_expert(layout, mtp, monkeypatch): + """`load` under static EPLB: coverage holds both ways, a rank reads each expert's + tensors once per slot that holds it and no expert it does not hold, and every slot + holds exactly what the world-size-1 table, which has no EPLB, loads for that slot's + expert.""" + 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) + for rank in range(layout[0]): + core, assignments = _eplb_core(layout, rank, cfg, mtp) + d = core.dims + 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) + + 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") + ) + 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) + assert torch.equal(core.w[f"l{i}_{name}"][slot], want), (rank, i, slot, name) From 1bf6bcf77efa1d83f7e13d39747a0e9b2bfff959 Mon Sep 17 00:00:00 2001 From: Ruocheng Jia Date: Tue, 17 Nov 2026 11:07:44 -0800 Subject: [PATCH 12/16] [TRTLLM-17824][doc] Show how to run EPLB on the DeepSeek-R1 modeling_v2 target The EPLB example said which Modeling V2 targets run which EPLB modes, but not how to run one. Its "Modeling V2 targets" section now walks the DeepSeek-R1-0528 NVFP4 target through EPLB at dep8 with copyable configuration files and commands: - static EPLB: collect the expert statistics on the built-in model (modeling_v2: "off"), generate the placement for 8 ranks and 288 slots, and run trtllm-bench and trtllm-serve on the target (modeling_v2: require) with it; - online EPLB: the load balancer file and the run; - dep4, and the limits: dep4 and dep8 only, static and online only, statistics from the built-in model. A bare `modeling_v2: off` in a configuration file is YAML for `false`, which the configuration rejects. The Modeling V2 README and the features skill now quote it. Signed-off-by: Ruocheng Jia --- .../trtllm-modeling-v2-features/SKILL.md | 2 +- examples/wide_ep/ep_load_balancer/README.md | 145 +++++++++++++++++- tensorrt_llm/_torch/modeling_v2/README.md | 3 +- 3 files changed, 147 insertions(+), 3 deletions(-) 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 892fe50e6476..16dc4d9f5919 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 @@ -132,7 +132,7 @@ Climb only as far as the claim needs. Each rung says what it cannot see. it, and make a shared runtime change the smallest general one, never a branch on this model. Name each such file and why in your report; the regression check follows it. -- A stock-path control (`--mode off`, `modeling_v2: off`) splits a target bug +- A stock-path control (`--mode off`, `modeling_v2: "off"`) splits a target bug from an engine bug. A new architecture has none; say so instead of guessing. - Report each feature as *verified* (its proof passed), *configured* (on, not proven) or *unsupported*. Never report configured as verified. diff --git a/examples/wide_ep/ep_load_balancer/README.md b/examples/wide_ep/ep_load_balancer/README.md index d6af24a07a7a..0ef9c5eef899 100644 --- a/examples/wide_ep/ep_load_balancer/README.md +++ b/examples/wide_ep/ep_load_balancer/README.md @@ -323,4 +323,147 @@ A [Modeling V2](../../../tensorrt_llm/_torch/modeling_v2/README.md) target runs |---|---|---| | 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 < Date: Tue, 17 Nov 2026 19:44:09 -0800 Subject: [PATCH 13/16] [TRTLLM-17824][test] Check MTP acceptance under static EPLB, and gate the slot-window test by arch With the MTP layer, the static EPLB accuracy test now also reads the acceptance length against the target's MTP minimum. EPLB changes no expert's math, so a draft routed to the wrong slots would show only as rejected drafts, which GSM8K alone does not see. The slot-window test drives the NVFP4 MoE runner, which runs on sm_100 and sm_103 only, so it now skips on other architectures. Signed-off-by: Ruocheng Jia --- .../test_accuracy.py | 18 ++++++++++++++++-- .../modeling_v2/moe/test_modeling_v2_eplb.py | 8 +++++++- 2 files changed, 23 insertions(+), 3 deletions(-) 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 3ea7342469c2..9a5430695a04 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 @@ -41,6 +41,7 @@ GSM8K, LlmapiAccuracyTestHarness, assert_acceptance_length, + assert_acceptance_length_for_llm, compute_acceptance_length, ) from ..._env import scoped_env_overrides @@ -335,7 +336,9 @@ def test_gsm8k_static_eplb(self, mocker, parallel, mtp): 288 slots hold the 256 experts of every routed layer. Every layer registers with the engine's load balancer, loads its experts by slot and routes the router's ids to slots, so this is the whole EPLB path of the target against - the same GSM8K reference as the identity cases. + the same GSM8K reference as the identity cases. With the MTP layer the acceptance + length is read against the target's MTP minimum too: EPLB changes no expert's math, + and a draft routed to the wrong slots would be rejected without moving the score. """ mocker.patch.dict(GSM8K.EVALUATE_KWARGS, _SCORES_FILTER) cfg_layers, first_moe, num_slots = 61, 3, 288 @@ -347,7 +350,16 @@ def test_gsm8k_static_eplb(self, mocker, parallel, mtp): load_balancer = MoeLoadBalancerConfig( num_slots=num_slots, initial_global_assignments=assignments ) - spec = dict(speculative_config=self.MTP3, kv_cache_config=self.MTP3_KV) if mtp else {} + 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, @@ -362,3 +374,5 @@ def test_gsm8k_static_eplb(self, mocker, parallel, mtp): ): task = GSM8K(self.MODEL_NAME) task.evaluate(llm) + if mtp: + assert_acceptance_length_for_llm(self.ACCEPTANCE_KEY, llm) diff --git a/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py b/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py index 19039acd3aec..d0bf2cd83ce2 100644 --- a/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py +++ b/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py @@ -22,6 +22,7 @@ MoeLoadBalancer, get_moe_load_balancer, ) +from tensorrt_llm._utils import get_sm_version from tensorrt_llm.llmapi.llm_args import MoeLoadBalancerConfig __extra_import_path__ = [".."] @@ -29,6 +30,11 @@ 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") +# 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), + reason="the NVFP4 MoE runner runs on sm_100 and sm_103 only", +) # --- slot layouts (CPU) --------------------------------------------------------------------- @@ -259,7 +265,7 @@ def test_an_id_outside_the_experts_routes_to_no_slot() -> None: # --- a slot-routed layer sums to the layer (GPU) --------------------------------------------- -@requires_gpu +@requires_sm10x def test_slot_windows_sum_to_the_layer() -> None: """Under EPLB each rank runs its slot window on slot-routed ids, and the windows add up to the layer: the DeepSeek-V3-Lite routed geometry (72 experts, H 2560, I 1536, top-6) From 328be78d4d7f9adc28e5d12713d61b97fffca622 Mon Sep 17 00:00:00 2001 From: Ruocheng Jia Date: Mon, 23 Nov 2026 01:37:12 -0800 Subject: [PATCH 14/16] [TRTLLM-17824][feat] Route each expert call through an EPLB context A target maps its router's expert ids to slot ids with `eplb_call(eplb, topk_ids)`, a context that yields `(slot_ids, plan)` and inside which the target enqueues the call's expert kernels. Without EPLB it yields the expert ids unchanged. The plan is None under static EPLB, whose slots are fixed at load; the context gives a mode that places replicas per call a place to hold its plan until the kernels are enqueued, without changing the target's call sites again. `EplbLayer.call` replaces `EplbLayer.route`. The DeepSeek-R1 target's trunk and MTP expert calls use the context, and the Modeling V2 README and the features skill describe it. CPU tests cover the routing with and without EPLB. Signed-off-by: Ruocheng Jia --- .../references/features.md | 11 +- tensorrt_llm/_torch/modeling_v2/README.md | 14 ++- .../_torch/modeling_v2/catalog/moe/eplb.py | 47 ++++++-- .../modeling.py | 112 +++++++++--------- .../modeling_v2/moe/test_modeling_v2_eplb.py | 45 ++++++- 5 files changed, 152 insertions(+), 77 deletions(-) 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 b39272903858..bc4a1a05e805 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 @@ -568,18 +568,19 @@ an EPLB deployment only if its class lists the mode in `EPLB_MODES`. `catalog/moe/eplb.py`: `eplb_slots` for each routed layer's slots, `EplbLayer.register` for each routed layer at construction in run order (a one-model draft layer with `repeat_count=max_draft_len`), expert weights - and per-expert scales sized and loaded by slot, and `EplbLayer.route` after - the router's top-k. The expert kernel then takes `num_slots` as its expert - count and this rank's slot window. + and per-expert scales sized and loaded by slot, and each expert call run + inside `eplb_call(eplb, topk_ids)`, which yields the slot ids (and the + call's plan, None for static) after the router's top-k. The expert kernel + then takes `num_slots` as its expert count and this rank's slot window. - `route` admits EPLB only at the layouts it was measured at (`moe_eplb_mode`). EPLB needs attention DP over ranks that hold whole experts (moe_tp 1), as the built-in MoE does. - A target that gathers tokens before routing routes on every rank and must - get the same slots on every rank: `EplbLayer.route` does + get the same slots on every rank: `eplb_call` does (`offset_by_ep_rank=False`). **Grep.** `EPLB_MODES`, `moe_eplb_mode`, `eplb_slots`, `EplbLayer`, -`eplb_route`, `moe_load_balancer_mode`, `maybe_create_moe_load_balancer`, +`eplb_call`, `eplb_route`, `moe_load_balancer_mode`, `maybe_create_moe_load_balancer`, `MoeLoadBalancerConfig`, `initial_global_assignments`, `num_slots`. **Tests to imitate.** diff --git a/tensorrt_llm/_torch/modeling_v2/README.md b/tensorrt_llm/_torch/modeling_v2/README.md index 3f0c5ede8687..00841ba07b4f 100644 --- a/tensorrt_llm/_torch/modeling_v2/README.md +++ b/tensorrt_llm/_torch/modeling_v2/README.md @@ -421,11 +421,15 @@ the example. `local_slots`, and fill slot `j` from checkpoint expert `slot_experts[j]`. An expert in two slots is loaded twice, and a rank reads only the experts its slots hold. -4. **Routing.** After the router's top-k, map the expert ids to slot ids - with `EplbLayer.route`, and call the expert kernels with `num_slots` as - the expert count and `[slot_offset, slot_offset + local_slots)` as this - rank's window. Every rank that routes the same tokens gets the same slots, - so a target that gathers its tokens before routing stays consistent. +4. **Routing.** After the router's top-k, run each expert call inside + `eplb_call(eplb, topk_ids)`, which yields the slot ids and the call's + plan, and call the expert kernels inside it with `num_slots` as the expert + count and `[slot_offset, slot_offset + local_slots)` as this rank's + window. Pass `None` for `eplb` without EPLB, and the slot ids are the + expert ids. Every rank that routes the same tokens gets the same slots, so + a target that gathers its tokens before routing stays consistent. Static + EPLB's plan is None; the routing is a context so that a mode that places + replicas per call can keep its plan until the kernels are enqueued. Then list the mode in the target class, `EPLB_MODES = frozenset({"static"})`, and gate the layouts in `route` on `moe_eplb_mode(model_config)`. diff --git a/tensorrt_llm/_torch/modeling_v2/catalog/moe/eplb.py b/tensorrt_llm/_torch/modeling_v2/catalog/moe/eplb.py index b8b1c985ad8b..c4401ac9de28 100644 --- a/tensorrt_llm/_torch/modeling_v2/catalog/moe/eplb.py +++ b/tensorrt_llm/_torch/modeling_v2/catalog/moe/eplb.py @@ -14,9 +14,14 @@ way. 2. `EplbLayer.register`: register the layer with the engine's balancer, at construction and in the order the layers run. -3. `EplbLayer.route`: map the router's expert ids to slot ids before the expert - GEMMs, which then take `num_slots` as their expert count and this rank's - slot window as their local experts. +3. `eplb_call`: around each expert call, map the router's expert ids to slot + ids for the expert GEMMs run inside it, which then take `num_slots` as their + expert count and this rank's slot window as their local experts. + +`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. `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 @@ -25,8 +30,9 @@ from __future__ import annotations +import contextlib from dataclasses import dataclass -from typing import Optional, Sequence +from typing import Iterator, Optional, Sequence import torch @@ -270,10 +276,33 @@ def register(cls, slots: EplbSlots, top_k: int, repeat_count: int = 1) -> "EplbL balancer_layer.set_initial_weight_assignments(list(slots.global_assignments)) return cls(balancer_layer, slots) - def route(self, token_selected_experts: torch.Tensor) -> torch.Tensor: - """Global expert ids `[T, top_k]` int32 -> global slot ids `[T, top_k]` int32. + @contextlib.contextmanager + def call(self, token_selected_experts: torch.Tensor) -> Iterator[tuple[torch.Tensor, None]]: + """The routing of one expert call; see `eplb_call`, which a target calls instead. - Routes with `offset_by_ep_rank=False`, so every rank that routes the same - tokens gets the same slots. + 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. """ - return eplb_route(token_selected_experts, self.balancer_layer, False) + yield eplb_route(token_selected_experts, self.balancer_layer, False), None + + +@contextlib.contextmanager +def eplb_call( + eplb: Optional[EplbLayer], token_selected_experts: torch.Tensor +) -> Iterator[tuple[torch.Tensor, None]]: + """The routing of one expert call, with or without EPLB. + + A context that yields `(slot_ids, plan)` for the expert kernels run inside it: + `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). + """ + if eplb is None: + yield token_selected_experts, None + return + with eplb.call(token_selected_experts) 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 fe6f16d3219a..1d486efa06d1 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 @@ -79,7 +79,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 +from tensorrt_llm._torch.modeling_v2.catalog.moe.eplb import EplbLayer, eplb_call from tensorrt_llm._torch.modeling_v2.catalog.moe.fp4_block_scale_moe_runner import ( # noqa: E501 fp4_block_scale_moe_runner, ) @@ -677,42 +677,41 @@ def _experts(core: DeepseekV3DefaultModelingV2, L: _LayerWeights, x: torch.Tenso cfg.num_experts_per_tok, float(cfg.routed_scaling_factor), ) - if L.eplb is not None: - topk_ids = L.eplb.route(topk_ids) - xq, xsf = fp4_quantize(chunk, L.moe_gscale, _SF_VEC, False, _SF_LINEAR) - parts.append( - fp4_block_scale_moe_runner( - routing_logits=None, - routing_bias=None, - hidden_states=xq, - hidden_states_scale=xsf.view(torch.float8_e4m3fn), - gemm1_weights=L.fc1_w, - gemm1_weights_scale=L.fc1_s, - gemm1_bias=None, - gemm1_alpha=None, - gemm1_beta=None, - gemm1_clamp_limit=None, - gemm2_weights=L.fc2_w, - gemm2_weights_scale=L.fc2_s, - gemm2_bias=None, - output1_scale_scalar=L.out1_scale, - output1_scale_gate_scalar=L.out1_gate_scale, - output2_scale_scalar=L.out2_scale, - num_experts=d.num_slots, - top_k=cfg.num_experts_per_tok, - n_group=None, - topk_group=None, - intermediate_size=d.moe_inter, - local_expert_offset=d.slot_offset, - local_num_experts=d.local_slots, - routed_scaling_factor=None, - routing_method_type=_ROUTING_METHOD_INERT, - do_finalize=True, - act_type=_ACT_TYPE_SWIGLU, - topk_weights=topk_w, - topk_ids=topk_ids, - )[0] - ) + with eplb_call(L.eplb, topk_ids) as (slot_ids, _): + xq, xsf = fp4_quantize(chunk, L.moe_gscale, _SF_VEC, False, _SF_LINEAR) + parts.append( + fp4_block_scale_moe_runner( + routing_logits=None, + routing_bias=None, + hidden_states=xq, + hidden_states_scale=xsf.view(torch.float8_e4m3fn), + gemm1_weights=L.fc1_w, + gemm1_weights_scale=L.fc1_s, + gemm1_bias=None, + gemm1_alpha=None, + gemm1_beta=None, + gemm1_clamp_limit=None, + gemm2_weights=L.fc2_w, + gemm2_weights_scale=L.fc2_s, + gemm2_bias=None, + output1_scale_scalar=L.out1_scale, + output1_scale_gate_scalar=L.out1_gate_scale, + output2_scale_scalar=L.out2_scale, + num_experts=d.num_slots, + top_k=cfg.num_experts_per_tok, + n_group=None, + topk_group=None, + intermediate_size=d.moe_inter, + local_expert_offset=d.slot_offset, + local_num_experts=d.local_slots, + routed_scaling_factor=None, + routing_method_type=_ROUTING_METHOD_INERT, + do_finalize=True, + act_type=_ACT_TYPE_SWIGLU, + topk_weights=topk_w, + topk_ids=slot_ids, + )[0] + ) return parts[0] if len(parts) == 1 else torch.cat(parts, 0) @@ -817,26 +816,25 @@ def _mtp_experts( cfg.num_experts_per_tok, float(cfg.routed_scaling_factor), ) - if M.eplb is not None: - topk_ids = M.eplb.route(topk_ids) - parts.append( - fused_moe( - input=chunk, - token_selected_experts=topk_ids, - token_final_scales=topk_w, - fc1_expert_weights=M.fc1, - fc1_expert_biases=None, - fc2_expert_weights=M.fc2, - fc2_expert_biases=None, - output_dtype=chunk.dtype, - quant_scales=[], - tp_size=d.moe_tp, - tp_rank=d.moe_tp_rank, - ep_size=d.moe_ep, - ep_rank=d.moe_ep_rank, - activation_type=_FUSED_MOE_ACT_SWIGLU, - )[0] - ) + with eplb_call(M.eplb, topk_ids) as (slot_ids, _): + parts.append( + fused_moe( + input=chunk, + token_selected_experts=slot_ids, + token_final_scales=topk_w, + fc1_expert_weights=M.fc1, + fc1_expert_biases=None, + fc2_expert_weights=M.fc2, + fc2_expert_biases=None, + output_dtype=chunk.dtype, + quant_scales=[], + tp_size=d.moe_tp, + tp_rank=d.moe_tp_rank, + ep_size=d.moe_ep, + ep_rank=d.moe_ep_rank, + activation_type=_FUSED_MOE_ACT_SWIGLU, + )[0] + ) return parts[0] if len(parts) == 1 else torch.cat(parts, 0) diff --git a/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py b/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py index d0bf2cd83ce2..b3c1d797358b 100644 --- a/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py +++ b/tests/unittest/_torch/modeling_v2/moe/test_modeling_v2_eplb.py @@ -16,7 +16,8 @@ import torch from tensorrt_llm._torch.modeling_v2.catalog._op import Cell -from tensorrt_llm._torch.modeling_v2.catalog.moe.eplb import EplbLayer, EplbSlots +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 eplb_route as op from tensorrt_llm._torch.moe.fused_moe.moe_load_balancer import ( MoeLoadBalancer, @@ -137,6 +138,48 @@ def test_registering_adds_the_layer_with_its_placement(mocked_runtime): assert get_moe_load_balancer() is None +# --- the routing of one expert call (CPU) --------------------------------------------------- + + +@pytest.mark.cpu_only +def test_without_eplb_a_call_routes_to_the_expert_ids(): + ids = torch.tensor([[3, 1], [0, 2]], dtype=torch.int32) + with eplb_call(None, ids) as (slot_ids, plan): + assert slot_ids is ids + assert plan is None + + +@pytest.mark.cpu_only +def test_a_registered_layer_routes_each_call_through_its_balancer(mocked_runtime, monkeypatch): + """Each call routes its own ids with the layer's balancer handle and the same slot on + every rank (`offset_by_ep_rank=False`), and static EPLB has no plan to hold.""" + routed = [] + + def route(ids, balancer_layer, offset_by_ep_rank): + routed.append((ids, balancer_layer, offset_by_ep_rank)) + return ids + 100 + + monkeypatch.setattr(eplb_module, "eplb_route", route) + slots = EplbSlots.from_config(MoeLoadBalancerConfig(num_slots=288), 3, 256, 4, 1) + balancer = MoeLoadBalancer(ep_rank=1, ep_size=4, layer_updates_per_iter=0) + try: + with balancer: + layer = EplbLayer.register(slots, top_k=8) + first = torch.tensor([[5, 6]], dtype=torch.int32) + second = torch.tensor([[7, 8], [9, 10]], dtype=torch.int32) + for ids in (first, second): + with eplb_call(layer, ids) as (slot_ids, plan): + assert torch.equal(slot_ids, ids + 100) + assert plan is None + finally: + balancer.shutdown() + assert len(routed) == 2 + for (ids, handle, offset), want in zip(routed, (first, second)): + assert ids is want + assert handle is layer.balancer_layer + assert offset is False + + # --- the routing op (GPU) --------------------------------------------------------------------- From 3c99f6b07a73acb496b4302c19eabd39f79c4ad1 Mon Sep 17 00:00:00 2001 From: Ruocheng Jia Date: Mon, 23 Nov 2026 23:46:40 -0800 Subject: [PATCH 15/16] [TRTLLM-17824][fix] Decline warmup placement in the R1 target; keep the hot replicas in the EPLB test placement The DeepSeek-R1 target registers its MoE layers with the load balancer but not with the warmup placement controller, so a static EPLB deployment that sets warmup_placement would keep its configured placement without a word. Its route now declines that combination: auto keeps the built-in model, require names it. The EPLB route test's placement put rank 0's second copy of its own expert over the first spare slot, which could hold a copy of the hot expert; that slot is now kept for it, and the placement asserts the hot expert's copy count. Signed-off-by: Ruocheng Jia --- .../modeling_v2/models/deepseek_v3/routing.py | 7 +++++++ .../modeling_v2/moe/ops/test_modeling_v2_eplb.py | 6 +++++- .../modeling_v2/test_modeling_v2_routing.py | 15 +++++++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/tensorrt_llm/_torch/modeling_v2/models/deepseek_v3/routing.py b/tensorrt_llm/_torch/modeling_v2/models/deepseek_v3/routing.py index 55b8fee1e882..91a3e3ecc153 100644 --- a/tensorrt_llm/_torch/modeling_v2/models/deepseek_v3/routing.py +++ b/tensorrt_llm/_torch/modeling_v2/models/deepseek_v3/routing.py @@ -180,6 +180,13 @@ def route( raise NoTarget( f"{eplb} EPLB at parallel layout {split}; the default target runs EPLB at dep4 and dep8" ) + # Warmup placement re-places the experts of the layers registered with its controller; + # the target registers its layers with the balancer only, so the placement would never move. + if eplb is not None and getattr(model_config.moe_load_balancer, "warmup_placement", None): + raise NoTarget( + f"{eplb} EPLB with moe_config.load_balancer.warmup_placement; the default target " + "keeps its configured placement and does not take part in warmup placement" + ) # Attention TP across nodes reduces only over multi-node NVLink. if not tp_reaches_across_nodes(mapping): 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 c1a4e241aa23..e7119ec94bbb 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 @@ -194,7 +194,10 @@ def _placement(experts: int, slots: int, ep_size: int, hot_replicas: int, seed: order = torch.randperm(experts, generator=g).tolist() per_rank, spare = experts // ep_size, (slots - experts) // ep_size hot = order[-1] - extra = [hot] * min(hot_replicas - 1, ep_size * spare) + # Rank 0's first spare slot is kept for its second copy, so no copy of `hot` lands there. + kept = 1 if spare else 0 + copies = min(hot_replicas - 1, ep_size * spare - kept) + extra = [None] * kept + [hot] * copies extra += [e for e in order if e != hot][: ep_size * spare - len(extra)] out = [] for rank in range(ep_size): @@ -203,6 +206,7 @@ def _placement(experts: int, slots: int, ep_size: int, hot_replicas: int, seed: if rank == 0 and spare: mine[0] = own[0] out += own + mine + assert out.count(hot) == 1 + copies, (out.count(hot), hot_replicas) return out 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 6cfb15e3c441..98558a8ab387 100644 --- a/tests/unittest/_torch/modeling_v2/test_modeling_v2_routing.py +++ b/tests/unittest/_torch/modeling_v2/test_modeling_v2_routing.py @@ -58,6 +58,7 @@ KvCacheConfig, MoeLoadBalancerConfig, MoePerLayerDynamicLoadBalancerConfig, + MoeWarmupPlacementConfig, MTPDecodingConfig, MultimodalConfig, NGramDecodingConfig, @@ -1759,6 +1760,20 @@ def test_r1_static_eplb_is_refused_where_it_was_not_measured(mapping_kwargs): modeling_v2_resolve(config, _llm_args("require")) +def test_r1_static_eplb_with_warmup_placement_keeps_the_builtin_model(): + """Warmup placement moves the experts of the layers registered with its controller; the + default target registers none, so the deployment keeps the built-in model rather than + run without the placement it asked for.""" + warmup = MoeWarmupPlacementConfig(start_step=0, interval_steps=1) + balancer = MoeLoadBalancerConfig(num_slots=288, warmup_placement=warmup) + config = replace(_model_config(_r1_config(), **_DEP4), moe_load_balancer=balancer) + assert modeling_v2_resolve(config, _llm_args("auto")) is None + with pytest.raises( + ValueError, match="static EPLB with moe_config.load_balancer.warmup_placement" + ): + modeling_v2_resolve(config, _llm_args("require")) + + @pytest.mark.usefixtures("_glm52_sm") def test_glm52_tep4_with_eplb_keeps_the_builtin_model(): """The tep4 target is built by default; it must not serve an EPLB deployment on fixed expert windows.""" From f80d9cee1cb117a6922beac308065ab0aea8064e Mon Sep 17 00:00:00 2001 From: Ruocheng Jia Date: Wed, 25 Nov 2026 21:42:45 -0800 Subject: [PATCH 16/16] [TRTLLM-17824][fix] Classify every nonzero update count as online EPLB; address review notes moe_load_balancer_mode now calls standard EPLB static exactly when no layer updates, the test MoeLoadBalancer.is_static_routing makes, so a negative layer_updates_per_iter no longer makes the resolver build a static target for an online balancer. A CPU test runs the DeepSeek-R1 shell's forward with a stub spec worker and checks that the MTP layer's EPLB is handed back once, after the worker returns, with and without draft steps. The README says what `last` marks: the last call of a pass over a layer. The feature skill names `eplb_call(..., rows=...)` for padding rows and the shard test file that checks online host copies. Signed-off-by: Ruocheng Jia --- .../references/features.md | 4 +- tensorrt_llm/_torch/modeling_v2/README.md | 18 +++---- .../_torch/moe/fused_moe/moe_load_balancer.py | 4 +- .../test_modeling_v2_deepseek_eplb_shards.py | 47 +++++++++++++++++++ .../_torch/moe/test_moe_load_balancer.py | 8 ++++ 5 files changed, 70 insertions(+), 11 deletions(-) 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 b32e8d2a83a7..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 @@ -579,7 +579,7 @@ an EPLB deployment only if its class lists the mode in `EPLB_MODES`. 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_default_shards.py` +- `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 @@ -606,7 +606,7 @@ not report the registered layers, so the target's own tests carry that. 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. - Attention-DP dummy requests count in the statistic like real tokens; - only the padding rows a target names in `route` are left out. + 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, and so does every later forward: a missed diff --git a/tensorrt_llm/_torch/modeling_v2/README.md b/tensorrt_llm/_torch/modeling_v2/README.md index 1011a906c89a..7d2433e09207 100644 --- a/tensorrt_llm/_torch/modeling_v2/README.md +++ b/tensorrt_llm/_torch/modeling_v2/README.md @@ -467,14 +467,16 @@ target does three more, and lists `"online"` in `EPLB_MODES`: 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 - forward's last call of the layer. `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. + 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 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/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 69f42c21b8c5..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 @@ -34,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 @@ -224,3 +227,47 @@ def test_online_eplb_load_hands_over_this_ranks_experts(layout, mtp, monkeypatch 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/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,