Repository navigation
Enables HybridEP torch.compile support and adds eager integration tests - #3360
Conversation
92b1f57 to
d03684e
Compare
|
There are few things to unpack here:
|
d03684e to
12efc1f
Compare
12efc1f to
ba79350
Compare
| "deepseek_v3_fsdp+ep+compile", | ||
| ngpu=4, | ||
| ), | ||
| OverrideDefinitions( |
There was a problem hiding this comment.
The additions will add too much burden to current models.py CI. I'd recommend adding a single test, or better, repurposing an existing deepseek test to use hybridep.
There was a problem hiding this comment.
Addressed. Only have a single test now.
| w1t = w1.bfloat16().transpose(-2, -1).contiguous() | ||
| w2t = w2.bfloat16().transpose(-2, -1).contiguous() | ||
| w3t = w3.bfloat16().transpose(-2, -1).contiguous() |
There was a problem hiding this comment.
moe.py: Make transposed weights contiguous before _grouped_mm to fix CUTLASS initialization failures on sm_100 (GB200) in the compiled backward pass.
Hmm didn't get it. I think we deliberately make it so that after transpose it's column major.
There was a problem hiding this comment.
I actually don't know much about the grouped_mm path that inductor takes. Without these .contingous() calls, this is exact error I'm seeing. The other workaround is, if I set pad_multiple=8 for the DeepEPTokenDispatcher. I wonder if the hybrid ep path was lacking some improvements from: #2956.
[rank0]:[titan] 2026-05-14 16:00:12,548 - root - INFO - Initializing HybridEP buffer: hidden_dim=256, max_tokens_per_rank=16384, num_local_experts=4, ep_size=2
[rank0]:/opt/pytorch/pytorch/aten/src/ATen/native/cuda/GroupMMCommon.cuh:64: prepare_grouped_gemm_data: block: [0,0,0], thread: [1,0,0] Assertion `delta % align == 0 && "expected input tensor dynamic dimension byte size to be non-negative multiple of 16\n"` failed.
[rank0]:/opt/pytorch/pytorch/aten/src/ATen/native/cuda/GroupMMCommon.cuh:64: prepare_grouped_gemm_data: block: [0,0,0], thread: [2,0,0] Assertion `delta % align == 0 && "expected input tensor dynamic dimension byte size to be non-negative multiple of 16\n"` failed.
[rank0]:[rank0]: Traceback (most recent call last):
[rank0]:[rank0]: File "<frozen runpy>", line 198, in _run_module_as_main
[rank0]:[rank0]: File "<frozen runpy>", line 88, in _run_code
[rank0]:[rank0]: File "/workspace/torchtitan/torchtitan/train.py", line 79, in <module>
[rank0]:[rank0]: main()
[rank0]:[rank0]: File "/workspace/torchtitan/torchtitan/train.py", line 65, in main
[rank0]:[rank0]: trainer.train()
[rank0]:[rank0]: File "/opt/pytorch/pytorch/torch/distributed/elastic/multiprocessing/errors/__init__.py", line 367, in wrapper
[rank0]:[rank0]: return f(*args, **kwargs)
[rank0]:[rank0]: ^^^^^^^^^^^^^^^^^^
[rank0]:[rank0]: File "/workspace/torchtitan/torchtitan/trainer.py", line 829, in train
[rank0]:[rank0]: self.train_step(data_iterator)
[rank0]:[rank0]: File "/workspace/torchtitan/torchtitan/trainer.py", line 732, in train_step
[rank0]:[rank0]: loss = self.forward_backward_step(
[rank0]:[rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^
[rank0]:[rank0]: File "/workspace/torchtitan/torchtitan/observability/structured_logger/structured_logging.py", line 436, in sync_wrapper
[rank0]:[rank0]: return func(*args, **kwargs)
[rank0]:[rank0]: ^^^^^^^^^^^^^^^^^^^^^
[rank0]:[rank0]: File "/workspace/torchtitan/torchtitan/trainer.py", line 688, in forward_backward_step
[rank0]:[rank0]: loss.backward()
[rank0]:[rank0]: File "/opt/pytorch/pytorch/torch/_tensor.py", line 633, in backward
[rank0]:[rank0]: torch.autograd.backward(
[rank0]:[rank0]: File "/opt/pytorch/pytorch/torch/autograd/__init__.py", line 395, in backward
[rank0]:[rank0]: _engine_run_backward(
[rank0]:[rank0]: File "/opt/pytorch/pytorch/torch/autograd/graph.py", line 913, in _engine_run_backward
[rank0]:[rank0]: return Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass
[rank0]:[rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[rank0]:[rank0]: File "/opt/pytorch/pytorch/torch/autograd/function.py", line 333, in apply_boxed
[rank0]:[rank0]: return self._get_user_fn()(self, *args)
[rank0]:[rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[rank0]:[rank0]: File "/opt/pytorch/pytorch/torch/_functorch/_aot_autograd/runtime_wrappers.py", line 3402, in backward
[rank0]:[rank0]: return CompiledFunction._bwd_fn(
[rank0]:[rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^
[rank0]:[rank0]: File "/opt/pytorch/pytorch/torch/_functorch/_aot_autograd/subclass_codegen.py:codegen(compiled_function_backward)", line 23, in _compiled_backward
[rank0]:[rank0]: File "/opt/pytorch/pytorch/torch/_functorch/_aot_autograd/subclass_codegen.py:codegen(compiled_function_backward)", line 14, in impl_fn
[rank0]:[rank0]: File "/opt/pytorch/pytorch/torch/_functorch/_aot_autograd/runtime_wrappers.py", line 3472, in _backward_impl
[rank0]:[rank0]: return call_func_at_runtime_with_args(
[rank0]:[rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[rank0]:[rank0]: File "/opt/pytorch/pytorch/torch/_functorch/_aot_autograd/utils.py", line 126, in call_func_at_runtime_with_args
[rank0]:[rank0]: out = normalize_as_list(f(args))
[rank0]:[rank0]: ^^^^^^^
[rank0]:[rank0]: File "/opt/pytorch/pytorch/torch/_dynamo/eval_frame.py", line 1382, in _fn
[rank0]:[rank0]: return fn(*args, **kwargs)
[rank0]:[rank0]: ^^^^^^^^^^^^^^^^^^^
[rank0]:[rank0]: File "/opt/pytorch/pytorch/torch/_inductor/output_code.py", line 753, in __call__
[rank0]:[rank0]: return self.current_callable(inputs)
[rank0]:[rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[rank0]:[rank0]: File "/tmp/torchinductor_root/tz/ctz7rncet4c3rb6t7rkxub4qo6akzvp3y3szkrwoj2vvlc5zoyee.py", line 2206, in call
[rank0]:[rank0]: buf22 = extern_kernels._grouped_mm(buf21, getitem_17, buf13, out_dtype=None)
[rank0]:[rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[rank0]:[rank0]: RuntimeError: cutlass cannot initialize
[rank0]:CUDA error encountered at: file=/workspace/DeepEP/csrc/hybrid_ep/hybrid_ep.cu, line=81, call='cudaDeviceSynchronize()', Reason=cudaErrorAssert:device-side assert triggeredFatal Python error: Aborted
[rank0]:
There was a problem hiding this comment.
Does this error only show up when compile is enabled? If so probably should ask @xmfan
There was a problem hiding this comment.
Yes, only when compile is enabled with --compile.enable --compile.components model,loss
There was a problem hiding this comment.
Is this a pytorch bug to be upstreamed? If this error only happens on sm_100, should we make these operations (memory heavy) conditional and leave a TODO until a fix is in pytorch?
There was a problem hiding this comment.
Does this happen only with HybridEP? If the code path before runs fine with compile, it suggests the HybridEP path has different metadata of inputs to the grouped mm
There was a problem hiding this comment.
Yes, only happens with HybridEP (verified by running NGPU=4 MODULE=deepseek_v3 CONFIG=deepseek_v3_debugmodel ./run_train.sh --parallelism.expert_parallel_degree=4 --compile.enable --compile.components model,loss). Thanks for this pointer! Let me investigate a bit more.
There was a problem hiding this comment.
Ok @xmfan is right I believe. The fake backward for dispatch and combine in hybridep uses new_zeros:
torchtitan/torchtitan/distributed/deepep/hybridep.py
Lines 327 to 328 in 52a292d
Inductor sees these as plain allocations it fully controls, so when the downstream graph does grad * scores -> transpose -> _grouped_mm, Inductor fuses the chain and materializes the result as a row-major (hidden_dim, tokens) buffer, triggering the CUTLASS TMA alignment assertion on sm_100 because the 2D/2D _grouped_mm backward requires per-expert token counts to be 8-aligned when A is row-major.
The standard EP path doesn't hit this because its combine backward uses native PyTorch ops (scatter_add, all_to_all) - Inductor traces through them fully and reuses existing buffers via reinterpret_tensor (column-major view), never allocating a fresh row-major transposed buffer.
I have tried replacing the new_zeros calls in the backward tracing path with dedicated custom ops (hybridep::combine_bwd, hybridep::dispatch_bwd) that have register_fake implementations. Inductor cannot optimize through custom op boundaries, so it must accept the output in standard (tokens, hidden_dim) contiguous layout and use reinterpret_tensor for the subsequent transpose - producing column-major A, which bypasses the alignment check entirely. Do you think that's the correct approach?
There was a problem hiding this comment.
Ok I consulted:
- https://docs.google.com/document/d/1_W62p8WJOQQUzPsJYa7s701JXt0qf2OfLub2sbkHOaU/edit?tab=t.0#heading=h.ptttacy8y1u9
- https://docs.pytorch.org/docs/2.12/library.html#torch.library.custom_op
and looks like hybridep should have declared the backward formulas for combine and dispatch to be custom ops per this comment from the manual: "If your operator's backward pass is a custom kernel, then it should be invoked through a custom operator.". By doing that, we don't need to have workarounds like checking if the untraceable dispatch handle is none (if dispatch_handle is None or dispatch_handle.value is None:) and based on that use new_zeros to have fake implementation. Now the backwards have their own custom ops, and inductor doesn't try to trace into it and cause the alignment problem.
| num_local_experts = num_experts // ep_size | ||
|
|
||
| # pyrefly: ignore [implicit-import, bad-argument-type] | ||
| group = torch._C._distributed_c10d._resolve_process_group(group_name) |
There was a problem hiding this comment.
Any reason to prefer the c++ binding here? a previous similar usage (
) used a pure python wrapper. We can remove the implicit import pyrefly error suppression if using a python wrapper.There was a problem hiding this comment.
Thanks! Addressed.
| w1t = w1.bfloat16().transpose(-2, -1).contiguous() | ||
| w2t = w2.bfloat16().transpose(-2, -1).contiguous() | ||
| w3t = w3.bfloat16().transpose(-2, -1).contiguous() |
There was a problem hiding this comment.
Is this a pytorch bug to be upstreamed? If this error only happens on sm_100, should we make these operations (memory heavy) conditional and leave a TODO until a fix is in pytorch?
c223a8a to
28c986b
Compare
@shuhuayu addressed the comment. See thread above. |
| """ | ||
| Pad per-expert token groups to this multiple for MXFP8 grouped GEMM alignment. | ||
| The CuTeDSL quantization kernel on sm_100 requires multiples of 128. | ||
| """ |
There was a problem hiding this comment.
Note this change is needed to run with MXFP8 on GB200. Tested using the following config:
def deepseek_v3_671b() -> Trainer.Config:
compile_config = CompileConfig(enable=True, components=["loss"])
model_compile_enabled = (
compile_config.enable and "model" in compile_config.components
)
return Trainer.Config(
loss=ChunkedCELoss.Config(),
hf_assets_path="./assets/hf/DeepSeek-V3.1-Base",
model_spec=model_registry(
"671B",
attn_backend="flex",
converters=[
MXFP8LinearConverter.Config(
recipe_name="mxfp8_rceil",
fqns=[
"attention.wq",
"attention.wo",
"feed_forward",
"shared_experts",
],
model_compile_enabled=model_compile_enabled,
),
MXFP8GroupedExpertsConverter.Config(
recipe_name="mxfp8_rceil",
model_compile_enabled=model_compile_enabled,
pad_multiple=128,
),
],
moe_comm_backend="hybridep",
non_blocking_capacity_factor=0.0375
),
dataloader=HuggingFaceTextDataLoader.Config(
dataset="c4",
),
optimizer=OptimizersContainer.Config(lr=2.2e-4),
lr_scheduler=LRSchedulersContainer.Config(
warmup_steps=2000,
decay_ratio=0.8,
decay_type="cosine",
min_lr_factor=0.1,
),
training=TrainingConfig(
local_batch_size=4,
seq_len=4096,
steps=10000,
),
parallelism=ParallelismConfig(
pipeline_parallel_schedule="Interleaved1F1B",
expert_parallel_degree=2,
),
checkpoint=CheckpointManager.Config(interval=500),
activation_checkpoint=ActivationCheckpointConfig(
mode="selective",
),
compile=compile_config,
)
There was a problem hiding this comment.
- compared with making it configurable, I wonder if we should detect hardware capability and make it automatically adapting
- at least we should error out when incompatible, similar to https://github.com/pytorch/torchtitan/blob/main/torchtitan/models/common/config_utils.py#L48
There was a problem hiding this comment.
@tianyu-l This is a tile size requirement set by the kernel that TorchAO selects:
I'm not sure if there is a clean way to detect this. Handling this in TorchTitan might add maintenance burden if TorchAO updates the kernel in the future, and changes the block size. I think keeping it just configurable is the most flexible here, until there is a better way to detect what TorchAO is using.
|
DSV3 671B run (PP=1, EP=64, DP=256, BS=8, --compile.components model,loss, full AC) on 64x4 GB200: |
| torch.library.define( | ||
| "hybridep::dispatch_bwd", | ||
| f"(Tensor grad_combined, {_handle_type} handle, int num_permuted_tokens, int? pad_multiple) -> Tensor", | ||
| ) |
There was a problem hiding this comment.
any reason to use torch.library.define instead of torch.library.custom_op?
xmfan
left a comment
There was a problem hiding this comment.
looks good, please use torch.library.custom_op if possible: https://docs.pytorch.org/docs/2.12/library.html#torch.library.custom_op
c430e7b to
decffe0
Compare
@tianyu-l This is a tile size requirement set by the kernel that TorchAO selects: I'm not sure if there is a clean way to detect this. Handling this in TorchTitan might add maintenance burden if TorchAO updates the kernel in the future, and changes the block size. I think keeping it just configurable is the most flexible here, until there is a better way to detect what TorchAO is using. |
There was a problem hiding this comment.
could you help remove this outdated comment?
| @@ -63,6 +63,16 @@ def deepseek_v3_debugmodel_ep() -> Trainer.Config: | |||
| return config | |||
There was a problem hiding this comment.
it seems we no longer need this, could you help clean up?
There was a problem hiding this comment.
Seems like this config is used by graph_trainer and other tests: https://github.com/search?q=repo%3Apytorch%2Ftorchtitan%20deepseek_v3_debugmodel_ep&type=code exercising the standard ep path.
There was a problem hiding this comment.
Maybe I missed something, but it looks identical to deepseek_v3_debugmodel. Can we do a global switch?
| OverrideDefinitions( | ||
| [ | ||
| [ | ||
| "--module deepseek_v3 --config deepseek_v3_debugmodel_hybridep", |
There was a problem hiding this comment.
oh I probably didn't understand why we are testing this on H100?
- Does it not work on A10 CI machines? If it works, why don't we test on them, as H is more limited resource.
- I thought the value of HybridEP is more for GB. Is testing on H100 a good proxy?
- Also I don't think we have a test for DeepEP on A/H CI. What would you suggest?
There was a problem hiding this comment.
- I haven't tried DeepEP on ampere machines. From the readme and existing issues (Does DeepEP support sm86?(4A6000 without NVL) deepseek-ai/DeepEP#481), it doesn't look like it's actively maintained or there are environment variable workarounds to disable h100 features to make it work. I think it might be easier to just follow the minimum requirement of hopper for this feature.
- Since we don't have GB in the CI yet, I think testing on H100 is a good proxy to maintain the integration.
- TBH, I think we should deprecate/cleanup deepep backend since it doesn't compose with CUDAGraph or figure out how to upgrade to the new DeepEP V2 backend (and see if it composes with cudagraphs? Not sure if it does.).
There was a problem hiding this comment.
Does HybridEP completely cover DeepEP on H100, in terms of features and efficiency?
The nightly x86 cuda wheel builds have been broken after 5/22. Prepared (updated link with a new PR:pytorch/pytorch#185560) to increase the default timeout for x86_64 nightly cuda wheel builds to restore the build health. Once this gets merged, we should have the manylinux wheels back again. Feel free to ping us (@nWEIdia @tinglvv) for CI/CD related issues in the future. |
b65059d to
8300477
Compare
|
@tianyu-l summary so far:
|
| @@ -63,6 +63,16 @@ def deepseek_v3_debugmodel_ep() -> Trainer.Config: | |||
| return config | |||
There was a problem hiding this comment.
Maybe I missed something, but it looks identical to deepseek_v3_debugmodel. Can we do a global switch?
Make the HybridEP dispatch custom op compatible with torch.compile by moving buffer initialization inside the op impl (opaque to dynamo) and passing ep_size/group_name through the op schema instead of relying on global state accessed during tracing. Key changes: - hybridep.py: Add ep_size (int) and group_name (str) to the dispatch op schema. Resolve the ProcessGroup from the name inside _dispatch_impl and call get_buffer there, avoiding dynamo tracing issues with _disable_current_modes and pybind11 objects. Fix buffer_config access for the refactored HybridEPBuffer API (configurer.buffer_config). Add initialization logging. - moe.py: Make transposed weights contiguous before _grouped_mm to fix CUTLASS initialization failures on sm_100 (GB200) in the compiled backward pass. - config_registry.py: Add deepseek_v3_debugmodel_hybridep config with non-blocking dispatch (capacity_factor=1.0). - models.py: Add FSDP+HybridEP and FSDP+HybridEP+compile integration tests. - CI: Move DeepEP installation from graph_trainer CI yaml into the Docker image (install_deepep.sh), gated on INSTALL_DEEPEP=true for the CUDA container only. Set CUDA_HOME in the Dockerfile so CI workflows no longer need to prefix it per-command.
8300477 to
d0c2fa1
Compare
|
Cleaned up deepseek_v3_debugmodel_ep config globally. Will merge after verifying CI status tomorrow. |
|
Verified that pytorch/pytorch#185560 is pulling latest nightly pytorch and existing 8 GPU model tests are passing. Merging based on this signal. |
…orch#3436 thread Merged 7 upstream commits (b72d986..04a3098). Headline is PR pytorch#3450 — the upstream-canonical fix for the histc->scatter swap that our PR pytorch#3436 was tracking. Approach: build boolean routing_map_BLE via scatter_ in router, compute num_tokens_per_expert via routing_map.sum, thread the map through to dispatcher. Same scatter direction we recommended, done better (computed once, reused). API change at the boundary: router returns 4-tuple; dispatch() takes new num_local_tokens_per_expert_E positional arg. ezpz doesn't override these methods or unpack router output directly, inherits cleanly. set_moe_sharding_config call into upstream's helper picks up the new shard declaration automatically. No ezpz replay needed. Other 6 commits: HybridEP compile (pytorch#3360), MXFP8 consolidation (pytorch#3473), graph_trainer DTensor fix (pytorch#3480), graph_trainer test skips (pytorch#3432), two CI migrations (pytorch#3464, pytorch#3479). None touch ezpz. Live 2N smoke deferred to Aurora: the project .venv/bin/python symlinks at an Aurora-only Spack hash (python-3.12.12-5zo3wzv) that Sunspot doesn't have (Sunspot equivalent is the nvje3vk hash). Smoke per the journal's "always smoke after GroupedExperts touches" lesson should run on Aurora. Also: updated ~/.ezpz/utils.sh from bit.ly canonical (now exposes unified ezpz_setup; backup at utils.sh-20260602-065437).
) fix CI errors on rocm when running `deepseek_v3_fsdp+hybridep+compile` example: https://github.com/pytorch/torchtitan/actions/runs/27108561047/job/80002013308 ``` ImportError: HybridEP requires deep_ep library. Install from: https://github.com/deepseek-ai/DeepEP, branch: hybrid-ep ``` Claude summary: What happened: - #3360 added the deepseek_v3_fsdp+hybridep+compile test to the h100 suite (tests/integration_tests/h100.py:82-95) and installed deep_ep in CUDA CI. That worked fine — at the time only the CUDA H100 job ran the h100 suite. - #3562 made the ROCm runner also execute the same h100 suite via the new shared run_8xgpu_integration_tests.sh. But deep_ep/NVSHMEM is CUDA-only, so the script deliberately skips installing it on ROCm (run_8xgpu_integration_tests.sh:71). The hybridep test still runs on ROCm → ModuleNotFoundError: No module named 'deep_ep'.
Make the HybridEP dispatch custom op compatible with torch.compile by moving buffer initialization inside the op impl (opaque to dynamo) and passing ep_size/group_name through the op schema instead of relying on global state accessed during tracing.
Key changes:
Assistant used: Claude Opus 4.7 (1M context)