Skip to content

Enables HybridEP torch.compile support and adds eager integration tests - #3360

Merged
syed-ahmed merged 9 commits into
mainfrom
syeahmed/hybrid-ep-fixes
Jun 1, 2026
Merged

syed-ahmed merged 9 commits into
mainfrom
syeahmed/hybrid-ep-fixes

Conversation

@syed-ahmed

@syed-ahmed syed-ahmed commented May 14, 2026 •

Copy link
Copy Markdown
Collaborator

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: Uses custom_op to resolve 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.
  • 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 install_deepep.sh.

Assistant used: Claude Opus 4.7 (1M context)

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label May 14, 2026
@syed-ahmed
syed-ahmed force-pushed the syeahmed/hybrid-ep-fixes branch from 92b1f57 to d03684e Compare May 14, 2026 22:13
@syed-ahmed

Copy link
Copy Markdown
Collaborator Author

There are few things to unpack here:

  • When @elfiegg 's HybridEP landed in , torch.compile was not being used for expert computation:
    if isinstance(submod, moe_module.MoE):
    # avoid graph breaking on the GroupedExperts' FSDP hooks
    # by wrapping each submod's forward instead of their __call__
    moe = submod
    for attr_name, submod in moe.named_children():
    if attr_name == "experts":
    # NOTE: We don't compile token dispatch and token combine due to an issue on B200:
    # https://github.com/pytorch/torchtitan/issues/1940
    continue
  • Fast forward, the full transformer block is now compiled with fullgraph=True. Without the changes in this PR, HybridEP initialization causes graph breaks.
  • a5a60cc added _disable_current_modes for DeepEP Buffer.__init__ calling all_gather_object(). However, HybridEP buffer object doesn't do that: https://github.com/deepseek-ai/DeepEP/blob/hybrid-ep/deep_ep/hybrid_ep_buffer.py. So I believe adding _disable_current_modes for HybridEP was wrong to begin with. We need to remove it first because it's not torch.compilable. Also remove the _buffer is None condition because get_buffer already checks that, and I needed that originally to get around _disable_current_modes in graph trainer as well (115f4c9).
  • After that, we need to move get_buffer into the custom op, so that dynamo doesn't trace it causing graph breaks. That brings in all the ep_size and ProcessGroup string plumbing.
  • Now that things are compilable, grouped_mm backward fails when running with compile, most likely because Inductor materializes the transposed X^T as an intermediate buffer with column-major strides (I'm not the expert here). It then passes this non-contiguous buffer directly to extern_kernels._grouped_mm. On GB200, the CUTLASS _grouped_mm kernel fails to initialize with these column-major strides. Note this doesn't happen on eager. Adding .contiguous() before _grouped_mm in the forward ensures the weight tensors are row-major. This propagates through autograd - inductor's backward intermediate buffers for the grad-weight computation are then also contiguous, so CUTLASS initializes successfully.

@syed-ahmed
syed-ahmed force-pushed the syeahmed/hybrid-ep-fixes branch from d03684e to 12efc1f Compare May 14, 2026 22:42
@syed-ahmed syed-ahmed changed the title Enable HybridEP torch.compile support and add eager integration tests Enables HybridEP torch.compile support and adds eager integration tests May 14, 2026
@tianyu-l
tianyu-l requested a review from shuhuayu May 14, 2026 22:50
@syed-ahmed
syed-ahmed force-pushed the syeahmed/hybrid-ep-fixes branch from 12efc1f to ba79350 Compare May 14, 2026 22:52
"deepseek_v3_fsdp+ep+compile",
ngpu=4,
),
OverrideDefinitions(

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Addressed. Only have a single test now.

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.

@shuhuayu could you help review this file

Comment thread torchtitan/models/common/moe.py Outdated
Comment on lines +66 to +68
w1t = w1.bfloat16().transpose(-2, -1).contiguous()
w2t = w2.bfloat16().transpose(-2, -1).contiguous()
w3t = w3.bfloat16().transpose(-2, -1).contiguous()

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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]:                                                                                                                                                                                                               

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.

Does this error only show up when compile is enabled? If so probably should ask @xmfan

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yes, only when compile is enabled with --compile.enable --compile.components model,loss

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 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?

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.

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Ok @xmfan is right I believe. The fake backward for dispatch and combine in hybridep uses new_zeros:

grad_x = grad_hidden.new_zeros(topk_idx.shape[0], grad_hidden.shape[-1])

grad_x = grad_combined.new_zeros(
ctx.num_permuted_tokens, grad_combined.shape[-1]

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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Ok I consulted:

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)

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.

Any reason to prefer the c++ binding here? a previous similar usage (

source_pg = dist.distributed_c10d._resolve_process_group(source_pg_name)
) used a pure python wrapper. We can remove the implicit import pyrefly error suppression if using a python wrapper.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Thanks! Addressed.

Comment thread torchtitan/models/common/moe.py Outdated
Comment on lines +66 to +68
w1t = w1.bfloat16().transpose(-2, -1).contiguous()
w2t = w2.bfloat16().transpose(-2, -1).contiguous()
w3t = w3.bfloat16().transpose(-2, -1).contiguous()

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 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?

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.

should we delete this?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yes.

@syed-ahmed
syed-ahmed force-pushed the syeahmed/hybrid-ep-fixes branch 5 times, most recently from c223a8a to 28c986b Compare May 20, 2026 22:33
@syed-ahmed

Copy link
Copy Markdown
Collaborator Author

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?

@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.
"""

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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,
    )

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

@tianyu-l This is a tile size requirement set by the kernel that TorchAO selects:

https://github.com/pytorch/ao/blob/c81eb798a5256f8807690a05cdca6843a22f6527/torchao/prototype/moe_training/kernels/mxfp8/cutedsl_quantize_2d_32x1.py#L1011-L1012

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.

@syed-ahmed syed-ahmed added the ciflow/h100.8 Trigger H100.8 CI label May 20, 2026
@syed-ahmed

Copy link
Copy Markdown
Collaborator Author

DSV3 671B run (PP=1, EP=64, DP=256, BS=8, --compile.components model,loss, full AC) on 64x4 GB200:

--rdzv_conf read_timeout=3600 --local-ranks-filter 0 --role rank --tee 3 -m torchtitan.train --module torchtitan_configs.deepseek_v3 --config deepseek_v3_671b --profiler.no-enable-profiling --metrics.enable-tensorboard --metrics.save_for_all_ranks --training.steps 50 --training.local_batch_size 8 --training.seq_len 4096 --parallelism.tensor_parallel_degree 1 --parallelism.pipeline_parallel_degree 1 --parallelism.context_parallel_degree 1 --parallelism.expert_parallel_degree 64 --dataloader.dataset c4_test --debug.seed 42 --compile.enable --compile.components model,loss --activation_checkpoint.mode=full --parallelism.data_parallel_shard_degree=-1 --comm.init_timeout_seconds=3600 --comm.train_timeout_seconds=3600
[rank0]:[titan] 2026-05-21 13:41:40,784 - root - INFO - torchtitan version: 0.2.2+git28c986b (0.0.0 means __version__ is not defined correctly).
[rank0]:[titan] 2026-05-21 13:41:40,994 - torchtitan.observability.structured_logger.jsonl_handler - INFO - Structured logging -> JSONL: /workspace/torchtitan/outputs/structured_logs/training.global_rank_0.20260521-134140-81UE0N.jsonl
[rank0]:[titan] 2026-05-21 13:41:41,422 - root - WARNING - ENV[TORCH_NCCL_ASYNC_ERROR_HANDLING] = 1 will be overridden to 3 based on job config
[rank0]:[titan] 2026-05-21 13:41:41,424 - root - INFO - Building device mesh with parallelism: pp=1, dp_replicate=1, dp_shard=256, cp=1, tp=1, ep=64
[rank0]:[titan] 2026-05-21 13:41:41,469 - root - INFO - Successfully created meshes with active dimensions: ['batch', 'loss', 'ep', 'efsdp', 'fsdp']
[rank0]:[titan] 2026-05-21 13:41:41,470 - root - INFO - [GC] Initial GC collection took 0.00 seconds
[rank0]:[titan] 2026-05-21 13:41:41,472 - root - INFO - Loading tokenizer from tokenizer.json
[rank0]:[titan] 2026-05-21 13:41:41,651 - root - INFO - Preparing c4_test dataset from /jet_art_root/unverified/text/core-models/c4/en_train_3gb
[rank0]:[titan] 2026-05-21 13:42:24,485 - root - INFO - Building deepseek_v3 671B
[rank0]:[titan] 2026-05-21 13:42:24,689 - root - INFO - TensorBoard logging enabled. Logs will be saved at ./outputs/tb/20260521-1342/rank_0
[rank0]:[titan] 2026-05-21 13:42:24,689 - root - INFO - CUDA capacity: NVIDIA GB200 with 184.31GiB memory
[rank0]:[titan] 2026-05-21 13:42:24,825 - root - INFO - Total parameter count: dense 14,456,871,936, sparse 656,569,532,416, active 37,552,282,624
[rank0]:[titan] 2026-05-21 13:42:24,825 - root - INFO - Model deepseek_v3 671B size: 671,026,404,352 total parameters
[rank0]:[titan] 2026-05-21 13:42:24,825 - root - INFO - Compiling the loss function with torch.compile
[rank0]:[titan] 2026-05-21 13:42:24,900 - root - INFO - Applied full activation checkpointing to the model
[rank0]:[titan] 2026-05-21 13:42:24,908 - root - INFO - Compiling each TransformerBlock with torch.compile
[rank0]:[titan] 2026-05-21 13:42:25,485 - root - INFO - Applied fully_shard to the model
[rank0]:[titan] 2026-05-21 13:42:26,501 - root - INFO - Peak FLOPS used for computing MFU: 2.500e+15
[rank0]:[titan] 2026-05-21 13:42:26,502 - root - INFO - CUDA memory usage for model: 9.85GiB(5.35%)
[rank0]:[titan] 2026-05-21 13:42:26,505 - root - WARNING - Warmup steps (2000) exceed total steps (50). Adjusting warmup steps to 50.
[rank0]:[titan] 2026-05-21 13:42:26,505 - root - WARNING - Warmup (50) + decay (40) steps exceed total steps (50). Adjusting decay steps to 0.
[rank0]:[titan] 2026-05-21 13:42:26,506 - root - WARNING - model.safetensors.index.json not found at hf_assets_path: /jet_art_root/unverified/model/core-models/deepseek-v3.1-base_tokenizer/hf-d3d4eaf/model.safetensors.index.json.                     Defaulting to saving a single safetensors file if checkpoint is saved in HF format
[rank0]:[titan] 2026-05-21 13:42:26,553 - root - INFO - Trainer is initialized with local batch size 8, global batch size 2048, gradient accumulation steps 1, sequence length 4096, total steps 50 (warmup 2000)
[rank0]:[titan] 2026-05-21 13:42:26,553 - root - INFO - Training starts at step 1
[rank0]:[titan] 2026-05-21 13:42:48,136 - root - INFO - Initializing HybridEP buffer: hidden_dim=7168, max_tokens_per_rank=32768, num_local_experts=4, ep_size=64
[rank0]:[titan] 2026-05-21 13:43:42,739 - root - INFO - step:  1  loss: 12.27126  grad_norm:  2.3152  memory: 87.19GiB(47.30%)  tps: 421  tflops: 118.24  mfu: 4.73%
[rank0]:[titan] 2026-05-21 13:43:42,740 - root - INFO - Synchronizing and adjusting timeout for all ProcessGroups to 1:00:00
[rank0]:[titan] 2026-05-21 13:46:27,278 - root - INFO - step: 10  loss:  9.35680  grad_norm: 10.0919  memory: 108.15GiB(58.68%)  tps: 1,792  tflops: 503.94  mfu: 20.16%
[rank0]:[titan] 2026-05-21 13:50:01,018 - root - INFO - step: 20  loss:  7.53822  grad_norm:  5.1168  memory: 108.15GiB(58.68%)  tps: 1,533  tflops: 431.04  mfu: 17.24%
[rank0]:[titan] 2026-05-21 13:53:45,236 - root - INFO - step: 30  loss:  7.00716  grad_norm:  3.7247  memory: 108.15GiB(58.68%)  tps: 1,461  tflops: 410.89  mfu: 16.44%
[rank0]:[titan] 2026-05-21 13:57:27,142 - root - INFO - step: 40  loss:  6.92056  grad_norm:  8.6678  memory: 108.15GiB(58.68%)  tps: 1,477  tflops: 415.18  mfu: 16.61%
[rank0]:[titan] 2026-05-21 14:00:47,618 - root - INFO - [GC] Performing periodic GC collection took 0.14 seconds
[rank0]:[titan] 2026-05-21 14:01:10,962 - root - INFO - step: 50  loss:  6.53257  grad_norm:  3.0405  memory: 108.15GiB(58.68%)  tps: 1,464  tflops: 411.63  mfu: 16.47%
[rank0]:[titan] 2026-05-21 14:01:10,963 - root - INFO - Sleeping 2 seconds for other ranks to complete
[rank0]:[titan] 2026-05-21 14:01:12,963 - root - INFO - Training completed
[rank0]:[titan] 2026-05-21 14:01:15,633 - root - INFO - Process group destroyed

@syed-ahmed
syed-ahmed requested review from shuhuayu, tianyu-l and xmfan May 22, 2026 00:29
Comment on lines +112 to +115
torch.library.define(
"hybridep::dispatch_bwd",
f"(Tensor grad_combined, {_handle_type} handle, int num_permuted_tokens, int? pad_multiple) -> Tensor",
)

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.

any reason to use torch.library.define instead of torch.library.custom_op?

@xmfan xmfan left a comment

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.

@syed-ahmed
syed-ahmed force-pushed the syeahmed/hybrid-ep-fixes branch from c430e7b to decffe0 Compare May 22, 2026 02:04
@syed-ahmed

Copy link
Copy Markdown
Collaborator Author

@tianyu-l This is a tile size requirement set by the kernel that TorchAO selects:

https://github.com/pytorch/ao/blob/c81eb798a5256f8807690a05cdca6843a22f6527/torchao/prototype/moe_training/kernels/mxfp8/cutedsl_quantize_2d_32x1.py#L1011-L1012

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.

Comment thread tests/integration_tests/h100.py Outdated

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.

could you help remove this outdated comment?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Addressed.

Comment thread tests/integration_tests/h100.py Outdated

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.

similar

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Addressed.

Comment on lines 60 to 63
@@ -63,6 +63,16 @@ def deepseek_v3_debugmodel_ep() -> Trainer.Config:
return config

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.

it seems we no longer need this, could you help clean up?

@syed-ahmed syed-ahmed May 27, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

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",

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.

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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

  • 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.).

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.

Does HybridEP completely cover DeepEP on H100, in terms of features and efficiency?

@tinglvv

tinglvv commented May 26, 2026 •

Copy link
Copy Markdown

@atalman @nWEIdia @tinglvv Would you know why there are no manylinux wheels after dev20260521?

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.

@syed-ahmed
syed-ahmed force-pushed the syeahmed/hybrid-ep-fixes branch from b65059d to 8300477 Compare May 27, 2026 00:44
@syed-ahmed

Copy link
Copy Markdown
Collaborator Author

@tianyu-l summary so far:

  • deepep test failures should now be exposed in upstream CI without blocking other tests.
  • the PAD_MULTIPLE factor should just remain configurable since it's a torchao specific variable and there isn't a good way to handle it without adding maintenance burden.
  • the histogram_cpu failures should be resolved in torchtitan when @tinglvv's [CD] Raise timeout for x86 cuda build pytorch#185289 lands in pytorch/pytorch and nightly wheel is available.
  • async TP tests are now enabled in CI.

Comment on lines 60 to 63
@@ -63,6 +63,16 @@ def deepseek_v3_debugmodel_ep() -> Trainer.Config:
return config

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.

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.
@syed-ahmed
syed-ahmed force-pushed the syeahmed/hybrid-ep-fixes branch from 8300477 to d0c2fa1 Compare May 29, 2026 02:45
@syed-ahmed

Copy link
Copy Markdown
Collaborator Author

Cleaned up deepseek_v3_debugmodel_ep config globally. Will merge after verifying CI status tomorrow.

@syed-ahmed

Copy link
Copy Markdown
Collaborator Author

Verified that pytorch/pytorch#185560 is pulling latest nightly pytorch and existing 8 GPU model tests are passing. Merging based on this signal.

@syed-ahmed
syed-ahmed merged commit 0acaaa1 into main Jun 1, 2026
27 of 36 checks passed
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Jun 2, 2026
…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).
wconstab added a commit that referenced this pull request Jun 8, 2026
)

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'.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/h100.8 Trigger H100.8 CI 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.

7 participants