Runtime error when enabling CP (context parallelism) during SFT of DeepSeek V4
I am performing full-parameter SFT on DeepSeek V4 using Megatron-Bridge framework. The training runs normally with both packed and non-packed data when context parallelism (CP) is disabled (i.e., --context-parallel-size 1).
However, when I enable CP with --context-parallel-size 2, both packed and non-packed data fail with errors.
Error logs:
- Non-packed data error:
[rank11]: File "/usr/local/lib/python3.12/dist-packages/torch/nn/modules/module.py", line 1832, in inner
[rank11]: result = forward_call(*args, **kwargs)
[rank11]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[rank11]: File "/opt/Megatron-Bridge/3rdparty/Megatron-LM/megatron/core/transformer/experimental_attention_variant/deepseek_v4_hybrid_attention.py", line 393, in forward
[rank11]: rot_part_out = apply_rotary_pos_emb(
[rank11]: ^^^^^^^^^^^^^^^^^^^^^
[rank11]: File "/opt/Megatron-Bridge/3rdparty/Megatron-LM/megatron/core/models/common/embeddings/rope_utils.py", line 381, in apply_rotary_pos_emb
[rank11]: return _apply_rotary_pos_emb_bshd(
[rank11]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^
[rank11]: File "/opt/Megatron-Bridge/3rdparty/Megatron-LM/megatron/core/models/common/embeddings/rope_utils.py", line 147, in _apply_rotary_pos_emb_bshd
[rank11]: t = (t * cos_) + (_rotate_half(t, rotary_interleaved) * sin_)
[rank11]: ~~^~~~~~
[rank11]: RuntimeError: The size of tensor a (848) must match the size of tensor b (424) at non-singleton dimension 0
- Packed data error:
0: /opt/pytorch/pytorch/aten/src/ATen/native/cuda/IndexKernelUtils.cu:16: vectorized_gather_kernel: block: [1687,0,0], thread: [1,0,0] Assertion `ind >=0 && ind < ind_dim_size && "vectorized gather kernel index out of bounds"` failed.
0: /opt/pytorch/pytorch/aten/src/ATen/native/cuda/IndexKernelUtils.cu:16: vectorized_gather_kernel: block: [1687,0,0], thread: [2,0,0] Assertion `ind >=0 && ind < ind_dim_size && "vectorized gather kernel index out of bounds"` failed.
.....
0: /opt/pytorch/pytorch/aten/src/ATen/native/cuda/IndexKernelUtils.cu:16: vectorized_gather_kernel: block: [1687,0,0], thread: [30,0,0] Assertion `ind >=0 && ind < ind_dim_size && "vectorized gather kernel index out of bounds"` failed.
0: /opt/pytorch/pytorch/aten/src/ATen/native/cuda/IndexKernelUtils.cu:16: vectorized_gather_kernel: block: [1687,0,0], thread: [31,0,0] Assertion `ind >=0 && ind < ind_dim_size && "vectorized gather kernel index out of bounds"` failed.
......
0: [rank0]: File "/opt/Megatron-Bridge/3rdparty/Megatron-LM/megatron/core/transformer/experimental_attention_variant/csa.py", line 1592, in forward
0: [rank0]: output = self._forward_thd(query, key, x, qr, packed_seq_params)
0: [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
0: [rank0]: File "/opt/Megatron-Bridge/3rdparty/Megatron-LM/megatron/core/transformer/experimental_attention_variant/csa.py", line 2078, in _forward_thd
0: [rank0]: compressed_kv, cu_seqlens_compressed = self.compressor(
0: [rank0]: ^^^^^^^^^^^^^^^^
0: [rank0]: File "/usr/local/lib/python3.12/dist-packages/torch/nn/modules/module.py", line 1778, in _wrapped_call_impl
0: [rank0]: return self._call_impl(*args, **kwargs)
0: [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
0: [rank0]: File "/usr/local/lib/python3.12/dist-packages/torch/nn/modules/module.py", line 1884, in _call_impl
0: [rank0]: return inner()
0: [rank0]: ^^^^^^^
0: [rank0]: File "/usr/local/lib/python3.12/dist-packages/torch/nn/modules/module.py", line 1832, in inner
0: [rank0]: result = forward_call(*args, **kwargs)
0: [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
0: [rank0]: File "/opt/Megatron-Bridge/3rdparty/Megatron-LM/megatron/core/transformer/experimental_attention_variant/csa.py", line 955, in forward
0: [rank0]: result = self._forward_thd(
0: [rank0]: ^^^^^^^^^^^^^^^^^^
0: [rank0]: File "/opt/Megatron-Bridge/3rdparty/Megatron-LM/megatron/core/transformer/experimental_attention_variant/csa.py", line 893, in _forward_thd
0: [rank0]: is_first = local_pos == 0 # (total_comp,)
0: [rank0]: ^^^^^^^^^^^^^^
0: [rank0]: torch.AcceleratorError: CUDA error: device-side assert triggered
0: [rank0]: Search for `cudaErrorAssert' in https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__TYPES.html for more information.
Environment:
Framework: Megatron-Bridge commit: c9ab9cc124a0553(main branch)
Megatron-LM commit: 3b9c248a1b7af07 (dev branch)
GPU: NVIDIA H100
CP size: 2
--seq-length: 4096
--max-position-embeddings: 65536
My training script:
def create_finetune_config():
model = AutoBridge.from_hf_pretrained("hf path to deepseekv4").to_megatron_provider(
load_weights=False
)
return ConfigContainer(
model= model,
ddp=DistributedDataParallelConfig(
check_for_nan_in_grad=True,
grad_reduce_in_fp32=True,
overlap_grad_reduce=True,
overlap_param_gather=True,
bucket_size=100000000,
),
train=TrainingConfig(
micro_batch_size=1,
global_batch_size=GLOBAL_BATCH_SIZE,
train_iters=MAX_STEP,
),
# optimizer=OptimizerConfig(
# optimizer="adam",
# lr = 2.4e-5,
# min_lr=3e-6,
# weight_decay = 0.1,
# adam_beta1 = 0.9,
# adam_beta2 = 0.95,
# use_distributed_optimizer = True,
# clip_grad = 1.0,
# bf16 = True,
# fp8_recipe = None,
# adam_eps = 1e-8,
# ),
optimizer=OptimizerConfig(
optimizer="dist_muon",
lr=2.4e-5,
min_lr=3e-6,
muon_extra_scale_factor = 0.2,
#muon_scale_mode = "unit_rms_norm",
weight_decay = 0.1,
adam_beta1 = 0.9,
adam_beta2 = 0.95,
clip_grad = 1.0,
bf16 = True,
fp8_recipe = None,
adam_eps = 1e-8,
use_distributed_optimizer = False, # True, ...muon must be false
overlap_param_gather = True,
),
scheduler=SchedulerConfig(
start_weight_decay=0.1,
end_weight_decay=0.1,
weight_decay_incr_style="constant",
lr_decay_style="cosine",
lr_warmup_iters=50,
),
# Finetuning dataset instead of pretraining dataset
dataset=FinetuningDatasetConfig(
dataset_root="data path root",
seq_length=SEQ_LENGTH,
do_validation=False,
do_test=False,
# Optional: packed sequence support
#packed_sequence_specs=PackedSequenceSpecs(
# packed_sequence_size=SEQ_LENGTH,
# packed_train_data_path=PACKED_TRAIN_DATA,
# packed_val_data_path=PACKED_VAL_DATA,
#),
dataset_kwargs = {
"chat": True
}
),
tokenizer=TokenizerConfig(
tokenizer_type="HuggingFaceTokenizer",
tokenizer_model="tokenizer path",
),
# Must specify pretrained checkpoint
checkpoint=CheckpointConfig(
pretrained_checkpoint=RESTORE_PATH,
save=CKPT_DIR,
load=CKPT_DIR,
save_interval=EVERY_N_TRAIN_STEPS,
most_recent_k=100,
async_save=True,
fully_parallel_save=True,
fully_parallel_load=True,
dist_ckpt_strictness="log_unexpected",
),
mixed_precision="bf16_mixed",
rng=RNGConfig(seed=1234),
comm_overlap=CommOverlapConfig(
tp_comm_overlap=False,
delay_wgrad_compute=False,
overlap_moe_expert_parallel_comm=False
),
logger=LoggerConfig(
log_interval=1,
tensorboard_dir=CKPT_DIR,
),
)
if __name__ == "__main__":
cfg = create_finetune_config()
#debug
cfg.model.use_fused_mhc = False
cfg.model.dsa_indexer_loss_coeff = 0.0
cfg.model.dsa_indexer_use_sparse_loss = False
#debug
cfg.model.fp8_recipe = None
cfg.optimizer.fp8_recipe = None
#mtp
cfg.model.mtp_num_layers = 1
cfg.model.mtp_loss_scaling_factor = 0.1
#moe
cfg.model.moe_router_pre_softmax = True
# rope
cfg.model.seq_length = SEQ_LENGTH
# recompute
cfg.model.recompute_granularity = 'full'
cfg.model.recompute_method = 'uniform'
cfg.model.recompute_num_layers = 1
# 3d parallel
cfg.model.sequence_parallel = False
cfg.model.pipeline_dtype = torch.bfloat16
cfg.model.params_dtype = torch.bfloat16
cfg.model.tensor_model_parallel_size=1
cfg.model.pipeline_model_parallel_size=16
cfg.model.expert_model_parallel_size=16
cfg.model.expert_tensor_parallel_size=1
cfg.model.context_parallel_size=2
cfg.model.batch_p2p_comm=True
set_deepseek_v4_pipeline_model_parallel_layout(cfg.model)
# fusion
cfg.model.attention_softmax_in_fp32 = True
cfg.model.moe_permute_fusion = False
cfg.model.apply_rope_fusion = False
cfg.model.bias_activation_fusion = False
cfg.model.bias_dropout_fusion = False
cfg.model.masked_softmax_fusion = False
cfg.model.gradient_accumulation_fusion = False
cfg.model.cross_entropy_loss_fusion = False
cfg.model.persist_layer_norm = False
#cfg.model.params_dtype = torch.float32
# when cp > 1,calculate_per_token_loss must be True
cfg.model.calculate_per_token_loss = True if cfg.model.context_parallel_size > 1 else False
cfg.model.sequence_parallel = True if cfg.model.tensor_model_parallel_size > 1 else False
if cfg.dataset.packed_sequence_specs is not None:
cfg.dataset.packed_sequence_specs.pad_seq_to_mult = cfg.model.context_parallel_size * 2 if cfg.model.context_parallel_size > 1 else 1
cfg.dataset.packed_sequence_specs.dataset_kwargs = {"pad_to_max_length": True} if cfg.model.context_parallel_size > 1 else None
print_rank_0("-----all transformer config-------")
print_rank_0(cfg.model)
finetune(cfg, forward_step_func=forward_step)
Thanks for the detailed configuration and traces. The Megatron-LM SHA in this report (3b9c248, June 30) predates DeepSeek-v4 context-parallel support. PR #5087 merged into dev on July 3 as bfa33263.
Please update the Megatron-LM revision used by Bridge and retest the packed THD path. The merged implementation requires qkv_format="thd" and cp_partition_mode="contiguous" when CP is enabled, so you may also need:
cfg.model.cp_partition_mode = "contiguous"
Non-packed BSHD DeepSeek-v4 CP is not supported by this implementation and should now produce an explicit error. If the packed path still fails after updating, please provide the new Bridge/Megatron-LM SHAs, printed model config, and updated traceback.
@Connor-XY , I update megatron-lm dev branch to commit bfa33263。and get a new error, whenever set sequence_packing_scheduler = "dp_balanced" or "default_dynamic_cp"
3: [rank3]: File "/opt/Megatron-Bridge/src/megatron/bridge/training/pretrain.py", line 98, in pretrain
3: [rank3]: _pretrain(state=state, forward_step_func=forward_step_func, callback_manager=callback_manager)
3: [rank3]: File "/opt/Megatron-Bridge/src/megatron/bridge/training/pretrain.py", line 142, in _pretrain
3: [rank3]: train(
3: [rank3]: File "/opt/Megatron-Bridge/src/megatron/bridge/training/train.py", line 453, in train
3: [rank3]: ) = wrapped_train_step(
3: [rank3]: ^^^^^^^^^^^^^^^^^^^
3: [rank3]: File "/opt/Megatron-Bridge/3rdparty/Megatron-LM/megatron/core/utils.py", line 2618, in wrapper
3: [rank3]: return func(*args, **kwargs)
3: [rank3]: ^^^^^^^^^^^^^^^^^^^^^
3: [rank3]: File "/opt/Megatron-Bridge/src/megatron/bridge/training/train.py", line 856, in train_step
3: [rank3]: model_chunk.zero_grad_buffer()
3: [rank3]: File "/opt/Megatron-Bridge/3rdparty/Megatron-LM/megatron/core/distributed/distributed_data_parallel.py", line 580, in zero_grad_buffer
3: [rank3]: bucket_group.reset()
3: [rank3]: File "/opt/Megatron-Bridge/3rdparty/Megatron-LM/megatron/core/distributed/param_and_grad_buffer.py", line 276, in reset
3: [rank3]: assert len(self.per_param_grad_ready_counts) == len(self.params)
3: [rank3]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3: [rank3]: AssertionError
When I set overlap_grad_reduce to False, the error disappears and the program runs normally. So I feel there is still some issue somewhere, because overlap_grad_reduce is usually set to True。this is my transformer config
tensor_model_parallel_size=1
pipeline_model_parallel_comm_backend=None
pipeline_model_parallel_size=16
virtual_pipeline_model_parallel_size=None
sequence_parallel=False
context_parallel_size=2
hierarchical_context_parallel_sizes=None
max_seqlen_per_dp_cp_rank=None
dynamic_context_parallel=False
min_dynamic_context_parallel_size=1
hybrid_context_parallel=False
sequence_packing_scheduler='dp_balanced'
pad_packed_seq_alignment=None
pad_packed_seq_by_appending_dummy_seq=True
expert_model_parallel_size=16
expert_tensor_parallel_size=1
perform_initialization=True
use_cpu_initialization=False
fp16=False
bf16=True
params_dtype=torch.bfloat16
timers=None
finalize_model_grads_func=None
grad_scale_func=None
moe_grad_scale_func=None
mtp_grad_scale_func=None
no_sync_func=None
grad_sync_func=None
param_sync_func=None
deterministic_mode=False
enable_autocast=False
autocast_dtype=None
num_microbatches_with_partial_activation_checkpoints=None
gradient_accumulation_fusion=False
use_te_rng_tracker=False
tp_comm_overlap=False
tp_comm_bulk_wgrad=True
tp_comm_bulk_dgrad=True
tp_comm_overlap_ag=True
tp_comm_overlap_rs=True
tp_comm_overlap_rs_dgrad=False
tp_comm_split_ag=True
tp_comm_atomic_ag=False
tp_comm_split_rs=True
tp_comm_atomic_rs=False
cross_entropy_loss_fusion=False
cross_entropy_fusion_impl='te'
tp_comm_overlap_disable_qkv=False
tp_comm_overlap_disable_fc1=False
tp_comm_bootstrap_backend='nccl'
overlap_moe_expert_parallel_comm=False
delay_wgrad_compute=False
overlap_dispatch_backward_with_experts_wgrad=False
ep_overlap_early_attn_memory_release=False
pipeline_dtype=torch.bfloat16
variable_seq_lengths=False
overlap_p2p_comm=False
batch_p2p_comm=True
batch_p2p_sync=True
use_ring_exchange_p2p=False
deallocate_pipeline_outputs=False
defer_embedding_wgrad_compute=False
wgrad_deferral_limit=0
overlap_p2p_comm_warmup_flush=False
microbatch_group_size_per_vp_stage=None
mtp_standalone=False
cpu_offloading=False
cpu_offloading_num_layers=0
_cpu_offloading_context=None
cpu_offloading_activations=True
cpu_offloading_weights=False
cpu_offloading_double_buffering=False
cpu_offloading_retain_pinned_cpu_buffers=False
barrier_with_L1_time=True
num_layers=43
mtp_num_layers=1
mtp_loss_scaling_factor=0.1
mtp_use_repeated_layer=False
mtp_detach_heads=False
mtp_hybrid_override_pattern=None
num_layers_in_first_pipeline_stage=None
num_layers_in_last_pipeline_stage=None
pipeline_model_parallel_layout=[['embedding', 'decoder', 'decoder', 'decoder'], ['decoder', 'decoder', 'decoder'], ['decoder', 'decoder', 'decoder'], ['decoder', 'decoder', 'decoder'], ['decoder', 'decoder', 'decoder'], ['decoder', 'decoder', 'decoder'], ['decoder', 'decoder', 'decoder'], ['decoder', 'decoder', 'decoder'], ['decoder', 'decoder', 'decoder'], ['decoder', 'decoder', 'decoder'], ['decoder', 'decoder', 'decoder'], ['decoder', 'decoder'], ['decoder', 'decoder'], ['decoder', 'decoder'], ['decoder', 'decoder'], ['decoder', 'decoder', 'mtp', 'loss']]
account_for_embedding_in_pipeline_split=False
account_for_loss_in_pipeline_split=False
hidden_size=4096
num_attention_heads=64
attention_backend=<AttnBackend.auto: 5>
softmax_scale=None
softmax_type='vanilla'
num_query_groups=1
ffn_hidden_size=2048
kv_channels=512
hidden_dropout=0.0
attention_dropout=0.0
fp32_residual_connection=False
apply_residual_connection_post_layernorm=False
layernorm_epsilon=1e-06
layernorm_zero_centered_gamma=False
add_bias_linear=False
add_qkv_bias=False
gated_linear_unit=True
activation_func=<function silu at 0x7f3ad913a340>
activation_func_fp8_input_store=False
glu_linear_offset=0.0
activation_func_clamp_value=10.0
num_moe_experts=256
rotary_interleaved=False
window_size=None
window_attn_skip_freq=None
normalization='RMSNorm'
qk_layernorm=True
qk_l2_norm=False
qk_clip=False
qk_clip_alpha=0.5
qk_clip_threshold=100
log_max_attention_logit=False
attention_output_gate=False
rotary_base_per_layer=None
head_wise_attn_gate=False
test_mode=False
calculate_per_token_loss=True
multi_latent_attention=True
no_rope_freq=None
experimental_attention_variant='dsv4_hybrid'
cp_partition_mode='contiguous'
dsa_indexer_n_heads=64
dsa_indexer_head_dim=128
dsa_indexer_topk=512
dsa_indexer_loss_coeff=0.0
dsa_indexer_use_sparse_loss=False
csa_window_size=128
csa_compress_ratios=[0, 0, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 0]
csa_compress_rotary_base=160000.0
csa_dense_mode=False
apply_dsa_kernel_fusion=False
linear_attention_type=None
linear_attention_freq=None
linear_conv_kernel_dim=4
linear_key_head_dim=128
linear_value_head_dim=128
linear_num_key_heads=16
linear_num_value_heads=32
gdn_pre_gated_delta_rule_fusion=False
gdn_conv_pad_alignment=None
init_method=None
output_layer_init_method=None
init_method_std=0.02
embedding_init_method=None
embedding_init_method_std=None
init_model_with_meta_device=False
use_mup=False
mup_width_mult=1.0
mup_base_hidden_size=None
mup_embedding_mult=1.0
mup_output_mult=1.0
mup_base_head_dim=None
mup_attn_scale_power=1.0
apply_query_key_layer_scaling=False
attention_softmax_in_fp32=True
disable_bf16_reduced_precision_matmul=False
bias_activation_fusion=False
masked_softmax_fusion=False
persist_layer_norm=False
memory_efficient_layer_norm=False
bias_dropout_fusion=False
apply_rope_fusion=False
use_fused_weighted_squared_relu=False
fused_single_qkv_rope=False
use_transformer_engine_op_fuser=False
fused_residual_rmsnorm=False
recompute_granularity='full'
recompute_method='uniform'
recompute_num_layers=1
distribute_saved_activations=False
recompute_modules=None
fp8=None
fp8_recipe=None
fp8_param=False
fp8_quantizer_factory=None
fp8_margin=0
fp8_interval=1
fp8_amax_history_len=1
fp8_amax_compute_algo='most_recent'
fp8_wgrad=True
fp8_output_proj=False
fp8_dot_product_attention=False
fp8_multi_head_attention=False
tp_only_amax_red=False
first_last_layers_bf16=False
num_layers_at_start_in_bf16=1
num_layers_at_end_in_bf16=1
use_kitchen=False
use_kitchen_attention=False
kitchen_attention_backend='sdpa'
fp4=None
fp4_recipe='nvfp4'
fp4_param=False
fp4_quantizer_factory=None
high_priority_a2a_comm_stream=False
moe_shared_expert_intermediate_size=2048
moe_shared_expert_gate=False
moe_shared_expert_overlap=True
moe_layer_freq=[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
moe_ffn_hidden_size=2048
moe_router_load_balancing_type='noaux_tc'
moe_router_topk=6
moe_enable_routing_replay=False
moe_router_topk_limited_devices=None
moe_router_padding_for_quantization=False
moe_router_padding_for_fp8=False
moe_router_num_groups=None
moe_router_group_topk=None
moe_router_pre_softmax=True
moe_router_topk_scaling_factor=1.5
moe_router_score_function='sqrtsoftplus'
moe_router_dtype='fp32'
moe_router_enable_expert_bias=True
moe_router_bias_update_rate=0.001
moe_router_force_load_balancing=False
moe_router_force_biased=None
moe_n_hash_layers=3
actual_vocab_size=129280
dense_grouped_gemm=False
use_grouped_gemm_for_dense_mlp=False
log_moe_overload_factor=False
moe_grouped_gemm=True
moe_single_grouped_weight=False
moe_single_grouped_bias=False
moe_aux_loss_coeff=0.0
moe_z_loss_coeff=None
moe_input_jitter_eps=None
moe_token_dropping=False
moe_token_dispatcher_type='alltoall'
moe_enable_deepep=False
moe_flex_dispatcher_backend='deepep'
moe_permute_fusion_into_hybridep=False
moe_hybridep_pad_variable_tokens=False
moe_per_layer_logging=False
moe_expert_capacity_factor=None
moe_expert_rank_capacity_factor=None
moe_pad_expert_input_to_capacity=False
moe_pad_experts_for_cuda_graph_inference=False
moe_token_drop_policy='probs'
moe_layer_recompute=False
moe_permute_fusion=False
moe_router_fusion=False
moe_apply_probs_on_input=False
moe_latent_size=None
moe_deepep_num_sms=None
moe_hybridep_num_sms=None
moe_hybridep_num_blocks_permute=None
moe_hybridep_num_blocks_unpermute=None
moe_hybridep_num_sms_preprocessing=108
moe_mlp_glu_interleave_size=None
cp_comm_type=None
linear_cp_mode='chunkwise'
enable_cuda_graph=False
cuda_graph_use_single_mempool=True
cuda_graph_retain_backward_graph=False
cuda_graph_warmup_steps=3
external_cuda_graph=False
cuda_graph_impl='none'
cuda_graph_modules='full'
create_attention_mask_in_dataloader=True
inference_cuda_graph_scope=None
cuda_graph_scope=None
thd_max_packed_sequences=32
cuda_graph_dynamic_microbatches=False
enable_hyper_connections=True
num_residual_streams=4
mhc_sinkhorn_iterations=20
mhc_init_gating_factor=0.01
use_fused_mhc=False
mhc_recompute_layer_num=None
clone_scatter_output_in_embedding=True
disable_parameter_transpose_cache=False
config_logger_dir=''
flash_decode=False
batch_invariant_mode=False
use_te_activation_func=False
inference_rng_tracker=False
inference_sampling_seed=42
symmetric_ar_type=None
nccl_all_reduce_for_prefill=False
use_inference_optimized_layers=False
inference_fuse_tp_communication=False
inference_disable_triton_nvls_kernels=False
inference_grouped_gemm_backend='vllm'
inference_moe_disable_fused_quant_kernels=False
inference_moe_token_dispatcher_type='nvls'
mrope_section=None
mrope_interleaved=False
is_hybrid_model=False
mamba_state_dim=128
mamba_head_dim=64
mamba_num_groups=8
mamba_num_heads=None
mamba_training_ssm_states_dtype=None
use_mamba_mem_eff_path=True
mlp_chunks_for_prefill=1
mlp_chunks_for_training=1
heterogeneous_block_specs=False
hetereogenous_dist_checkpoint=False
quant_recipe=None
transformer_impl='transformer_engine'
fallback_to_eager_attn=False
fine_grained_activation_offloading=False
offload_modules=[]
min_offloaded_tensor_size=1048576
delay_offload_until_cuda_graph=False
delta_offload_bytes_across_pp_ranks=0
activation_offload_fraction=1.0
fine_grained_offloading_max_inflight_offloads=None
moe_paged_stash=False
moe_paged_stash_page_size=64
moe_paged_stash_buffer_size_factor_cuda=1.1
moe_paged_stash_buffer_size_factor_cpu=0.0
q_lora_rank=1024
kv_lora_rank=512
qk_head_dim=128
qk_pos_emb_head_dim=64
v_head_dim=512
rope_type='yarn'
rotary_base=10000.0
rotary_percent=1.0
rotary_scaling_factor=16.0
original_max_position_embeddings=65536
beta_fast=32.0
beta_slow=1.0
mscale=1.0
mscale_all_dim=1.0
o_groups=8
o_lora_rank=1024
cache_mla_latents=False
mla_down_proj_fusion=False
fp16_lm_cross_entropy=False
parallel_output=True
share_embeddings_and_output_weights=False
make_vocab_size_divisible_by=1280
position_embedding_type='rope'
rope_scaling=False
rope_scaling_factor=1.0
seq_len_interpolation_factor=None
yarn_rotary_scaling_factor=None
yarn_original_max_position_embeddings=None
yarn_beta_fast=None
yarn_beta_slow=None
yarn_mscale=None
yarn_mscale_all_dim=None
yarn_correction_range_round_to_int=None
seq_length=4096
scatter_embedding_sequence_parallel=True
tp_comm_overlap_cfg=None
use_transformer_engine_full_layer_spec=False
transformer_layer_spec=<function get_transformer_block_with_experimental_attention_variant_spec at 0x7f379d347e>
hf_model_id='/gpfsprd/OpenSourceModels/DeepSeek-V4-Flash'
vocab_size=129280
should_pad_vocab=False
mtp_enabled=False
restore_modelopt_state=False
use_arbitrary_attention_mask=None
_pg_collection=None
Thanks for retesting on bfa33263 and for the updated config. This looks like a new failure class from the original RoPE/CSA CP issue.
The new assertion is in BucketGroup.reset() during the first-batch grad-ready accounting. Since it disappears when overlap_grad_reduce=False, I would treat this as an overlap-grad-reduce / gradient-hook readiness issue under the DSv4 + packed sequence scheduler + CP/PP/EP configuration, not as the original missing DeepSeek-v4 CP support.
A couple of useful narrowing checks, if you have bandwidth:
- Does it reproduce with the Adam optimizer path from your script, or only with
dist_muon? - Does it reproduce with
sequence_packing_scheduler="default_dynamic_cp"and"dp_balanced"equally, or is one path different? - Please share the exact Megatron-Bridge SHA after the update as well, since the traceback is through Bridge training wrappers.
I am leaving this open for maintainer investigation. The likely area to inspect is the interaction between overlap grad reduce, the first-iteration per_param_grad_ready_counts bookkeeping, and this DSv4 pipeline/MTP/MoE layout.
- I switched to the Adam optimizer, but the error still persists.
- The same error occurs with both sequence_packing_scheduler="default_dynamic_cp" and "dp_balanced".
- my Megatron-Bridge commit id: c9ab9cc124a0553 on main branch. In Megatron-Bridge source code, the cp_partition_mode parameter is missing in the _forward_step_common function in gpt_step.py. I added it myself, like this,but total_tokens、seq_idx、pad_between_seqs is not set,I'm not sure whether they need to set it or not.
if cu_seqlens is not None:
packed_seq_params = {
"cu_seqlens": cu_seqlens,
"cu_seqlens_argmin": cu_seqlens_argmin,
"max_seqlen": max_seqlen,
"cu_seqlens_unpadded": cu_seqlens_unpadded,
"cu_seqlens_unpadded_argmin": cu_seqlens_unpadded_argmin,
}
# total_tokens drives seq_idx computation in PackedSeqParams.__post_init__,
# which is only needed for Mamba/hybrid SSM layers. Skip it for pure
# transformer models to avoid per-step CUDA overhead.
if getattr(config, "is_hybrid_model", False):
if tokens is not None:
packed_seq_params["total_tokens"] = tokens.size(1)
elif labels is not None:
packed_seq_params["total_tokens"] = labels.size(1)
else:
packed_seq_params["total_tokens"] = getattr(config, "seq_length", None)
forward_args["packed_seq_params"] = get_packed_seq_params(packed_seq_params)
forward_args["packed_seq_params"].cp_partition_mode = "contiguous" #<---------- add by myself
- I tried skipping Megatron-Bridge and training directly with Megatron-LM, but I'm still getting the same error above.
@Connor-XY Hi, sorry to bother you. I'm trying to fully fine-tune DeepSeek-V4-Flash on H100. I currently have 32 nodes, with a 3D parallel strategy of TP=1, PP=16, EP=16, ETP=1, and CP=8. With this setup, the max sequence length I can run is 16k. When I try to increase it to 32k, even setting CP=16 still results in OOM.
I've tried tweaking some parameters , but they don't seem to help, and they don't support the Muon optimizer anyway.
cfg.optimizer.optimizer_cpu_offload = True
cfg.optimizer.use_precision_aware_optimizer = True
cfg.optimizer.optimizer_offload_fraction = 1.0
cfg.optimizer.overlap_cpu_optimizer_d2h_h2d = True
My ultimate goal is to train with a sequence length of 256k. I can add more H100 nodes if needed, but I'd really appreciate your advice on how to partition the model more efficiently. Also, is TP strictly limited to 1? Or can it be increased?
Dug into the per_param_grad_ready_counts assertion. The trigger is dsa_indexer_loss_coeff = 0.0 combined with CP, not the packing scheduler.
With overlap_grad_reduce=True, DDP records which params report a ready grad on the last microbatch of the first iteration and asserts that every param in the bucket did (BucketGroup.reset). The CP THD attention path only attaches the indexer loss to the autograd graph when the coefficient is positive (use_indexer_loss in _forward_thd_cp). At coeff 0 the indexer projections feed nothing but the non-differentiable top-k selection, so the indexer weights on every ratio-4 CSA layer receive no gradient, and the assert trips when iteration 2 starts. The CP=1 paths behave differently: they run FusedDSAIndexerLoss unconditionally during training and attach it via DSAIndexerLossAutoScaler, so the indexer params get zero-valued (but present) grads and the bookkeeping is satisfied. That explains everything you observed: CP=1 works, CP≥2 fails, independent of optimizer, scheduler choice, and Bridge vs bare Megatron-LM.
Two options:
- If you want the indexer trained, and for full SFT you probably do (at coeff 0 under CP it gets no signal at all, so it stays frozen while the attention it approximates moves), set
dsa_indexer_loss_coeffto a nonzero value. That reconnects the params, andoverlap_grad_reduce=Trueshould work again. If the assert still fires with a nonzero coeff, it means some CP shard produced no complete compression blocks in a microbatch; please report that here, the fix needs to cover it too. - If you deliberately want the indexer frozen, keep
overlap_grad_reduce=False. That's the supported fallback for models where some params legitimately get no grads.
On our side the CP path should attach the zero loss the same way CP=1 does, or reject this combination at validation time with a clear message. I'll follow up with a fix.
Separate from the assert: you're on bfa33263 with mtp_num_layers=1, and MTP label shifting was wrong under cp_partition_mode='contiguous' until #5706 (merged July 9). Pull latest dev, otherwise MTP trains on misaligned targets.
On the Bridge patch: total_tokens/seq_idx are only needed for Mamba/hybrid-SSM models and pad_between_seqs only matters for FP8, so you can skip all three. Setting cp_partition_mode there is the right call; the missing plumbing is a Megatron-Bridge gap, worth filing on their tracker.
On 32k/256k: TP is a hard limit for now, DSv4 hybrid attention asserts TP == 1, so your parallelism budget is PP × EP × CP. The reason CP16 didn't buy you 32k is apply_dsa_kernel_fusion=False: the unfused fallback keeps tensors proportional to the global sequence length on every rank regardless of CP. Compressed KV and indexer K are all-gathered over the CP group, and the unfused indexer top-k materializes local_tokens × (seq/ratio) score tensors in fp32, so doubling seq while doubling CP keeps local tokens flat but doubles those terms. The intended long-sequence path is apply_dsa_kernel_fusion=True: it works on H100 (SM90+) and needs flash_mla from the FlashMLA nv_dev branch plus nvidia-cudnn-frontend[cutedsl] in the container; on SM90 you also need dsa_indexer_use_sparse_loss=True if the indexer loss is on. Past that, 256k is beyond what this code has been validated at (the CP support merged at the start of the month), so please open a separate enhancement issue for long-context DSv4 SFT and we can go through partitioning there instead of in this bug thread.
Hi @gaojingwei could you share more information on the scenarios that need dsa_indexer_loss_coeff = 0.0?
@Connor-XY ,Thank you very much for the detailed information. I will follow your suggestions and try the following steps:
-
Enable
overlap_grad_reducewhile settingdsa_indexer_loss_coeffto a non-zero value. -
Use the latest dev branch code to avoid the MTP layer errors.
-
Enable
apply_dsa_kernel_fusion.
I will keep you updated as soon as I have any results.
Hi @gaojingwei could you share more information on the scenarios that need
dsa_indexer_loss_coeff = 0.0?你好,能否分享一下需要dsa_indexer_loss_coeff = 0.0的情景?
I don't have a specific requirement to set dsa_indexer_loss_coeff to 0. Its default value is None, and the compute_dsa_indexer_loss function in dsa.py would raise an error in that case. So I simply set it to 0 just to bypass that error.
File "/opt/Megatron-Bridge/3rdparty/Megatron-LM/megatron/core/transformer/experimental_attention_variant/dsa.py", line 361, in compute_dsa_indexer_loss
indexer_loss = kl_div * loss_coeff
~~~~~~~^~~~~~~~~~~~
TypeError: unsupported operand type(s) for *: 'Tensor' and 'NoneType'
https://github.com/NVIDIA/Megatron-LM/pull/5809 this should solve the dsa_indexer_loss_coeff = 0 issue
Hi, @Connor-XY,I install FlashMLA nv_dev , nvidia-cudnn-frontend[cutedsl], and update code to dev branch commit-id d1384c2d95c4fb18 on July 14 and add code #5809 and set overlap_grad_reduce=true , then I ran the following experiment and found that setting apply_dsa_kernel_fusion=True does not work properly.
apply_dsa_kernel_fusion =false, dsa_indexer_loss_coeff > 0, dsa_indexer_use_sparse_loss = trueResult: The training runs normallyapply_dsa_kernel_fusion = false, dsa_indexer_loss_coeff = 0, dsa_indexer_use_sparse_loss = falseResult: The training runs normallyapply_dsa_kernel_fusion = true, dsa_indexer_loss_coeff > 0, dsa_indexer_use_sparse_loss = trueResult: timeout before print first loss , the logs is:
[rank92]:[E716 07:59:41.278598554 ProcessGroupNCCL.cpp:750] [Rank 5] Some NCCL operations have failed or timed out. Due to the asynchronous nature of CUDA kernels, subsequent GPU operations might run on corrupted/incomplete data.
[rank92]:[E716 07:59:41.278653870 ProcessGroupNCCL.cpp:764] [Rank 5] To avoid data inconsistency, we are taking the entire process down.
[rank90]:[E716 07:59:41.278759327 ProcessGroupNCCL.cpp:750] [Rank 5] Some NCCL operations have failed or timed out. Due to the asynchronous nature of CUDA kernels, subsequent GPU operations might run on corrupted/incomplete data.
[rank90]:[E716 07:59:41.278826534 ProcessGroupNCCL.cpp:764] [Rank 5] To avoid data inconsistency, we are taking the entire process down.
[rank92]:[E716 07:59:41.279638860 ProcessGroupNCCL.cpp:2109] [PG ID 6 PG GUID 629(PIPELINE_MODEL_PARALLEL_GROUP) Rank 5] Process group watchdog thread terminated with exception: [Rank 5] Watchdog caught collective operation timeout: WorkNCCL(SeqNum=17, OpType=COALESCED, NumelIn=0, NumelOut=0, Timeout(ms)=600000) ran for 631973 milliseconds before timing out.
apply_dsa_kernel_fusion = true, dsa_indexer_loss_coeff=0, dsa_indexer_use_sparse_loss = falseResult:
[rank255]: File "/opt/Megatron-Bridge/3rdparty/Megatron-LM/megatron/core/transformer/experimental_attention_variant/csa.py", line 1838, in forward
[rank255]: output = self._forward_thd_cp(
[rank255]: ^^^^^^^^^^^^^^^^^^^^^
[rank255]: File "/opt/Megatron-Bridge/3rdparty/Megatron-LM/megatron/core/transformer/experimental_attention_variant/csa.py", line 2509, in _forward_thd_cp
[rank255]: output, indexer_loss = (
[rank255]: ^
[rank255]: File "/usr/local/lib/python3.12/dist-packages/torch/autograd/function.py", line 583, in apply
[rank255]: return super().apply(*args, **kwargs) # type: ignore[misc]
[rank255]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[rank255]: File "/opt/Megatron-Bridge/3rdparty/Megatron-LM/megatron/core/transformer/experimental_attention_variant/dsa_kernels.py", line 1598, in forward
[rank255]: index_score, index_lse = _compute_dense_indexer_score(
[rank255]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[rank255]: File "/opt/Megatron-Bridge/3rdparty/Megatron-LM/megatron/core/transformer/experimental_attention_variant/dsa_kernels.py", line 878, in _compute_dense_indexer_score
[rank255]: result = _DSA.dense_indexer_score_recompute_wrapper(
[rank255]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[rank255]: File "/opt/venv/lib/python3.12/site-packages/cudnn/deepseek_sparse_attention/score_recompute/api.py", line 690, in dense_indexer_score_recompute_wrapper
[rank255]: o, d = obj.execute(
[rank255]: ^^^^^^^^^^^^
[rank255]: File "/opt/venv/lib/python3.12/site-packages/cudnn/deepseek_sparse_attention/score_recompute/api.py", line 577, in execute
[rank255]: return _iface_sm90.dense_indexer_score_recompute(
[rank255]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[rank255]: File "/opt/venv/lib/python3.12/site-packages/cudnn/deepseek_sparse_attention/score_recompute/_interface_sm90.py", line 566, in dense_indexer_score_recompute
[rank255]: return _dense_score_recompute_varlen(
[rank255]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[rank255]: File "/opt/venv/lib/python3.12/site-packages/cudnn/deepseek_sparse_attention/score_recompute/_interface_sm90.py", line 515, in _dense_score_recompute_varlen
[rank255]: out_b, denom_b = _dense_score_recompute(
[rank255]: ^^^^^^^^^^^^^^^^^^^^^^^
[rank255]: File "/opt/venv/lib/python3.12/site-packages/cudnn/deepseek_sparse_attention/score_recompute/_interface_sm90.py", line 404, in _dense_score_recompute
[rank255]: cache[compile_key] = cute.compile(
[rank255]: ^^^^^^^^^^^^^
[rank255]: File "/opt/venv/lib/python3.12/site-packages/nvidia_cutlass_dsl/python_packages/cutlass/cute/runtime.py", line 425, in __c_pointers__
[rank255]: self._memref_desc = self._dltensor_wrapper.build_memref_desc(
[rank255]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[rank255]: RuntimeError: Tensor data pointer is not aligned to 16 bytes.
apply_dsa_kernel_fusion = true, dsa_indexer_loss_coeff = 0, dsa_indexer_use_sparse_loss = trueResult: timeout like experiment 3
Summary: It seems that with apply_dsa_kernel_fusion=True, sparse loss leads to a timeout, whereas dense loss triggers a "tensor not aligned to 16 bytes" error.
@kunlunl @hxbai, could you take a look at the fused DSA results above?
@Connor-XY @kunlunl @hxbai Regarding the timeout issue caused by enabling apply_dsa_kernel_fusion and dsa_indexer_use_sparse_loss, I have conducted further debugging. I added debug log to the following code:
- at CompressedSparseAttention::_forward_thd_cp() in csa.py
compressed_topk = seq_to_rank_row = None
ratio = self.compress_ratio
indexer = self.indexer
indexer_loss_coeff = self.config.dsa_indexer_loss_coeff or 0.0
training_with_grad = self.training and torch.is_grad_enabled()
sparse_indexer_loss = self.config.dsa_indexer_use_sparse_loss
# debug log
rank = torch.distributed.get_rank()
print(f"[rank {rank}] self.compressor={self.compressor}, indexer={indexer}, self.training={self.training}, torch.is_grad_enabled()={torch.is_grad_enabled()}")
- at FusedIndexerSparseAttnFromTopkFunc::forward() in dsa_kernels.py
total_q, np_ = query.shape[:2]
idx_nh, idx_hd = q_indexer.shape[1], q_indexer.shape[2]
total_comp = k_indexer.shape[0]
indexer_topk = indexer_topk_idxs.shape[-1]
# debug log
rank = torch.distributed.get_rank()
print(f"[rank {rank}] FusedIndexerSparseAttnFromTopkFunc.forward: total_q={total_q}, total_comp={total_comp}, np_={np_}, idx_nh={idx_nh}, idx_hd={idx_hd}, indexer_topk={indexer_topk}, sparse_loss={sparse_loss}")
I have 32 nodes in total. I observed the following log patterns:
For nodes 10–31:
Initially, indexer is None and torch.is_grad_enabled() is False. Later, indexer becomes CSAIndexer and torch.is_grad_enabled() becomes True. The program successfully executes into FusedIndexerSparseAttnFromTopkFunc. After that, indexer becomes None again while torch.is_grad_enabled() remains True, and then the program hangs indefinitely until timeout.
For nodes 0–9:
The indexer state changes follow the same pattern as nodes 10–31, but torch.is_grad_enabled() remains False throughout. As a result, the program never enters FusedIndexerSparseAttnFromTopkFunc.
It seems that the inconsistency in torch.is_grad_enabled() across nodes might be causing the hang. Any suggestions on how to debug or fix this would be greatly appreciated. Thanks!
These are the changes I applied to the training script that I shared previously:
cfg.model.dsa_indexer_loss_coeff = 0.01
cfg.model.dsa_indexer_use_sparse_loss = True
cfg.model.apply_dsa_kernel_fusion = True
cfg.model.tensor_model_parallel_size=1
cfg.model.pipeline_model_parallel_size=16
cfg.model.expert_model_parallel_size=16
cfg.model.expert_tensor_parallel_size=1
cfg.model.context_parallel_size=8
cfg.model.seq_length = 16384
cfg.model.cp_partition_mode = "contiguous"
cfg.model.sequence_packing_scheduler = "dp_balanced"
In the CompressedSparseAttention::_forward_thd_cp() function in csa.py, I added a condition at the following code block: if indexer is not None, I forcibly set training_with_grad to True. This ensures that all nodes execute into FusedIndexerSparseAttnFromTopkFunc. However, the timeout still occurred. Interestingly, when I set vpp=2, the timeout disappeared, and I successfully ran training with a 32k sequence length.
compressed_topk = seq_to_rank_row = None
ratio = self.compress_ratio
indexer = self.indexer
indexer_loss_coeff = self.config.dsa_indexer_loss_coeff or 0.0
is_grad_enabled = torch.is_grad_enabled()
training_with_grad = self.training and is_grad_enabled
sparse_indexer_loss = self.config.dsa_indexer_use_sparse_loss
rank = torch.distributed.get_rank() if torch.distributed.is_initialized() else 0
# set training_with_grad to True when indexer is not None
if indexer is not None and self.training and not is_grad_enabled:
print(f"[rank {torch.distributed.get_rank() if torch.distributed.is_initialized() else 0}] WARNING: indexer is not None but torch.is_grad_enabled() is False")
print(f"[rank {torch.distributed.get_rank() if torch.distributed.is_initialized() else 0}] Forcing training_with_grad=True because model is in training mode")
training_with_grad = True
Thanks for the detailed report. We ran a reproduction on H100 with PP16, CP2, VPP1, full recompute, and fused DSA, and observed the same type of pipeline watchdog timeout.
In our reproduction, the timeout appeared to come from one-time JIT compilation of several DSA kernels. With full recompute, the indexer-loss path is skipped during the initial no-grad forward and first runs during backward recomputation, so that is when the compilation happens. This may also explain the different torch.is_grad_enabled() values across ranks: some pipeline stages had started recomputation while others were still waiting. The flag indicates which phase a stage is in, but did not appear to be the cause of the timeout.
As an A/B test, we prewarmed the same kernels on all ranks before starting the pipeline. The previously failing VPP1 case then completed within the same timeout, with matching loss and gradient results. VPP2 likely helps by allowing more frequent pipeline progress, although it does not remove the compilation overhead.
Our reproduction is smaller than your PP16/CP8 setup, so there may still be differences between the two cases. For now, increasing the distributed timeout should work around the issue. A longer-term solution would be to precompile these kernels before pipeline execution and keep the varlen TopK shapes stable.
Thanks for the detailed report. We ran a reproduction on H100 with PP16, CP2, VPP1, full recompute, and fused DSA, and observed the same type of pipeline watchdog timeout.
In our reproduction, the timeout appeared to come from one-time JIT compilation of several DSA kernels. With full recompute, the indexer-loss path is skipped during the initial no-grad forward and first runs during backward recomputation, so that is when the compilation happens. This may also explain the different torch.is_grad_enabled() values across ranks: some pipeline stages had started recomputation while others were still waiting. The flag indicates which phase a stage is in, but did not appear to be the cause of the timeout.
As an A/B test, we prewarmed the same kernels on all ranks before starting the pipeline. The previously failing VPP1 case then completed within the same timeout, with matching loss and gradient results. VPP2 likely helps by allowing more frequent pipeline progress, although it does not remove the compilation overhead.
Our reproduction is smaller than your PP16/CP8 setup, so there may still be differences between the two cases. For now, increasing the distributed timeout should work around the issue. A longer-term solution would be to precompile these kernels before pipeline execution and keep the varlen TopK shapes stable.
Thanks for the A/B test. You mentioned increasing the distributed timeout earlier — do you mean setting it like this:
export NCCL_TIMEOUT=1200000
Also, regarding my modification — is it reasonable to forcibly set training_with_grad to True when indexer is not None? If I increase the distributed timeout, would this modification no longer be needed?
In our experiment, we did not set NCCL_TIMEOUT. We changed the Megatron argument from:
--distributed-timeout-minutes=5
to:
--distributed-timeout-minutes=10
This changed the pipeline process-group timeout from 300,000 ms to 600,000 ms. For a 20-minute timeout, use --distributed-timeout-minutes=20, or the equivalent Megatron-Bridge configuration.
I would also recommend removing the change that forcibly sets training_with_grad=True. With full recompute, False during the initial forward and True during backward recomputation is expected. Forcing it to True changes the intended checkpoint behavior and did not resolve the timeout in our experiment. I think it is not needed when increasing the timeout.
Feel free to tell us if it doesn't apply to your case.
@kunlunl ,Thank you for your advice. The default value of --distributed-timeout-minutes is 10 minutes. After I changed it to 20 minutes, the timeout issue no longer occurred. Indeed, no code modification was needed.
Thank you @kunlunl ! Please re-open issue if needed.