Skip to content

Upgrade DeepEP to DeepEP v2 APIs, enabling cudagraphable mode - #3808

Merged
wwwjn merged 11 commits into
mainfrom
deepep-v2-main
Jun 29, 2026
Merged

wwwjn merged 11 commits into
mainfrom
deepep-v2-main

Conversation

@wwwjn

@wwwjn wwwjn commented Jun 27, 2026 •

Copy link
Copy Markdown
Contributor

Start iterating per comments here: #3799 (comment) (Leave the DeepEP-LL untouched)

https://github.com/deepseek-ai/DeepEP#buffer-initialization

Compact vs. expand mode

  • DeepEP V1 High-Throughput mode = V2 Compact mode (do_expand=False, cudagraph off, training): recv_x is deduplicated + dynamically sized — one row per unique received token. Needs a CPU sync, is backward-able, not cudagraph-able. Must be gathered (_permute) into expert order before the grouped GEMM.
  • DeepEP V1 Low-latency mode = V2 Expand (do_expand=True, cudagraph on, inference): recv_x is a static slab — one slot per (token, expert), already expert-grouped. No CPU sync, not backward-able, is cudagraph-able.

num_max_tokens_per_rank meaning

  • Buffer allocation: sizes the single static ElasticBuffer used by both modes. Each local expert gets capacity num_max_tokens_per_rank × num_ranks (every EP rank can send up to num_max to any one expert). Required regardless of cudagraph.
  • Dispatch: does not cap/shrink your actual send (your batch does that). It's the upper bound the buffer is sized for; exceeding it = buffer overflow (misconfiguration, not a feature).
  • Combine: reduces the per-(token,expert) expert outputs back to tokens via the handle. In expand mode the unused padding slots are discarded by the handle (they never contribute), so combine doesn't add garbage and doesn't drop legitimate tokens.

Token dropping

  • Compact: unconditionally dropless in its output (allocated to the exact received count). The only failure mode is dispatcher needs to sending more tokens exceeding the buffer's num_max_tokens_per_rank reservation → overflow.
  • Expand: dropless iff num_max_tokens_per_rank ≥ actual max tokens/rank — the static slab's num_max × num_ranks per-expert capacity covers the worst case (a rank's whole batch routed to one expert). If a rank dispatches more than num_max, the excess overflows the slab → dropped.

Test (TBA)

  • Pre-training numerics parity w/ DeePEP Screenshot 2026-06-27 at 4 47 41 PM
    • baseline: AllToAllTokenDispatcher
  • Loss comparison w/ current main
  • Inference cudagraph-able
    • MoE expand mode is cudagraph captured.
  • RL end to end run: (trainer DeepEP no cudagraphable, and generator cudagraph-able)
    • 30B multi-node (16GPU) run: verified. DeepEP v2 (EP16, 2 nodes) + FULL_AND_PIECEWISE cudagraph + generation is conherent correct end-to-end
  • Composability with Activation checkpointing:
    • tested with FullAC, recomputing DeepEP to save memory, run succeed

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jun 27, 2026
top_k: int,
comm_backend: str,
non_blocking_capacity_factor: float | None = None,
hidden: int = 0,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
hidden: int = 0,
hidden_dim: int = 0,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unresolved

Comment thread torchtitan/distributed/deepep/deepep.py Outdated
"""Execute DeepEP dispatch."""
"""Execute DeepEP v2 dispatch.

``cudagraph=False`` (training/prefill): the COMPACT (non-expand) layout. ``recv_x`` is

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cudagraph=False (training/prefill)

Does this mean we could not use cudagraph for prefill, during generation?

@wwwjn wwwjn Jun 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it doesn't support MoE expand mode(cudagraph on) with gradients. So training can not use DeepEP + cudagraph

Comment thread torchtitan/distributed/deepep/deepep.py Outdated
Comment on lines +120 to +123
``cudagraph=True`` (inference/decode): the static ``do_expand`` layout, already
expert-grouped (tokens packed in ``[0:sum(counts)]``, tail unused) with no host sync, so
the forward is cudagraph-capturable; per-expert counts come from the device-side
``psum_num_recv_tokens_per_expert``.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When True, is it absolutely dropless? IIUC it's only possible if we allocate large enough buffer, I guess controlled by num_max_tokens_per_rank.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, in DeepEP num_max_tokens_per_rank definition is "any single local expert receives at most num_max_tokens_per_rank tokens from each of the num_ranks ranks.

  • num_ranks = EP ranks
  • The expand buffer is sized as num_local_experts × num_max_tokens_per_rank × num_ranks. So each local expert gets a fixed capacity of num_max_tokens_per_rank × num_ranks slots.

Comment thread torchtitan/distributed/deepep/deepep.py Outdated
num_tokens_per_expert: torch.Tensor,
num_experts: int,
num_max_tokens_per_rank: int,
cudagraph: bool,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cudagraphable or not is result, source is

Suggested change
cudagraph: bool,
do_cpu_sync: bool,

to be consistent with DeepEP API


needed_bytes = ElasticBuffer.get_buffer_size_hint(
group,
num_max_tokens_per_rank,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Question 1: Is this field required even when cudagraph is off?
Question 2: compared with always setting this to worst case (all tokens are routed to one EP rank), can user accept dropping tokens and set it to a smaller number to avoid OOM? like the HybridEP capacity factor.

@wwwjn wwwjn Jun 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In v2 definition: num_max_tokens_per_rank is a per rank send bound

Q1: yes, it's also used to size the Elastic buffer. So V2 used more memory than v1 https://github.com/deepseek-ai/DeepEP#notes
Q2: Lowing it will lower the buffer GPU memory usage. but it's not controlling the drop/dropless behavior,

Comment thread torchtitan/distributed/deepep/deepep.py Outdated
# generator -- which runs the forward under torch.no_grad()/inference_mode -- takes
# the cudagraph-able expand path. A cudagraph=True spec used in a grad context
# safely falls back to compact rather than hitting the no-backward kernel error.
cudagraph = cudagraph and not torch.is_grad_enabled()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a bad name cudagraph, this is a on/off switch between cudagraph mode / non-cudagraph

Comment thread torchtitan/distributed/deepep/deepep.py Outdated
"""Execute DeepEP dispatch."""
"""Execute DeepEP v2 dispatch.

``cudagraph=False`` (training/prefill): the COMPACT (non-expand) layout. ``recv_x`` is

@wwwjn wwwjn Jun 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it doesn't support MoE expand mode(cudagraph on) with gradients. So training can not use DeepEP + cudagraph

Comment thread torchtitan/distributed/deepep/deepep.py Outdated
Comment on lines +120 to +123
``cudagraph=True`` (inference/decode): the static ``do_expand`` layout, already
expert-grouped (tokens packed in ``[0:sum(counts)]``, tail unused) with no host sync, so
the forward is cudagraph-capturable; per-expert counts come from the device-side
``psum_num_recv_tokens_per_expert``.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, in DeepEP num_max_tokens_per_rank definition is "any single local expert receives at most num_max_tokens_per_rank tokens from each of the num_ranks ranks.

  • num_ranks = EP ranks
  • The expand buffer is sized as num_local_experts × num_max_tokens_per_rank × num_ranks. So each local expert gets a fixed capacity of num_max_tokens_per_rank × num_ranks slots.

Comment thread torchtitan/distributed/deepep/deepep.py Resolved
Comment thread torchtitan/distributed/deepep/deepep.py Resolved

# combine returns: combined_x
_lib.define("combine(Tensor x, Tensor handle_id) -> Tensor")
def _resolve_dispatch_num_sms(buffer, num_experts: int, num_topk: int) -> int:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is needed to run mulitnode on our cluster - but it seems it's a common patch to avoid using 0 sm

top_k: int,
comm_backend: str,
non_blocking_capacity_factor: float | None = None,
hidden: int = 0,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unresolved

comm_backend: str,
non_blocking_capacity_factor: float | None = None,
hidden: int = 0,
num_max_tokens_per_rank: int = 128,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we discussed offline that this field should be auto-computed to accommodate worst-case, instead of being configurable by user

@wwwjn wwwjn Jun 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the current code, I set the auto-computed path for compact mode, but not expand mode. Here's my rational:

For compact mode:

  • The compact path can size per-forward because it (a) runs eagerly and (b) is allowed to host-sync. So I set it to num_max_tokens_per_rank = hidden_states.shape[0]

For expand mode:

  • The buffer size can NOT be sized per-forward, and have to be decided at graph capture time.
  • The worst case would be <longest_possible_sequence_length> // sp_rank. In inference context ,we can know the <longest_possible_sequence_length> is vllm's chunked-prefill max_number_of_batched_token. But if a user use torchtitan trainer run forward + cudagraph, we can not know <longest_possible_sequence_length> in advance.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Can we not have default? For inference it should be max_num_batched_tokens, but what if users don't set it?
  2. For non-cudagraph it should be no-op, right?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Oh right, let don't have a default, and in inference path, if user don't set it, we can error out and let user aware this field is required? I don't want to introduce vllm_config. max_num_batched_tokens and depend on vllm in deepep.py

  2. For non cudagraph, now the user set value has higher priority. If user don't set it (leave it None), we auto size to num_max_tokens_per_rank = hidden_states.shape[0]. We can make it a non-op: just ignore what user set under non-cudagraph mode, which makes more sense

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree with 2.

For 1, you could do that in RL config -- wiring max_num_batched_tokens into deepep config. But I don't know what to set if max_num_batched_tokens is none.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In a RL config, if max_num_batched_tokens is not set explicity, then we cannot wiring max_num_batched_tokens to deepep.num_max_tokens_per_rank, then it's user's responsibility to set num_max_tokens_per_rank directly

# layout), so set it >= the largest per-rank token count to keep inference dropless.
# IGNORED in compact (cudagraphable=False) mode: training auto-sizes the buffer from
# the actual per-rank token count at dispatch (always dropless), so it need not be set.
num_max_tokens_per_rank: int = 128

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shouldn't be configurable

Comment on lines +80 to +83
config.model_spec = model_registry(
"debugmodel",
moe_comm_backend="deepep",
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how are you going to specify cudagraphable for generator model and non-cudagraphable for trainer model?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In my local run, I have a copy of model_spec for generator field, but it's not included in this PR. It would need more changes, like have another generator_model_spec in Controller.Config. This woud technically "break" our unified model path.

generator_model_spec = config.model_spec and then change dispatch config.

Let me add this change in current PR and have your review, and also give an example in RL config_registry.py

Comment thread torchtitan/experiments/rl/controller.py Outdated
``generator_model_spec`` is unset. Set programmatically via config_registry
(not from CLI)."""

generator_model_spec: Annotated[ModelSpec | None, tyro.conf.Suppress] = None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This breaks our unified modeling approach. Can we use ModeConfigConverter / override? Ideally the former, as it's code we maintain and recommend.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually converter happens also at config construction time, which doesn't allow trainer generator mismatch. Maybe the only way we could do it right now is through override.

comm_backend: str,
non_blocking_capacity_factor: float | None = None,
hidden: int = 0,
num_max_tokens_per_rank: int = 128,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Can we not have default? For inference it should be max_num_batched_tokens, but what if users don't set it?
  2. For non-cudagraph it should be no-op, right?

wwwjn added 8 commits June 28, 2026 15:27
DeepEP v2 (>=2.0.0) collapses the v1 two-path design -- high-throughput
(buffer.dispatch/combine) and low-latency (buffer.low_latency_dispatch/combine)
-- into a single dispatch/combine on deep_ep.ElasticBuffer. This replaces the
v1 DeepEP primitives with one ElasticBuffer-based implementation:

- deepep.py: one get_buffer (no HT/LL modes) and one dispatch_tokens/
  combine_tokens. v2 non-expand layout is already grouped by local expert
  (handle.num_recv_tokens_per_expert_list), so the manual _permute/_unpermute
  are dropped. Autograd keeps the validated v1 structure (pure-comm custom ops:
  dispatch backward = combine, combine backward = dispatch via cached handle;
  routing scores applied in plain PyTorch). LLDispatchState, the dual buffer
  modes, and the explicitly_destroy capture workaround are removed.
- token_dispatcher.py: DeepEPTokenDispatcher drops low_latency; adds
  num_max_tokens_per_rank/hidden (v2 sizes the buffer statically) and eager
  buffer creation in wire_meshes.
- config_utils.py / gpt_oss: thread hidden + num_max_tokens_per_rank through
  the backend-agnostic config builders.

Net -92 lines.
@wwwjn wwwjn changed the title [WIP] Upgrade DeepEP to DeepEP v2 APIs, enabling cudagraphable mode Upgrade DeepEP to DeepEP v2 APIs, enabling cudagraphable mode Jun 28, 2026
this generator's model spec after ``update_from_config`` and before build.
Separate from the trainer's override so the two can differ."""

converters: list[ModelConfigConverter.Config] = field(default_factory=list)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sorry for the back-and-forth, trying to make sure my message was delivered #3808 (comment)

Today converters in pretraining is a pure config time thing -- we do config conversion during config construction, and we don't modify the config any more when it's passed to the trainer using config converter (override still does).

I think we should use override for DeepEP inference in RL

  • reason 1 is to be consistent with how we use converters in pretraining
  • reason 2 is that it sort of aligns with the perf run spirit.

@wwwjn wwwjn Jun 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see, thank for correcting the behavior of converter and override. I just realized the converter is applied at model regsitry time now. Let me update to override

sort of aligns with the perf run spirit.

If we think cudagraph in generator is a perf improvement, that sounds reasonable. This override is to improve perf during inference and it aligns with our code cause we have seperete override for trainer and generator. Using DeepEP-v2 naturally post discrepancy in trainer and generator model definition

Comment thread .ci/docker/common/install_deepep.sh Outdated
# DeepEP is unavailable.
git clone --branch hybrid-ep https://github.com/deepseek-ai/deepep.git /tmp/deepep
# nightlies (ABI changes). DeepEP tests are skipped when it is unavailable.
git clone --branch main https://github.com/deepseek-ai/deepep.git /tmp/deepep

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One caveat about setting up the test is:

  • Previously we only test hybrid EP, and install from hybrid-ep branch.
  • We can not install both deepep v2 and hybrid EP in the same H100 environment
  • The only solution have both is to have 2 separate h100 test yaml file and have 2 separate environment (Keep HybridEP test using current h100 test yaml, and create a new one for DeepEP-v2). We can have a ciflow/deepep tag to trigger deepep-v2 test.

Which test we should keep? I could also leave a TODO to setup the test later

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we leave HybridEP in core and only test DeepEP in RL, for now?

num_max_tokens_per_rank: int = 128
# Model hidden dim, threaded so the expand buffer can be created eagerly at
# wire_meshes (before any cudagraph capture).
hidden: int = 0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
hidden: int = 0
hidden_dim: int = 0

Comment on lines +775 to +778
num_max_tokens_per_rank: int = 128
# Model hidden dim, threaded so the expand buffer can be created eagerly at
# wire_meshes (before any cudagraph capture).
hidden: int = 0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

don't need default value for these two?

imports=["torchtitan.overrides.deepep_inference"]
)
# Cap the per-step token budget so the worst-case per-rank expand count
# (max_num_batched_tokens / sp_size = 256 / 2 = 128) fits the dispatcher's default

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this assume SP degree being 2? Sounds not robust

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This config inherited from rl_grpo_qwen3_moe_debug_varlen , where

the sp size should equal to EP size is 4 (SP in dispatcher.. ) .

And the max_num_batched_tokens is set by heuristic which need to be tuned to fit generator into memory.

This config is an example, and we can set max_num_batched_tokens to be 2048 (vllm default), and ep=4, so it should be 2048/4=512.

Let me update the comment to note how we should set that:

  1. decided the inference max_num_batched_tokens (we expose the knob but default to None) according to your input sequence length
  2. decide num_max_tokens_per_rank: to make the model dropless (highest memory usage), set to <longest_sequecne_length > /sp; to save memory, gradually lower this bugget.

# Cap the per-step token budget so the worst-case per-rank expand count
# (max_num_batched_tokens / sp_size = 256 / 2 = 128) fits the dispatcher's default
# num_max_tokens_per_rank (128). Sizing that from the budget is a separate TODO.
config.generator.max_num_batched_tokens = 256

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this centering around DeepEP default max tokens being 128, which is not proven as a golden config either?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's put this in distributed/deepep/inference_override.py

Since the actual code is already in core, it's OK to put registration code in core.

the expand path to ``not torch.is_grad_enabled()``, so it only takes effect for the no-grad
inference forward.

The static per-rank EXPAND capacity (``num_max_tokens_per_rank``) is left at the dispatcher

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still not 100% clear to me how to set num_max_tokens_per_rank when vllm max_num_batched_tokens is not set. If it's set, it's should be wired up during rl config construction.

But I won't block this PR.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My current mindset is:

  • Let me update the comment to note how we should set that:

  • decided the inference max_num_batched_tokens (we expose the knob but default to None) according to your input sequence length

  • decide num_max_tokens_per_rank:

    • to make the model dropless (highest memory usage), set to <longest_sequence_length> // sp. <longest_sequence_length> would be equal to vllm_config.max_num_batched_tokens.
    • To save memory, gradually lower this bugget.

Vllm has a default max_num_batched_tokens (2048), but it's just a way of knowing the longest input sequence lenght

@wwwjn
wwwjn merged commit 756213e into main Jun 29, 2026
17 of 24 checks passed
yichuan-w added a commit that referenced this pull request Jun 29, 2026
Trainer: use mixed precision (fp32 master weights, bf16 compute via FSDP)
instead of full bf16, matching the other search_r1 trainer configs (per review).

Lint: the DeepEP v2 upgrade (#3808) plus a torch nightly that tightened
all_to_all_single's `group` type left 10 latent pyrefly errors on main. Push to
main does not run lint, so they only surface on any PR that runs lint (this one).
Fix them so the branch is green:
- deepep.py: narrow the global _buffer before .combine/.dispatch (existing
  idiom), enforce num_max_tokens_per_rank in expand mode, assert permuted_indices
  on the compact combine path.
- token_dispatcher.py: assert ep_mesh is set in the all-to-all helpers (only
  reached after the EP=1 early return); require hidden_dim for the expand buffer.
- pyproject.toml: treat optional deps batch_invariant_ops / torchcomms as Any.
yichuan-w added a commit that referenced this pull request Jun 29, 2026
Trainer: use mixed precision (fp32 master weights, bf16 compute via FSDP)
instead of full bf16, matching the other search_r1 trainer configs (per review).

Lint: the DeepEP v2 upgrade (#3808) plus a torch nightly that tightened
all_to_all_single's `group` type left 10 latent pyrefly errors on main. Push to
main does not run lint, so they only surface on any PR that runs lint (this one).
Fix them so the branch is green:
- deepep.py: narrow the global _buffer before .combine/.dispatch (existing
  idiom), enforce num_max_tokens_per_rank in expand mode, assert permuted_indices
  on the compact combine path.
- token_dispatcher.py: assert ep_mesh is set in the all-to-all helpers (only
  reached after the EP=1 early return); require hidden_dim for the expand buffer.
- pyproject.toml: treat optional deps batch_invariant_ops / torchcomms as Any.
yichuan-w added a commit that referenced this pull request Jun 29, 2026
Trainer: use mixed precision (fp32 master weights, bf16 compute via FSDP)
instead of full bf16, matching the other search_r1 trainer configs (per review).

Lint: the DeepEP v2 upgrade (#3808) plus a torch nightly that tightened
all_to_all_single's `group` type left 10 latent pyrefly errors on main. Push to
main does not run lint, so they only surface on any PR that runs lint (this one).
Fix them so the branch is green:
- deepep.py: narrow the global _buffer before .combine/.dispatch (existing
  idiom), enforce num_max_tokens_per_rank in expand mode, assert permuted_indices
  on the compact combine path.
- token_dispatcher.py: assert ep_mesh is set in the all-to-all helpers (only
  reached after the EP=1 early return); require hidden_dim for the expand buffer.
- pyproject.toml: treat optional deps batch_invariant_ops / torchcomms as Any.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Jul 1, 2026
Merge upstream/main (390ea37..). No replay triggers (llama3/deepseek_v3
untouched); agpt/moe byte-identical post-merge. One RL conflict in
generator.py resolved by taking upstream (spmd_types if/else superset).
DeepEP v2 upgrade (pytorch#3808) touches the moe token-dispatcher path -> smoking
agpt 2B (regression) + moe (deepep path) on Sunspot.
jemitche1 pushed a commit to jemitche1/torchtitan that referenced this pull request Jul 15, 2026
…h#3808)

Start iterating per comments here:
pytorch#3799 (comment)
(Leave the DeepEP-LL untouched)

 https://github.com/deepseek-ai/DeepEP#buffer-initialization

## Compact vs. expand mode

- DeepEP V1 High-Throughput mode = V2 Compact mode (do_expand=False,
cudagraph off, training): recv_x is deduplicated + dynamically sized —
one row per unique received token. Needs a CPU sync, is backward-able,
not cudagraph-able. Must be gathered (_permute) into expert order before
the grouped GEMM.
- DeepEP V1 Low-latency mode = V2 Expand (do_expand=True, cudagraph on,
inference): recv_x is a static slab — one slot per (token, expert),
already expert-grouped. No CPU sync, not backward-able, is
cudagraph-able.

## `num_max_tokens_per_rank` meaning

- Buffer allocation: sizes the single static ElasticBuffer used by both
modes. Each local expert gets capacity num_max_tokens_per_rank ×
num_ranks (every EP rank can send up to num_max to any one expert).
Required regardless of cudagraph.
- Dispatch: does not cap/shrink your actual send (your batch does that).
It's the upper bound the buffer is sized for; exceeding it = buffer
overflow (misconfiguration, not a feature).
- Combine: reduces the per-(token,expert) expert outputs back to tokens
via the handle. In expand mode the unused padding slots are discarded by
the handle (they never contribute), so combine doesn't add garbage and
doesn't drop legitimate tokens.

## Token dropping

- Compact: unconditionally dropless in its output (allocated to the
exact received count). The only failure mode is dispatcher needs to
sending more tokens exceeding the buffer's num_max_tokens_per_rank
reservation → overflow.
- Expand: dropless iff num_max_tokens_per_rank ≥ actual max tokens/rank
— the static slab's num_max × num_ranks per-expert capacity covers the
worst case (a rank's whole batch routed to one expert). If a rank
dispatches more than num_max, the excess overflows the slab → dropped.

## Test  (TBA)
- Pre-training numerics parity w/ DeePEP <img width="861" height="247"
alt="Screenshot 2026-06-27 at 4 47 41 PM"
src="https://github.com/user-attachments/assets/cca8f3e6-4885-4eb6-8b2a-5e448eeaa3f9"
/>
    - baseline: AllToAllTokenDispatcher
- Loss comparison w/ current main
- Inference cudagraph-able
   - MoE expand mode is cudagraph captured.
- RL end to end run: (trainer DeepEP no cudagraphable, and generator
cudagraph-able)
- 30B multi-node (16GPU) run: verified. DeepEP v2 (EP16, 2 nodes) +
FULL_AND_PIECEWISE cudagraph + generation is conherent correct
end-to-end
- Composability with Activation checkpointing:
    - tested with FullAC, recomputing DeepEP to save memory, run succeed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/rl ciflow/8gpu CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants