Skip to content

Conversation

@koutianzhengwen
Copy link

patch for megatron core part 2

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @koutianzhengwen, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly extends the Megatron-LM framework by integrating support for Huawei Atlas800TA3 NPUs and introducing robust mechanisms for heterogeneous training. It updates model configurations for Qwen2.5-VL, enhances checkpointing capabilities, and refines argument and feature management, paving the way for more diverse and efficient large language model training environments.

Highlights

  • Huawei Atlas800TA3 (NPU) Integration: Extensive adaptations have been introduced to support Huawei Atlas800TA3 NPUs, including NPU-specific rotary position embedding, matmul/add operations, and a comprehensive Megatron-LM adaptation layer (megatron_adaptor.py) to bridge with NPU functionalities.
  • Heterogeneous Training Support: New configurations and logic have been added to enable heterogeneous training, allowing for different device types and pipeline layer splits. This includes modifications to parallel state management, optimizer parameter grouping (e.g., is_vision_model_param), and communication handling for CPU-based groups.
  • Qwen2.5-VL Model Configuration & Checkpointing: Configuration files for Qwen2.5-VL 3B and 7B models have been added/updated, specifying system, model, optimizer, and data parameters suitable for training. A dedicated script for converting Qwen2.5-VL HuggingFace checkpoints to Megatron-Core format (and vice-versa) is also included, supporting vision models and tensor/pipeline parallelism.
  • DualPipeV Pipeline Scheduling: The use_dualpipev feature has been integrated into pipeline scheduling, allowing for specialized handling of model chunks and mixed-precision operations within the pipeline, particularly for MoE models.
  • Enhanced Argument and Feature Management: A MindSpeedFeaturesManager and associated patching utilities have been introduced to dynamically manage and apply various features and arguments, providing a more flexible and extensible way to configure Megatron-LM.
  • Tokenizer and Dataset Expansions: New tokenizer types (AquilaTokenizerFS, HFTokenizerFS, Llama3TokenizerFS, QwenTokenizerFS, Qwen2TokenizerFS, Qwen2VLTokenizer, RWKVTokenizer) and dataset utilities (e.g., for Aquila models and LLaVA conversion) have been added, broadening the range of supported models and data formats.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a large set of patches for Megatron-LM, primarily aimed at enabling and optimizing training on Huawei Atlas800TA3 hardware. The changes span configuration files, model adaptation layers, custom optimizers, and hardware-specific communication logic. While the patch adds significant new functionality, there are several critical issues that need to be addressed, including hardcoded device types that will cause crashes on non-CUDA platforms, potential NameError and IndexError exceptions, and a security vulnerability related to torch.load. Additionally, there are maintainability concerns like hardcoded paths in configuration files and the inclusion of backup files in the repository. A number of unit tests have also been disabled, which is a significant concern for code quality and should be rectified.

+ mode = 1 if rotary_interleaved else 0
+ t = npu_rotary_position_embedding(t.contiguous(), cos_, sin_, mode).to(t.dtype)
+ else:
+ t = (t * cos_) + (_rotate_half(t, rotary_interleaved) * sin_)
Copy link
Contributor

Choose a reason for hiding this comment

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

critical

The function _rotate_half is called here but it is not defined or imported within this file. This will result in a NameError at runtime when args.use_fused_rotary_pos_emb is False. Please ensure this function is available in the scope, for example by importing it from its definition location.

Comment on lines +127 to +130
+ if group['step'].is_cpu:
+ group['step'] = group['step'].cuda()
+ else:
+ group['step'] = torch.tensor(1, dtype=torch.int64, device=torch.cuda.current_device())
Copy link
Contributor

Choose a reason for hiding this comment

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

critical

The device for the optimizer's step tensor is hardcoded to cuda. This will cause a crash on non-CUDA hardware like the target NPU platform. The device should be dynamically inferred from the model parameters to ensure portability.

                if group['step'].device != group['params'][0].device:
                    group['step'] = group['step'].to(group['params'][0].device)
            else:
                group['step'] = torch.tensor(1, dtype=torch.int64, device=group['params'][0].device)

Comment on lines +101 to +103
+ seq_len = actual_seq_len[0]
+ actual_seq_len = [elem + i * seq_len for i, elem in enumerate(actual_seq_len)]
+ batch['actual_seq_len'] = torch.tensor(actual_seq_len, dtype=torch.long)
Copy link
Contributor

Choose a reason for hiding this comment

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

high

Accessing actual_seq_len[0] without checking if the list is empty will raise an IndexError if the input samples list is empty. This can crash the data loading process. It's important to add a guard clause to handle this edge case gracefully.

        if not actual_seq_len:
            return batch
        seq_len = actual_seq_len[0]
        actual_seq_len = [elem + i * seq_len for i, elem in enumerate(actual_seq_len)]
        batch['actual_seq_len'] = torch.tensor(actual_seq_len, dtype=torch.long)

+ #data_path: [40,/mnt/share/hetero_data/datasets/fineweb-edu-CC-3_5_text_document,28,/mnt/share/hetero_data/datasets/dclm-baseline-1.0-top_pct5_text_document,3,/mnt/share/hetero_data/datasets/k73_edu_qwen_text_document,5,/mnt/share/hetero_data/datasets/wxb_edu_qwen_text_document,20,/mnt/share/hetero_data/datasets/cosmopedia-v2-full_text_document,4,/mnt/share/hetero_data/datasets/infinst-kg-0712_text_document]
+ # exp02
+ # data_path: [4.08,/mnt/share/hetero_data/datasets/k73_edu_qwen_text_document,6.52,/mnt/share/hetero_data/datasets/wxb_edu_qwen_text_document,14.4,/mnt/share/hetero_data/datasets/opencsg-chinese-fineweb-edu-v2_20241104_text_document,4.81,/mnt/share/hetero_data/datasets/fineweb-code-corpus_20241112_text_document,0.32,/mnt/share/hetero_data/datasets/smollm-corpus-python-edu_text_document,0.4,/mnt/share/hetero_data/datasets/opc-annealing-corpus-algorithmic_corpus_text_document,0.11,/mnt/share/hetero_data/datasets/opc-annealing-corpus-synthetic_code_snippet_text_document,0.09,/mnt/share/hetero_data/datasets/opc-annealing-corpus-synthetic_qa_text_document,1.7,/mnt/share/hetero_data/datasets/K76/code_filter_qwen05_loss3/c_text_document,1.37,/mnt/share/hetero_data/datasets/K76/code_filter_qwen05_loss3/cpp_text_document,0.7,/mnt/share/hetero_data/datasets/K76/code_filter_qwen05_loss3/go_text_document,1.89,/mnt/share/hetero_data/datasets/K76/code_filter_qwen05_loss3/java_text_document,1.61,/mnt/share/hetero_data/datasets/K76/code_filter_qwen05_loss3/javascript_text_document,0.16,/mnt/share/hetero_data/datasets/K76/code_filter_qwen05_loss3/json_text_document,0.2,/mnt/share/hetero_data/datasets/K76/code_filter_qwen05_loss3/jupyter-scripts-dedup-filtered_text_document,0.16,/mnt/share/hetero_data/datasets/K76/code_filter_qwen05_loss3/jupyter-structured-clean-dedup_text_document,1.93,/mnt/share/hetero_data/datasets/K76/code_filter_qwen05_loss3/markdown_text_document,1.45,/mnt/share/hetero_data/datasets/K76/code_filter_qwen05_loss3/python_text_document,0.09,/mnt/share/hetero_data/datasets/K76/code_filter_qwen05_loss3/shell_text_document,26.11,/mnt/share/hetero_data/datasets/Nemotron-CC-HQ/Nemotron-CC-high-synthetic-diverse_qa_pairs_text_document,28.89,/mnt/share/hetero_data/datasets/Nemotron-CC-HQ/Nemotron-CC-high-actual-actual_text_document,0.18,/mnt/share/hetero_data/datasets/EleutherAI-proof-pile-2/EleutherAI-proof-pile-2-open-web-math_text_document,0.3,/mnt/share/hetero_data/datasets/finemath/infiwebmath-3plus_text_document,0.52,/mnt/share/hetero_data/datasets/finemath/finemath-3plus_text_document,1.0,/mnt/share/hetero_data/datasets/dolma_arxiv_text_document,1.0,/mnt/share/hetero_data/datasets/dolma_pes2o_v2_text_document]
+ data_path: /share/project/lizhiyu/data/pile_wikipedia_demo
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The data_path is hardcoded to /share/project/lizhiyu/data/pile_wikipedia_demo. Hardcoding paths makes the configuration less portable and harder to use in different environments. Consider using a placeholder or an environment variable, like ${data_path:??} which is used in other configuration files in this repository.

Comment on lines +1 to +71
diff --git a/examples/aquila/conf/train/7b.yaml.bak b/examples/aquila/conf/train/7b.yaml.bak
new file mode 100644
index 00000000..a534b9e1
--- /dev/null
+++ b/examples/aquila/conf/train/7b.yaml.bak
@@ -0,0 +1,64 @@
+system:
+ tensor_model_parallel_size: 1
+ pipeline_model_parallel_size: 1
+ disable_bias_linear: True
+ use_flash_attn: True
+ use_distributed_optimizer: True
+ precision:
+ fp16: True
+ initial_loss_scale: 522893
+ min_loss_scale: 1.0
+ attention_softmax_in_fp32: True
+ accumulate_allreduce_grads_in_fp32: True
+ logging:
+ log_interval: 1
+ tensorboard_log_interval: 1
+ wandb_project: "train-aquila-7B"
+ wandb_exp_name: "train-test-7B"
+ checkpoint:
+ save_interval: 2000
+
+model:
+ num_layers: 32
+ hidden_size: 4096
+ num_attention_heads: 32
+ seq_length: 2048
+ max_position_embeddings: 2048
+ norm_epsilon: 1e-5
+ use_rotary_position_embeddings: true
+ no_position_embedding: true
+ swiglu: true
+ multiple_of: 256
+ normalization: RMSNorm
+ # rotary_interleaved_patch: true
+ untie_embeddings_and_output_weights: true
+ init_method_std: 0.02
+ attention_dropout: 0.0
+ hidden_dropout: 0.0
+ weight_decay: 0.1
+ clip_grad: 1.0
+ train_samples: 1002539063
+ eval_iters: 0
+ micro_batch_size: 2
+ global_batch_size: 1728
+ seed: 1234
+
+ optimizer:
+ weight_decay: 0.1
+ adam_beta1: 0.9
+ adam_beta2: 0.95
+ lr_scheduler:
+ lr: 2.0e-5
+ min_lr: 2.0e-6
+ lr_warmup_samples: 3076172
+ lr_decay_style: cosine
+
+data:
+ data_path: ${data_path:??}
+ split: 1
+ tokenizer:
+ tokenizer_type: AquilaTokenizerFS
+ vocab_file: ./examples/aquila/tokenizer/vocab.json
+ merge_file: ./examples/aquila/tokenizer/merges.txt
+ special_tokens_file: ./examples/aquila/tokenizer/special_tokens.txt
+ vocab_size: 100008

Copy link
Contributor

Choose a reason for hiding this comment

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

medium

This patch adds a .bak file to the repository. Backup files should not be committed to version control. The history of the file should be managed by Git itself. Please remove this backup file to keep the repository clean.


data:
- data_path: ${data_path:??}
+ data_path: /home/dataset/pile_wikipedia_demo
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The data_path is hardcoded to /home/dataset/pile_wikipedia_demo. Hardcoding paths makes the configuration less portable and harder to use in different environments. It is recommended to use a placeholder like ${data_path:??} to allow for easier configuration in different setups.

@CLAassistant
Copy link

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.


zhaoxuncheng seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account.
You have signed the CLA already but the status is still pending? Let us recheck it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants