Merged
modify document:合入英文文档 #7682
chic666Add on Aug 24
modify document:合入英文文档 #7682
Merged
chic666Add on Aug 24
Merged fromDeleted :masterintoAscend/ModelZoo-PyTorchmaster
Total: 137 files changed+5848-31
@@ -155,3 +155,6 @@ kernel_meta*/
155!PyTorch/docs/zh/figures/155!PyTorch/docs/zh/figures/
156!PyTorch/docs/zh/figures/*.png156!PyTorch/docs/zh/figures/*.png
157!PyTorch/docs/zh/figures/*.jpg157!PyTorch/docs/zh/figures/*.jpg
158+!PyTorch/docs/en/figures/
159+!PyTorch/docs/en/figures/*.png
160+!PyTorch/docs/en/figures/*.jpg
@@ -1,5 +1,9 @@
1# 欢迎使用ModelZoo-PyTorch1# 欢迎使用ModelZoo-PyTorch
2 2 
3+<p align="center">
4+ 简体中文 | <a href="./README.EN.md">English</a>
5+</p>
6+ 
3## 简介7## 简介
4 8 
5ModelZoo-PyTorch提供基于昇腾设备适配的训练模型参考,覆盖计算机视觉、自然语言处理、语音、多模态、推荐等常见AI任务。目录中的模型通常包含环境准备、数据集与预训练权重准备、训练脚本、结果说明等内容,可作为开发者在昇腾训练环境中上手、验证和迁移PyTorch模型的参考。我们会持续补充典型网络和相关预训练模型,如果您在使用过程中有需求或建议,欢迎在[ModelZoo-PyTorch/issues](https://gitcode.com/Ascend/ModelZoo-PyTorch/issues)提交issue。9ModelZoo-PyTorch提供基于昇腾设备适配的训练模型参考,覆盖计算机视觉、自然语言处理、语音、多模态、推荐等常见AI任务。目录中的模型通常包含环境准备、数据集与预训练权重准备、训练脚本、结果说明等内容,可作为开发者在昇腾训练环境中上手、验证和迁移PyTorch模型的参考。我们会持续补充典型网络和相关预训练模型,如果您在使用过程中有需求或建议,欢迎在[ModelZoo-PyTorch/issues](https://gitcode.com/Ascend/ModelZoo-PyTorch/issues)提交issue。
@@ -0,0 +1,116 @@
1+# Welcome to ModelZoo-PyTorch
2+ 
3+<p align="center">
4+ English | <a href="./README.CN.md">简体中文</a>
5+</p>
6+ 
7+## Introduction
8+ 
9+ModelZoo-PyTorch provides training model references adapted for Ascend devices, covering common AI tasks such as computer vision, natural language processing, speech, multimodality, and recommendation. The models in the repository typically include environment setup, dataset and pre-trained weights preparation, training scripts, and result descriptions, serving as a reference for developers to get started, validate, and migrate PyTorch models in the Ascend training environment. We will continue to add more representative networks and pre-trained models. If you have any needs or suggestions during use, feel free to submit an issue at [ModelZoo-PyTorch/issues](https://gitcode.com/Ascend/ModelZoo-PyTorch/issues).
10+ 
11+## How to Contribute
12+ 
13+Please read [CONTRIBUTING_TRAIN](../CONTRIBUTING_TRAIN.md) before getting started with contributions.
14+Thank you!
15+ 
16+## Version Notes
17+ 
18+The version compatibility may vary across different models. It is recommended to use the version specified in the documentation of each model under the [Maintenance Policy](#maintenance-policy). If you wish to experience the latest version of Ascend, please refer to [Latest Version Compatibility](docs/en/install_guide.md#basic-environment-installation).
19+ 
20+## Quick Start
21+ 
22+If you wish to quickly understand how to use models in ModelZoo-PyTorch, it is recommended to start with [BERT-NER-Pytorch](https://gitcode.com/ascend/ModelZoo-PyTorch/tree/master/PyTorch/contrib/nlp/BERT-NER-Pytorch). This use case takes the Named Entity Recognition (NER) task as an example and covers environment setup, dataset preparation, pre-trained weight preparation, and training script examples, making it a suitable reference for first-time users.
23+ 
24+We recommend following the steps below:
25+ 
26+1. Complete the installation of the base environment, including PyTorch, TorchNPU, and CANN.
27+2. Navigate to the `PyTorch/contrib/nlp/BERT-NER-Pytorch` directory and read the `README.md` file within that use case.
28+3. Prepare the `Cluener` dataset and `bert-base-chinese` pre-trained weights according to the use case instructions.
29+4. Execute the training script in the `test` directory to experience single-node multi-device training.
30+ 
31+Through this use case, you can quickly become familiar with the model directory organization, dependency installation methods, and standard training workflow in ModelZoo-PyTorch. After completing the trial, you can choose other models for your specific scenarios.
32+ 
33+## Model Training
34+ 
35+1. ModelZoo-PyTorch contains various model use cases, and different models may differ in environment dependencies, dataset preparation, pre-trained weight acquisition, and training script usage. Therefore, for model training, please follow the instructions in the `README.md` file within each model directory.
36+2. We recommend you to select a model to experience or train from the [Models Evolving with Versions](#models-evolving-with-versions) list below, click the corresponding link to enter the model directory, and then complete model training according to the model documents.
37+ 
38+## Model Migration and Tuning
39+ 
40+You can perform model migration, precision debugging, and performance tuning by referring to the [PyTorch Training Model Migration and Tuning Guide](docs/en/README.md).
41+ 
42+## Maintenance Policy
43+ 
44+💡 Models in ModelZoo-PyTorch are categorized into version-evolving models and non-version-evolving models.
45+ 
46+- For models that evolve with releases: please see the version compatibility table and choose the latest version for use.
47+- For models that do not evolve with releases: these models no longer track the version evolution of PyTorch and PyTorch Extensions. You may choose the following strategies:
48+ - Select the corresponding PyTorch, PyTorch Extension, CANN, and HDK versions as specified in the model's README.
49+ - If you have a requirement to adapt this model to newer versions of PyTorch, PyTorch Extension, CANN, or HDK, please feel free to submit an issue at [modelzoo/issues](https://gitcode.com/ascend/modelzoo/issues). We will address it in a timely manner.
50+ 
51+## Scope Definition
52+ 
53+### Models Evolving with Versions
54+ 
55+See [Version-Evolving Models](docs/en/model_usage.md#version-evolving-models).
56+ 
57+### Models Not Evolved with Versions
58+ 
59+Except for the version-evolving models, all other models in ModelZoo-PyTorch are classified as models not evolved with versions.
60+ 
61+## Security Statement
62+ 
63+### Running User Recommendations
64+ 
65+For security and the principle of least privilege, it is not recommended to use administrator-type accounts such as `root`.
66+ 
67+### File Permission Control
68+ 
69+1. It is recommended that users set the system `umask` value to `0027` or higher on the host (including the physical machine) and in containers, ensuring that the default maximum permission for newly created folders is `750` and for newly created files is `640`.
70+2. It is recommended that users properly manage permissions for sensitive content such as personal data, business assets, source files, and various files saved during training. Permission control can be configured by referring to Table 1.
71+ 
72+ Table 1 Recommended maximum permission settings for files (folders) in various scenarios
73+ 
74+ | Type | Maximum Linux Permission |
75+ | -------------- | --------------- |
76+ | User home directory | 750 (rwxr-x---) |
77+ | Program files (including script files, library files, etc.) | 550 (r-xr-x---) |
78+ | Program file directories | 550 (r-xr-x---) |
79+ | Configuration files | 640 (rw-r-----) |
80+ | Configuration file directories | 750 (rwxr-x---) |
81+ | Log files (recording completed or archived) | 440 (r--r-----) |
82+ | Log files (currently recording) | 640 (rw-r-----) |
83+ | Log file directories | 750 (rwxr-x---) |
84+ | Debug files | 640 (rw-r-----) |
85+ | Debug file directories | 750 (rwxr-x---) |
86+ | Temporary file directories | 750 (rwxr-x---) |
87+ | Maintenance and upgrade file directories | 770 (rwxrwx---) |
88+ | Business data files | 640 (rw-r-----) |
89+ | Business data file directories | 750 (rwxr-x---) |
90+ | Key components, private keys, certificates, and ciphertext file directories | 700 (rwx------) |
91+ | Key components, private keys, certificates, and encrypted ciphertext | 600 (rw-------) |
92+ | Encryption/decryption interfaces and encryption/decryption scripts | 500 (r-x------) |
93+ 
94+### Runtime Safety Statement
95+ 
96+It is recommended that you write training scripts that match the available resources of the runtime environment. If the training script does not align with the resource constraints — for example, dataset loading memory exceeding the memory capacity limit, or training scripts generating local data that exceeds disk space — errors may occur and cause unexpected process termination.
97+ 
98+### Public Network Address Statement
99+ 
100+For details, see `public_address_statement.md` in each model directory.
101+ 
102+## Disclaimer
103+ 
104+### To ModelZoo Users
105+ 
106+1. The models provided by ModelZoo are intended solely for your non-commercial use.
107+2. For each model, ModelZoo only suggests datasets that may be used for training. Huawei does not provide any datasets. If you use these datasets for training, please ensure that you comply with the corresponding dataset licenses. If any infringement disputes arise from your use of the datasets, Huawei assumes no liability.
108+3. If you encounter any issues (including but not limited to functional or compliance issues) while using ModelZoo models, please submit an issue on GitCode. We will review and address it in a timely manner.
109+ 
110+### To Dataset Owners
111+ 
112+If you do not wish for your dataset to be mentioned in the models within ModelZoo, or if you wish to update the description of your dataset in the models within ModelZoo, please submit an issue on GitCode. We will remove or update your dataset description in accordance with your issue request. We sincerely appreciate your understanding and contributions to ModelZoo.
113+ 
114+### License Statement
115+ 
116+For models provided in Ascend ModelZoo, if a license exists in the model directory, that license shall prevail. If no license exists in the model directory, the model is licensed under the Apache 2.0 license, and the corresponding license text can be found in the root directory of Ascend ModelZoo.
@@ -0,0 +1,68 @@
1+# PyTorch Training Model Migration and Tuning Guide
2+ 
3+## What Is Model Migration
4+ 
5+Refer to [What Is Model Migration](migration_process.md#what-is-model-migration).
6+ 
7+## Why Perform Model Migration
8+ 
9+Refer to [Why Perform Model Migration](migration_process.md#why-perform-model-migration).
10+ 
11+## How to Perform Model Migration
12+ 
13+Refer to [Table 1](#table1).
14+ 
15+<a id="table1"></a>
16+ 
17+**Table 1** Model migration guidance
18+ 
19+<table>
20+ <thead>
21+ <tr>
22+ <th colspan="2" align="center">Category</th>
23+ <th align="center">Migration Guide</th>
24+ </tr>
25+ </thead>
26+ <tbody>
27+ <tr>
28+ <td rowspan="2">Conventional models</td>
29+ <td>Adapted Conventional models</td>
30+ <td>Refer to the <a href="../../README.EN.md">Model Scope</a> and follow the corresponding model's README for training and inference.</td>
31+ </tr>
32+ <tr>
33+ <td>Unadapted Conventional models</td>
34+ <td>Refer to this document for migration and training.</td>
35+ </tr>
36+ </tbody>
37+</table>
38+ 
39+## Directory Navigation
40+ 
41+- [Pre-Migration Preparation](pre-migration_prepare.md): Introduces model selection, pre-migration analysis, and common preparations.
42+- [Model Migration](model_migration/README.md): Covers automatic migration, tool-based migration, and manual migration.
43+- [Mixed Precision Adaptation](mixed_precision_adaptation/README.md): Introduces mixed precision training adaptation and typical examples.
44+- [Model Training](model_training/README.md): Introduces the training environment, launch methods, and training debugging.
45+- [Model Saving](model_saving.md): Introduces methods for saving model weights.
46+- [Accuracy Debugging](accuracy_debugging/README.md): Introduces accuracy issue analysis methods and tuning tools.
47+- [Performance Tuning](performance_tuning/README.md): Introduces performance metrics, analysis process, and tuning methods.
48+- [Appendixes](appendixes/README.md): Contains `pdb` parameters, multi-card launch examples, and common migration interfaces.
49+- [Figure Resources](figures/README.md): Stores figures referenced by the documents.
50+ 
51+## Migration Process
52+ 
53+Refer to [Migration Process](migration_process.md#migration-process).
54+ 
55+## Performance Tuning
56+ 
57+Refer to [Performance Tuning](performance_tuning/README.md).
58+ 
59+Performance data collection and evaluation:
60+ 
61+1. In an NPU environment, refer to the [Performance Tuning Tool Introduction](performance_tuning/performance_tuning_process.md#performance-tuning-toolkit) section for model performance breakdown.
62+2. Based on the data obtained from performance breakdown, analyze bottleneck modules and identify the direction for performance optimization.
63+ 
64+Model performance optimization implementation:
65+ 
66+Based on the type of performance bottleneck modules, seek optimization methods from [Performance Tuning Methods](performance_tuning/performance_tuning_methods/README.md#performance-tuning-methods). Specific methods include data loading optimization, NPU affinity optimization, memory optimization, communication optimization, and scheduling optimization.
67+ 
68+In addition, this section provides recommendations for communication optimization, communication algorithms that can be enabled, and scheduling optimization methods.
@@ -0,0 +1,34 @@
1+# ModelZoo
2+ 
3+- [ModelZoo Introduction](introduction.md)
4+- [Installation Guide](install_guide.md)
5+- [Quick Start](quick_start.md)
6+- [Model Usage](model_usage.md)
7+- [Model Migration and Debugging]()
8+ - [Migration Process](migration_process.md)
9+ - [Pre-migration Preparation](pre-migration_prepare.md)
10+ - [Model Migration]()
11+ - [Migration Method Comparison](model_migration/mig_methods_comp.md)
12+ - [(Recommended) Automatic Migration](model_migration/auto_migration.md)
13+ - [Tool-based Migration](model_migration/tool_migration.md)
14+ - [Manual Migration](model_migration/manual_migration.md)
15+ - [Mixed Precision Adaptation]()
16+ - [Adaptation Introduction](mixed_precision_adaptation/adaptation_introduction.md)
17+ - [Adaptation Example](mixed_precision_adaptation/adaptation_example.md)
18+ - [Mixed Precision Issue Debugging](mixed_precision_adaptation/mixed_prec_debug.md)
19+ - [Model Training]()
20+ - [Environment Variable Configuration](model_training/env_config.md)
21+ - [Training Execution](model_training/training_execution.md)
22+ - [Model Debugging](model_training/model_debug.md)
23+ - [Model Saving](model_saving.md)
24+ - [Precision Debugging]()
25+ - [Main Sources and Phenomenon Analysis of Precision Issues](accuracy_debugging/precision_tuning_process.md)
26+ - [Precision Tuning Methods and Tool Usage](accuracy_debugging/precision_tuning_methods_tools.md)
27+- [Model Performance Tuning]()
28+ - [Performance Metrics](performance_tuning/performance_overview.md)
29+ - [Performance Optimization Analysis](performance_tuning/performance_tuning_process.md)
30+ - [Performance Tuning Methods](performance_tuning/performance_tuning_methods/README.md)
31+ - [Data Loading Optimization](performance_tuning/performance_tuning_methods/data_loading_optimization.md)
32+ - [Communication Optimization](performance_tuning/performance_tuning_methods/communication_basics_overview.md)
33+ - [Scheduling Optimization](performance_tuning/performance_tuning_methods/scheduling_opt.md)
34+ - [NPU Affinity Optimization](performance_tuning/performance_tuning_methods/npu_affinity_opt/README.md)
@@ -0,0 +1,21 @@
1+# ModelZoo
2+ 
3+- [Migration Process](migration_process.md)
4+- [Pre-migration Preparation](pre-migration_prepare.md)
5+- [Model Migration]()
6+ - [Migration Method Comparison](model_migration/mig_methods_comp.md)
7+ - [(Recommended) Automatic Migration](model_migration/auto_migration.md)
8+ - [Tool-based Migration](model_migration/tool_migration.md)
9+ - [Manual Migration](model_migration/manual_migration.md)
10+- [Mixed Precision Adaptation](mixed_precision_adaptation/README.md)
11+ - [Adaptation Introduction](mixed_precision_adaptation/adaptation_introduction.md)
12+ - [Adaptation Example](mixed_precision_adaptation/adaptation_example.md)
13+ - [Mixed Precision Issue Debugging](mixed_precision_adaptation/mixed_prec_debug.md)
14+- [Model Training]()
15+ - [Environment Variable Configuration](model_training/env_config.md)
16+ - [Training Execution](model_training/training_execution.md)
17+ - [Model Debugging](model_training/model_debug.md)
18+- [Model Saving](model_saving.md)
19+- [Precision Debugging]()
20+ - [Main Sources and Phenomenon Analysis of Precision Issues](accuracy_debugging/precision_tuning_process.md)
21+ - [Precision Tuning Methods and Tool Usage](accuracy_debugging/precision_tuning_methods_tools.md)
@@ -0,0 +1,10 @@
1+# ModelZoo
2+ 
3+- [Performance Metrics](performance_tuning/performance_overview.md)
4+- [Performance Optimization Analysis](performance_tuning/performance_tuning_process.md)
5+- [Performance Tuning Methods](performance_tuning/performance_tuning_methods/README.md)
6+ - [Data Loading Optimization](performance_tuning/performance_tuning_methods/data_loading_optimization.md)
7+ - [Communication Optimization](performance_tuning/performance_tuning_methods/communication_basics_overview.md)
8+ - [Scheduling Optimization](performance_tuning/performance_tuning_methods/scheduling_opt.md)
9+ - [NPU Affinity Optimization](performance_tuning/performance_tuning_methods/npu_affinity_opt/README.md)
10+
@@ -0,0 +1,6 @@
1+# Precision Debugging
2+ 
3+This section introduces the analysis, localization methods, and common tools for precision issues during model migration and training.
4+ 
5+- [Analysis of Primary Sources and Phenomena of Precision Issues](precision_tuning_process.md): Introduces common sources of precision issues such as datasets, hyperparameters, floating-point computation, and mixed precision.
6+- [Precision Tuning Methods and Tool Usage](precision_tuning_methods_tools.md): Introduces methods for localizing precision issues and the use of related tools.
@@ -0,0 +1,99 @@
1+# Accuracy Tuning Methods and Tool Usage
2+ 
3+## Accuracy Tuning Methods
4+ 
5+### Dataset Cleaning
6+ 
7+In the process of building high-quality machine learning models, dataset cleaning is a crucial preliminary task aimed at improving model training effectiveness and preventing overfitting and redundancy in generated content.
8+ 
9+- **Removal of non-target languages and low-quality samples**: Eliminate non-target languages, discard data with low perplexity, remove sentences with excessive punctuation/symbols or those that are too long or too short, and delete sentences containing specific vocabulary (such as HTML tags, links, profanity, and sensitive words).
10+- **Deduplication**: Remove sentences containing a large number of repeated words or phrases; delete paragraphs with excessively high repetition rates (word/n-gram co-occurrence); remove content in the training set that may be overly correlated with the test set. This improves the quality of the training set, mitigates the problem of repetitive content generated by a language model, and avoids overfitting caused by test set leakage.
11+ 
12+When encountering loss or perplexity spikes, if it is determined that the issue is caused by certain data batches, you may skip those data batches seen during the spike and resume training from a previously normal checkpoint.
13+ 
14+### Hyperparameter Configuration Tuning
15+ 
16+- **Batch size configuration**: During model training, the batch size is typically set to a large value to fully utilize large-scale training data and enhance the stability of the training process. For example, setting the batch size to `8196` with a sample sequence length of 2K allows each batch to process approximately 16M token inputs. The gradient average of large samples makes parameter updates more precise, thereby mitigating loss fluctuations caused by imprecise updates.
17+ 
18+- **Learning rate**: The learning rate is generally small and includes a warm-up setting to ensure stable training. For instance, a linear learning rate increase is set during the first 0.1% to 0.5% of training steps. The peak learning rate is usually below 10<sup>-4</sup>, after which a cosine decay or linear decay learning rate scheduling is adopted to gradually reduce the learning rate, decreasing it to about 10% of the peak learning rate before convergence.
19+ 
20+- **Optimizer**: Optimizers commonly used include Adam, AdamW, and Adafactor. Among them, Adafactor is a memory-efficient variant of Adam. SGD is also used in some cases, though it is less common.
21+ 
22+- **Weight initialization**: Proper weight initialization helps the model converge faster and improves performance. For example, small Gaussian noise or T-Fixup initialization is typically used.
23+ 
24+- **Other training stabilization techniques**:
25+ - Gradient clipping: As a commonly used training stabilization technique, the clipping threshold is typically set to `1.0` to prevent excessively large gradients from causing training instability.
26+ - Weight decay (L2 regularization): Setting a reasonable weight decay rate, such as `0.1`, helps prevent overfitting and enhances the model's generalization capability.
27+ - Adjustment of special layers: Embedding layers often exhibit significant gradient anomalies, so relevant parameters need to be moderately adjusted based on actual conditions.
28+ 
29+### Precision Requirements for Specific Computational Operations
30+ 
31+In the design and training of large-scale deep neural networks, selecting appropriate precision types for different computational operations is crucial. This decision requires both a solid foundation in mathematical analysis and extensive practical experience. This section summarizes practical insights from a large body of research literature and introduces the specific precision requirements of key computational operations that affect model performance.
32+ 
33+- **Softmax function**: The softmax function involves exponential operations, which are prone to overflow and underflow, and its denominator requires summation. Currently, mainstream operator libraries only use FP32 to implement softmax.
34+- **Cross-Entropy loss calculation**: `cross_entropy` is used to calculate cross-entropy loss. Like many loss functions, it requires FP32 computation to maintain numerical stability, so operator implementations only accept FP32 inputs.
35+- **Matrix multiplication (Matmul)**: Matmul can generally use half precision. However, in the model's attention layers, the matrix multiplication between attention scores and the V tensor requires FP32 to maintain numerical stability, avoid overflow, and minimize accumulated errors.
36+- **Normalization functions**: Normalization functions such as `layer_norm`, `Batch_norm`, and `RMSNorm` require FP32 computation. `Layer_norm` computes variance, which involves summation. If FP16 is used, overflow and significant errors are likely to occur during computation, affecting final convergence. `Batch_norm` is similar to `layer_norm` and also requires upcasting the input tensor to FP32. `RMSNorm` is an extension of `layer_norm`. If implemented by developers, care must be taken to force the input tensor to upcast to FP32 for computation, though the results can be converted back to half precision. The main reason is that `RMSNorm` requires computing the root mean square, which involves accumulation. However, low-precision computation tends to accumulate errors.
37+- **Convolution and pooling**: Convolution is an element-wise matrix multiplication and is not sensitive to precision. BF16 can be used without affecting model convergence. Similar to convolution, pooling can also use BF16. ReLU and GeLU are point-wise operations and are likewise not sensitive to precision.
38+- **Recurrent neural networks (RNNs)**: RNNs are generally sensitive to precision, but the LSTM-cell is not. BF16 can be used.
39+- **Model's first and last layers**: Typically, the first and last layers of a model are sensitive to precision. For example, the embedding layer requires FP32. Even if the final output layer is not a softmax, the computation and output results should still be in FP32.
40+- **Communication operators**: Communication operators involving gradient or activation accumulation, such as `all_reduce` and `reduce_scatter`, require upcasting the input tensor to FP32 to ensure numerical stability.
41+ 
42+## Using Monitor to Debug Model Convergence Issues
43+ 
44+If model convergence issues occur, a common approach is to dump the suspected problematic tensors in full or in compressed form. However, this approach has the following drawbacks:
45+ 
46+1. Self-added dump code may significantly impact performance, causing the issue to become unreproducible or severely affecting performance, and it cannot be used for long-term monitoring throughout training.
47+2. Adding tensor dump code requires a deep understanding of the training framework or model structure and involves lengthy code testing, resulting in a high barrier to entry for manually adding tensor dump code.
48+3. If the debugging personnel and the model developers are not from the same organization, the debugging personnel may not have access to all training scripts, making it difficult to quickly add tensor dump code or modify the dump code based on debugging results.
49+ 
50+Therefore, to help Ascend customers overcome various difficulties during model debugging, Monitor, the debugging tool based on tensor inspection technology, was developed.
51+ 
52+### Introduction to Monitor
53+ 
54+Monitor provides the following functions:
55+ 
56+- Prints the model hierarchy and the collective communication APIs used during training, to specify network layers and communications to be monitored.
57+- Supports layer-by-layer on-demand inspection of various intermediate tensors specified during training by adding just a few lines of code, such as parameter gradients, activation gradients, weights and Adam optimizer states, and the input/output tensors of collective communication operators (e.g., `all-reduce`, `reduce-scatter`, and `all-gather`) for gradient synchronization.
58+- Supports multiple tensor compression operations, such as `norm`, `max`, `min`, and `zeros`.
59+- Supports monitoring and alerting for abnormal fluctuations in tensor eigenvalue.
60+ 
61+For detailed usage of Monitor, see its usage instruction<!-- ](https://gitcode.com/Ascend/msprobe/blob/26.1.0/docs/en/user_guide/monitor_instruct.md) -->.
62+ 
63+### Training Case Study
64+ 
65+- Identifying the root cause of llama2 loss spikes
66+ 
67+ An Ascend user encountered frequent loss spikes while training a model similar to llama2-13b and suspected that the issue was caused by unreasonable hyperparameter configuration of the Adam optimizer. Then, Monitor was used to collect the actual update tensors of the word embedding layer, with the formula as follows:
68+ 
69+ ![](../figures/debug_model_conv_monitor_fig_01.png)
70+ 
71+ The collected results revealed that after training had stabilized, the word embedding layer received almost no updates for a long period. However, upon encountering a specific batch (not necessarily a bad data batch), the word embedding layer suddenly underwent drastic updates. It was ultimately confirmed that the issue was caused by an excessively large Adam optimizer beta2 value. After `beta2` was reduced, the problem was resolved.
72+ 
73+- Identifying the non-convergence issue of Open-Sora under the DeepSpeed ZeRO-1 configuration
74+ 
75+A user reported that when training under DeepSpeed ZeRO-1, the model could converge normally when using FP32 for backward gradient computation, but failed to converge when using BF16 mixed-precision training. By using Monitor, the user compared the trend of weight gradients in the network layers near the input (early layers) of the Open-Sora model under both FP32 and BF16 dtypes. It was found that several hundred steps before the loss diverged, the gradients of the early layers increased under both FP32 and BF16. However, due to BF16's floating-point precision limitations, the gradient fluctuations under BF16 were much more severe. The user had set the gradient clipping `max norm` to `1`, which was far larger than the normal training `GNorm` (approximately `1e-4`), rendering gradient clipping ineffective. Consequently, after reducing `max norm` to an appropriate range, the BF16 mixed-precision training converged successfully.
76+ 
77+Using tools to debug training issues is more systematic and deterministic compared to blindly adjusting hyperparameters. In large-scale training scenarios, this approach significantly reduces problem-solving time and saves substantial computational resources. Therefore, we recommend that when encountering training convergence issues, users should first enable training process monitoring with Monitor.
78+ 
79+### Training Status Monitoring
80+ 
81+During model training, to ensure training stability and effectiveness, it is necessary to closely monitor multiple key metrics to evaluate the training status, including but not limited to perplexity (PPL), gradient norm (GNorm), activation norm, memory usage, and loss scale. It is recommended to use the TensorBoard tool for data visualization.
82+ 
83+**Figure 1** Data visualization on TensorBoard
84+ 
85+<img src="../figures/debug_model_conv_monitor_fig_02.png" height="287.25" width="523.6875">
86+ 
87+Additionally, during model training, hooks can be configured for specific layers prone to issues using the hook mechanism in PyTorch to monitor the gradient information of these layers. This allows for timely handling of abnormal steps, thereby reducing the negative impact on the model's training effectiveness. The specific operations are as follows:
88+ 
89+1. After obtaining the model structure in the `train` method, pass the model into the specified collector.
90+ 
91+ <img src="../figures/debug_model_conv_monitor_fig_03.png" height="82.9521" width="465.5">
92+ 
93+2. Register a tensor hook for the tensor of the specified layer. This type of hook only returns the gradient information of the corresponding tensor. The hook is invoked after the backward propagation of each micro batch of data is completed, meaning that gradient values are recorded for every micro batch of data.
94+ 
95+ <img src="../figures/debug_model_conv_monitor_fig_04.png" height="144.05257" width="465.5">
96+ 
97+By monitoring and analyzing this gradient information, some abnormal states during training can be detected. When collecting gradient values, it is recommended to collect only statistical information such as the maximum, minimum, and average values of the gradients as monitoring indicators for the training status.
98+ 
99+In addition to monitoring gradient explosion, attention should also be paid to gradient underflow. Especially for FP16, if a large number of zeros appear in the gradients, it often indicates that the training is abnormal. In this case, training needs to be stopped to identify the problem (for example, pseudo FP32, which is actually mixed precision). If the trainer uses loss scale, monitoring the loss scale is mandatory.
@@ -0,0 +1,203 @@
1+# Analysis of Primary Sources and Phenomena of Precision Issues
2+ 
3+Training a model is influenced by factors such as the dataset, model architecture, parallelism strategies, and hyperparameters. During the training process, issues like NaN, overflow/underflow, and loss divergence may occur, requiring precision debugging. When training models on Ascend processors, the loss generally shows an overall downward convergence trend. Even if occasional spikes occur, they can be mitigated by skipping dataset batches or resuming training from checkpoints. When the trained weights are used to evaluate the model's scores on standard datasets and the results align with the expected performance reported in the community, the precision debugging process can be considered complete.
4+ 
5+This document summarizes common issues encountered during model training and their debugging methods, aiming to help users eliminate problems before training begins and shorten the time required to locate model precision issues.
6+ 
7+## Dataset
8+ 
9+Data is one of the decisive factors in enhancing model capabilities. Models are sensitive to dataset quality; invalid or low-quality data can cause the model to learn incorrect patterns and even affect model convergence. Duplicate data exacerbates content repetition in language models and leads to overfitting. In terms of metrics, dataset issues may cause spikes in the gradient norm, indicating an abnormal increase in the gradient norm that leads to training instability.
10+ 
11+- **Training instability triggered by anomalous data**: Corpus that triggers training anomalies includes bytecode, Unicode garbled text, pure numeric text, and the like. Such corpus is silently tokenized by mainstream subword tokenizers into tokens and converted into ID sequences, which then enter the normal training iteration steps. However, because this corpus lacks grammatical and semantic regularity, updating parameters based on it may interfere with the model's normal learning process. When the volume of anomalous corpus is significant, the model may fail to converge properly.
12+- **Corpus mixing ratio and type**: The mixing ratios and scale of different languages and corpus types (code, text) also have a significant impact on model training precision. The mixing ratios of corpus from different sources must be adjusted, and raw corpus should not be directly merged for training. A balanced corpus ratio helps improve the model's generalization ability, while specific types of corpus can enhance the model's capabilities in particular areas.
13+- **Matching data scale with model parameter scale**: Larger parameter scale is not always better. Research by Hoffmann et al. on the Chinchilla series of models shows that, given a fixed computational budget, the model performs relatively better when the number of corpus tokens is comparable to the number of model parameters. Therefore, one should not blindly pursue large-scale corpus; instead, emphasis should also be placed on controlling scale, improving quality, and ensuring sufficient training.
14+ 
15+## Hyperparameter Configuration
16+ 
17+Hyperparameters have a critical impact on model training convergence. The hyperparameters discussed here primarily include: **optimizer selection, learning rate setting, gradient clipping threshold, loss scale**, and others.
18+ 
19+- **Optimizer and learning rate**: The choice of optimizer directly affects the update strategy during model training. As one of the core hyperparameters, an improperly set learning rate may lead to issues such as sudden changes in the global gradient norm (`GNorm`), failure of the loss curve to converge, upward trends, or even severe fluctuations. Therefore, when training large models, it is necessary to carefully search for an appropriate learning rate to ensure convergence performance.
20+- **Gradient clipping threshold**: Gradient clipping is also critical to the stability of model training. Using an excessively high gradient clipping threshold may cause `GNorm` to remain persistently high, as shown by the blue line in Figure 1. Gradient clipping can reduce the gradient values of certain tensors after backward propagation is complete, which helps prevent gradient explosion and makes the training process more stable. The clipping range can be configured through experimentation, by using common values from the literature, or by observing the range through experiments and then selecting a reasonable value. All layers in the network typically use the same gradient clipping configuration; generally, the output layer allows a larger gradient range than the hidden layers.
21+ 
22+ **Figure 1** Excessively high gradient clipping threshold
23+ 
24+ <img src="../figures/hparams_fig_01.png" height="180.9598" width="497.42">
25+ 
26+- **Dynamic loss scale adjustment**: During training, the loss scale acts as a dynamically adjusted scaling factor, and its magnitude changes also reflect the stability state of training. If the loss scale remains below 1 for an extended period, it usually means that some gradient values are too large and prone to overflow. At the same time, smaller gradient values are also more likely to underflow to 0, causing training to remain in an unstable state.
27+- **Impact of batch size**: Batch size is another hyperparameter that significantly affects training performance, striking a balance between meeting memory requirements and improving training efficiency. In distributed model training scenarios, it is common to choose larger batch sizes to shorten training duration. However, an excessively large batch size may also cause the loss curve to show an upward trend. Therefore, when adjusting batch size, it is necessary to comprehensively consider its impact on both training efficiency and convergence to achieve an optimal configuration.
28+ 
29+## Floating-Point Computation
30+ 
31+Precision issues in floating-point computation stem from the fact that computers use binary numbers in specific formats to represent real numbers, and binary can only represent a finite set of discrete real numbers. As a result, certain decimal fractions can only be represented approximately. Precision issues in floating-point computation can be mitigated but not eliminated, so understanding the differences between various floating-point types is crucial for model training.
32+ 
33+In CPU-based computing scenarios, the double-precision floating-point type, also known as FP64 or float64, is frequently used. However, in machine learning and AI accelerator-based computing scenarios, due to the massive scale of parameters, it is difficult and unnecessary to use double-precision numbers for storage and computation. Single-precision floating-point numbers and half-precision floating-point numbers are the commonly used data types in model training.
34+ 
35+### Single-Precision Floating-Point Number
36+ 
37+FP32, or float32, is a floating-point format defined by the IEEE 754 standard. It uses 32 bits to represent a floating-point number, consisting of a 1-bit sign bit, an 8-bit exponent, and a 23-bit fraction. The bit layout is as follows:
38+ 
39+![](../figures/floating_point_calc_fig_01.png)
40+ 
41+When the exponent bits are not zero, the floating-point number V represented by these 32 bits is called a normalized number, defined by the following formula:
42+ 
43+![](../figures/floating_point_calc_fig_02.png)
44+ 
45+When the exponent is zero, the floating-point number is called a subnormal number, defined by the following formula:
46+ 
47+![](../figures/floating_point_calc_fig_03.png)
48+ 
49+In fast mode, NPUs or mainstream AI processors can only perform operations on normalized numbers. Subormal numbers are flushed to zero, and division and square root operations are not computed to the nearest representable floating-point value.
50+ 
51+When the exponent bits are all ones, the floating-point number represented has a special meaning. If the fraction is 0 at this point, V is positive or negative infinity; if the fraction is not 0, V is NaN (Not a Number).
52+ 
53+The smallest absolute normalized floating-point number that the FP32 format can represent is 2<sup>-126</sup>, approximately 1.18e-38. The largest absolute normalized floating-point number is 2<sup>127</sup> * [1 + (2<sup>23</sup> − 1)/2<sup>23</sup>], approximately 3.4e38. Around 1.0, the spacing between two adjacent floating-point numbers is 2<sup>-23</sup>, approximately 1.2e-7. The relative spacing between adjacent floating-point numbers at all positions is approximately 1.2e-7. This shows that FP32 has very high floating-point precision.
54+ 
55+### Half-Precision Floating-Point Number
56+ 
57+Due to the massive scale of model parameters, AI accelerators have high memory requirements, so using a 16-bit half-precision format offers more advantages than 32-bit single precision. Additionally, half-precision computation is faster, and its precision is often sufficient for machine learning models. Like mainstream AI processors, the latest Ascend AI accelerators also support two half-precision floating-point formats: FP16 and BF16.
58+ 
59+- **FP16 format**
60+ 
61+ FP16, or float16, is a half-precision floating-point format defined by the IEEE 754 standard. It uses 16 bits to represent a floating-point number, including 1-bit sign, 5-bit exponent, and 10-bit fraction. The bit layout is as follows:
62+ 
63+ ![](../figures/floating_point_calc_fig_04.png)
64+ 
65+ Similar to FP32, if the exponent is non-zero, it represents a normalized floating-point number V, defined by the following formula:
66+ 
67+ ![](../figures/floating_point_calc_fig_05.png)
68+ 
69+ We will not elaborate further on denormalized numbers for FP16 here.
70+ 
71+ Around 1.0, the spacing between two adjacent floating-point numbers is 2<sup>-10</sup>. The relative spacing between two adjacent floating-point numbers at any position is also 2<sup>-10</sup>, which is approximately one-thousandth. A serious problem caused by the precision error of FP16 is the "large number swallowing small number" effect in addition. For example:
72+ 
73+ ```python
74+ x = torch.tensor(1, dtype=torch.float16)
75+ y = torch.tensor(0.0001, dtype=torch.float16)
76+ ```
77+ 
78+ x+y remains 1.0 because 1.0001 cannot be represented in FP16. The smallest number that FP16 can represent after 1 is 1.0009765625.
79+ 
80+ The maximum absolute value of the normalized floating-point number that FP16 can represent is 2<sup>15</sup> \* \(1+1023/1024\)=65504, and the minimum absolute value is 2<sup>-14</sup>, which is approximately 6.1e-5. This means that numbers exceeding 65504 and numbers smaller than 6.1e-5 cannot be represented in FP16, yet these numbers are very common in model training. To avoid underflow, FP16 must be combined with loss scaling for model training.
81+ 
82+- **BF16 format**
83+ 
84+ To address the issue of FP16's limited representation range, the Google Brain research team proposed the bfloat16 floating-point format, also known as BF16. The bit structure layout of BF16 is as follows:
85+ 
86+ ![](../figures/floating_point_calc_fig_06.png)
87+ 
88+ Compared to FP16, BF16 increases the exponent bit width to 8 (the same as FP32) and reduces the fraction bit width to 7. This expands the floating-point representation range but sacrifices representation precision. When the exponent is not 0, the BF16 floating-point formula is as follows:
89+ 
90+ ![](../figures/floating_point_calc_fig_07.png)
91+ 
92+Around 1.0, the spacing between adjacent floating-point numbers representable in BF16 is 1/128. The relative spacing between adjacent floating-point numbers at any position is 1/128, indicating that the precision of BF16 is very low, only one-eighth of the precision of FP16. The maximum representable normalized floating-point number in BF16 is 2<sup>127</sup> \* \(1+127/128\), approximately 3.4e38, and the normalized floating-point number with the smallest absolute value is 2<sup>-126</sup>, approximately 1.176e-38.
93+ 
94+The precision of BF16 is still sufficient for most model training scenarios. However, care must be taken with certain operations, such as accumulation, which should be performed with higher-precision FP32.
95+ 
96+In summary, selecting an appropriate floating-point number precision is crucial for optimizing the model training process. Especially when dealing with convergence issues caused by floating-point precision, it is necessary to combine literature research findings and practical experience, and to perform debugging and optimization through extensive comparative experiments.
97+ 
98+## Mixed-Precision Computation
99+ 
100+Although low-precision computation can provide a very significant increase in training speed, low-precision operations can also cause numerical errors and numerical stability issues compared to FP32. Therefore, when using low-precision operations to accelerate training, understanding the numerical behavior of core tensor operations is also very important.
101+ 
102+The representable range of FP16 is ±65504, and the smallest absolute values of normalized numbers it can represent are 2<sup>-14</sup> and -2<sup>-14</sup>, which is +/-0.000061035. The relative spacing between two adjacent floating-point numbers is approximately one-thousandth. For example, the first floating-point number greater than 1 is 1+1/1024, which means 1.0001 cannot be represented. FP16 incurs significantly larger precision errors compared to FP32. The following code demonstrates the relative error when computing the mean of a 10,000-dimensional random tensor (drawn from a normal distribution with mean 0 and variance 1) on a mainstream AI processor using FP32 and FP16, respectively. When computed with FP16, the average relative error is around 0.1%, and the maximum error is 23%. In model training scenarios, because many tensors are very small and have high dimensionality, attention must be paid to FP16 precision issues. If the same code is computed with BF16, the average relative error is about 1%, and the maximum error approaches 4800%. Because accumulation operations have inherent variability, running the program twice may yield different results.
103+ 
104+```shell
105+python non-distributed.py --dtype fp16 --device npu
106+python non-distributed.py --dtype bf16 --device npu
107+```
108+ 
109+```python
110+import torch
111+import argparse
112+parser = argparse.ArgumentParser(
113+ prog='test_mean',
114+ description='check the effect to final result under different floating point precision')
115+parser.add_argument("-t", "--dtype", default="fp16",help="precision selection")
116+parser.add_argument("-d", "--device", default="cuda", help="accelerator selection")
117+args = parser.parse_args()
118+# accelerator selection
119+if args.device == 'cuda':
120+ device = torch.device('cuda:0')
121+elif args.device == 'npu':
122+ import torch_npu
123+ device = torch.device('npu:0')
124+dtype = torch.bfloat16 if args.dtype == "bf16" else torch.float16
125+fn = torch.mean
126+ 
127+def test(fn):
128+ N, batch = 10000, 1000
129+ # calculations based on FP16 or BF16
130+ x = torch.randn((batch, N))
131+ x_16 = x.to(device, dtype=dtype)
132+ x_mean_16 = fn(x_16, dim=-1, dtype=dtype)
133+
134+ # calculations based on FP32
135+ x_fp32 = x.to(device)
136+ x_mean_fp32 = fn(x_fp32, dim=-1, dtype=torch.float32)
137+ 
138+ # error analysis
139+ rel_diff = abs((x_mean_16.float() - x_mean_fp32) / x_mean_fp32)
140+ return rel_diff
141+rel_diff= test(fn=fn)
142+max_rel_diff = rel_diff.max() # maximum calculation error
143+avg_rel_diff = rel_diff.mean() # average calculation error
144+print("average relative difference is: ", avg_rel_diff)
145+print("max relative difference is: ", max_rel_diff)
146+```
147+ 
148+Because FP16 has a very limited floating-point representation range, overflow can easily occur during computation, resulting in Inf or NaN. Some hardware may convert Inf values to the maximum representable number, which alleviates overflow to a certain extent but still introduces computational errors.
149+ 
150+BF16 expands the floating-point representable range by increasing the exponent bit width and reducing the fraction bit width, at the cost of representable precision. Its maximum finite value is approximately 3.39 × 10<sup>38</sup>, and the smallest normalized number in terms of absolute value is 2<sup>-126</sup>, approximately 1.18 × 10<sup>-38</sup>. Around 1.0, the spacing between two adjacent BF16 floating-point numbers is 1/128, about 0.78%, so 1.001 cannot be represented precisely. The precision of BF16 is lower than that of FP16, but it is less prone to overflow, and the risk of normalized number underflow is also significantly lower than FP16, making it more convenient than FP16 in precision-insensitive computation scenarios. Experiments on existing large Transformer models have shown that using BF16 for mixed-precision training generally does not significantly affect model convergence.
151+ 
152+When distributed communication operators involve accumulation operations, error accumulation issues with low-precision numbers also arise. As shown in the code below, the average error of FP16 all\_reduce across 8 ranks on a mainstream AI processor is approximately one-thousandth, with a maximum error of about 2x. When using BF16, the average relative error is around 1.5%, and the maximum relative error is 9x. Due to the non-deterministic computation of communication operators, running the same input twice will yield different results.
153+ 
154+```shell
155+torchrun --nnodes=1 --nproc-per-node=8 distributed.py --dtype fp16 --device npu
156+torchrun --nnodes=1 --nproc-per-node=8 distributed.py --dtype bf16 --device npu
157+```
158+ 
159+```python
160+import os
161+import torch
162+import torch.distributed as dist
163+ 
164+import argparse
165+parser = argparse.ArgumentParser(
166+ prog='fp precision test',
167+ description='check the effect to final result under different floating point precision')
168+parser.add_argument("-t", "--dtype", default="fp16")
169+parser.add_argument("-d", "--device", default="cuda", help='accelerator selection')
170+args = parser.parse_args()
171+ 
172+dtype = torch.bfloat16 if args.dtype == "bf16" else torch.float16
173+# distributed environment
174+local_rank = int(os.environ['LOCAL_RANK'])
175+world_size = int(os.environ['WORLD_SIZE'])
176+# accelerator selection
177+if args.device == 'cuda':
178+ device = torch.device(f"cuda:{local_rank}")
179+ dist.init_process_group(backend='nccl', rank=local_rank, world_size=world_size)
180+elif args.device == 'npu':
181+ import torch_npu
182+ device = torch.device(f"npu:{local_rank}")
183+ torch.npu.set_device(device)
184+ dist.init_process_group(backend='hccl', rank=local_rank, world_size=world_size)
185+if __name__ == "__main__":
186+ print("start all reduce!")
187+ hccl_input = torch.randn(10000)
188+ print(local_rank, hccl_input.shape)
189+ 
190+ # collective communication
191+ hccl_input16 = hccl_input.to(device=device,dtype=dtype)
192+ hccl_input32 = hccl_input.to(device=device)
193+ torch.distributed.all_reduce(hccl_input16)
194+ torch.distributed.all_reduce(hccl_input32)
195+ if local_rank == 0:
196+ rel_diff = abs((hccl_input16.float() - hccl_input32) / hccl_input32)
197+ diff_mean = torch.mean(rel_diff)
198+ diff_max = torch.max(rel_diff)
199+ print("diff_mean=", diff_mean)
200+ print("max diff=", diff_max)
201+```
202+ 
203+In summary, the choice of which precision to use for mixed-precision training requires a trade-off between precision loss and training speedup based on specific task requirements, while also taking into account the error accumulation effects in distributed environments.
@@ -0,0 +1,7 @@
1+# Appendix
2+ 
3+This section contains notes and examples for migration and training.
4+ 
5+- [Common pdb Arguments](common_pdb_args.md): Commonly used commands in pdb debugging.
6+- [Examples of Launching Multi-Device Training Scripts](launch_multi_device_train_demo.md): Introduction to examples for launching multi-device training scripts.
7+- [Common PyTorch Interfaces to Be Replaced](pytorch_migrate_api.md): Common PyTorch interface to be replaced and migrated.
@@ -0,0 +1,21 @@
1+# Common pdb Arguments
2+ 
3+**Table 1** pdb arguments
4+ 
5+|Command|Shortcut|Description|
6+|--|--|--|
7+|break|b|Set a breakpoint.|
8+|continue|c|Continue execution until the next breakpoint or call point.|
9+|list|l|View the code segment around the current line.|
10+|step|s|Step into a function.|
11+|return|r|Execute until returning from the current function.|
12+|quit|q|Abort and exit.|
13+|next|n|Execute the next line.|
14+|print|p|Print the value of a variable.|
15+|help|h|Help.|
16+|args|a|View the passed arguments.|
17+|Enter key (keyboard)|None|Repeat the last command.|
18+|break lineno|b lineno|Set a breakpoint at the specified line.|
19+|break file:lineno|b file:lineno|Set a breakpoint at the specified line in a file.|
20+|clear num|None|Delete the specified breakpoint.|
21+|bt|None|View the function call stack frames.|
@@ -0,0 +1,665 @@
1+# Examples of Launching Multi-Device Training Scripts
2+ 
3+This section uses a single-node eight-device training script with torchrun as an example to introduce code adaptations required for single-node eight-device and dual-node 16-device training.
4+ 
5+## Model Script Example<a id="custom-anchor"></a>
6+ 
7+Example of a model script for single-node 8-device training with torchrun:
8+ 
9+```python
10+import argparse
11+import os
12+from datetime import timedelta
13+ 
14+import torch
15+import torch.distributed as dist
16+import torch.nn as nn
17+import torch.optim as optim
18+from torch.nn.parallel import DistributedDataParallel as DDP
19+from torch.utils.data import DataLoader
20+from torch.utils.data.distributed import DistributedSampler
21+import torch_npu
22+from torchvision import datasets, transforms
23+ 
24+DATA_DIR = "./data" # Dataset directory
25+ 
26+ 
27+def cleanup():
28+ """Clean up the process group for distributed training"""
29+ dist.destroy_process_group()
30+ 
31+ 
32+class ToyModel(nn.Module):
33+ """Simple neural network model"""
34+ def __init__(self):
35+ super(ToyModel, self).__init__()
36+ self.layer1 = nn.Linear(784, 128) # First fully-connected layer
37+ self.relu = nn.ReLU() # ReLU activation function
38+ self.layer2 = nn.Linear(128, 10) # Second fully-connected layer
39+ 
40+ def forward(self, x):
41+ """Forward propagation function"""
42+ return self.layer2(self.relu(self.layer1(x))) # The input passes through two fully-connected layers and the ReLU activation function
43+ 
44+ 
45+def data_process(inputs, labels):
46+ """Data preprocessing function"""
47+ inputs = inputs.view(-1, 784) # Flatten the input tensor to (batch_size, 784)
48+ labels = labels.view(-1) # Flatten the label tensor to (batch_size)
49+ return inputs, labels
50+ 
51+ 
52+def get_train_args():
53+ """Get training arguments"""
54+ parser = argparse.ArgumentParser(description="command line arguments") # Create an argument parser
55+ parser.add_argument("--batch_size", type=int, default=64) # Set the batch size, defaulted to 64
56+ parser.add_argument("--epochs", type=int, default=1) # Set the number of training epochs, defaulted to 1
57+ parser.add_argument("--learning_rate", type=float, default=0.0001) # Set the learning rate, defaulted to 0.0001
58+ args = parser.parse_args() # Parse command line arguments
59+ return args
60+ 
61+ 
62+def train(args):
63+ """Training function"""
64+ world_size = int(os.environ["WORLD_SIZE"]) # Get the number of processes for distributed training
65+ local_rank_idx = int(os.environ["LOCAL_RANK"]) # Get the local rank index
66+ 
67+ devices_per_node = torch.npu.device_count() # Get the number of NPU devices per node
68+ 
69+ dist.init_process_group("hccl", rank=local_rank_idx, world_size=world_size, timeout=timedelta(minutes=30)) # Initialize the distributed process group
70+ torch_npu.npu.set_device(local_rank_idx) # Set the current NPU device to use
71+ 
72+ device_id = f"npu:{local_rank_idx}" # NPU device identifier
73+ 
74+ model = ToyModel().to(device_id) # Instantiate the model and move it to the specified device
75+ 
76+ transform = transforms.Compose([
77+ transforms.ToTensor(), # Convert image to tensor
78+ transforms.Normalize((0.5,), (0.5,)) # Normalize
79+ ])
80+ 
81+ train_dataset = datasets.MNIST(root=DATA_DIR, train=True, download=True, transform=transform) # Load MNIST training dataset
82+ train_sampler = DistributedSampler(train_dataset, num_replicas=devices_per_node, rank=local_rank_idx) # Create a distributed data sampler
83+ train_dataloader = DataLoader(train_dataset, batch_size=args.batch_size, sampler=train_sampler) # Create a data loader
84+ 
85+ criterion = nn.CrossEntropyLoss().to(device_id) # Define the loss function
86+ optimizer = optim.Adam(model.parameters(), lr=args.learning_rate) # Define the optimizer
87+ 
88+ model = DDP(model) # Wrap model to support distributed training
89+ 
90+ for epoch in range(args.epochs):
91+ if local_rank_idx == 0:
92+ print(f"\nCurrent epoch: {epoch}") # Print current epoch
93+ 
94+ train_sampler.set_epoch(epoch) # Set epoch for data sampler
95+ 
96+ model.train() # Set the model to training mode
97+ 
98+ for i, (inputs, labels) in enumerate(train_dataloader):
99+ inputs, labels = data_process(inputs, labels) # Preprocess data
100+ inputs, labels = inputs.to(device_id), labels.to(device_id) # Move data to the specified device
@@ -0,0 +1,41 @@
1+# Common PyTorch Interfaces to Be Replaced
2+ 
3+You need to replace certain interfaces of the native PyTorch framework to use the Ascend-adapted PyTorch framework. During network migration, you need to convert some interfaces into those adapted for the Ascend AI Processor. For some of the currently adapted interfaces, see Table 1. For more interfaces, see *[TorchNPU Custom API Reference](https://gitcode.com/Ascend/op-plugin/blob/26.1.0/docs/en/custom_APIs/overview.md)*.
4+ 
5+**Table 1** Interfaces to be replaced
6+ 
7+|Native PyTorch Interface|Interface Adapted to Ascend AI Processor|Description|
8+|--|--|--|
9+|torch.cuda.is_available()|torch_npu.npu.is_available()|Determines whether available NPUs exist in the current environment (returns True if at least one NPU is available).|
10+|torch.cuda.current_device()|torch_npu.npu.current_device()|Gets the device currently in use.|
11+|torch.cuda.device_count()|torch_npu.npu.device_count()|Gets the number of devices in the current environment.|
12+|torch.cuda.set_device()|torch_npu.npu.set_device()|Sets the device currently in use.|
13+|torch.tensor([1,2,3]).is_cuda|torch.tensor([1,2,3]).is_npu|Determines whether a tensor is in CUDA/NPU format on the device.|
14+|torch.tensor([1,2,3]).cuda()|torch.tensor([1,2,3]).npu()|Converts a tensor to CUDA/NPU format.|
15+|torch.tensor([1,2,3]).to("cuda")|torch.tensor([1,2,3]).to("npu")|Converts a tensor to CUDA/NPU format.|
16+|torch.cuda.synchronize()|torch_npu.npu.synchronize()|Synchronously waits for an event to complete.|
17+|torch.cuda.device|torch_npu.npu.device|Creates a device instance for performing device-related operations.|
18+|torch.cuda.Stream(device)|torch_npu.npu.Stream(device)|Creates a stream object.|
19+|torch.cuda.stream(Stream)|torch_npu.npu.stream(Stream)|Mostly used for scope limitation.|
20+|torch.cuda.current_stream()|torch_npu.npu.current_stream()|Gets the current stream.|
21+|torch.cuda.default_stream()|torch_npu.npu.default_stream()|Gets the default stream.|
22+|device = torch.device("cuda:0")|device = torch.device("npu:0")|Specifies a device.|
23+|torch.autograd.profiler.profile(use_cuda=True)|torch.autograd.profiler.profile(use_npu=True)|Specifies the use of CUDA/NPU during profiler execution.|
24+|torch.cuda.Event()|torch_npu.npu.Event()|Returns an event on a device.|
25+ 
26+When building a network or performing network migration, you need to create tensors of specified data types. Some of the tensors created on the Ascend AI Processor are as follows. For more interfaces, see *[TorchNPU Custom API Reference](https://gitcode.com/Ascend/op-plugin/blob/26.1.0/docs/en/custom_APIs/overview.md)*.
27+ 
28+**Table 2** Tensor creation interfaces
29+ 
30+|GPU Tensor|Interface Adapted to Ascend AI Processor|
31+|--|--|
32+|torch.tensor([1,2,3],dtype=torch.long,device="cuda")|torch.tensor([1,2,3],dtype=torch.long,device="npu")|
33+|torch.tensor([1,2,3],dtype=torch.int,device="cuda")|torch.tensor([1,2,3],dtype=torch.int,device="npu")|
34+|torch.tensor([1,2,3],dtype=torch.half,device="cuda")|torch.tensor([1,2,3],dtype=torch.half,device="npu")|
35+|torch.tensor([1,2,3],dtype=torch.float,device="cuda")|torch.tensor([1,2,3],dtype=torch.float,device="npu")|
36+|torch.tensor([1,2,3],dtype=torch.bool,device="cuda")|torch.tensor([1,2,3],dtype=torch.bool,device="npu")|
37+|torch.cuda.BoolTensor([1,2,3])|torch.npu.BoolTensor([1,2,3])|
38+|torch.cuda.FloatTensor([1,2,3])|torch.npu.FloatTensor([1,2,3])|
39+|torch.cuda.IntTensor([1,2,3])|torch.npu.IntTensor([1,2,3])|
40+|torch.cuda.LongTensor([1,2,3])|torch.npu.LongTensor([1,2,3])|
41+|torch.cuda.HalfTensor([1,2,3])|torch.npu.HalfTensor([1,2,3])|
@@ -0,0 +1,5 @@
1+# Figure Resources
2+ 
3+This folder stores figures referenced by the `PyTorch/docs` documents.
4+ 
5+When adding or moving figures, please synchronously check the Markdown links referencing those figures to avoid broken figures in the documents.
@@ -0,0 +1,68 @@
1+# Installation Guide
2+ 
3+## Supported Hardware and Operating Systems
4+ 
5+**Table 1** Supported hardware products
6+ 
7+|Product|Supported|
8+|--|:-:|
9+|<term>Ascend 950 products</term>|√|
10+|<term>Atlas A3 training products</term>|√|
11+|<term>Atlas A3 inference products</term>|x|
12+|<term>Atlas A2 training products</term>|√|
13+|<term>Atlas A2 inference products</term>|x|
14+|<term>Atlas 200I/500 A2 inference product</term>|x|
15+|<term>Atlas inference products</term>|x|
16+|<term>Atlas training products</term>|x|
17+ 
18+> [!NOTE]
19+>
20+> In the table above, "√" indicates supported, and "x" indicates not supported.
21+ 
22+- For the operating systems supported by each hardware product in physical machine deployment scenarios, see [Compatibility Query Assistant](https://www.hiascend.com/hardware/compatibility).
23+- For the operating systems supported by each hardware product in virtual machine and container deployment scenarios, refer to the "Operating System Compatibility Notes" section in *CANN Software Installation<!-- ](https://www.hiascend.com/document/detail/en/CANNCommunityEdition/910/softwareinst/instg/instg_0101.html?OS=openEuler&InstallType=netyum) -->*.
24+ 
25+## Version Description
26+ 
27+The version compatibility of different models may vary. For [version-evolving models](model_usage.md#version-evolving-models), it is recommended to use their latest version. For details, see [Table 2](#table-2-latest-version-compatibility-and-installation-guide).
28+ 
29+## Basic Environment Installation
30+ 
31+Download [the firmware and driver](https://www.hiascend.com/hardware/firmware-drivers) of the community or commercial version according to your system and hardware models.
32+ 
33+Example commands for installation:
34+ 
35+```shell
36+chmod +x Ascend-hdk-<chip_type>-npu-driver_<version>_linux-<arch>.run
37+chmod +x Ascend-hdk-<chip_type>-npu-firmware_<version>.run
38+./Ascend-hdk-<chip_type>-npu-driver_<version>_linux-<arch>.run --full --force
39+./Ascend-hdk-<chip_type>-npu-firmware_<version>.run --full
40+```
41+ 
42+[Table 2](<a id="table-2-latest-version-compatibility-and-installation-guide"></a>) lists installation guide for CANN, PyTorch, and TorchNPU. To view the mapping of PyTorch between Python and TorchNPU, see [PyTorch and Python Version Mapping](https://gitcode.com/Ascend/pytorch#pytorch%E4%B8%8Epython%E7%89%88%E6%9C%AC%E9%85%8D%E5%A5%97%E8%A1%A8) and [TorchNPU](https://gitcode.com/Ascend/pytorch#ascend-extension-for-pytorch%E7%89%88%E6%9C%AC%E9%85%8D%E5%A5%97%E8%A1%A8).
43+ 
44+<a id="table-2-latest-version-compatibility-and-installation-guide"></a>
45+ 
46+**Table 2** Latest version compatibility and installation guide
47+ 
48+ <table border="0">
49+ <tr>
50+ <th>Software</th>
51+ <th>Version</th>
52+ <th>Installation Guide</th>
53+ </tr>
54+ <tr>
55+ <td> CANN </td>
56+ <td> 9.1.0 </td>
57+ <td><a href="https://www.hiascend.com/en/cann/download">CANN Quick Installation</a> </td>
58+ </tr>
59+ <tr>
60+ <td> PyTorch </td>
61+ <td> 2.7.1 </td>
62+ <td rowspan="2"><a href="https://www.hiascend.com/en/developer/software/ai-frameworks/pytorch/download">TorchNPU Installation</a> </td>
63+ </tr>
64+ <tr>
65+ <td> TorchNPU </td>
66+ <td> 26.1.0 </td>
67+ </tr>
68+ </table>
@@ -0,0 +1,25 @@
1+# Introduction
2+ 
3+ModelZoo-PyTorch provides training references for conventional models adapted to Ascend devices, covering common AI tasks such as computer vision, natural language processing, speech, multi-modality, and recommendation.
4+ 
5+## Getting Started
6+ 
7+[Installation Guide](install_guide.md)
8+ 
9+ Introduces the installation procedure of the basic environment, including NPU driver and firmware, CANN, PyTorch, and the TorchNPU plugin.
10+ 
11+[Quick Start](quick_start.md)
12+ 
13+ Guides developers through environment setup, dataset preparation, pre-trained weight preparation, and training script examples based on ModelZoo for conventional models, making it suitable as a first-time reference.
14+ 
15+[Model Usage](model_usage.md)
16+ 
17+ Introduces models that evolve with version updates.
18+ 
19+[Model Migration and Tuning](migration_process.md)
20+ 
21+ Describes the migration process for conventional models, including pre-migration preparation, migration process, mixed precision adaptation, model training, model saving, and precision debugging.
22+ 
23+[Model Performance Debugging](performance_tuning/performance_overview.md)
24+ 
25+ Introduces performance metrics, performance analysis process, and common optimization methods for conventional models.
@@ -0,0 +1,124 @@
1+# Migration Process
2+ 
3+## What Is Model Migration
4+ 
5+Model migration refers to migrating a deep learning model originally running on a GPU or other hardware platform to an NPU, while ensuring the model runs with high performance within a reasonable accuracy error range.
6+ 
7+## Why Perform Model Migration
8+ 
9+When a model is migrated from other hardware platforms to an NPU, a series of adaptation operations from the bottom layer to the upper layer are involved due to differences in hardware architecture and libraries. Taking GPU as an example, the reasons why model migration to an NPU requires adaptation can be divided into three aspects:
10+ 
11+- Differences in hardware characteristics and performance features
12+ 
13+ Due to the different hardware characteristics and performance features of NPUs and GPUs, models may require further performance debugging and optimization on NPUs to fully leverage their potential.
14+ 
15+- Differences in computing architecture
16+ 
17+ GPUs use the Compute Unified Device Architecture (CUDA) parallel computing architecture, while NPUs use the Compute Architecture for Neural Networks (CANN) heterogeneous computing architecture.
18+ 
19+- Differences in deep learning frameworks
20+ 
21+ To support NPU hardware, the PyTorch framework needs to be adapted through [TorchNPU](https://www.hiascend.com/document/detail/en/Pytorch/2610/userguide/fastexperience/docs/en/quick_start/quick_start.md), including adapting tensor operations, automatic differentiation, and other functionalities for efficient execution on NPUs. In addition, [PyTorch](https://pytorch.org/tutorials/advanced/privateuseone.html) is continuously providing native support for NPUs to deliver a better model experience for users and minimize migration modifications.
22+ 
23+## How to Perform Model Migration
24+ 
25+For model migration guidance, see [Table 1](#table1).
26+ 
27+<a id="table1"></a>
28+ 
29+**Table 1** Model migration guidance
30+ 
31+<table>
32+ <thead>
33+ <tr>
34+ <th colspan="2" align="center">Category</th>
35+ <th align="center">Migration Guide</th>
36+ </tr>
37+ </thead>
38+ <tbody>
39+ <tr>
40+ <td rowspan="2">Conventional models</td>
41+ <td>Adapted models</td>
42+ <td>See the <a href="./model_usage.md#version-evolving-models">list of version-evolving models</a> and perform training and inference according to the corresponding model's README.</td>
43+ </tr>
44+ <tr>
45+ <td>Unadapted models</td>
46+ <td>See this document for migration and training.</td>
47+ </tr>
48+ </tbody>
49+</table>
50+ 
51+## Migration-Phase Tasks
52+ 
53+The chapters of this manual are designed based on the migration phases and their corresponding tasks, as shown in the table below.
54+ 
55+**Table 2** Migration-phase tasks
56+ 
57+<table>
58+ <thead align="left">
59+ <tr>
60+ <th>Migration Phase</th>
61+ <th>Task</th>
62+ <th>Task Description</th>
63+ </tr>
64+ </thead>
65+ <tbody>
66+ <tr>
67+ <td rowspan="2"><a href="pre-migration_prepare.md">Pre-migration preparation</a></td>
68+ <td><a href="pre-migration_prepare.md#model-selection">Model selection</a></td>
69+ <td>
70+ <ol>
71+ <li>Investigate business requirements and select a model from mainstream repositories.</li>
72+ <li>Ensure the selected model can run on a third-party platform (such as GPU).</li>
73+ <li>Clarify the hardware model, precision, and performance baseline of the model before migration. Obtain the performance baseline of the source model from authoritative websites or data platforms, or measure the performance baseline on a third-party platform.</li>
74+ </ol>
75+ </td>
76+ </tr>
77+ <tr>
78+ <td><a href="pre-migration_prepare.md#pre-migration-analysis">Pre-migration analysis</a></td>
79+ <td>
80+ <ol>
81+ <li>Use the PyTorch Analyse tool to collect the list of models/operators in the target network, identify third-party libraries and operator support status in the target network, and analyze the feasibility of model migration.</li>
82+ <ul>
83+ <li>If there are unsupported operators found on the platform during the migration support analysis, operator replacement, development, or adaptation is required.</li>
84+ <li>If model suites or third-party libraries need to be called, NPU support must be checked.</li>
85+ </ul>
86+ <li>Confirm whether there are any currently known unsupported scenarios.</li>
87+ </ol>
88+ </td>
89+ </tr>
90+ <tr>
91+ <td rowspan="5">Model migration and training</td>
92+ <td><a href="model_migration/mig_methods_comp.md">Model migration</a></td>
93+ <td>Follow the provided migration methods to replace GPU-to-NPU interfaces and adapt the NPU distributed framework.</td>
94+ </tr>
95+ <tr>
96+ <td><a href="mixed_precision_adaptation/adaptation_introduction.md">Mixed-precision adaptation</a></td>
97+ <td>Use a mix of single-precision (float32) and half-precision (float16) data types during training to improve training efficiency.</td>
98+ </tr>
99+ <tr>
100+ <td><a href="model_training/env_config.md">Model training</a></td>
101+ <td>
102+ <ol>
103+ <li>Configure training-related environment variables to ensure that model training can run properly on NPU. For details, see <a href="model_training/env_config.md">Environment Variable Configuration</a>.</li>
104+ <li>Select the appropriate operation based on the actual scenario to complete model script configuration and start training. For details, see <a href="model_training/training_execution.md">Executing Training</a>.</li>
105+ <li>Follow the provided debugging methods for common issues encountered during training to identify the location and cause of problems. For details, see <a href="model_training/model_debug.md">Model Debugging</a>.</li>
106+ </ol>
107+ </td>
108+ </tr>
109+ <tr>
110+ <td><a href="model_saving.md">Model saving</a></td>
111+ <td>Save the model for subsequent weight loading, resumable training resumption, or online inference.</td>
112+ </tr>
113+ <tr>
114+ <td><a href="accuracy_debugging/precision_tuning_process.md">Accuracy debugging</a></td>
115+ <td>
116+ <ol>
117+ <li>Analyze model accuracy issues during training and promptly address training instability problems.</li>
118+ <li>Analyze and evaluate model accuracy differences before and after migration in terms of loss/ppl and downstream evaluation task scores, and assess the accuracy deviation.</li>
119+ <li>Ensure that the model accuracy difference before and after migration is within an acceptable range and that there is no abnormal data overflow/underflow. If accuracy-related issues occur, use accuracy issue analysis tools for analysis.</li>
120+ </ol>
121+ </td>
122+ </tr>
123+ </tbody>
124+</table>
APyTorch/docs/en/mixed_precision_adaptation/README.md+8-0File content is under review, please try again later
@@ -0,0 +1,323 @@
1+# Adaptation Examples
2+ 
3+## Typical Scenario
4+ 
5+The typical scenario involves enabling mixed precision for general model training. The following example uses a simple custom model to illustrate how to adapt to NPU.
6+ 
7+### Importing the AMP Module
8+ 
9+Import the Automatic Mixed Precision (AMP) module before constructing the neural network.
10+ 
11+```python
12+# Import modules
13+import argparse
14+ 
15+import torch
16+import torch_npu
17+import torch.nn as nn
18+import torch.optim as optim
19+ 
20+from torch.utils.data import DataLoader
21+from torchvision import datasets, transforms
22+# Import AMP module
23+from torch_npu.npu import amp
24+```
25+ 
26+### Defining the Loss Scale
27+ 
28+After defining the model and optimizer, define `GradScaler` for AMP.
29+ 
30+For the definitions of `parse_args` and `ToyModel` in the following code snippet, refer to the end-to-end model script example at the end of this document.
31+ 
32+```python
33+args = parse_args()
34+transform = transforms.Compose([
35+ transforms.ToTensor(),
36+ transforms.Normalize((0.5,), (0.5,))
37+])
38+train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform) # Acquire the dataset
39+train_loader = DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True) # Define DataLoader
40+ 
41+device = torch.device("npu")
42+model = ToyModel().to(device) # Place the model on the specified NPU
43+criterion = nn.CrossEntropyLoss() # Define the loss function
44+optimizer = optim.Adam(model.parameters(), lr=args.learning_rate) # Define the optimizer
45+scaler = amp.GradScaler() # Define GradScaler after defining the model and optimizer
46+ 
47+```
48+ 
49+### Adapting AMP and Starting Training
50+ 
51+Add AMP adaptation code to the training code. Then, run the script for mixed-precision training.
52+ 
53+```python
54+for epoch in range(args.epochs):
55+ model.train()
56+ for inputs, labels in train_loader:
57+ inputs, labels = data_process(inputs, labels) # Data preprocessing: convert the dataset data into the required shape
58+ inputs, labels = inputs.to(device), labels.to(device) # Transfer data to NPU for processing
59+ 
60+ with amp.autocast(): # Set AMP
61+ outputs = model(inputs) # Forward computation
62+ loss = criterion(outputs, labels).to(device) # Loss function computation
63+ optimizer.zero_grad()
64+ # Perform loss scaling and parameter update before and after backward propagation
65+ scaler.scale(loss).backward() # Loss scaling and backward propagation
66+ scaler.step(optimizer) # Update parameters (automatic unscaling)
67+ scaler.update() # Update the loss_scaling coefficient based on the dynamic loss scale
68+```
69+ 
70+Execute the command to start training. For an end-to-end model script, see [this example](https://gitcode.com/ascend/ModelZoo-PyTorch/blob/master/PyTorch/contrib/others/ToyModel_for_PyTorch/train_1p_with_amp.py); and for a startup script example, see [this example](https://gitcode.com/ascend/ModelZoo-PyTorch/blob/master/PyTorch/contrib/others/ToyModel_for_PyTorch/test/run_1p_with_amp.sh).
71+ 
72+## Gradient Accumulation
73+ 
74+In gradient accumulation scenario, gradients are accumulated rather than cleared after gradients of each batch are computed. The parameters are updated and the gradients are cleared only after a certain number of accumulation steps. Gradient accumulation can achieve the effect of training with a larger batch size without significantly increasing memory consumption. The following example uses a simple custom model to introduce how to adapt to NPU.
75+ 
76+### Importing the AMP Module
77+ 
78+Import the AMP module before constructing the neural network.
79+ 
80+```python
81+# Import modules
82+import argparse
83+ 
84+import torch
85+import torch_npu
86+import torch.nn as nn
87+import torch.optim as optim
88+ 
89+from torch.utils.data import DataLoader
90+from torchvision import datasets, transforms
91+# Import the AMP module
92+from torch_npu.npu import amp
93+```
94+ 
95+### Defining the Loss Scale
96+ 
97+After defining the model and optimizer, define `GradScaler` for AMP.
98+ 
99+For the definitions of `parse_args` and `ToyModel` in the following code snippet, refer to the end-to-end model script example at the end of this document.
100+ 
101+```python
102+args = parse_args()
103+transform = transforms.Compose([
104+ transforms.ToTensor(),
105+ transforms.Normalize((0.5,), (0.5,))
106+])
107+train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform = transform) # Acquire the dataset
108+train_loader = DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True) # Define DataLoader
109+ 
110+device = torch.device("npu")
111+model = ToyModel().to(device) # Place the model on the specified NPU
112+criterion = nn.CrossEntropyLoss() # Define loss function
113+optimizer = optim.Adam(model.parameters(), lr=args.learning_rate) # Define optimizer
114+scaler = amp.GradScaler() # Define GradScaler after defining the model and optimizer
115+```
116+ 
117+### Adapting AMP and Starting Training
118+ 
119+Add AMP adaptation code to the training code. Then, run the script for mixed-precision training.
120+ 
121+```python
122+iters_to_accumulate = 8 # Set the number of steps for gradient accumulation before updating parameters and clearing gradients. Configure this based on the actual model being used.
123+for epoch in range(args.epochs):
124+ i = 0
125+ model.train()
126+ for inputs, labels in train_loader:
127+ inputs, labels = data_process(inputs, labels)
128+ inputs, labels = inputs.to(device), labels.to(device)
129+ 
130+ with amp.autocast(): # Set AMP
131+ outputs = model(inputs) # Forward computation
132+ loss = criterion(outputs, labels).to(device)
133+ loss = loss / iters_to_accumulate
134+ 
135+ # Perform loss scaling and parameter update before and after backward propagation
136+ scaler.scale(loss).backward() # Loss scaling and backward propagation
137+ if (i + 1) % iters_to_accumulate == 0: # Update parameters and clear gradients after reaching the set number of steps
138+ scaler.step(optimizer) # Update parameters (automatic unscaling)
139+ scaler.update() # Update the loss_scaling coefficient based on the dynamic loss scale
140+ optimizer.zero_grad() # Clear gradients
141+ i += 1 # Step count
142+```
143+ 
144+Execute the command to start training. For an end-to-end model script, see [this example](https://gitcode.com/ascend/ModelZoo-PyTorch/blob/master/PyTorch/contrib/others/ToyModel_for_PyTorch/train_with_accumulate_amp.py); for a startup script, see [this example](https://gitcode.com/ascend/ModelZoo-PyTorch/blob/master/PyTorch/contrib/others/ToyModel_for_PyTorch/test/run_with_accumulate_amp.sh).
145+ 
146+## Scenarios with Multiple Models, Loss Functions, and Optimizers
147+ 
148+In such scenarios, multiple models, loss functions, and optimizers coexist within a neural network. The following example uses a simple custom model to illustrate how to adapt to NPU.
149+ 
150+### Importing the AMP Module
151+ 
152+Import the AMP module and define two simple neural networks.
153+ 
154+```python
155+import argparse
156+ 
157+import torch
158+import torch_npu
159+import torch.nn as nn
160+import torch.optim as optim
161+ 
162+from torch.utils.data import DataLoader
163+from torchvision import datasets, transforms
164+from torch_npu.npu import amp
165+ 
166+# Define a simple neural network
167+class ToyModel1(nn.Module):
168+ def __init__(self):
169+ super(ToyModel1, self).__init__()
170+ self.layer1 = nn.Linear(10, 10)
171+ self.relu = nn.ReLU()
172+ self.layer2 = nn.Linear(10, 5)
173+ 
174+ def forward(self, x):
175+ return self.layer2(self.relu(self.layer1(x)))
176+ 
177+# Define a similar neural network with an additional linear layer
178+class ToyModel2(nn.Module):
179+ def __init__(self):
180+ super(ToyModel2, self).__init__()
181+ self.layer1 = nn.Linear(10, 10)
182+ self.relu1 = nn.ReLU()
183+ self.layer2 = nn.Linear(10, 10)
184+ self.relu2 = nn.ReLU()
185+ self.layer3 = nn.Linear(10, 5)
186+ 
187+ def forward(self, x):
188+ return self.layer3(self.relu2(self.layer2(self.relu1(self.layer1(x)))))
189+```
190+ 
191+### Defining the Loss Scale
192+ 
193+After defining the model and optimizer, define `GradScaler` for AMP.
194+ 
195+```python
196+args = parse_args()
197+transform = transforms.Compose([
198+ transforms.ToTensor(),
199+ transforms.Normalize((0.5,), (0.5,))
200+])
201+train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform = transform) # Acquire the dataset
202+train_dataloader = DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True) # Define DataLoader
203+ 
204+device = torch.device("npu")
205+model1 = ToyModel1().to(device) # Place the model on the specified NPU
206+model2 = ToyModel2().to(device) # Place the model on the specified NPU
207+criterion = nn.CrossEntropyLoss() # Define the loss function
208+optimizer1 = optim.Adam(model1.parameters(), lr=args.learning_rate) # Define the optimizer
209+optimizer2 = optim.Adam(model2.parameters(), lr=args.learning_rate) # Define the optimizer
210+ 
211+scaler = amp.GradScaler() # Define GradScaler after defining the model and optimizer
212+```
213+ 
214+### Adapting AMP and Starting Training
215+ 
216+Add AMP-related code to the training code to enable AMP, and perform computations for multiple loss functions and optimizers.
217+ 
218+```python
219+for epoch in range(args.epochs):
220+ model1.train()
221+ model2.train()
222+ for inputs, labels in train_dataloader:
223+ inputs, labels = data_process(inputs, labels)
224+ inputs, labels = inputs.to(device), labels.to(device)
225+ 
226+ with amp.autocast(): # Set AMP
227+ outputs1 = model1(inputs) # Forward computation
228+ outputs2 = model2(inputs) # Forward computation
229+ loss1 = criterion(outputs1, labels).to(device) # Loss function computation
230+ loss2 = criterion(outputs2, labels).to(device) # Loss function computation
231+ 
232+ optimizer1.zero_grad()
233+ optimizer2.zero_grad()
234+ 
235+ # Perform loss scaling and parameter update before and after backward propagation
236+ scaler.scale(loss1).backward(retain_graph=True) # Loss scaling and backward propagation
237+ scaler.scale(loss2).backward()
238+ scaler.step(optimizer1) # Update parameters (automatic unscaling)
239+ scaler.step(optimizer2) # Update parameters (automatic unscaling)
240+ scaler.update() # Update the loss_scaling coefficient based on the dynamic loss scale
241+```
242+ 
243+Use the execution command to start training. For an end-to-end model script, see [this example](https://gitcode.com/ascend/ModelZoo-PyTorch/blob/master/PyTorch/contrib/others/ToyModel_for_PyTorch/train_with_multi_amp.py); for a startup script, see [this example](https://gitcode.com/ascend/ModelZoo-PyTorch/blob/master/PyTorch/contrib/others/ToyModel_for_PyTorch/test/run_with_multi_amp.sh).
244+ 
245+## DDP Single-NPU Single-Process Scenario
246+ 
247+The native PyTorch framework's AMP supports three multi-device training scenarios. The NPU-adapted AMP currently only supports the DDP multi-device training in single-NPU single-process scenario. In addition to adding AMP-related modifications to the sample code, necessary changes must also be made to the sample code to enable multi-device training. The following example uses a simple custom model to illustrate how to adapt to NPU.
248+ 
249+### Importing the AMP Module
250+ 
251+Import the AMP module, and perform initialization for multi-device training.
252+ 
253+```python
254+import os
255+import argparse
256+import tempfile
257+ 
258+import torch
259+import torch_npu
260+import torch.distributed as dist
261+import torch.nn as nn
262+import torch.optim as optim
263+ 
264+from torch.utils.data import DataLoader
265+from torchvision import datasets, transforms
266+from torch.utils.data.distributed import DistributedSampler
267+from torch.nn.parallel import DistributedDataParallel as DDP
268+from torch_npu.npu import amp # Import the AMP module
269+```
270+ 
271+### Defining the Loss Scale
272+ 
273+Obtain the training dataset from torchvision, set training-related distributed hyperparameters, define the model, set `train_sampler`, define the optimizer, and define `GradScaler`.
274+ 
275+For the definitions of `parse_args` and `ToyModel` in the following code snippet, refer to the end-to-end model script example at the end of this document.
276+ 
277+```python
278+args = parse_args() # Obtain distributed hyperparameters
279+# Add distributed logic
280+local_rank = int(os.environ.get("LOCAL_RANK", 0))
281+world_size = int(os.environ.get("WORLD_SIZE", 1))
282+dist.init_process_group("hccl", rank=(args.node_rank)*(args.nproc_per_node) + local_rank, world_size=world_size) # Set the communication method to hccl
283+transform = transforms.Compose([
284+ transforms.ToTensor(),
285+ transforms.Normalize((0.5,), (0.5,))
286+])
287+torch_npu.npu.set_device(local_rank)
288+device = torch.device(f'npu:{local_rank}')
289+ 
290+model = ToyModel().to(device) # Place the model on the specified NPU
291+model = DDP(model, device_ids=[local_rank], find_unused_parameters=True) # Enable DDP mode
292+ 
293+ 
294+train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform = transform)
295+train_sampler = DistributedSampler(train_dataset, num_replicas=world_size, rank=local_rank)
296+train_loader = DataLoader(train_dataset, batch_size=args.batch_size, sampler=train_sampler) # Define DataLoader
297+ 
298+criterion = nn.CrossEntropyLoss()
299+optimizer = optim.Adam(model.parameters(), lr=args.learning_rate) # Define the optimizer
300+scaler = amp.GradScaler() # Define GradScaler after defining the model and optimizer
301+```
302+ 
303+### Adapting AMP and Starting Training
304+ 
305+Add AMP-related code to the training code to enable AMP.
306+ 
307+```python
308+for epoch in range(args.epochs):
309+ model.train()
310+ for inputs, labels in train_loader:
311+ inputs, labels = data_process(inputs, labels) # Data preprocessing: convert the dataset data into the required shape
312+ inputs, labels = inputs.to(device), labels.to(device)
313+ with amp.autocast(): # Set AMP
314+ outputs = model(inputs)
315+ loss = criterion(outputs, labels).to(device)
316+ optimizer.zero_grad()
317+ # Perform loss scaling and parameter update before and after backward propagation
318+ scaler.scale(loss).backward() # Loss scale and backward propagation
319+ scaler.step(optimizer) # Update parameters (automatic unscaling)
320+ scaler.update() # Update the loss_scaling coefficient based on dynamic loss scale
321+```
322+ 
323+Execute the command to launch multi-device training. For an end-to-end model script, see [this example](https://gitcode.com/ascend/ModelZoo-PyTorch/tree/master/PyTorch/contrib/others/ToyModel_for_PyTorch/train_multi_with_amp.py); and for a startup script, refer to [this example](https://gitcode.com/ascend/ModelZoo-PyTorch/tree/master/PyTorch/contrib/others/ToyModel_for_PyTorch/test/run_16p_with_amp.sh).
@@ -0,0 +1,45 @@
1+# Adaptation Introduction
2+ 
3+Mixed precision training involves using both single-precision (float32) and half-precision (float16) data types during training. With the same hyperparameters, it can achieve nearly the same accuracy as float32.
4+ 
5+Mixed precision adaptation supports two methods:
6+ 
7+- The built-in AMP module of the PyTorch framework
8+- The third-party APEX mixed precision module
9+ 
10+It is recommended to use the built-in AMP module of the PyTorch framework for mixed precision training. If you want to use the APEX module, see [APEX documents](https://gitcode.com/Ascend/apex).
11+ 
12+## Constraints
13+ 
14+The constraints on mixed precision adaptation are as follows:
15+ 
16+- Mixed precision adaptation should be performed after script migration is complete and before training starts.
17+- If you use <term>Atlas training products</term>, due to its architectural characteristics, you need to enable mixed precision after migration is complete and before training starts. If you use <term>Atlas A2 training products</term>/<term>Atlas A3 training products</term>/<term>Ascend 950 products</term>, enable mixed precision as needed.
18+- Enabling mixed precision may improve performance, but it does not take effect for all models. If performance does not improve, further performance tuning modifications are required.
19+- After enabling mixed precision training, changes in the numerical representation range and minimum spacing may cause a very small number of networks to experience precision degradation or even failure to converge. Refer to [Mixed Precision Issue Debugging](mixed_prec_debug.md) for resolution.
20+ 
21+## Interface Description
22+ 
23+AMP adaptation primarily includes the adaptation of the mixed precision [amp.autocast\(\)](https://docs.pytorch.org/docs/2.1/amp.html#torch.autocast) interface and the loss scaling [amp.GradScaler\(\)](https://docs.pytorch.org/docs/2.1/amp.html#torch.cuda.amp.GradScaler) interface.
24+ 
25+For the AMP module, after the training script is adapted, the following four AMP scenarios are supported on NPU. For specific scenario descriptions, click the corresponding link to view them on the PyTorch official website.
26+ 
27+- [Typical Scenario](https://docs.pytorch.org/docs/2.1/notes/amp_examples.html#typical-mixed-precision-training): A scenario where mixed precision is enabled for general model training.
28+- [Gradient Accumulation](https://docs.pytorch.org/docs/2.1/notes/amp_examples.html#working-with-scaled-gradients): A scenario where gradients are accumulated rather than cleared after each batch is computed, and parameters are updated and gradients are cleared only after a certain number of accumulations is reached.
29+- [Multiple Models, Loss Functions, and Optimizers](https://docs.pytorch.org/docs/2.1/notes/amp_examples.html#working-with-multiple-models-losses-and-optimizers): A scenario where multiple loss functions and optimizers exist simultaneously in a neural network.
30+- [DDP Single-NPU Single-Process Scenario](https://docs.pytorch.org/docs/2.1/notes/amp_examples.html#distributeddataparallel-one-gpu-per-process): A scenario in distributed training where one process runs on one NPU.
31+ 
32+This section first provides a description of the AMP adaptation interface (`amp.GradScaler()`), and subsequent chapters provide NPU adaptation code for AMP, to introduce AMP adaptation.
33+ 
34+For the `amp.GradScaler()` interface, native PyTorch uses dynamic loss scaling by default, where the loss scale value is dynamically adjusted based on training conditions. The `amp.GradScaler` interface adapted for NPU now includes a `dynamic` parameter. When `dynamic` is set to `False`, a fixed loss scale value is supported, and the loss scale value can be set via the `init_scale` parameter, as shown below:
35+ 
36+```python
37+scaler = amp.GradScaler(init_scale = 2.**10, dynamic = False)
38+```
39+ 
40+**Table 1** Parameter description
41+ 
42+|Parameter|Description|Value|
43+|--|--|--|
44+|dynamic|Whether AMP uses dynamic loss scaling.|True (default): Uses dynamic loss scaling; False: Uses static loss scale.|
45+|init_scale|Initial scale factor when using static loss scaling.|Available only when dynamic=False. Set it based on actual conditions.|
@@ -0,0 +1,72 @@
1+# Mixed Precision Issue Debugging
2+ 
3+## Problem Identification
4+ 
5+After mixed precision is enabled, changes in the numerical representation range and minimum spacing may cause a very small number of networks to experience accuracy degradation or even failure to converge, as shown in the following figures.
6+ 
7+**Figure 1** Normal loss
8+ 
9+<img src="../figures/mixed_prec_debug_fig_01.png" height="115.710" width="522.69">
10+ 
11+**Figure 2** Abnormal loss
12+ 
13+<img src="../figures/mixed_prec_debug_fig_02.png" height="118.37" width="522.69">
14+ 
15+In the above example, improper mixed precision configuration may cause gradient overflow, leading to abnormal loss.
16+ 
17+## Tuning Approach
18+ 
19+The following provides several solutions for precision tuning. If you encounter the preceding issue on <term>Atlas A2 training products</term>/<term>Atlas A3 training products</term>, you can fall back to full-precision computation to avoid this issue.
20+ 
21+1. Modify the mixed precision level.
22+ 
23+ You can try to have more operators use float32 computation to compensate for precision loss. The specific methods are as follows:
24+ 
25+ - Using the APEX module: If the original `opt_level` is `O2`, try changing it to `O1`. For detailed mode descriptions, see [APEX documents](https://gitcode.com/ascend/apex).
26+ - Using AMP: No modification is required, because AMP is equivalent to the O1 mode of APEX.
27+ 
28+2. Enable static loss scaling.
29+ 
30+ APEX and AMP use dynamic loss scaling by default. Some networks may be sensitive to frequently changing scale values, which can affect convergence. You can try switching to static loss scaling for training. The specific method is as follows:
31+ 
32+ - Using the APEX module: Pass `loss_scale` when calling `amp.initialize`, which can be set to values such as 128, 256, 512, 1024, or 2048. An example is as follows:
33+ 
34+ ```python
35+ model, optimizer = amp.initialize(model, optimizer, combine_grad=True, opt_level='O1', loss_scale=128.0)
36+ ```
37+ 
38+ - Using AMP: Enable static loss scaling by configuring `growth_factor=1.0`, `backoff_factor=1.0`, and setting `growth_interval` to a large value in the `amp.GradScaler` parameters. An example is as follows:
39+ 
40+ ```python
41+ scaler = amp.GradScaler(init_scale=2.**10, growth_factor=1.0, backoff_factor=1.0, growth_interval=100000, enabled=True)
42+ ```
43+ 
44+3. Perform gradient clipping.
45+ 
46+ The float16 computation precision is lower than float32, which may cause unstable gradient computation in some networks, leading to gradient explosion. You can try using gradient clipping, either by norm using `torch.nn.utils.clip_grad_norm_()` or by value using `torch.nn.utils.clip_grad_value_()`. The specific method is as follows:
47+ 
48+ - Using APEX module: After gradient computation is complete and the context manager exits, call the gradient clipping function.
49+ 
50+ ```python
51+ output = model(input)
52+ loss = criterion(output, target)
53+ with amp.scale_loss(loss, optimizer) as scaled_loss:
54+ scaled_loss.backward()
55+ torch.nn.utils.clip_grad_norm_(parameters=amp.master_params(optimizer), max_norm=10)
56+ optimizer.step()
57+ ```
58+ 
59+ - Using AMP: After gradient computation is complete and before the optimizer is updated, manually unscale the gradients and call the gradient clipping function.
60+ 
61+ ```python
62+ with autocast():
63+ output = model(input)
64+ loss = criterion(output, target)
65+ scaler.scale(loss).backward()
66+ scaler.unscale_(optimizer)
67+ torch.nn.utils.clip_grad_norm_(parameters=model.parameters(), max_norm=10)
68+ scaler.step(optimizer)
69+ scaler.update()
70+ ```
71+ 
72+ If precision improves, you can further tune the gradient clipping hyperparameters for optimization; if it does not improve, it is recommended to try other tuning methods.
APyTorch/docs/en/model_migration/README.md+9-0File content is under review, please try again later
@@ -0,0 +1,53 @@
1+# Automatic Migration
2+ 
3+## Introduction
4+ 
5+Automatic migration is simple to perform and requires minimal modifications. You only need to add `from torch_npu.contrib import transfer_to_npu` to the training script for script migration.
6+ 
7+## Constraints
8+ 
9+- Automatic migration currently does not support the `channel_last` feature. It is recommended to use `contiguous` instead.
10+ 
11+- If the backend used in the original script is NCCL, after `init_process_group` initializes the process group, the backend will be replaced with HCCL by the automatic migration tool. If the subsequent code logic includes a check on whether the backend is NCCL, such as `assert backend in ['gloo', 'nccl']` or if `backend == 'nccl'`, please manually change the `nccl` string to `hccl`.
12+ 
13+- Automatic migration leverages Python's dynamic features, but `torch.jit.script` does not support Python's dynamic syntax. Therefore, using the automatic migration feature will cause conflicts when your original training script contains `torch.jit.script`. Currently, the `torch.jit.script` feature is disabled during automatic migration. If `torch.jit.script` is required in your script, please refer to [Tool-based Migration](tool_migration.md) for migration.
14+ 
15+## How to Use
16+ 
17+1. Add the migration code `from torch_npu.contrib import transfer_to_npu` to the training script.
18+ 
19+ > [!NOTE]
20+ >
21+ > - The code `from torch_npu.contrib import transfer_to_npu` only needs to be added under the PyTorch framework.
22+ > - Automatic migration may have functional conflicts with the adapted suites. If a conflict occurs, please refer to [Tool-based Migration](tool_migration.md).
23+ 
24+ - For PyTorch 2.4.0 and earlier versions, add the following migration code:
25+ 
26+ ```python
27+ import torch
28+ import torch_npu
29+ ...
30+ from torch_npu.contrib import transfer_to_npu
31+ ```
32+ 
33+ - For PyTorch 2.5.1 and later versions, add the following migration code:
34+ 
35+ ```python
36+ import torch
37+ ...
38+ from torch_npu.contrib import transfer_to_npu
39+ ```
40+ 
41+ > [!NOTE]
42+ >
43+ > PyTorch 2.5.1 and later versions support automatic device plugin loading, allowing you to use NPU devices without executing `import torch_npu`. For specific usage and limitations, see [Autoloading Out-of-Tree Extension](https://docs.pytorch.org/tutorials/unstable/python_extension_autoload.html).
44+ 
45+2. Perform training by referring to [Model Training](../model_training/README.md). If training proceeds normally and iteration logs begin to print, training functionality migration is successful.
46+3. Save weights by referring to [Model Saving](../model_saving.md). If the weights are saved successfully, weight saving functionality migration is successful.
47+ 
48+## Precautions
49+ 
50+- If your model includes evaluation or online inference functionality, you can also import the automatic migration library code in the corresponding scripts and determine whether the migration is successful by comparing the evaluation/inference results and log outputs with those from GPU/CPU.
51+- If some CUDA API errors are reported during training, it may be caused by unsupported APIs (operator APIs or framework APIs). You can refer to the following solutions to resolve the issue.
52+ 
53+ Use the PyTorch Analyse tool to analyze the model script and obtain a list of APIs whose support status is uncertain. Then, go to the [Ascend Open-Source Community](https://gitcode.com/Ascend/pytorch) to raise an issue for assistance. For unsupported operators, refer to the "Custom Operator Adaptation<!-- ](https://www.hiascend.com/document/detail/en/Pytorch/2610/devguide/fwfeatures/docs/en/framework_feature_guide_pytorch/adaptation_overview_opplugin.md) -->" section in the *TorchNPU Framework Feature Guide* for adaptation.
@@ -0,0 +1,109 @@
1+# Manual Migration
2+ 
3+## Introduction
4+ 
5+Manual migration requires users to have a foundational understanding of AI model migration, including the similarities and differences in interface design between GPU and NPU, as well as various migration techniques. During the manual migration process, the migration methods used for each model may not be identical. The core points of manual migration are provided below.
6+ 
7+## Single-Device Migration
8+ 
9+1. Import NPU-related libraries.
10+ 
11+ ```python
12+ import torch
13+ import torch_npu
14+ ```
15+ 
16+2. Specify NPU as the training device. To specify the training device, you need to modify the model training script. There are two methods:
17+ - `to(device)` method: After defining the device, you can load the model or dataset onto GPU or NPU using `xx_.to(device)`, such as `model.to(device)`. This method allows you to specify the required training resources and is more flexible to use.
18+ 
19+ Before migration:
20+ 
21+ ```python
22+ device = torch.device('cuda:{}'.format(local_rank)) # local_rank is the current device number
23+ model.to(device)
24+ ```
25+ 
26+ After migration:
27+ 
28+ ```python
29+ device = torch.device('npu:{}'.format(local_rank))
30+ model.to(device)
31+ ```
32+ 
33+ - `set_device` method: Call the `set_device` interface to specify the training device. Note that this method does not automatically use NPU. You need to manually add `xx_.npu()` code where you want to use NPU to load models, datasets, etc., onto NPU, such as `model.npu()`.
34+ 
35+ Before migration:
36+ 
37+ ```python
38+ torch.cuda.set_device(local_rank)
39+ ```
40+ 
41+ After migration:
42+ 
43+ ```python
44+ torch_npu.npu.set_device(local_rank)
45+ ```
46+ 
47+3. Replace CUDA interfaces: Replace the CUDA interfaces in the training script with NPU interfaces, for example, interfaces for migrating models, loss functions, datasets, etc., to NPU. For common replaceable interfaces, see [Common PyTorch Interfaces to Be Replaced](../appendixes/pytorch_migrate_api.md). For more interfaces, see *[TorchNPU Custom API Reference](https://gitcode.com/Ascend/op-plugin/blob/26.1.0/docs/en/custom_APIs/menu_Pytorch_API.md)*.
48+ 
49+ 1. Replace CUDA interfaces with NPU interfaces.
50+ 
51+ Before migration:
52+ 
53+ ```python
54+ torch.cuda.is_available()
55+ ```
56+ 
57+ After migration:
58+ 
59+ ```python
60+ torch_npu.npu.is_available()
61+ ```
62+ 
63+ 2. Perform model migration.
64+ 
65+ Before migration:
66+ 
67+ ```python
68+ model.cuda(local_rank)
69+ ```
70+ 
71+ After migration:
72+ 
73+ ```python
74+ model.npu(local_rank)
75+ ```
76+ 
77+ 3. Perform dataset migration.
78+ 
79+ Before migration:
80+ 
81+ ```python
82+ images = images.cuda(local_rank, non_blocking=True)
83+ target = target.cuda(local_rank, non_blocking=True)
84+ ```
85+ 
86+ After migration:
87+ 
88+ ```python
89+ images = images.npu(local_rank, non_blocking=True)
90+ target = target.npu(local_rank, non_blocking=True)
91+ ```
92+ 
93+## Multi-Device Migration (Distributed Training)
94+ 
95+In addition to the three key modifications involved in single-device migration, in a distributed scenario, you also need to switch the communication method by directly modifying the value of `init_process_group`.
96+ 
97+Before modification, GPU uses the NCCL method:
98+ 
99+```python
100+import torch.distributed as dist
101+dist.init_process_group(backend='nccl',init_method="tcp://127.0.0.1:**", ... ,rank=args.rank) # ** is the port number. Fill in an available port based on the actual situation.
102+```
103+ 
104+After modification, NPU uses the HCCL method:
105+ 
106+```python
107+import torch.distributed as dist
108+dist.init_process_group(backend='hccl',init_method="tcp://127.0.0.1:**", ... ,rank=args.rank) # ** is the port number. Fill in an available port based on the actual situation.
109+```
@@ -0,0 +1,16 @@
1+# Migration Method Comparison
2+ 
3+The purpose of script migration is to migrate PyTorch training scripts to Ascend AI Processors, enabling models to be trained on NPUs.
4+ 
5+Three migration methods are currently supported: [Automatic Migration](auto_migration.md), [Tool-based Migration](tool_migration.md), and [Manual Migration](manual_migration.md). **It is recommended to use the automatic migration mode**.
6+ 
7+> [!CAUTION]
8+>
9+> Ensure that the script can run on GPU or CPU before migration.
10+ 
11+- **Automatic migration**: Import the script conversion library into the training script, then launch the script to perform training. During runtime, the training script automatically replaces CUDA interfaces in the script with NPU interfaces supported by Ascend AI Processors. The overall process involves conversion during training.
12+- Tool-based migration: Use the migration tool PyTorch GPU2Ascend to automatically replace CUDA interfaces in the training script with NPU interfaces supported by Ascend AI Processors, and generate a migration report (script conversion log, list of unsupported operators, and script modification records). During training, run the converted script. The overall process is to convert the script first, then perform training.
13+- Manual migration: Analyze the model, compare GPU and NPU interfaces, and manually modify the training script to support training on Ascend AI Processors. Key migration points are as follows:
14+ - Define NPU as the training device, and switch the interfaces adapted for GPU in the training script to those adapted for NPU;
15+ - For multi-device migration, change the communication method to HCCL supported by Ascend.
16+
@@ -0,0 +1,128 @@
1+# Tool-based Migration
2+ 
3+Tool-based migration supports migration using the command line.
4+ 
5+## Constraints
6+ 
7+> [!NOTE]
8+>
9+> - If your training script contains the `amp_C` module, which is not supported on the NPU platform, you need to manually delete it before training.
10+> - Due to platform differences between the converted script and the original script, the migrated script may throw exceptions during debugging and running due to operator differences or other reasons, causing the process to terminate. Such exceptions need to be further debugged and resolved according to the exception information.
11+ 
12+## How to Use
13+ 
14+The core steps for tool-based migration using the command line are as follows:
15+ 
16+1. Set up the environment.
17+ 1. Install the development suite Ascend-cann-toolkit by referring to *[CANN Quick Installation](https://www.hiascend.com/en/cann/download)*.
18+ 2. Install the following dependencies (root user is used as an example; the `--user` parameter needs to be added for non-root users).
19+ 
20+ ```shell
21+ pip3 install pandas # pandas version must be equal to or greater than 1.2.4
22+ pip3 install libcst # Python syntax tree parser, used to parse Python files
23+ pip3 install prettytable # Visualize data as charts
24+ pip3 install jedi # Used for cross-file parsing, recommended to install
25+ ```
26+ 
27+2. Go to the path where the migration tool is located.
28+ 
29+ ```shell
30+ cd Ascend-cann-toolkit_installation_directory/cann/tools/ms_fmk_transplt/
31+ ```
32+ 
33+3. Go to the path where the analysis and migration tool is located, and execute the script migration task.
34+ 
35+ ```shell
36+ ./pytorch_gpu2npu.sh -i Original_script_path -o Output_path_of_script_migration_result -v original_framework_version [-s] [distributed -m entry_file_of_training_script -t target_model_variable_name]
37+ ```
38+ 
39+ `distributed` and its parameters `-m` and `-t` are specified at the end of the statement.
40+ 
41+ Example:
42+ 
43+ ```shell
44+ # Single-device
45+ ./pytorch_gpu2npu.sh -i /home/train/ -o /home/out -v 2.1.0 [-s]
46+ # Distributed
47+ ./pytorch_gpu2npu.sh -i /home/train/ -o /home/out -v 2.1.0 [-s] distributed -m /home/train/train.py [-t model]
48+ ```
49+ 
50+ "\[\]" indicates optional parameters, which can be omitted in actual use.
51+ 
52+ **Table 1** Parameter description
53+ 
54+ |Parameter|Description|Example Value|
55+ |--|--|--|
56+ |-i<br>--input|&#8226; Path to the folder containing the original script files to be migrated.<br>&#8226; Mandatory.|/home/username/fmktransplt|
57+ |-o<br>--output|&#8226; Output path for the script migration result files.<br>&#8226; When `distributed` is not enabled, i.e., migrating a single-device script, the output directory is named `xxx_msft`; when `distributed` is enabled, i.e., migrating a multi-device script, the output directory is named `xxx_msft_multi`, where `xxx` is the name of the folder containing the original scripts.<br>&#8226; Mandatory.|/home/username/fmktransplt_output|
58+ |-v<br>--version|&#8226; PyTorch version of the scripts to be migrated.<br>&#8226; Mandatory.|&#8226; 2.1.0<br>&#8226; 2.6.0<br>&#8226; 2.7.1<br>&#8226; 2.8.0 |
59+ |-s<br>--specify-device|&#8226; Specifies a device via the environment variable `DEVICE_ID` as an advanced feature, but this may cause the distributed functionality in the original script to become invalid.<br>&#8226; Optional.|-|
60+ |distributed|&#8226; Migrates a GPU single-device script to an NPU multi-device script. This is only supported for scenarios where data is loaded using `torch.utils.data.DataLoader`. For details, refer to the "Migrating Training > Typical Cases > Loading Data Using torch.utils.data.DataLoader" section in the *CANN Analysis and Migration Tool User Guide*. The `-t`/`--target_model` parameter can only be specified when this parameter is set.<br>&#8226; `-m`, `--main`: Entry Python file for the training script. Mandatory.<br>&#8226; `-t`, `--target_model`: Name of the instantiated model variable in the script to be migrated. The default value is `model`. This parameter is optional. If the variable name is not `model`, this parameter must be configured. For example, for `my_model = Model()`, configure it as `-t my_model`.|-|
61+ |-h<br>--help|Displays help information.|-|
62+ 
63+## Precautions
64+ 
65+If the `distributed` parameter is enabled to migrate a GPU single-device script to an NPU multi-device script, perform the following operations to obtain the result files.
66+ 
67+> [!NOTE]
68+>
69+> After migrating a GPU single-device script to an NPU multi-device script, if the original model training command contains a parameter for specifying a device ID for single-device execution (such as `--gpu`), you need to delete this parameter to ensure that multi-device execution does not become invalid.
70+ 
71+1. Replace the training script statement.
72+ 
73+ Replace the `please input your shell script here` statement in the `run_distributed_npu.sh` file generated after executing the migration command with the model's original training shell script. For example, replace `please input your shell script here` with the model training command `bash model_train_script.sh --data_path data_path`.
74+ 
75+ The `run_distributed_npu.sh` file is as follows:
76+ 
77+ ```shell
78+ export MASTER_ADDR=127.0.0.1
79+ export MASTER_PORT=29688
80+ export HCCL_WHITELIST_DISABLE=1
81+
82+ NPUS=($(seq 0 7))
83+ export RANK_SIZE=${#NPUS[@]}
84+ rank=0
85+ for i in ${NPUS[@]}
86+ do
87+ export DEVICE_ID=${i}
88+ export RANK_ID=${rank}
89+ echo run process ${rank}
90+ please input your shell script here > output_npu_${i}.log 2>&1 &
91+ let rank++
92+ done
93+ ```
94+ 
95+ **Table 2** run_distributed_npu.sh parameter description
96+ 
97+ |Parameter|Description|
98+ |--|--|
99+ |MASTER_ADDR|Specifies the IP address of the training server|
100+ |MASTER_PORT|Specifies the port of the training server|
101+ |HCCL_WHITELIST_DISABLE|HCCL communication trustlist verification|
102+ |NPUS|Specifies running on specific NPUs|
103+ |RANK_SIZE|Specifies the number of devices to call|
104+ |DEVICE_ID|Specifies the device ID to call|
105+ |RANK_ID|Specifies the logical ID of the device to call|
106+ 
107+2. After replacement, go to the directory where the script is located and run the following command to generate a log file for the specified NPU.
108+ 
109+ ```shell
110+ bash run_distributed_npu.sh
111+ ```
112+ 
113+3. View the result files.
114+ 
115+ After the script migration is complete, go to the script migration result output path to view the result files. Taking the migration of a GPU single-device script to an NPU multi-device script as an example, the result files include the following:
116+ 
117+ ```shell
118+ ├── xxx_msft/xxx_msft_multi // Script migration result output directory
119+ │ ├── Generated script files // Consistent with the directory structure of the script files before migration
120+ │ ├── msFmkTranspltlog.txt // Script migration process log file. The log file size is limited to 1 MB. If this limit is exceeded, it will be split into multiple files for storage, with a maximum of 10 files.
121+ │ ├── cuda_op_list.csv //List of analyzed CUDA operators
122+ │ ├── unknown_api.csv //List of APIs with uncertain support status
123+ │ ├── unsupported_api.csv //List of unsupported APIs
124+ │ ├── change_list.csv // Change record
125+ │ ├── run_distributed_npu.sh // Multi-device startup shell script
126+ ```
127+ 
128+For more information about command-line tool-based migration, see *[CANN Analysis and Migration Tool User Guide](https://www.hiascend.com/document/detail/en/CANNCommunityEdition/910/devaids/migrationtools/msfmktransplt/README.md)*.
@@ -0,0 +1,78 @@
1+# Model Saving
2+ 
3+During training in PyTorch, `torch.save()` is typically used to save checkpoint files. Model files are saved in two formats depending on their subsequent use, as described below.
4+ 
5+## `.pth` or `.pt` File
6+ 
7+Files with `.pth` or `.pt` extensions are used for online inference. Only model parameters are saved, without the model structure, in order to reduce file size. They can be opened with visualization tools such as Netron, as shown in Figure 1.
8+ 
9+ **Figure 1** `.pth` file
10+ 
11+ <img src="./figures/save_model_fig_01.png" height="142.31" width="497.42">
12+ 
13+ Save and load the model via `state_dict`.
14+ 
15+ The following is a simple model. For an end-to-end example, see [train_1p.py](https://gitcode.com/ascend/ModelZoo-PyTorch/blob/master/PyTorch/contrib/others/ToyModel_for_PyTorch/train_1p.py#L75).
16+ 
17+ ```python
18+ # Create the save path
19+ save_pt_path = "state_dict_model.pt"
20+ # Save the model
21+ torch.save(model.state_dict(), save_pt_path) # model is the variable defined during previous training
22+ ```
23+ 
24+ Load the model for online inference. An example is as follows:
25+ 
26+ ```python
27+ # Model file save path
28+ save_pt_path = "state_dict_model.pt"
29+
30+ model = TheModelClass(*args, **kwargs) # Fill in the function and parameters based on the actual model definition
31+ # Take model = ToyModel() as an example
32+
33+ # Load the model
34+ model.load_state_dict(torch.load(save_pt_path))
35+ model.eval()
36+ ```
37+ 
38+ > [!NOTE]
39+ >
40+ > When saving as a `.pth` or `.pt` file, you must provide the model definition file; otherwise, the model cannot be deployed later.
41+ 
42+## `.pth.tar` File
43+ 
44+Files with the `.pth.tar` extension are typically used to save training checkpoints, which can be reloaded to resume training. The file content is generally saved in dictionary format, which may include the model's `state_dict`, the optimizer's `state_dict`, the stopping epoch, and the most recent training loss. For inference-only deployment, it is usually enough to save just the model's `state_dict` and load it together with the model definition for restoration.
45+ 
46+The following is a simple model. For an end-to-end example, see [train_1p.py](https://gitcode.com/ascend/ModelZoo-PyTorch/blob/master/PyTorch/contrib/others/ToyModel_for_PyTorch/train_1p.py#L67).
47+ 
48+ ```python
49+ checkpoint_path = "checkpoint.pth.tar"
50+ torch.save({
51+ 'epoch': epoch,
52+ 'loss': loss,
53+ 'state_dict': model.state_dict(),
54+ 'optimizer': optimizer.state_dict(),
55+ ...
56+ }, checkpoint_path)
57+ ```
58+ 
59+An example of loading a model for inference or resumable training is shown below:
60+ 
61+ ```python
62+ model = TheModelClass(*args, **kwargs) # Fill in the function and parameters according to the actual model definition
63+ optimizer = TheOptimizerClass(*args, **kwargs) # Fill in the function and parameters based on the actual optimizer
64+
65+ checkpoint = torch.load(checkpoint_path)
66+ model.load_state_dict(checkpoint['state_dict'])
67+ optimizer.load_state_dict(checkpoint['optimizer'])
68+ epoch = checkpoint['epoch']
69+ loss = checkpoint['loss']
70+
71+ model.eval()
72+ # - or -
73+ model.train()
74+ ```
75+ 
76+ > [!NOTICE]
77+ >
78+ > Typically, the same operator, for example, operators such as BatchNorm and Dropout, may behave differently in training mode and inference mode. Therefore, before running inference, you must call `model.eval()` to set the model to inference mode.
APyTorch/docs/en/model_training/README.md+7-0File content is under review, please try again later
@@ -0,0 +1,51 @@
1+# Environment Variable Configuration
2+ 
3+Before starting training, you need to configure the training-related environment variables to set up the PyTorch training environment on NPU. A shell script is generally used for configuration. The specific configuration steps and examples are as follows:
4+ 
5+1. <a id="custom-anchor"></a>Configure the shell script for environment variables. The default configuration example is shown below. You can add other environment variables as needed. For details, refer to [Environment Variable Reference](https://gitcode.com/Ascend/pytorch/blob/v2.7.1-26.1.0/docs/en/environment_variable_reference/env_variable_list.md).
6+ 
7+ ```shell
8+ #!/bin/bash
9+ CANN_INSTALL_PATH_CONF='/etc/Ascend/ascend_cann_install.info' # CANN configuration file path
10+
11+ if [ -f $CANN_INSTALL_PATH_CONF ]; then
12+ CANN_INSTALL_PATH=$(cat $CANN_INSTALL_PATH_CONF | grep Install_Path | cut -d "=" -f 2)
13+ else
14+ CANN_INSTALL_PATH="/usr/local/Ascend" # Actual CANN installation path
15+ fi
16+
17+ source ${CANN_INSTALL_PATH}/cann/set_env.sh
18+
19+ # Set the device-side log level to error
20+ msnpureport -g error -d 0
21+ msnpureport -g error -d 1
22+ msnpureport -g error -d 2
23+ msnpureport -g error -d 3
24+ msnpureport -g error -d 4
25+ msnpureport -g error -d 5
26+ msnpureport -g error -d 6
27+ msnpureport -g error -d 7
28+ # Disable device-side Event logging
29+ msnpureport -e disable
30+ # Output host logs to the serial port: 0-disable/1-enable
31+ export ASCEND_SLOG_PRINT_TO_STDOUT=0
32+ # Set the default log level: 0-debug/1-info/2-warning/3-error
33+ export ASCEND_GLOBAL_LOG_LEVEL=3
34+ # Set the Event logging enable flag: 0-disable/1-enable
35+ export ASCEND_GLOBAL_EVENT_ENABLE=0
36+ # Set whether to enable taskqueue: 0-disable/1-enable/2-taskqueue after two-level pipeline optimization
37+ export TASK_QUEUE_ENABLE=1
38+ # Set whether to enable PTCopy: 0-disable/1-enable
39+ export PTCOPY_ENABLE=1
40+ # Set whether to recompile in special scenarios, no modification required
41+ export DYNAMIC_OP="ADD#MUL"
42+ # Set HCCL whitelist: 1-disable/0-enable
43+ export HCCL_WHITELIST_DISABLE=1
44+ export HCCL_IF_IP=$(hostname -I |awk '{print $1}')
45+ ```
46+ 
47+2. Before starting training, execute the environment variable script configured in [1](#custom-anchor).
48+ 
49+ ```shell
50+ source env.sh # env.sh is the name of the environment variable script. Modify it according to the actual situation.
51+ ```
@@ -0,0 +1,141 @@
1+# Model Debugging
2+ 
3+If you encounter issues during training, use the following methods for debugging to identify the location and cause of the problematic code.
4+ 
5+## Print-based Locating
6+
7+Use `print` to determine the code location where the model issue occurs. Since the PyTorch framework is an asynchronous execution framework, direct printing may result in inaccurate locations, requiring the addition of stream synchronization logic to assist with print-based debugging.
8+ 
9+```python
10+print(torch.npu.synchronize(),"debug message")
11+ 
12+print(inputs.shape, inputs.dtype) # The parameters to print can be changed based on the actual situation
13+```
14+ 
15+> [!NOTE]
16+>
17+> This method is suitable for problem location scenarios and can be removed during formal training.
18+ 
19+## pdb Breakpoint Debugging
20+ 
21+Add a function at the location where a breakpoint needs to be set.
22+ 
23+- Method 1: Import the pdb module in the code and add the `set_trace` function at the location where a breakpoint needs to be set to trigger the debugger.
24+ 
25+ ```python
26+ import pdb
27+ pdb.set_trace()
28+ ```
29+ 
30+ The script will pause when it reaches `pdb.set_trace()`. You can proceed by entering commands in the command line. For example, entering `n` executes the next line of code, and entering `p {variable_name}` prints the current value of a variable. For more parameter descriptions, see [Common pdb Arguments](../appendixes/common_pdb_args.md).
31+ 
32+ The following figure shows the effect of setting pdb in the training loop and attempting to print the value of the variable `loss`.
33+ 
34+ <img src="../figures/model_debug_fig_01.png" height="62.51" width="469.49">
35+ 
36+- Method 2: Add the `breakpoint` function at the location where you want to set a breakpoint. The script will pause when it reaches this point.
37+ 
38+ ```python
39+ breakpoint()
40+ ```
41+ 
42+ The following image shows the effect of setting a breakpoint within the training loop.
43+ 
44+ <img src="../figures/model_debug_fig_02.png" height="35.91" width="469.49">
45+ 
46+## GDB Command-line Debugging
47+ 
48+The main functions of the GDB debugging tool include setting breakpoints in a program, monitoring variables, single-step execution, changing variable values at runtime, tracing paths, and switching threads. This method is primarily used for core dump scenarios. A core dump file is generated in the execution directory. Use GDB to debug this file and print the stack trace. The detailed steps are as follows:
49+ 
50+1. Install GDB by referring to the [official GDB documents](https://sourceware.org/gdb/).
51+2. Set up core dump file generation via `ulimit`.
52+ 
53+ ```shell
54+ ulimit -c # Check the current setting. 0 indicates that no core dump file will be generated, and the ulimit setting needs to be changed.
55+ ulimit -c unlimited # Setting to unlimited removes the size limit for core dump files. If the process crashes, a core dump file will be generated.
56+ ```
57+ 
58+3. Set the storage location and name of the core dump file.
59+ 
60+ ```shell
61+ # Temporarily modify the name of the generated core dump file. The variable placeholders can be configured as needed.
62+ sysctl -w kernel.core_pattern=core-%e.%p.%h.%t
63+ # Set the core dump generation directory. The variable placeholders and the generation directory can be configured as needed.
64+ echo "/pathtocore dump/core.%e.%p" >/proc/sys/kernel/core_pattern
65+ ```
66+ 
67+ The variables that can be used in the `core.pattern` template are shown in Table 1.
68+ 
69+ **Table 1** Variables available in the `core.pattern` template
70+ 
71+ |Name|Description|
72+ |--|--|
73+ |%%|A single % character|
74+ |%p|Process ID of the dumped processes|
75+ |%u|Real user ID of the dumped processes|
76+ |%g|Real group ID of the dumped processes|
77+ |%s|Signal that caused the core dump|
78+ |%t|Time of the core dump (seconds since January 1, 1970)|
79+ |%h|Host name|
80+ |%e|Program file name|
81+ 
82+4. Generate the core dump file.
83+ 
84+ Run the model script. If the model reports an error or the process crashes, a core dump file will be generated in the current directory.
85+ 
86+5. Debug the core dump file.
87+ 
88+ Execute the following command to enter GDB mode and debug the core dump file.
89+ 
90+ ```shell
91+ gdb python3 core*.* # Modify the core dump file name according to the actual situation
92+ ```
93+ 
94+ After executing the command, the GDB tool will print the code where the exception occurred, its function, file name, and line number to the screen, making it easier to locate the problem. A sample output is shown in the following figure.
95+ 
96+ <img src="../figures/model_debug_fig_03.png" height="185.1094" width="469.49">
97+ 
98+ Common debugging commands in GDB mode are shown in Table 2.
99+ 
100+ **Table 2** Common debugging commands in GDB mode
101+ 
102+ |Command|Description|
103+ |--|--|
104+ |l|List code|
105+ |break *num*|Set a breakpoint at a line, where *num* is the sample line number|
106+ |info break|View breakpoint information|
107+ |r|Run the program|
108+ |n|Execute a single command|
109+ |c|Continue execution|
110+ |p *paramname*|Print a variable|
111+ |bt|View the function stack|
112+ |finish|Exit the function|
113+ |q|Quit GDB|
114+ 
115+ For more debugging commands, refer to the [official documents](https://www.sourceware.org/gdb/documentation/).
116+ 
117+## Hook-based Locating
118+
119+This method is primarily used to locate errors in a specific module within the model, and is generally suitable for locating errors in forward and backward modules.
120+ 
121+Add the following code to the script to define the hook.
122+ 
123+```python
124+def hook_func(name, module):
125+ def hook_function(module, inputs, outputs):
126+ print(name)
127+ return hook_function
128+```
129+ 
130+Add the following hook code before the code executes model computation to print the module names during the model's forward and backward execution. After locating the specific issue, print all shapes, dtypes, and formats, and then use host logs to assist in troubleshooting.
131+ 
132+```python
133+for name, module in model.named_modules():
134+ if module is not None:
135+ module.register_forward_hook(hook_func('[forward]:' + name, module))
136+ module.register_backward_hook(hook_func('[backward]:' + name, module))
137+```
138+ 
139+The following figure shows the log output after adding the hook function. You can see that the name of each module in the model is printed. Users can also customize the content to be printed by modifying the `hook_func` function.
140+ 
141+![](../figures/model_debug_fig_04.png)
APyTorch/docs/en/performance_tuning/README.md+7-0File content is under review, please try again later
MPyTorch/docs/zh/introduction.md+2-2File content is under review, please try again later
MPyTorch/docs/zh/model_migration/manual_migration.md+1-1File content is under review, please try again later
MPyTorch/docs/zh/model_migration/tool_migration.md+1-1File content is under review, please try again later
MPyTorch/docs/zh/performance_tuning/performance_tuning_methods/scheduling_opt.md+1-1File content is under review, please try again later
MPyTorch/docs/zh/quick_start.md+1-3File content is under review, please try again later