Megatron-LM icon indicating copy to clipboard operation
Megatron-LM copied to clipboard

[Bug] 256K DSA training with Megatron fails while 32K succeeds (dsa_kernel_backend="cudnn", experimental_attention_variant="dsa")

Open gaojingwei opened this issue 2 months ago • 3 comments

the log

  File "/opt/Megatron-Bridge/3rdparty/Megatron-LM/megatron/core/transformer/experimental_attention_variant/dsa_cudnn_kernels.py", line 1177, in _indexer_topk_bshd
    topk_indices, topk_scores = _indexer_topk_multi_packed_cp_thd(
                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/Megatron-Bridge/3rdparty/Megatron-LM/megatron/core/transformer/experimental_attention_variant/dsa_cudnn_kernels.py", line 766, in _indexer_topk_multi_packed_cp_thd
    tk_result = _indexer_top_k_wrapper_chunked(
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/Megatron-Bridge/3rdparty/Megatron-LM/megatron/core/transformer/experimental_attention_variant/dsa_cudnn_kernels.py", line 483, in _indexer_top_k_wrapper_chunked
    tk_result = _cudnn_dsa.indexer_top_k_wrapper(
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/venv/lib/python3.12/site-packages/cudnn/deepseek_sparse_attention/indexer_top_k/api.py", line 198, in indexer_top_k_wrapper
    indices, values = obj.execute(input_values, seq_lens, current_stream=stream)
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/venv/lib/python3.12/site-packages/cudnn/deepseek_sparse_attention/indexer_top_k/api.py", line 139, in execute
    indices, values = kernel(
                      ^^^^^^^
  File "/opt/venv/lib/python3.12/site-packages/cudnn/deepseek_sparse_attention/indexer_top_k/indexer_top_k_decode_varlen.py", line 710, in cute_dsl_topk_wrapper
    compiled_kernel(
  File "/usr/local/lib/python3.12/dist-packages/nvidia_cutlass_dsl/python_packages/cutlass/cutlass_dsl/tvm_ffi_provider.py", line 593, in __call__
    return tvm_ffi.Function.__call__(self, *args)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "python/tvm_ffi/cython/function.pxi", line 968, in tvm_ffi.core.Function.__call__
RuntimeError: CUDA Error: cudaErrorIllegalAddress

I use packed data, the 32k training was successful, and the configuration remained the same. However, switching to 256k data resulted in an error. docker image: nemo2608 Code: Using megatron-bridge and megatron-lm within the image, the megatron-lm version is 0.19.

this is my code:

def create_finetune_config():
    model=MLAModelProvider()
    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=52428800,
        ),
        train=TrainingConfig(
            micro_batch_size=1,
            global_batch_size=GLOBAL_BATCH_SIZE,
            train_iters=MAX_STEP,

        ),
        optimizer=OptimizerConfig(
            optimizer="dist_muon",
            lr=3e-4,
            min_lr=4.2e-5,
            muon_extra_scale_factor = 0.2,
            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,           # 与ddp里保持一直
            #params_dtype = torch.float32,          # 不影响grad为float32
        ),
        scheduler=SchedulerConfig(
            start_weight_decay=0.1,
            end_weight_decay=0.1,
            weight_decay_incr_style="constant",
            lr_decay_style="cosine",
            lr_warmup_iters=200,
        ),
        # Finetuning dataset instead of pretraining dataset
        dataset=GPTSFTDatasetConfig(
            dataset_root="/cpfs01/gjw/nemo2608/data",
            seq_length=SEQ_LENGTH,
            do_validation=False,
            do_test=False,
            enable_offline_packing=True,
            offline_packing_specs=PackedSequenceSpecs(
                packed_sequence_size=SEQ_LENGTH,
                packed_train_data_path=PACKED_TRAIN_DATA,
            ),
            dataset_kwargs = {"pad_to_max_length": True}
        ),
        tokenizer=TokenizerConfig(
            tokenizer_type="HuggingFaceTokenizer",
            tokenizer_model="/cpfs01/jt-models/jt_236b/jt-aa-cot-0905-epoch3/"
        ),
        # 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",
        mixed_precision=bf16_mixed(),
        rng=RNGConfig(seed=1234),
        dist=DistributedInitConfig(),
        comm_overlap=CommOverlapConfig(
            tp_comm_overlap=False,
        ),
        logger=LoggerConfig(
            log_interval=1,
            tensorboard_dir=CKPT_DIR,
        ),
        
    )

if __name__ == "__main__":
    cfg = create_finetune_config()

    cfg.model.fp8_recipe = None
    cfg.model.params_dtype = torch.float32
    cfg.optimizer.params_dtype = torch.float32
    cfg.optimizer.fp8_recipe = None

    from megatron.core.models.gpt.experimental_attention_variant_module_specs import (
        get_transformer_block_with_experimental_attention_variant_spec,
    )
    cfg.model.transformer_layer_spec = get_transformer_block_with_experimental_attention_variant_spec
    
    cfg.dist.distributed_timeout_minutes = 20

    # dsa
    cfg.model.experimental_attention_variant = "dsa"
    cfg.model.dsa_indexer_n_heads = 64
    cfg.model.dsa_indexer_head_dim = 128
    cfg.model.dsa_indexer_topk = 2048
    cfg.model.dsa_indexer_loss_coeff = 0.01
    cfg.model.dsa_indexer_use_sparse_loss = True
    cfg.model.cp_comm_type = "all_gather"
    cfg.model.apply_dsa_kernel_fusion = True
    cfg.model.dsa_kernel_backend = "cudnn"
    
    # attention
    cfg.model.num_attention_heads = 128
    cfg.model.kv_channels = 40
    cfg.model.num_query_groups = 128
    cfg.model.num_layers = 60
    cfg.model.hidden_size = 5120
    cfg.model.ffn_hidden_size = 12288
    cfg.model.vocab_size = 152064
    cfg.model.add_bias_linear=False

    cfg.model.normalization = "RMSNorm"
    cfg.model.layernorm_epsilon = 1e-6
    cfg.model.attention_dropout = 0.0
    cfg.model.hidden_dropout = 0.0
    cfg.model.qk_layernorm = True

    #mtp
    cfg.model.mtp_num_layers = 1
    cfg.model.mtp_loss_scaling_factor = 0.1

    #moe
    cfg.model.num_moe_experts = 160
    cfg.model.moe_ffn_hidden_size = 1536
    cfg.model.moe_shared_expert_intermediate_size = 3072
    cfg.model.moe_layer_freq= [0] * 1 + [1] * 59
    cfg.model.moe_token_dispatcher_type = "flex"
    cfg.model.moe_enable_deepep = True
    cfg.model.moe_shared_expert_overlap = False           # moe_shared_expert_overlap only works with alltoall token dispatcher
    cfg.model.moe_aux_loss_coeff = 1e-4
    cfg.model.moe_z_loss_coeff = None
    cfg.model.moe_router_topk = 6
    cfg.model.moe_router_num_groups = 1
    cfg.model.moe_router_group_topk = 1
    cfg.model.moe_router_topk_scaling_factor = 2.827
    cfg.model.make_vocab_size_divisible_by = 512
    cfg.model.moe_router_score_function = "sigmoid"
    cfg.model.moe_router_enable_expert_bias = True
    cfg.model.moe_router_bias_update_rate = 1e-3
    cfg.model.moe_router_pre_softmax = True
    cfg.model.moe_grouped_gemm = True
    cfg.model.moe_router_load_balancing_type = "seq_aux_loss"
    cfg.model.moe_router_dtype = "fp32"

    #MLA
    cfg.model.multi_latent_attention=True
    cfg.model.kv_lora_rank = 512
    cfg.model.q_lora_rank = 1536
    cfg.model.qk_head_dim = 128
    cfg.model.qk_pos_emb_head_dim = 64
    cfg.model.v_head_dim = 128
    cfg.model.mscale = 1.0
    cfg.model.mscale_all_dim = 1.0

    # rope
    cfg.model.max_position_embeddings = SEQ_LENGTH
    cfg.model.seq_length = SEQ_LENGTH
    cfg.model.rotary_base = 5000000
    cfg.model.rope_type="rope"
    cfg.model.rotary_scaling_factor = 1.0

    # 重计算
    cfg.model.recompute_granularity = 'full'
    cfg.model.recompute_method = 'uniform'
    cfg.model.recompute_num_layers = 1

    # 并行策略
    cfg.model.sequence_parallel=True
    #cfg.model.num_layers_in_first_pipeline_stage=8
    cfg.model.num_layers_in_last_pipeline_stage=4
    cfg.model.tensor_model_parallel_size=8
    cfg.model.pipeline_model_parallel_size=8
    cfg.model.expert_model_parallel_size=8
    cfg.model.expert_tensor_parallel_size=1
    cfg.model.virtual_pipeline_model_parallel_size=4
    cfg.model.context_parallel_size=2
    cfg.model.batch_p2p_comm=True

    # 融合计算
    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

    cfg.model.init_method_std = 0.006
    cfg.model.embedding_init_method_std = 0.006


    # cp > 1时,calculate_per_token_loss必须是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
    #cfg.dataset.offline_packing_specs.pad_seq_to_mult = cfg.model.context_parallel_size * 2 if  cfg.model.context_parallel_size > 1 else 1
    cfg.dataset.offline_packing_specs.pad_seq_to_mult = 4 
    
    print_rank_0("-----all transformer config-------")
    print_rank_0(cfg.model)

    pretrain(cfg, forward_step_func=forward_step)

gaojingwei avatar Sep 18 '26 03:09 gaojingwei

Thanks for the traceback and launch configuration. Assigning @hxbai to help triage the DSA path.

To narrow down the 32K-versus-256K difference, please add the GPU model, exact Megatron-LM and Megatron-Bridge commits, and cuDNN Frontend/CUTLASS versions from the container. Please also share the failing packed-sequence lengths/cu_seqlens metadata and, if possible, a small reproducer for the indexer top-k call with those shapes. The illegal-address traceback alone does not yet establish whether this is a shape/packing issue or an upstream kernel defect.

Connor-XY avatar Sep 21 '26 18:09 Connor-XY

@Connor-XY

  1. GPU information gpu: L20D
    NVIDIA-SMI 580.105.08 Driver Version: 580.105.08 CUDA Version: 13.0

  2. Information about cuDNN/Cutlass: In a UV environment: nvidia-cudnn-frontend 1.26.0 I am unable to locate the cutlass. in /usr/local/lib/python3.12/ found: nvidia-cutlass-dsl 4.5.0 nvidia-cutlass-dsl-libs-base 4.5.0 nvidia-cutlass-dsl-libs-cu13 4.5.0

  3. Commit information Megatron bridge:

commit c93251151adeeadbae3ff2a2bf5ee7a1c34cff01 (HEAD)
Author: Ajay <[email protected]>
Date:   Thu Aug 13 12:45:37 2026 -0700

   Update nemo-evaluator path in fw_pyproject.toml (#5571)
   
   Signed-off-by: Ajay <[email protected]>
megatron-lm:  core_v0.19.0
  1. data demo: this datasets is packed to 256k by cp = 2.

ds5_256k_cp2_four.tar.gz

gaojingwei avatar Sep 28 '26 01:09 gaojingwei

This is the analysis given by the large model:

scores = _cudnn_dsa.indexer_forward_wrapper(
    q_bshd[0],
    segmented_k,                # 所有 segment 经 layout.source_indices 聚合后的整体
    w_bsh[0],
    ...
    cu_seqlens_q=layout.segment_cu_q...,
    cu_seqlens_k=layout.segment_cu_k...,
    max_seqlen_k=max_segment_k,
)["scores"]

This call will materialize a complete dense fp32 score tensor with shape [1, sq, total_segment_k]. Under 256k packed + CP, sq≈131072 and total_segment_k≈327680, approximately:

Number of elements ≈ 131072 × 327680 ≈ 4.3e10, exceeding 2^31

Bytes ≈ 160 GiB

The cuDNN CuTe scoring kernel internally uses int32 linear offsets for addressing. Once the offset exceeds 2^31, it wraps around, resulting in out-of-bounds reads.

_indexer_top_k_wrapper_chunked does chunk by row (with a 2 GiB scratch budget), but the scoring step indexer_forward_wrapper is called on the entire tensor in one shot, and this path has no chunking protection whatsoever. At 32k, the tensor is on the order of ~20 GiB with the element count still within 2^31, so no error is raised; only at 256k does the overflow get triggered.

It should be modified as follows:

Score each CP segment independently, reducing the score tensor to [1, seg_sq, seg_sk], which is far smaller than the fused version's [1, sq, total_segment_k].

_indexer_topk_from_score_chunks internally also chunks by query rows, constrained by _INDEXER_SCORE_CHUNK_MAX_BYTES = 1 GiB (line 135), ensuring that any single score chunk does not exceed 1 GiB and its element count stays far below 2^31 → no more overflow.

Uniformly use seg_topk = topk_k (a power of two), so that the cuDNN CuTe top-k kernel's compile-time assertion top_k % vecsize_out == 0 holds for every segment.

For short segments (seg_nk < topk_k), zero-pad the keys to topk_k columns, then use seg_seq_lens to mask the zero-padded positions as -inf; the zero-padded indices that sneak into the top-k are afterwards cleaned to -1 and their scores to -inf.

Pass down the valid prefix length of each row via score_seq_lens=seg_seq_lens, so that chunks other than the first block use the correct zigzag causal mask

for seg_idx in range(len(seg_q_bounds) - 1):
    seg_q = q_rows[q0:q1].unsqueeze(0).contiguous()
    seg_k_raw = segmented_k[k0:k1]
    if seg_nk < topk_k:              # 短 segment 补零到 topk_k 列
        seg_k = torch.cat([seg_k_raw, pad_tensor], dim=0)...
    seg_indices, seg_values = _indexer_topk_from_score_chunks(
        seg_q, seg_k, seg_w, seg_seq_lens, seg_topk, ...
    )
    if seg_nk < topk_k:              # 清掉补零位置混入的 top-k 索引
        seg_indices = torch.where(valid_seg, seg_indices, -1)
    seg_indices, seg_values = _pad_topk_result(...)
    indices_segments.append(seg_indices)
topk_indices = torch.cat(indices_segments, dim=1)

gaojingwei avatar Oct 08 '26 02:10 gaojingwei