Merged
docs:26.2.0英文更新翻译 #583
cai-weiwei1989Add on Oct 16
docs:26.2.0英文更新翻译 #583
Merged
Merged fromcai-weiwei1989/msprof126.2.0intoAscend/msprof26.2.0
Total: 59 files changed+2560-3805
| @@ -6,7 +6,7 @@ | |||
| 6 | [](docs/en/quick_start/msprof_quick_start.md) | 6 | [](docs/en/quick_start/msprof_quick_start.md) |
| 7 | [](https://deepwiki.com/Ascend/msprof) | 7 | [](https://deepwiki.com/Ascend/msprof) |
| 8 | [](https://zread.ai/Ascend/msprof) | 8 | [](https://zread.ai/Ascend/msprof) |
| 9 | - [](https://mindstudio-docs-master.readthedocs.io/zh-cn/latest/msprof) | 9 | + [](https://mindstudio-docs-master.readthedocs.io/zh-cn/latest/msprof/) |
| 10 | [](https://www.hiascend.com/en/developer/software/mindstudio) | 10 | [](https://www.hiascend.com/en/developer/software/mindstudio) |
| 11 | [](https://gitcode.com/Ascend/msprof/issues) | 11 | [](https://gitcode.com/Ascend/msprof/issues) |
| 12 | 12 | ||
| @@ -20,7 +20,7 @@ English | [简体中文](./README.md) | |||
| 20 | 20 | ||
| 21 | ## ℹ️ Overview | 21 | ## ℹ️ Overview |
| 22 | 22 | ||
| 23 | -MindStudio Profiler (msProf) is a performance analysis tool for AI training and inference scenarios. It supports the collection and parsing of software and hardware profile data from the CANN layer and the Ascend AI Processor NPU hardware layer, helping users identify performance issues during model training or inference. `msProf` also provides the foundational capability for other profiling collection interfaces, and many upper-layer performance collection and analysis capabilities rely on `msProf` for underlying data collection. | 23 | +MindStudio Profiler (msProf) is a performance analysis tool for AI training and inference scenarios. It supports the collection and parsing of software and hardware profile data from the CANN layer and the Ascend AI Processor NPU hardware layer, helping users identify performance issues during model training or inference. msProf also provides the foundational capability for other profiling collection interfaces, and many upper-layer performance collection and analysis capabilities rely on msProf for underlying data collection. For a complete overview of Ascend performance tuning tools, see [MindStudio Profiler Documentation Overview](https://mindstudio-profiler-docs.readthedocs.io/zh-cn/latest/). |
| 24 | 24 | ||
| 25 | <div align="center"> | 25 | <div align="center"> |
| 26 | <img src="./docs/en/figures/msprof.png" alt="Architecture diagram" width="700"> | 26 | <img src="./docs/en/figures/msprof.png" alt="Architecture diagram" width="700"> |
| @@ -30,8 +30,8 @@ MindStudio Profiler (msProf) is a performance analysis tool for AI training and | |||
| 30 | 30 | ||
| 31 | | Feature | Description | Documentation | Source Code Repository | | 31 | | Feature | Description | Documentation | Source Code Repository | |
| 32 | | --- | --- | :---: | --- | | 32 | | --- | --- | :---: | --- | |
| 33 | -| **Profile data collection** | Collects software and hardware profile data from the CANN platform and Ascend AI Processors using the `msProf` command. | [Profile Data Collection](https://www.hiascend.com/document/detail/en/CANNCommunityEdition/latest/devaids/Profiling/atlasprofiling_16_0010.html) | [msprof](https://gitcode.com/cann/runtime/tree/master/src/dfx/msprof) | | 33 | +| **Profile data collection** | Collects software and hardware profile data from the CANN platform and Ascend AI Processors using the `msprof` command. | [Profile Data Collection](https://gitcode.com/cann/oam-tools/blob/9.2.0/docs/en/profiling/README.md) | [msprof](https://gitcode.com/cann/runtime/tree/9.2.0/src/dfx/msprof) | |
| 34 | -| **Profile data parsing** | Parses the collected profile data using the `msProf` tool to generate readable analysis results. | [Profile Data Parsing](docs/en/user_guide/msprof_parsing_instruct.md) | [analysis](analysis) | | 34 | +| **Profile data parsing** | Parses the collected profile data using the msProf tool to generate readable analysis results. | [Profile Data Parsing](docs/en/user_guide/msprof_parsing_instruct.md) | [analysis](https://gitcode.com/Ascend/msprof/tree/26.2.0/analysis) | |
| 35 | 35 | ||
| 36 | ## 🚀 Quick Start | 36 | ## 🚀 Quick Start |
| 37 | 37 | ||
| @@ -50,9 +50,7 @@ msprof --output=./output --application="./run_standalone_train.sh" | |||
| 50 | 50 | ||
| 51 | ## 📦 Installation Guide | 51 | ## 📦 Installation Guide |
| 52 | 52 | ||
| 53 | -msProf is included in the CANN Toolkit development suite. You are advised to download and install the CANN package directly. For details, see [CANN Quick Installation](https://www.hiascend.com/en/cann/download). | 53 | +For the environment dependencies and installation method, see [msProf Installation Guide](docs/en/install_guide/msprof_install_guide.md). |
| 54 | - | ||
| 55 | -To install msProf through building from source code, see [msProf Installation Guide](docs/en/install_guide/msprof_install_guide.md). | ||
| 56 | 54 | ||
| 57 | ## 📘 User Guide | 55 | ## 📘 User Guide |
| 58 | 56 | ||
| @@ -60,11 +58,11 @@ For detailed usage instructions, see [msProf User Guide](docs/en/user_guide/mspr | |||
| 60 | 58 | ||
| 61 | ## 💡 Typical Cases | 59 | ## 💡 Typical Cases |
| 62 | 60 | ||
| 63 | -To understand and master the tool through typical problem scenarios, see [msProf Typical Cases](docs/en/best_practices/basic_cases.md). | 61 | +To understand and master the tool through typical problem scenarios, see [msProf Typical Cases](docs/en/best_practices/README.md). |
| 64 | 62 | ||
| 65 | -## ❓ FAQ | 63 | +## ❓ FAQs |
| 66 | 64 | ||
| 67 | -For common questions and solutions, see [msProf FAQ](docs/en/support/faq.md). | 65 | +For common questions and solutions, see [msProf FAQs](docs/en/support/faq.md). |
| 68 | 66 | ||
| 69 | ## 🌌 Smart Search | 67 | ## 🌌 Smart Search |
| 70 | 68 | ||
| @@ -91,7 +89,7 @@ We welcome everyone to contribute to the community. If you have any questions or | |||
| 91 | 89 | ||
| 92 | | Instant Messaging (WeChat Group) | Official News (Official Account) | In-Depth Support (Assistant / Forum) | | 90 | | Instant Messaging (WeChat Group) | Official News (Official Account) | In-Depth Support (Assistant / Forum) | |
| 93 | | :---: | :----: | :---- | | 91 | | :---: | :----: | :---- | |
| 94 | -| <img src="https://raw.gitcode.com/Ascend/docs/files/master/common/Writing_Template/figures/qr_code_wechat_work.png" width="120"><br><sub>*Scan to join the technical discussion group*</sub> | <img src="https://raw.gitcode.com/Ascend/docs/files/master/common/Writing_Template/figures/qr_code_wechat_official_account.png" width="120"><br><sub>*Scan to follow the official account*</sub> | Scan the QR code to join the group and follow the official account for the fastest way to connect with MindStudio users and developers:<br> **Ask questions:** Discuss technical issues with community members in real time<br>**Stay updated:** Get the latest version releases and feature update notifications firsthand<br> **Share experience:** Exchange best practices and practical insights with fellow developers <br> <br> **More support channels**:<br>👉 Ascend Assistant: [](https://gitcode.com/Ascend/msit/blob/master/docs/zh/figures/readme/xiaozhushou.png)<br> 👉 Ascend Forum: [](https://www.hiascend.com/forum/) | | 92 | +| <img src="https://raw.gitcode.com/Ascend/docs/files/master/common/Writing_Template/figures/qr_code_wechat_work.png" width="120"><br><sub>*Scan to join the technical discussion group*</sub> | <img src="https://raw.gitcode.com/Ascend/docs/files/master/common/Writing_Template/figures/qr_code_wechat_official_account.png" width="120"><br><sub>*Scan to follow the official account*</sub> | Scan the QR code to join the group and follow the official account for the fastest way to connect with MindStudio users and developers:<br> **Ask questions:** Discuss technical issues with community members in real time<br>**Stay updated:** Get the latest version releases and feature update notifications firsthand<br> **Share experience:** Exchange best practices and practical insights with fellow developers <br> <br> **More support channels**:<br>👉 Ascend Assistant: [](https://gitcode.com/Ascend/msit/blob/master/docs/zh/figures/readme/xiaozhushou.png)<br> 👉 Ascend Forum: [](https://www.hiascend.com/forum/) | |
| 95 | 93 | ||
| 96 | ## 🙏 Acknowledgments | 94 | ## 🙏 Acknowledgments |
| 97 | 95 | ||
| @@ -0,0 +1,33 @@ | |||
| 1 | +# msProf Typical Cases | ||
| 2 | + | ||
| 3 | +This chapter provides performance tuning cases for typical performance tuning scenarios, including the following cases: | ||
| 4 | + | ||
| 5 | +**Basic Cases** | ||
| 6 | + | ||
| 7 | +- [ResNet50 Inference Model Performance Analysis](basic_cases.md) | ||
| 8 | + | ||
| 9 | +**Host Side** | ||
| 10 | + | ||
| 11 | +- Model Code | ||
| 12 | + - [Optimizing Operators with Long Execution Time](code_high_latency_function.md) | ||
| 13 | + - [Dispatch Performance Below Expectations](dispatch_small_batch_performance.md) | ||
| 14 | + - [High Latency in Operator Compilation](operator_compilation_latency.md) | ||
| 15 | + - [Frequent Calls to Synchronous APIs](sync_api_frequent_call.md) | ||
| 16 | +- System scheduling | ||
| 17 | + - [CPU Cache Miss Resource Contention and Constraints](cpu_cache_miss_conflict.md) | ||
| 18 | + - [Frequent CPU Thread Switching](cpu_thread_frequent_switching.md) | ||
| 19 | + - [GIL Contention Analysis](gil_lock_preemption.md) | ||
| 20 | + - [IRQ Interruption Analysis](irq_interruption.md) | ||
| 21 | + - [Frequent Kernel Process Switching](kernel_thread_switching.md) | ||
| 22 | + - [Pthread Lock Wait](pthread_lock_wait.md) | ||
| 23 | + - [High Python GC Overhead](python_gc_high_latency.md) | ||
| 24 | + - [High-Latency System Calls](syscall_high_latency.md) | ||
| 25 | + | ||
| 26 | +**Device side** | ||
| 27 | + | ||
| 28 | +- NPU communication | ||
| 29 | + - [Performance Degradation Caused by Communication Address Misalignment](communication_address_misalignment.md) | ||
| 30 | + | ||
| 31 | +- Memory | ||
| 32 | + - [Memory Fragmentation](memory_fragmentation.md) | ||
| 33 | + - [Memory Leak](memory_leak.md) | ||
| @@ -1,278 +0,0 @@ | |||
| 1 | -# Troubleshooting Guide: Asynchronous Scheduling Does Not Take Effect | ||
| 2 | - | ||
| 3 | -## Scenario Description | ||
| 4 | - | ||
| 5 | -Asynchronous scheduling (also known as asynchronous dual dispatch) aims to maximize the overlap of CPU-side scheduling, host-side task dispatch, NPU-side model execution, and communication during model inference serving, thereby reducing synchronous waits and scheduling gaps. This capability typically requires the environment variables, pipeline optimization, startup parameters, hardware and software versions, and communication configuration to satisfy the required conditions. If the configuration is incomplete or there are conflicts, the service may start normally, but asynchronous scheduling may not be enabled. As a result, there is no significant improvement in throughput, decode latency may not decrease, or CPU/NPU pipeline stages may fail to overlap. | ||
| 6 | - | ||
| 7 | -Using a case where asynchronous scheduling does not take effect, this document describes how to use `msServiceProfiler` to collect `BatchSchedule`, `ModelExecute`, and `Communication` data, determine whether asynchronous scheduling takes effect, and troubleshoot issues related to environment variables, pipeline optimization, startup parameters, compatibility, and configuration conflicts. | ||
| 8 | - | ||
| 9 | -## Symptoms | ||
| 10 | - | ||
| 11 | -**Typical Symptoms** | ||
| 12 | - | ||
| 13 | -- After environment variables related to asynchronous scheduling are set, there is no significant improvement in throughput, Time to First Token, or decode latency. | ||
| 14 | -- In the timeline, `BatchSchedule`, host-side dispatch, and `ModelExecute` still appear strictly serial, with no overlap between scheduling and execution. | ||
| 15 | -- The CPU-side scheduling thread waits for NPU execution to complete before submitting the next round of tasks, resulting in obvious pipeline gaps. | ||
| 16 | -- `Decode_Generate_Speed_Latency_curve` does not decrease, and P90/P99 values of `Request_Latency_curve` remain high. | ||
| 17 | -- In single-node prefill/decode (PD) disaggregation or multi-card scenarios, communication waits are not effectively overlapped, and communication duration in the `Communication` domain remains exposed on the critical path. | ||
| 18 | -- The service startup logs do not show that asynchronous scheduling has been enabled, or that the startup parameters or environment variables have been recognized by the framework. | ||
| 19 | - | ||
| 20 | -**Impact** | ||
| 21 | - | ||
| 22 | -| Item | Symptom | | ||
| 23 | -| --- | --- | | ||
| 24 | -| Throughput | CPU-side scheduling and NPU execution cannot overlap, resulting in limited improvement in tokens/s. | | ||
| 25 | -| Decode latency | The decode stage remains affected by synchronous dispatch and communication waits. | | ||
| 26 | -| End-to-end latency | Request latency P90/P99 is difficult to reduce. | | ||
| 27 | -| Resource utilization | Gaps exist between NPU executions, resulting in discontinuous CPU/NPU pipelines. | | ||
| 28 | -| PD disaggregation performance | Insufficient overlap between KV cache transfer and compute-communication fusion increases cross-stage waits. | | ||
| 29 | - | ||
| 30 | -## Data Collection | ||
| 31 | - | ||
| 32 | -### Function Description | ||
| 33 | - | ||
| 34 | -Uses `msServiceProfiler` to collect data for the `BatchSchedule`, `ModelExecute`, `Communication`, and `Request` domains. It also uses the timeline, `span_info`, `batch.csv`, `forward.csv`, `pd_split_communication.csv`, and visualization curves to help determine whether asynchronous scheduling takes effect. | ||
| 35 | - | ||
| 36 | -### Precautions | ||
| 37 | - | ||
| 38 | -- Before collection, record the service startup command, environment variables, MindIE version, CANN version, hardware model, and deployment configuration. | ||
| 39 | -- You are advised to collect two sets of data, one with asynchronous scheduling disabled and the other with this feature enabled, and then compare them under the same stress testing conditions. | ||
| 40 | -- If further analysis of host-to-device task dispatch duration is required, ACL task duration collection can be enabled, but the additional overhead should be evaluated. | ||
| 41 | -- In multi-device or PD disaggregation scenarios, the `Communication` domain must also be collected. Otherwise, it cannot be determined whether communication waits are effectively overlapped with other operations through asynchronous scheduling. | ||
| 42 | - | ||
| 43 | -### Configuration Example | ||
| 44 | - | ||
| 45 | -Create `ms_service_profiler_config.json` to collect scheduling, execution, communication, and request data. | ||
| 46 | - | ||
| 47 | -```json | ||
| 48 | -{ | ||
| 49 | - "enable": 1, | ||
| 50 | - "prof_dir": "${HOME}/.ms_server_profiler", | ||
| 51 | - "profiler_level": "INFO", | ||
| 52 | - "domain": "Request;BatchSchedule;ModelExecute;Communication", | ||
| 53 | - "acl_task_time": 1, | ||
| 54 | - "acl_prof_task_time_level": "L0" | ||
| 55 | -} | ||
| 56 | -``` | ||
| 57 | - | ||
| 58 | -Set the collection configuration path. | ||
| 59 | - | ||
| 60 | -```bash | ||
| 61 | -export SERVICE_PROF_CONFIG_PATH=/path/to/ms_service_profiler_config.json | ||
| 62 | -``` | ||
| 63 | - | ||
| 64 | -Export span data during parsing to facilitate observation of whether `BatchSchedule` and `forward` overlap. | ||
| 65 | - | ||
| 66 | -```bash | ||
| 67 | -ms_service_profiler_parse --input-path ${PROF_DIR} --output-path ${OUTPUT_DIR} --span | ||
| 68 | -``` | ||
| 69 | - | ||
| 70 | -## Determining Whether Asynchronous Scheduling Takes Effect | ||
| 71 | - | ||
| 72 | -### Characteristics When Asynchronous Scheduling Takes Effect | ||
| 73 | - | ||
| 74 | -When asynchronous scheduling takes effect, you can typically observe the following results: | ||
| 75 | - | ||
| 76 | -- In the timeline, the next `BatchSchedule` or host-side dispatch overlaps the previous `ModelExecute`. | ||
| 77 | -- The CPU-side scheduling span no longer waits for NPU-side `forward` execution to complete before starting the next round. | ||
| 78 | -- Decode execution becomes more continuous, and the intervals between adjacent decode executions in `forward.csv` are shortened. | ||
| 79 | -- Communication duration in the `Communication` domain is partially overlapped and is no longer fully exposed on the critical path. | ||
| 80 | -- Observable improvements are seen in `Decode_Generate_Speed_Latency_curve`, `Request_Latency_curve`, or throughput metrics. | ||
| 81 | - | ||
| 82 | -### Characteristics When Asynchronous Scheduling Does Not Take Effect | ||
| 83 | - | ||
| 84 | -If asynchronous scheduling does not take effect, the following symptoms are typically observed: | ||
| 85 | - | ||
| 86 | -- In `BatchSchedule.csv`, scheduling always starts after the previous `forward` execution ends. | ||
| 87 | -- Obvious gaps exist between adjacent executions in `forward.csv`. | ||
| 88 | -- Communication duration and ModelExecute are arranged serially and do not overlap with the computation stage. | ||
| 89 | -- The `Batch_Size_curve` is similar with and without asynchronous scheduling, but throughput and decode latency remain almost unchanged. | ||
| 90 | -- The service logs do not show that asynchronous scheduling or the pipeline queue has been enabled, or that the relevant startup parameters have taken effect. | ||
| 91 | - | ||
| 92 | -## Troubleshooting Methods | ||
| 93 | - | ||
| 94 | -1. Check that environment variables are set before the service starts. | ||
| 95 | - - Verify that `MINDIE_ASYNC_SCHEDULING_ENABLE=1` is configured in the startup script. | ||
| 96 | - - Verify that the variables are set before the service process starts, rather than being set temporarily in an interactive terminal after startup. | ||
| 97 | - - In container deployments, verify that the environment variables are passed into the container and can be read by the service process. | ||
| 98 | - | ||
| 99 | -2. Check that pipeline optimization is also enabled. | ||
| 100 | - - Asynchronous scheduling typically requires `TASK_QUEUE_ENABLE=2` to be configured as well. | ||
| 101 | - - If only asynchronous scheduling is enabled without pipeline optimization, CPU/NPU overlap may not reach the expected level. | ||
| 102 | - - Use the timeline to observe whether host-side dispatch and device-side execution form a continuous pipeline. | ||
| 103 | - | ||
| 104 | -3. Check that startup parameters are explicitly enabled. | ||
| 105 | - - Some frameworks rely not only on environment variables but also require asynchronous scheduling parameters in the startup command. | ||
| 106 | - - In vLLM-Ascend scenarios, confirm whether `--async-scheduling` is passed. | ||
| 107 | - - If the framework startup script encapsulates parameters, check the actual startup command that takes effect. | ||
| 108 | - | ||
| 109 | -4. Check hardware and software versions. | ||
| 110 | - - Verify that the hardware model supports the asynchronous scheduling feature, such as whether the target Ascend device model is within the supported range. | ||
| 111 | - - Verify that the CANN, MindIE, and inference framework versions support the current asynchronous scheduling capability. | ||
| 112 | - - For earlier versions with known compatibility issues, you are advised to upgrade the version and verify that asynchronous scheduling takes effect. | ||
| 113 | - | ||
| 114 | -## Root Cause Analysis and Solutions | ||
| 115 | - | ||
| 116 | -### Environment Variables Not Correctly Configured | ||
| 117 | - | ||
| 118 | -**Cause** | ||
| 119 | - | ||
| 120 | -If the core switch for asynchronous scheduling is not set, is set to an incorrect value, is set after the service starts, or is not inherited by the container or startup script, asynchronous scheduling will not take effect. | ||
| 121 | - | ||
| 122 | -**Solution** | ||
| 123 | - | ||
| 124 | -Configure the environment variables before the service starts. | ||
| 125 | - | ||
| 126 | -```bash | ||
| 127 | -export MINDIE_ASYNC_SCHEDULING_ENABLE=1 | ||
| 128 | -``` | ||
| 129 | - | ||
| 130 | -In container deployments, add the variables to the container startup command or service startup script, and confirm in the service logs that the variables have been read. When using `systemd`, Kubernetes, or platform-based orchestration, check the environment variables that reach the service process, not just those in the current shell. | ||
| 131 | - | ||
| 132 | -### Pipeline Optimization Not Enabled | ||
| 133 | - | ||
| 134 | -**Cause** | ||
| 135 | - | ||
| 136 | -Asynchronous scheduling needs to work together with the pipeline queue capability to overlap task dispatch, scheduling, and execution. If `TASK_QUEUE_ENABLE` is not set to the recommended value, task submission may still be synchronous and serial. | ||
| 137 | - | ||
| 138 | -**Solution** | ||
| 139 | - | ||
| 140 | -Enable pipeline optimization before startup. | ||
| 141 | - | ||
| 142 | -```bash | ||
| 143 | -export TASK_QUEUE_ENABLE=2 | ||
| 144 | -``` | ||
| 145 | - | ||
| 146 | -Recollect the timeline after enabling pipeline optimization. If `BatchSchedule` and `ModelExecute` are still completely serial, continue to check the startup parameters, versions, and conflicting configurations. | ||
| 147 | - | ||
| 148 | -### Startup Parameters Not Enabled | ||
| 149 | - | ||
| 150 | -**Cause** | ||
| 151 | - | ||
| 152 | -Some frameworks require asynchronous scheduling to be explicitly enabled in the startup command. When only environment variables are configured, the framework layer may not enter the asynchronous scheduling branch. | ||
| 153 | - | ||
| 154 | -**Solution** | ||
| 155 | - | ||
| 156 | -Check the service startup command. For frameworks that require explicit parameters, add the asynchronous scheduling parameter when starting the service. | ||
| 157 | - | ||
| 158 | -```bash | ||
| 159 | ---async-scheduling | ||
| 160 | -``` | ||
| 161 | - | ||
| 162 | -If a script wraps the startup command, verify that the parameter is not overwritten or filtered out by the configuration template. You are advised to print the final startup parameters in the logs for future review. | ||
| 163 | - | ||
| 164 | -### Hardware or Software Version Incompatibility | ||
| 165 | - | ||
| 166 | -**Cause** | ||
| 167 | - | ||
| 168 | -The asynchronous scheduling capability depends on hardware, CANN, MindIE, and framework versions. Earlier versions may not support this capability or may have compatibility issues related to asynchronous scheduling, communication, or memory management. | ||
| 169 | - | ||
| 170 | -**Solution** | ||
| 171 | - | ||
| 172 | -- Verify that the hardware model supports asynchronous scheduling, such as whether the target environment uses an Ascend device model that supports this feature. | ||
| 173 | -- Verify that the CANN version, MindIE version, and inference framework version meet the requirements for asynchronous scheduling. | ||
| 174 | -- Upgrade to a stable version that supports asynchronous scheduling and verify that asynchronous scheduling takes effect. | ||
| 175 | -- Collect `msServiceProfiler` data before and after the upgrade, and compare decode latency and timeline overlap under the same stress testing conditions. | ||
| 176 | - | ||
| 177 | -### Communication or Memory Configuration Conflicts | ||
| 178 | - | ||
| 179 | -**Cause** | ||
| 180 | - | ||
| 181 | -Some communication- or memory-related environment variables can change the execution graph, communication path, or task submission method, which may prevent asynchronous scheduling from being enabled or cause its benefits to be offset by synchronous communication waits. | ||
| 182 | - | ||
| 183 | -**Solution** | ||
| 184 | - | ||
| 185 | -Check whether the following configurations conflict with the current asynchronous scheduling scenario. | ||
| 186 | - | ||
| 187 | -```bash | ||
| 188 | -unset HCCL_OP_EXPANSION_MODE | ||
| 189 | -unset ATB_LLM_HCCL_ENABLE | ||
| 190 | -``` | ||
| 191 | - | ||
| 192 | -In single-node PD disaggregation scenarios, you are advised to enable compute-communication fusion. | ||
| 193 | - | ||
| 194 | -```bash | ||
| 195 | -export ATB_LLM_LCOC_ENABLE=1 | ||
| 196 | -``` | ||
| 197 | - | ||
| 198 | -In multi-device scenarios, ensure that the HCCL/LCCL configuration is correct to prevent issues such as communication initialization, rank configuration, or network problems that may prevent the benefits of asynchronous scheduling from being realized. | ||
| 199 | - | ||
| 200 | -### Lack of Collaborative Features Such as Prefix Cache and LCCL | ||
| 201 | - | ||
| 202 | -**Cause** | ||
| 203 | - | ||
| 204 | -Asynchronous scheduling can only reduce the wait time between scheduling and execution. If prefill computation is repeated, KV cache transfer is slow, or the communication library is not optimized, overall performance may still show little improvement. | ||
| 205 | - | ||
| 206 | -**Solution** | ||
| 207 | - | ||
| 208 | -- In single-node PD disaggregation scenarios, use prefix cache to reduce repeated prefill computation. | ||
| 209 | -- Enable the LCCL communication library to reduce KV cache transfer and decode communication overhead. | ||
| 210 | -- Collect data from the `Communication` domain to determine whether communication duration is hidden by the computation stage. | ||
| 211 | -- If communication is still exposed on the critical path, prioritize optimizing the communication configuration and then evaluate the benefits of asynchronous scheduling. | ||
| 212 | - | ||
| 213 | -## Instrumentation Recommendations | ||
| 214 | - | ||
| 215 | -If the framework allows custom instrumentation, add spans and events at key stages of asynchronous scheduling to help verify whether asynchronous task submission and completion are occurring. | ||
| 216 | - | ||
| 217 | -```C++ | ||
| 218 | -auto submitSpan = PROF(INFO, SpanStart("AsyncSubmit")); | ||
| 219 | - | ||
| 220 | -// Asynchronously submit the next round of tasks on the CPU side | ||
| 221 | - | ||
| 222 | -PROF(submitSpan.SpanEnd()); | ||
| 223 | - | ||
| 224 | -PROF(INFO, Event("AsyncTaskQueued")); | ||
| 225 | - | ||
| 226 | -auto waitSpan = PROF(INFO, SpanStart("AsyncWait")); | ||
| 227 | - | ||
| 228 | -// Wait for asynchronous tasks to complete or results to be collected | ||
| 229 | - | ||
| 230 | -PROF(waitSpan.SpanEnd()); | ||
| 231 | -``` | ||
| 232 | - | ||
| 233 | -Collect queue depth and asynchronous dispatch counts. | ||
| 234 | - | ||
| 235 | -```C++ | ||
| 236 | -PROF(INFO, Metric("asyncQueueDepth", asyncQueueDepth).MetricScope("scheduler", rankId).Launch()); | ||
| 237 | -PROF(INFO, MetricInc("asyncDispatchCount", 1).MetricScope("rank", rankId).Launch()); | ||
| 238 | -``` | ||
| 239 | - | ||
| 240 | -If `asyncDispatchCount` remains 0 for an extended period, the asynchronous branch is not being entered. If `asyncQueueDepth` remains 0, tasks are not forming an effective pipeline. | ||
| 241 | - | ||
| 242 | -## Optimization Validation | ||
| 243 | - | ||
| 244 | -You are advised to validate in the following order, changing only one variable at a time. | ||
| 245 | - | ||
| 246 | -| Step | Validation Content | Metrics to Observe | | ||
| 247 | -| --- | --- | --- | | ||
| 248 | -| Baseline collection | Disable asynchronous scheduling and collect synchronous execution data. | Timeline, `BatchSchedule.csv`, `forward.csv` | | ||
| 249 | -| Enable asynchronous variable | Configure `MINDIE_ASYNC_SCHEDULING_ENABLE=1`. | Whether the asynchronous branch is entered, decode latency | | ||
| 250 | -| Enable pipeline optimization | Configure `TASK_QUEUE_ENABLE=2`. | Whether `BatchSchedule` and `ModelExecute` overlap | | ||
| 251 | -| Add startup parameters | Configure `--async-scheduling`. | Framework logs, timeline overlap | | ||
| 252 | -| Eliminate conflicting configurations | Remove conflicting communication or memory variables. | Communication duration, request latency | | ||
| 253 | -| Collaborative optimization | Enable LCCL, prefix cache, or compute-communication fusion. | Decode latency, throughput, PD communication duration | | ||
| 254 | - | ||
| 255 | -When the optimization is effective, the following results are typically observed: | ||
| 256 | - | ||
| 257 | -- `BatchSchedule` and `ModelExecute` overlap in the timeline. | ||
| 258 | -- The intervals between adjacent decode executions in `forward.csv` are shortened. | ||
| 259 | -- Duration in the `Communication` domain is partially overlapped. | ||
| 260 | -- `Decode_Generate_Speed_Latency` decreases. | ||
| 261 | -- P90/P99 of `Request_Latency` decrease. | ||
| 262 | -- Throughput improves, and gaps in NPU execution are reduced. | ||
| 263 | - | ||
| 264 | -## Recommended Handling Strategies | ||
| 265 | - | ||
| 266 | -| Issue Type | Recommended Solution | | ||
| 267 | -| --- | --- | | ||
| 268 | -| Asynchronous switch does not take effect | Set `MINDIE_ASYNC_SCHEDULING_ENABLE=1` before startup and verify that the environment variable is readable by the service process. | | ||
| 269 | -| Switch enabled but no benefit | Also set `TASK_QUEUE_ENABLE=2` and check whether overlap appears in the timeline. | | ||
| 270 | -| Framework not entering asynchronous branch | Explicitly configure `--async-scheduling` in the startup command and check the final startup parameters. | | ||
| 271 | -| Compatibility issues with older versions | Upgrade CANN, MindIE, or the inference framework to a stable version that supports asynchronous scheduling. | | ||
| 272 | -| Communication configuration offsetting benefits | Check the HCCL/LCCL configuration, remove conflicting variables, and enable compute-communication fusion if necessary. | | ||
| 273 | -| Insufficient benefit in single-node PD disaggregation | Use in combination with `ATB_LLM_LCOC_ENABLE=1`, prefix cache, and the LCCL communication library. | | ||
| 274 | -| Multi-device scenario still serial | Check rank configuration, network communication, communication domain duration, and cross-device synchronization points. | | ||
| 275 | - | ||
| 276 | -## Summary | ||
| 277 | - | ||
| 278 | -Asynchronous scheduling failing to take effect is not caused by a single switch but by a combination of environment variables, pipeline optimization, framework startup parameters, hardware and software versions, and communication configuration. When troubleshooting, first collect `BatchSchedule`, `ModelExecute`, and `Communication` data using `msServiceProfiler` to determine whether scheduling, execution, and communication overlap in the timeline. During optimization, first verify that `MINDIE_ASYNC_SCHEDULING_ENABLE=1`, `TASK_QUEUE_ENABLE=2`, and the framework startup parameters are effective. Then, check version compatibility, conflicting environment variables, HCCL/LCCL communication configuration, compute-communication fusion in PD disaggregation, prefix cache, and other collaborative capabilities. | ||
| @@ -1,148 +0,0 @@ | |||
| 1 | -# Request Length Imbalance Within the Same Batch | ||
| 2 | - | ||
| 3 | -## Background | ||
| 4 | - | ||
| 5 | -A customer deployed an inference service based on MindIE-LLM for LLaMA2-70B on an Ascend A2 cluster. After deployment, stress testing showed that at a fixed concurrency level (QPS = 20), the serving throughput was only about **55%** of the expected value. 99th-percentile (P99) time to first token (TTFT) reached **820 ms** (SLA target: **300 ms**), and P99 time per output token (TPOT) reached **85 ms** (SLA target: **30 ms**). However, `npu-smi info` showed that the average NPU utilization (AICore) was **78%**, while AIPower was normal and the temperature did not trigger frequency throttling. On the surface, the hardware did not appear to be fully utilized, yet the service was slow. This is a typical serving-layer scheduling issue. | ||
| 6 | - | ||
| 7 | -Further stress testing produced the following results. | ||
| 8 | - | ||
| 9 | -| Concurrency | Theoretical Throughput (tokens/s) | Measured Throughput (tokens/s) | Throughput Achievement Rate | P99 TTFT (ms) | P99 TPOT (ms) | | ||
| 10 | -| ----------- | --------------------------------- | ------------------------------ | --------------------------- | ------------- | ------------- | | ||
| 11 | -| 10 | 1200 | 980 | 81.7% | 210 | 28 | | ||
| 12 | -| 20 | 2400 | 1320 | **55.0%** | **820** | **85** | | ||
| 13 | -| 40 | 4800 | 2280 | 47.5% | 1850 | 142 | | ||
| 14 | -| 80 | 9600 | 3920 | 40.8% | OOM/timeout | OOM/timeout | | ||
| 15 | - | ||
| 16 | -The throughput achievement rate **decreases significantly** as concurrency increases, which appears inconsistent with the observation that the hardware is not fully utilized. This may suggest a **structural bottleneck in the serving-layer scheduler**. | ||
| 17 | - | ||
| 18 | ---- | ||
| 19 | - | ||
| 20 | -## Symptoms | ||
| 21 | - | ||
| 22 | -In Continuous Batching mode of the serving-layer scheduler, a long request that has just completed prefill is mixed into the same decode batch with several short requests that are already in the decode stage. The execution time of a decode step is no longer determined primarily by the average length of the current batch, but is instead dominated by the longest request undergoing prefill. As a result: | ||
| 23 | - | ||
| 24 | -* **Short requests are slowed down:** A short request that would normally generate one token in approximately 25 ms may have to wait 80–100 ms because it is blocked by the long request prefill, causing TPOT to increase by 3–4 times. | ||
| 25 | -* **Decode step duration shows periodic spikes:** On the timeline, decode operator duration fluctuates in a "short-long-short-long" sawtooth pattern. | ||
| 26 | -* **AICore utilization is "artificially high":** The NPU remains busy computing, particularly during the compute-intensive prefill stage, but the computation does not translate into effective token output. | ||
| 27 | -* **KV cache allocation fluctuates:** When a long request enters the prefill stage, the framework needs to urgently allocate a large amount of KV cache, causing the scheduler to stall and delaying subsequent requests from entering the queue. | ||
| 28 | - | ||
| 29 | -**Core contradiction:** Although the 78% hardware utilization appears relatively high, the **effective token output per unit of time** (output tokens/s) is far below the expected level. | ||
| 30 | - | ||
| 31 | ---- | ||
| 32 | - | ||
| 33 | -## Troubleshooting Process | ||
| 34 | - | ||
| 35 | -First, use msServiceProfiler to collect the end-to-end serving trace and obtain the raw request, batch, and KV cache data. Then, import the data into MindStudio Insight. Use the **Summary** page to identify statistical anomalies in key metrics, such as throughput, latency, and batch-length distribution, and then use the **Timeline** page to compare representative "bad batches" with "good batches." This makes it possible to quickly identify the root cause: **prefill is slowing down decode**. | ||
| 36 | - | ||
| 37 | -### Step 1: Collecting End-to-End Serving Data Using msServiceProfiler | ||
| 38 | - | ||
| 39 | -**Purpose:** Collect request-level, batch-level, and KV cache-level data to establish an end-to-end timeline and provide the data source for subsequent visualization in MindStudio Insight. | ||
| 40 | - | ||
| 41 | -**Configuration file** (`/home/user/mindie/ms_service_profiler_config.json`): | ||
| 42 | - | ||
| 43 | -```json | ||
| 44 | -{ | ||
| 45 | - "enable": 1, | ||
| 46 | - "prof_dir": "/home/user/mindie/prof_data", | ||
| 47 | - "acl_task_time": 1, | ||
| 48 | - "l2_cache": 0, | ||
| 49 | - "data_frame": 1 | ||
| 50 | -} | ||
| 51 | -``` | ||
| 52 | - | ||
| 53 | -**Configure environment variables and start the MindIE Service:** | ||
| 54 | - | ||
| 55 | -```bash | ||
| 56 | -export SERVICE_PROF_CONFIG_PATH="/home/user/mindie/ms_service_profiler_config.json" | ||
| 57 | -bash /usr/local/Ascend/mindie/latest/scripts/start.sh \ | ||
| 58 | - --model-path /data/llama2-70b-fp16 \ | ||
| 59 | - --tensor-parallel-size 4 \ | ||
| 60 | - --max-batch-size 64 \ | ||
| 61 | - --max-prefill-tokens 8192 | ||
| 62 | -``` | ||
| 63 | - | ||
| 64 | -**Disable data collection after 60 seconds** (to limit the amount of collected data): | ||
| 65 | - | ||
| 66 | -```json | ||
| 67 | -{ | ||
| 68 | - "enable": 0, | ||
| 69 | - "prof_dir": "/home/user/mindie/prof_data" | ||
| 70 | -} | ||
| 71 | -``` | ||
| 72 | - | ||
| 73 | -**Parse the data using the `parse` subcommand:** | ||
| 74 | - | ||
| 75 | -```bash | ||
| 76 | -pip install -U msserviceprofiler | ||
| 77 | -python3 -m ms_service_profiler.parse \ | ||
| 78 | - --input-path=/home/user/mindie/prof_data \ | ||
| 79 | - --output-path=/home/user/mindie/prof_parsed | ||
| 80 | -``` | ||
| 81 | - | ||
| 82 | -**Output files:** | ||
| 83 | - | ||
| 84 | -* `prof_parsed/analysis.db`: an SQLite database that can be directly imported into MindStudio Insight. | ||
| 85 | -* `prof_parsed/rank*/request_*.csv`: request-level data for each rank. | ||
| 86 | -* `prof_parsed/rank*/batch_*.csv`: batch-level data. | ||
| 87 | -* `prof_parsed/rank*/kvcache_*.csv`: KV cache data. | ||
| 88 | - | ||
| 89 | ---- | ||
| 90 | - | ||
| 91 | -### Step 2: Identifying the Root Cause Using Summary and Timeline in MindStudio Insight | ||
| 92 | - | ||
| 93 | -Start MindStudio Insight and import `analysis.db`. | ||
| 94 | - | ||
| 95 | -#### 2.1 Viewing Macro Metrics on the Summary Page | ||
| 96 | - | ||
| 97 | -Open the **Summary** page and focus on the following three views: | ||
| 98 | - | ||
| 99 | -1. **End-to-end performance line chart:** Shows TTFT, TPOT, and throughput over time, making the "periodic spikes" visible. | ||
| 100 | -2. **Batch statistics:** Shows the distribution of `seq_cnt`, `max_len`, `min_len`, and `batch_time` for each batch. | ||
| 101 | -3. **Request length distribution:** Shows a histogram of `prompt_len` to confirm that the long-tail distribution is genuine rather than caused by an abnormal configuration. | ||
| 102 | - | ||
| 103 | -**Key observation:** The **Summary** page clearly shows a strong positive correlation between **batch duration (`batch_time`) and the length ratio (`len_ratio`) within a batch**. Most batches have a `batch_time` of less than 50 ms, while a small number of batches spike to 150–180 ms. These outliers correspond precisely to batches with a length ratio greater than 16. | ||
| 104 | - | ||
| 105 | -#### 2.2 Comparing Representative Batches on the Timeline | ||
| 106 | - | ||
| 107 | -Open the **Timeline** page and first select two representative batches from the batch list: | ||
| 108 | - | ||
| 109 | -* **Bad batch: b-15892** (`seq_cnt` = 8, `max_len` = 4096, `min_len` = 64, **`len_ratio` = 64**) | ||
| 110 | -* **Good batch: b-16301** (`seq_cnt` = 6, `max_len` = 512, `min_len` = 256, **`len_ratio` = 2**) | ||
| 111 | - | ||
| 112 | -Zoom in on an approximately 500 ms window for each of the two batches to compare them. | ||
| 113 | - | ||
| 114 | -**Expected observation** (**Figure 1: Bad batch b-15892 timeline**) | ||
| 115 | - | ||
| 116 | -<div align="center"><img src="../figures/bad_batch_timeline.png" /></div> | ||
| 117 | - | ||
| 118 | -* All eight sequences are in the same decode step: one long request (`prompt` = `4096`) is undergoing prefill, represented by a long yellow-green bar spanning approximately 140 ms, while the other seven short requests are stalled. | ||
| 119 | -* The operator bars for the entire decode step are **extended to approximately 180 ms**, with operators such as `FlashAttention`, `MLP`, and `RMSNorm` appearing almost continuously from one to the next. | ||
| 120 | -* None of the decode steps falls within the normal 30 ms range. | ||
| 121 | -* There are no clear boundaries between operator bars, resulting in a "flattened" appearance. | ||
| 122 | - | ||
| 123 | -**Comparison** (**Figure 2: Good batch b-16301 timeline**) | ||
| 124 | - | ||
| 125 | -<div align="center"><img src="../figures/good_batch_timeline.png" /></div> | ||
| 126 | - | ||
| 127 | -* The six sequences have similar lengths (256–512 tokens), are all in the decode stage, and are not affected by prefill. | ||
| 128 | -* Each decode step takes approximately **32 ms**, with clear boundaries between operator bars. | ||
| 129 | -* Small gaps are visible between operators, representing host scheduling overhead and producing a regular, "healthy" rhythm. | ||
| 130 | -* Natural intervals also exist between decode steps because the batch is waiting for the next round of requests or KV cache allocation. | ||
| 131 | - | ||
| 132 | ---- | ||
| 133 | - | ||
| 134 | -## Root Cause | ||
| 135 | - | ||
| 136 | -**Root Cause Type:** Framework adaptation issue. The scheduler in MindIE-LLM 1.0.RC2 does not sufficiently bucket or sort requests by length. | ||
| 137 | - | ||
| 138 | -## Methodology Summary | ||
| 139 | - | ||
| 140 | -1. **Step 1: Collect and parse profile data using msServiceProfiler.** | ||
| 141 | - * Write the configuration (`enable=1`, `acl_task_time=1`, `data_frame=1`) → start the service → collect service traffic data for 60 seconds → stop collection → parse the data using `ms_service_profiler.parse`. | ||
| 142 | - * The `analysis.db` file is the data source for all subsequent analysis. | ||
| 143 | - | ||
| 144 | -2. **Step 2: Perform macro- and micro-level comparisons in MindStudio Insight.** | ||
| 145 | - * **Summary** page: First check the `batch_time` distribution, identify outliers (batches with `batch_time` > 100 ms), and examine the `len_ratio` distribution to examine the correlation between the two metrics. | ||
| 146 | - * **Timeline** page: Select a representative outlier batch (a batch with `len_ratio` > 16), then select a normal batch (`len_ratio` < 4) for **direct comparison**. | ||
| 147 | - * Typical characteristics of a bad batch: one extremely long prefill request dominates the entire batch, all decode steps are extended to approximately 180 ms, and operator bars run continuously without clear boundaries. | ||
| 148 | - * Typical characteristics of a good batch: decode steps maintain a stable rhythm (approximately 32 ms per step), operator bars have clear boundaries, and host scheduling follows a regular pattern. | ||
| @@ -1,33 +1,43 @@ | |||
| 1 | -# 1. Background | 1 | +# Optimizing Operators with Long Execution Time |
| 2 | + | ||
| 3 | +## 1. Background | ||
| 2 | 4 | ||
| 3 | During NPU workload execution, the execution time does not meet expectations. Profile data collection and analysis show that some operators have long execution time and require optimization. | 5 | During NPU workload execution, the execution time does not meet expectations. Profile data collection and analysis show that some operators have long execution time and require optimization. |
| 4 | 6 | ||
| 5 | -# 2. Source | 7 | +## 2. Source |
| 6 | 8 | ||
| 7 | -Performance profiling. | 9 | +Performance tuning. |
| 8 | 10 | ||
| 9 | -# 3. Symptoms | 11 | +## 3. Symptoms |
| 10 | 12 | ||
| 11 | -Open `msprof.json` or `trace_view.json` in Insight. Some operators may have long execution time. Open `op_statistic.csv` and check the corresponding operators to confirm that their performance does not meet expectations due to long execution time, indicating potential performance gains from optimization. | 13 | +Open `msprof.json` or `trace_view.json` in MindStudio Insight. You can observe that some operators have long execution time. |
| 12 | 14 | ||
| 13 | -As shown in the following figure, the `nonzero` operator accounts for a large proportion of the execution time. | 15 | +Open `op_statistic.csv` and check the corresponding operators to confirm that their performance does not meet expectations and their execution time is long, indicating potential optimization benefits. |
| 16 | + | ||
| 17 | +As shown in the following figure, the `NonZero` operator accounts for a large proportion of the total execution time. | ||
| 14 | 18 | ||
| 15 |  | 19 |  |
| 16 | 20 | ||
| 17 | -# 4. Troubleshooting Process | 21 | +## 4. Troubleshooting Process |
| 18 | 22 | ||
| 19 | Similar optimization approaches can be divided into two categories: | 23 | Similar optimization approaches can be divided into two categories: |
| 20 | 24 | ||
| 21 | -1. **Operator-specific optimization**: Check the operator implementation to determine whether there is room for optimization. You may need to implement the required operator capabilities yourself or contact the relevant engineers for specific optimization guidance. | 25 | +1. **Operator-specific optimization**: Check the operator implementation to determine whether there is room for optimization. You may need to implement the required operator capabilities yourself or contact relevant engineers for specific optimization. |
| 22 | 26 | ||
| 23 | 2. **Operator or operation replacement**: Replace the current operator or operation with an equivalent alternative that has better NPU affinity. This section provides a brief introduction to this approach. | 27 | 2. **Operator or operation replacement**: Replace the current operator or operation with an equivalent alternative that has better NPU affinity. This section provides a brief introduction to this approach. |
| 24 | 28 | ||
| 25 | -For this issue, an existing "`nonzero` operator replacement" case is available. We refer to the official documentation and create a corresponding use case for a simple test. | 29 | +[NPU Affinity Adaptation](https://gitcode.com/Ascend/ModelZoo-PyTorch/blob/master/PyTorch/docs/en/performance_tuning/performance_tuning_methods/npu_affinity_opt/README.md) in *PyTorch Training Model Porting and Tuning Guide* describes many optimization methods. You can refer to similar solutions to learn about them. |
| 30 | + | ||
| 31 | +For this issue, an existing "nonzero operator replacement" case is available. We refer to the official documentation and create a simple test case. | ||
| 26 | 32 | ||
| 27 | ```python | 33 | ```python |
| 34 | +import torch | ||
| 35 | +import torch_npu | ||
| 36 | +... | ||
| 37 | + | ||
| 28 | def nonzero_ori(): | 38 | def nonzero_ori(): |
| 29 | shape = (1024, ) | 39 | shape = (1024, ) |
| 30 | - mask = torch.randint(-1, 2, shape).npu() | 40 | + mask= torch.randint(-1, 2, shape).npu() |
| 31 | gt_inds = torch.randint(-1, 2, shape).npu() | 41 | gt_inds = torch.randint(-1, 2, shape).npu() |
| 32 | tensor_a = torch.ones(shape).float().npu() | 42 | tensor_a = torch.ones(shape).float().npu() |
| 33 | mask_inds = torch.nonzero(gt_inds > 0, as_tuple=False).squeeze(1) | 43 | mask_inds = torch.nonzero(gt_inds > 0, as_tuple=False).squeeze(1) |
| @@ -60,20 +70,20 @@ def run(): | |||
| 60 | 70 | ||
| 61 | ``` | 71 | ``` |
| 62 | 72 | ||
| 63 | -The following figure shows the corresponding timeline. The new implementation demonstrates a performance gain. | 73 | +The following pipeline diagram shows the performance benefit of the new implementation. |
| 64 | 74 | ||
| 65 |  | 75 |  |
| 66 | 76 | ||
| 67 | -# 5. Root Cause | 77 | +## 5. Root Cause |
| 68 | 78 | ||
| 69 | -The `nonzero` operator is a commonly used indexing operator in deep learning frameworks. Its core function is to return the coordinate indices of nonzero elements in the input tensor in row-major order. It is a typical memory-bound operation and is not well suited to the Ascend Da Vinci architecture. Therefore, the key replacement strategy is to avoid a large number of memory accesses. | 79 | +The nonzero operator is a commonly used indexing operator in deep learning frameworks. Its core function is to return the coordinate indices of nonzero elements in the input tensor and output the results in row-major order. This is a typical memory-access-intensive operation that is not well suited to the Ascend Da Vinci architecture. Therefore, the core replacement idea is to avoid a large number of memory access operations. |
| 70 | 80 | ||
| 71 | -# 6. Methodology Summary | 81 | +## 6. Troubleshooting Methodology Summary |
| 72 | 82 | ||
| 73 | 1. Use visualization tools to identify operators that require optimization from perspectives such as the timeline and operator statistics tables. | 83 | 1. Use visualization tools to identify operators that require optimization from perspectives such as the timeline and operator statistics tables. |
| 74 | 84 | ||
| 75 | -2. Analyze the workload behavior of the operator and, taking the Ascend architecture into account, transform the operation into a more NPU-friendly alternative to improve performance. | 85 | +2. Analyze the workload behavior of the operator and, taking the Ascend architecture into account, transform the operation into an operation better suited to the Ascend NPU architecture to improve performance. |
| 76 | 86 | ||
| 77 | -# 7. Suggestions for Tool Improvements | 87 | +## 7. Suggestions for Tool Improvement |
| 78 | 88 | ||
| 79 | -None | 89 | +None. |
| @@ -1,10 +1,10 @@ | |||
| 1 | -# Performance Degradation Caused by Misaligned Communication Addresses | 1 | +# Performance Degradation Caused by Communication Address Misalignment |
| 2 | 2 | ||
| 3 | -## Background | 3 | +## 1. Background |
| 4 | 4 | ||
| 5 | -In a foundation-model training scenario, distributed training is performed on 8 Ascend 910B NPUs, with approximately 70B model parameters. During training, the execution time of a single step is much longer than expected. A communication bottleneck is suspected, and profiling is required to identify the root cause. | 5 | +In a foundation-model training scenario, distributed training is performed on 8 Atlas A2 products, with approximately 70B model parameters. During training, the execution time of a single step is found to far exceed expectations, and a communication bottleneck is suspected. The specific cause needs to be located using profiling tools. |
| 6 | 6 | ||
| 7 | -## Symptoms | 7 | +## 2. Symptoms |
| 8 | 8 | ||
| 9 | The issue can be reproduced consistently. During 8-rank training, communication accounts for more than 40% of the execution time of a single step, and the execution time of the `AllReduce` operator fluctuates significantly. In some steps, communication takes 2 to 3 times as long as in others. Single-rank inference performs normally, ruling out a computation bottleneck. | 9 | The issue can be reproduced consistently. During 8-rank training, communication accounts for more than 40% of the execution time of a single step, and the execution time of the `AllReduce` operator fluctuates significantly. In some steps, communication takes 2 to 3 times as long as in others. Single-rank inference performs normally, ruling out a computation bottleneck. |
| 10 | 10 | ||
| @@ -13,9 +13,9 @@ The issue can be reproduced consistently. During 8-rank training, communication | |||
| 13 | 13 | ||
| 14 | > Compute time remains stable at approximately 320 ms, while communication time fluctuates significantly between 195 ms and 410 ms, indicating an anomaly in the communication path. | 14 | > Compute time remains stable at approximately 320 ms, while communication time fluctuates significantly between 195 ms and 410 ms, indicating an anomaly in the communication path. |
| 15 | 15 | ||
| 16 | -## Troubleshooting Process | 16 | +## 3. Troubleshooting Process |
| 17 | 17 | ||
| 18 | -### 1 Collecting Profile Data to Confirm the Communication Bottleneck | 18 | +### 3.1 Collecting Performance Data to Confirm the Communication Bottleneck |
| 19 | 19 | ||
| 20 | Use `torch_npu.profiler` to collect profile data for a complete training step and confirm the proportion of communication time and the specific operators involved. | 20 | Use `torch_npu.profiler` to collect profile data for a complete training step and confirm the proportion of communication time and the specific operators involved. |
| 21 | 21 | ||
| @@ -42,19 +42,19 @@ with torch_npu.profiler.profile( | |||
| 42 | 42 | ||
| 43 | The timeline shows two distinctly different execution patterns for the `AllReduce` operator: | 43 | The timeline shows two distinctly different execution patterns for the `AllReduce` operator: |
| 44 | 44 | ||
| 45 | -- **Pattern A (normal)**: `AllReduce` takes approximately 200 ms, with collective communication initiated directly inside HCCL. | 45 | +- Pattern A (normal): AllReduce takes approximately 200 ms, with collective communication initiated directly inside HCCL. |
| 46 | -- **Pattern B (abnormal)**: `AllReduce` takes approximately 400 ms, with an additional `memcpy` operation inside HCCL. | 46 | +- Pattern B (abnormal): AllReduce takes approximately 400 ms, with an additional memcpy operation inside HCCL. |
| 47 | 47 | ||
| 48 | <div align="center"><img src="../figures/profiler_case_align_timeline.png" /></div> | 48 | <div align="center"><img src="../figures/profiler_case_align_timeline.png" /></div> |
| 49 | <div align="center"><b>Figure 2: Timeline comparison of the two AllReduce patterns</b></div> | 49 | <div align="center"><b>Figure 2: Timeline comparison of the two AllReduce patterns</b></div> |
| 50 | 50 | ||
| 51 | > Pattern B contains an additional `memcpy` operation compared with Pattern A, adding approximately 200 ms. The address or size of the input tensor may not meet HCCL alignment requirements, causing the library to perform an alignment copy first. | 51 | > Pattern B contains an additional `memcpy` operation compared with Pattern A, adding approximately 200 ms. The address or size of the input tensor may not meet HCCL alignment requirements, causing the library to perform an alignment copy first. |
| 52 | 52 | ||
| 53 | -### 2 Confirming Address Misalignment | 53 | +### 3.2 Confirming Address Misalignment |
| 54 | 54 | ||
| 55 | -The additional `memcpy` observed in the Step 1 timeline is itself a typical indication of address misalignment. The HCCL communication library requires input data to be aligned to 128 bytes. When the data is not aligned, HCCL automatically performs an alignment copy internally. In the timeline, this operation appears as an additional `memcpy` within the `AllReduce` operator. In normal steps, the memory allocation happens to be aligned, so the `AllReduce` operator contains only collective communication and no `memcpy`. | 55 | +The additional memcpy observed in the timeline in [Collecting Performance Data to Confirm the Communication Bottleneck](#31-collecting-performance-data-to-confirm-the-communication-bottleneck) is itself a typical indication of address misalignment. The HCCL communication library requires input data to be aligned to 128 bytes. When the data is not aligned, the library automatically performs an alignment copy internally, which appears in the timeline as an additional memcpy within the AllReduce operator. In a normal step, because memory allocation happens to be aligned, the AllReduce operator contains only collective communication and no memcpy. |
| 56 | 56 | ||
| 57 | -### 3 Tracing the Source of the Misaligned Tensor | 57 | +### 3.3 Tracing the Source of the Misaligned Tensor |
| 58 | 58 | ||
| 59 | After confirming the address misalignment, trace the upstream operator that produces the misaligned tensor. `with_stack=True` was enabled in the collection configuration in Step 1, so each operator event in the timeline contains a call stack. In `chrome://tracing`, click the `AllReduce` operator in Pattern B to view its complete call chain: | 59 | After confirming the address misalignment, trace the upstream operator that produces the misaligned tensor. `with_stack=True` was enabled in the collection configuration in Step 1, so each operator event in the timeline contains a call stack. In `chrome://tracing`, click the `AllReduce` operator in Pattern B to view its complete call chain: |
| 60 | 60 | ||
| @@ -72,34 +72,34 @@ The call stack shows that the input tensor for this `AllReduce` is allocated by | |||
| 72 | 72 | ||
| 73 | > Because whether the memory address returned by `torch.empty()` is aligned to 128 bytes depends on the current state of the memory allocator, the issue manifests as non-deterministic behavior: each allocation may produce a different result, and the `AllReduce` execution time fluctuates accordingly. | 73 | > Because whether the memory address returned by `torch.empty()` is aligned to 128 bytes depends on the current state of the memory allocator, the issue manifests as non-deterministic behavior: each allocation may produce a different result, and the `AllReduce` execution time fluctuates accordingly. |
| 74 | 74 | ||
| 75 | -## Root Cause | 75 | +## 4. Root Cause |
| 76 | 76 | ||
| 77 | When the custom operator uses `torch.empty()` to allocate output tensors without specifying `memory_format`, some starting addresses fail to meet the 128-byte HCCL alignment requirement. Consequently, HCCL automatically performs an alignment copy internally, adding approximately 200 ms of overhead. | 77 | When the custom operator uses `torch.empty()` to allocate output tensors without specifying `memory_format`, some starting addresses fail to meet the 128-byte HCCL alignment requirement. Consequently, HCCL automatically performs an alignment copy internally, adding approximately 200 ms of overhead. |
| 78 | 78 | ||
| 79 | This is a framework adaptation issue. The user did not consider the alignment constraint imposed by the HCCL communication library on input data. | 79 | This is a framework adaptation issue. The user did not consider the alignment constraint imposed by the HCCL communication library on input data. |
| 80 | 80 | ||
| 81 | -## Conclusion | 81 | +## 5. Conclusion |
| 82 | 82 | ||
| 83 | 1. The HCCL communication library requires input tensor addresses to be aligned to 128 bytes. When this requirement is not met, HCCL automatically performs an alignment copy internally, adding approximately 200 ms of overhead. | 83 | 1. The HCCL communication library requires input tensor addresses to be aligned to 128 bytes. When this requirement is not met, HCCL automatically performs an alignment copy internally, adding approximately 200 ms of overhead. |
| 84 | 2. An additional `memcpy` operation within an `AllReduce` operator in the profiling timeline is a typical indication of misaligned communication addresses and can serve as a troubleshooting signal. | 84 | 2. An additional `memcpy` operation within an `AllReduce` operator in the profiling timeline is a typical indication of misaligned communication addresses and can serve as a troubleshooting signal. |
| 85 | 3. Alignment issues manifest as non-deterministic behavior: the same operator may behave differently depending on the state of the memory allocator, unlike a stable performance bottleneck. | 85 | 3. Alignment issues manifest as non-deterministic behavior: the same operator may behave differently depending on the state of the memory allocator, unlike a stable performance bottleneck. |
| 86 | 4. **Resolution**: Ensure that the tensor passed to the communication operation satisfies the required address alignment, either by using an alignment-guaranteed allocation method or by explicitly handling alignment before communication. | 86 | 4. **Resolution**: Ensure that the tensor passed to the communication operation satisfies the required address alignment, either by using an alignment-guaranteed allocation method or by explicitly handling alignment before communication. |
| 87 | 87 | ||
| 88 | -```python | 88 | + ```python |
| 89 | -# Ensure alignment before communication | 89 | + # Force alignment before communication. |
| 90 | -if tensor.data_ptr() % 128 != 0: | 90 | + if tensor.data_ptr() % 128 != 0: |
| 91 | - tensor = tensor.contiguous() | 91 | + tensor = tensor.contiguous() |
| 92 | -``` | 92 | + ``` |
| 93 | 93 | ||
| 94 | -## Methodology Summary | 94 | +## 6. Methodology Summary |
| 95 | 95 | ||
| 96 | 1. When communication accounts for a high proportion of execution time, first use profiling to determine whether the issue is bandwidth-related or caused by additional overhead inside an operator. | 96 | 1. When communication accounts for a high proportion of execution time, first use profiling to determine whether the issue is bandwidth-related or caused by additional overhead inside an operator. |
| 97 | 2. If the `AllReduce` execution time fluctuates significantly and an additional `memcpy` operation is present in the timeline, prioritize checking whether the tensor address is aligned. | 97 | 2. If the `AllReduce` execution time fluctuates significantly and an additional `memcpy` operation is present in the timeline, prioritize checking whether the tensor address is aligned. |
| 98 | 3. Trace upward through the call stack to the upstream operator that produces the tensor and check how its memory is allocated. | 98 | 3. Trace upward through the call stack to the upstream operator that produces the tensor and check how its memory is allocated. |
| 99 | -4. Alignment issues typically manifest as non-deterministic behavior: the same code may behave differently depending on the state of the memory allocator. | 99 | +4. Alignment issues typically manifest as "randomness" (the same code behaves inconsistently depending on the state of the memory allocator). |
| 100 | 100 | ||
| 101 | -## Suggestions for Tool Improvements | 101 | +## 7. Suggestions for Tool Improvement |
| 102 | 102 | ||
| 103 | -- In the profiling timeline, directly indicate the tensor address alignment status on communication operators such as `AllReduce` to make such issues easier to identify. | 103 | +- In the profiling timeline, directly indicate the tensor address alignment status on communication operators such as AllReduce to make such issues easier to identify. |
| 104 | - Add automated diagnostic capabilities for HCCL communication alignment checks and flag misaligned communication operators in the collected data. | 104 | - Add automated diagnostic capabilities for HCCL communication alignment checks and flag misaligned communication operators in the collected data. |
| 105 | -- Add explicit markers for `memcpy` operations identified within `AllReduce` operators to distinguish them from ordinary memory copy operations. | 105 | +- Add explicit markers for memcpy operations identified within AllReduce operators to distinguish them from ordinary memory copy operations. |
Mdocs/en/best_practices/cpu_cache_miss_conflict.md+20-20File content is under review, please try again later
Mdocs/en/best_practices/cpu_thread_frequent_switching.md+30-30File content is under review, please try again later
| @@ -1,24 +1,26 @@ | |||
| 1 | -# 1. Background | 1 | +# Dispatch Performance Below Expectation |
| 2 | + | ||
| 3 | +## 1. Background | ||
| 2 | 4 | ||
| 3 | During NPU workload execution, the execution time is longer than expected. Analysis of the collected profile data confirms that task dispatch is slow and overall hardware utilization is low, indicating an urgent need to identify the issue and optimize performance. | 5 | During NPU workload execution, the execution time is longer than expected. Analysis of the collected profile data confirms that task dispatch is slow and overall hardware utilization is low, indicating an urgent need to identify the issue and optimize performance. |
| 4 | 6 | ||
| 5 | -# 2. Source | 7 | +## 2. Source |
| 6 | 8 | ||
| 7 | -Performance profiling. | 9 | +Performance tuning. |
| 8 | 10 | ||
| 9 | -# 3. Symptoms | 11 | +## 3. Symptoms |
| 10 | 12 | ||
| 11 | Open `msprof.json` or `trace_view.json` in MindStudio Insight. The overall workload has a relatively high proportion of idle time and low hardware resource utilization. | 13 | Open `msprof.json` or `trace_view.json` in MindStudio Insight. The overall workload has a relatively high proportion of idle time and low hardware resource utilization. |
| 12 | 14 | ||
| 13 |  | 15 |  |
| 14 | 16 | ||
| 15 | -# 4. Troubleshooting Process | 17 | +## 4. Troubleshooting Process |
| 16 | 18 | ||
| 17 | -First, the **CANN** track represents the API dispatch interface layer of the CANN software stack, while the **Ascend Hardware** track represents the actual operator execution layer. For the overall workload, a reasonable dispatch and execution pattern should consist of rapid API dispatch and sustained, high-density hardware execution. This relationship can be observed through the `host_to_device` connections provided by the Profiler. In an efficient execution timeline, the connections should be slightly inclined, indicating efficient utilization of hardware resources, as shown below. | 19 | +First, the CANN layer is the API dispatch interface layer of the CANN software stack, while the Ascend Hardware layer represents the actual operator execution layer. For the overall workload, only rapid API dispatch combined with long-term high-density hardware execution constitutes a reasonable dispatch-execution relationship. This relationship can be observed through the host-to-device connection provided by the profiler. A well-optimized pipeline diagram should exhibit a certain degree of inclination, which indicates efficient utilization of hardware resources, as shown in the following figure: |
| 18 | 20 | ||
| 19 |  | 21 |  |
| 20 | 22 | ||
| 21 | -However, the current connections are vertical, indicating that each operator starts executing immediately after being dispatched, followed by a wait for the next operator to be dispatched. This further indicates that there is significant room for improving hardware utilization, as shown below. | 23 | +However, the current connections are vertical, meaning that each operator is executed immediately after being dispatched, followed by a wait for the next operator to be dispatched. This further confirms that the hardware still has considerable utilization headroom, as shown in the following figure: |
| 22 | 24 | ||
| 23 |  | 25 |  |
| 24 | 26 | ||
| @@ -26,11 +28,11 @@ We also checked the overall memory usage of the workload and found that it was o | |||
| 26 | 28 | ||
| 27 |  | 29 |  |
| 28 | 30 | ||
| 29 | -# 5. Root Cause | 31 | +## 5. Root Cause |
| 30 | 32 | ||
| 31 | -The root cause is insufficient utilization of hardware resources, resulting in a certain degree of resource waste. The execution timeline, `host_to_device` connections, and memory data provided by the Profiler can intuitively present the current workload bottlenecks and resource utilization. They can also guide further workload adjustments, such as increasing the batch size, to improve overall workload performance. | 33 | +The essence of the problem is insufficient utilization of hardware resources, resulting in a certain degree of resource waste. The pipeline diagram, host-to-device connections, and memory data provided by the profiler can intuitively present the current service bottleneck and resource usage, and guide us in further adjusting the service, for example, by adjusting the batch size to improve the overall service performance. |
| 32 | 34 | ||
| 33 | -# 6. Methodology Summary | 35 | +## 6. Methodology Summary |
| 34 | 36 | ||
| 35 | 1. Use visualization tools to identify the dispatch and execution relationship between the host and device from the timeline perspective, and use this as a basis to determine whether low resource utilization is introduced at the dispatch layer or the execution layer. | 37 | 1. Use visualization tools to identify the dispatch and execution relationship between the host and device from the timeline perspective, and use this as a basis to determine whether low resource utilization is introduced at the dispatch layer or the execution layer. |
| 36 | 38 | ||
| @@ -38,6 +40,6 @@ The root cause is insufficient utilization of hardware resources, resulting in a | |||
| 38 | 40 | ||
| 39 | 3. Increase resource utilization by adjusting the batch size based on the goal of increasing the computation workload of individual operators, thereby improving workload performance and making full use of available resources. | 41 | 3. Increase resource utilization by adjusting the batch size based on the goal of increasing the computation workload of individual operators, thereby improving workload performance and making full use of available resources. |
| 40 | 42 | ||
| 41 | -# 7. Tool Improvement Suggestions | 43 | +## 7. Tool Improvement Suggestions |
| 42 | 44 | ||
| 43 | Consider adding detection of memory and dispatch bottlenecks to Advisor and providing recommendations for adjusting relevant workload parameters. | 45 | Consider adding detection of memory and dispatch bottlenecks to Advisor and providing recommendations for adjusting relevant workload parameters. |
| @@ -1,85 +0,0 @@ | |||
| 1 | -# DP Load Imbalance | ||
| 2 | - | ||
| 3 | -## Background | ||
| 4 | - | ||
| 5 | -In data parallelism (DP) scenarios, a service instance contains multiple DP domains. Under normal circumstances, requests and token loads should be distributed as evenly as possible across the DP domains. If a DP domain continuously handles more requests or heavier requests, it will first experience queueing, higher KV cache utilization, or longer execution durations, slowing down the entire instance. | ||
| 6 | - | ||
| 7 | -## Source | ||
| 8 | - | ||
| 9 | -Inference | ||
| 10 | - | ||
| 11 | -## Symptoms | ||
| 12 | - | ||
| 13 | -Users typically first observe that the overall instance throughput is lower than expected and P95/P99 latency is higher, but instance-level metrics alone may not explain the cause. After further breaking down the metrics by `dp`, common symptoms include: | ||
| 14 | - | ||
| 15 | -- The number of running/waiting requests in some DP domains remains higher than that in other DP domains for an extended period. | ||
| 16 | -- Some DP domains have higher prompt/generation token throughput or larger batch sizes. | ||
| 17 | -- Hotspot DP domains have higher KV cache utilization, and `free_kvcache_blocks` decreases faster. | ||
| 18 | -- Non-hotspot DP domains still have available capacity, but overall latency has been increased by the hotspot DP domains. | ||
| 19 | - | ||
| 20 | -## Troubleshooting Process | ||
| 21 | - | ||
| 22 | -### Step 1: Verifying Whether Only Some DP Domains Are Busy | ||
| 23 | - | ||
| 24 | -In the DP-dimension load panel in Grafana, compare the number of requests, prompt token throughput, generation token throughput, batch size, and number of waiting requests across `dp` or `engine` dimensions within the same time window. | ||
| 25 | - | ||
| 26 | -If the metrics diverge only for a short period and latency does not change significantly, the difference may be considered a traffic fluctuation. If some DP domains remain higher across multiple consecutive windows, proceed to the next step. | ||
| 27 | - | ||
| 28 | -### Step 2: Verifying Whether the Imbalance Is Caused by More Requests or Heavier Requests | ||
| 29 | - | ||
| 30 | -View the number of requests, prompt token throughput, and generation token throughput in Grafana together to determine the source of the load of the hotspot DP domain: | ||
| 31 | - | ||
| 32 | -- **More requests and more tokens:** This usually indicates that the hotspot DP domain is handling more traffic. Investigate the scheduling strategy, DP allocation strategy within the instance, or request stickiness. | ||
| 33 | -- **Similar number of requests but more prompt/generation tokens:** This usually indicates that the hotspot DP domain is handling heavier requests. Check request logs, load-testing datasets, or request length statistics to determine whether long inputs or long outputs are concentrated in this DP domain. | ||
| 34 | -- **Similar numbers of requests and tokens but longer execution duration in one DP domain:** Check device monitoring, process logs, and Profiler data to determine whether the process, device, or communication corresponding to that DP domain is abnormal. | ||
| 35 | - | ||
| 36 | -The findings from this step directly determines the subsequent handling approach: scheduling skew requires changes to the allocation strategy; request-weight skew requires balancing by token count or request length; and device anomalies require checking the hardware or process status first. | ||
| 37 | - | ||
| 38 | -### Step 3: Verifying Whether DP Imbalance Has Affected the Service | ||
| 39 | - | ||
| 40 | -Differences in DP curves alone are insufficient to determine that a fault exists. Check whether the hotspot DP domain also exhibits the following: | ||
| 41 | - | ||
| 42 | -- An increase in the number of waiting requests or queue wait duration. | ||
| 43 | -- High KV cache utilization and fewer free blocks. | ||
| 44 | -- Longer batch execution duration or decode duration than other DP domains. | ||
| 45 | -- An increase in overall instance P95/P99 latency during the same period. | ||
| 46 | - | ||
| 47 | -If these signals occur simultaneously, DP load imbalance may be a bottleneck. | ||
| 48 | - | ||
| 49 | -### Step 4: Using the Offline Profiler to Identify Specific Scheduling Differences | ||
| 50 | - | ||
| 51 | -After collecting `Schedule`-, `Request`-, and `KVCache`-related data, aggregate the data by `dp_rank`: | ||
| 52 | - | ||
| 53 | -- In `batch.csv`, compare `batch_size`, `prefill_batch_size`, `decode_batch_size`, `prefill_scheduled_tokens`, `decode_scheduled_tokens`, `total_scheduled_tokens`, and `during_time(ms)` across DP domains. | ||
| 54 | -- In `request.csv`, count the number of requests by DP domain and compare input length, output length, `queue_wait_time(ms)`, and `first_token_latency(ms)`. | ||
| 55 | -- In `kvcache.csv`, compare `used_blocks`, `free_blocks`, and `kvcache_usage_rate` across DP domains. | ||
| 56 | - | ||
| 57 | -If a DP domain continuously schedules more tokens per batch and has longer execution durations, while also having higher request wait time and KV cache utilization, this indicates that the hotspot is caused by skewed DP scheduling load. | ||
| 58 | - | ||
| 59 | -## Root Cause | ||
| 60 | - | ||
| 61 | -The number of requests, token load, or execution capability differs across DP domains. Common root causes include scheduling strategies that do not balance load by token count, concentration of long requests in some DP domains, abnormal DP process or device status, inconsistent configurations across DP domains, or request stickiness that causes traffic to remain concentrated in a small number of DP domains. | ||
| 62 | - | ||
| 63 | -## Resolution | ||
| 64 | - | ||
| 65 | -- **Uneven request distribution:** Adjust the DP scheduling strategy to avoid concentrating requests in some DP domains through fixed-order or fixed-stickiness scheduling. | ||
| 66 | -- **Uneven token load:** Balance requests based on input/output token counts, or schedule long requests separately to avoid balancing solely by request count. | ||
| 67 | -- **Concentrated KV cache pressure:** Reduce the number of requests scheduled to hotspot DP domains, or adjust the scheduling strategy to bring KV cache utilization across DP domains closer together. | ||
| 68 | -- **Abnormal device or process:** Compare device utilization, error logs, and Profiler execution durations between hotspot and other DP domains, and restore abnormal DP domains to normal operation first. | ||
| 69 | -- **Inconsistent configurations:** Check the service startup parameters and deployment configuration to ensure that the model, parallelism parameters, and device memory configurations are consistent across all DP domains. | ||
| 70 | - | ||
| 71 | -After the issue is addressed, observe token throughput, number of waiting requests, KV cache utilization, and P95/P99 latency again by DP domain to determine whether the metrics are normal. | ||
| 72 | - | ||
| 73 | -## Methodology Summary | ||
| 74 | - | ||
| 75 | -For DP load imbalance scenarios, first use ms-service-metric to compare the number of requests, prompt/generation tokens, waiting requests, batch size, and KV cache utilization across DP domains to determine whether persistent hotspot DP domains exist. After confirming persistent divergence in the online metrics, use msServiceProfiler to aggregate `request.csv`, `batch.csv`, and `kvcache.csv` by `dp_rank` to distinguish between uneven request distribution, uneven token load, concentrated KV cache pressure, and device or process anomalies. | ||
| 76 | - | ||
| 77 | -## Suggestions for Tool Improvements | ||
| 78 | - | ||
| 79 | -### `ms-service-metric` | ||
| 80 | - | ||
| 81 | -Currently, `ms-service-metric` can compare request volume, token volume, queues, and KV cache utilization across DP domains. It is recommended to add DP load imbalance alerts that automatically identify hotspot DP domains when the differences across DP domains continue to increase while overall instance P95/P99 latency also increases. | ||
| 82 | - | ||
| 83 | -### `msServiceProfiler` | ||
| 84 | - | ||
| 85 | -Currently, `msServiceProfiler` can aggregate and analyze scheduling differences by `dp_rank` using `request.csv`, `batch.csv`, and `kvcache.csv`. It is recommended to directly output comparisons of the number of requests, input/output tokens, batch scheduled tokens, execution duration, and KV cache utilization across DP domains in offline reports. | ||
| @@ -1,94 +0,0 @@ | |||
| 1 | -# EP Load Imbalance | ||
| 2 | - | ||
| 3 | -## Background | ||
| 4 | - | ||
| 5 | -During mixture of expert (MoE) model inference, expert parallelism (EP) distributes experts across different ranks or devices. After requests are routed, if a small number of experts are continuously selected, the corresponding ranks will handle more operations such as `GroupedMatmul` computation and `dispatch` or `combine` communication. As a result, these ranks have longer execution durations, consequently increasing the execution duration of the entire MoE layer. | ||
| 6 | - | ||
| 7 | -## Source | ||
| 8 | - | ||
| 9 | -Inference | ||
| 10 | - | ||
| 11 | -## Symptoms | ||
| 12 | - | ||
| 13 | -Users typically first observe that the throughput of MoE models such as DeepSeek is lower than expected, while decode duration or end-to-end latency increases. Further observation of MoE-related metrics may reveal the following: | ||
| 14 | - | ||
| 15 | -- Some expert hotspots are significantly higher than those of other experts in the same layer. | ||
| 16 | -- Some ranks consistently handle higher expert loads across multiple layers. | ||
| 17 | -- Hotspots are not significantly mitigated after the EPLB update. | ||
| 18 | -- The execution duration of the MoE layer increases, accompanied by longer execution durations on some ranks/devices. | ||
| 19 | - | ||
| 20 | -## Troubleshooting Process | ||
| 21 | - | ||
| 22 | -### Step 1: Verifying Whether the Performance Issue Occurs During an MoE-Related Stage | ||
| 23 | - | ||
| 24 | -First, verify whether the decrease in throughput or increase in latency observed by the user occurs simultaneously with an increase in MoE layer execution duration or decode duration. If overall performance remains stable and expert hotspots fluctuate only briefly, the issue should generally not be directly attributed to an EP problem. | ||
| 25 | - | ||
| 26 | -If decode duration increases while MoE operators or the MoE communication stage also become slower, continue to examine the expert load. | ||
| 27 | - | ||
| 28 | -### Step 2: Verifying Whether Persistent Expert Hotspots Exist | ||
| 29 | - | ||
| 30 | -In the EPLB or expert hotspot panel in Grafana, view the aggregated hotspot metrics to verify whether a small number of experts remain consistently hotter: | ||
| 31 | - | ||
| 32 | -- Whether `eplb:expert_hotness:current_max` remains significantly higher than `current_mean`. | ||
| 33 | -- Whether `eplb:expert_hotness:imbalance` remains high. | ||
| 34 | -- Whether the hotspots occur only briefly or persist across multiple windows. | ||
| 35 | - | ||
| 36 | -The purpose here is simply to determine whether persistent imbalance exists. If only transient spikes occur and throughput and latency do not deteriorate simultaneously, the issue can be monitored as business input fluctuation. | ||
| 37 | - | ||
| 38 | -### Step 3: Identifying the Specific Hotspot Layers, Ranks, and Experts | ||
| 39 | - | ||
| 40 | -After verifying that persistent imbalance exists, continue to identify the hotspots in the per-layer expert details panel: | ||
| 41 | - | ||
| 42 | -- Identify the layer in which an expert has significantly more selections or higher hotness. | ||
| 43 | -- Check whether the hotspot experts are concentrated on the same rank or a small number of ranks. | ||
| 44 | -- Check whether the same rank handles higher hotspot loads across multiple layers. | ||
| 45 | - | ||
| 46 | -If the hotspots are distributed across multiple ranks, their impact may be limited. If the hotspots are concentrated on a small number of ranks, they are more likely to cause those ranks to become performance bottlenecks. | ||
| 47 | - | ||
| 48 | -### Step 4: Determining Whether EPLB Is Effective | ||
| 49 | - | ||
| 50 | -Use the hotspot distribution before and after the EPLB update, together with the EPLB configuration and service startup parameters in Grafana, to determine whether load balancing is effective: | ||
| 51 | - | ||
| 52 | -- If `update_max / update_mean` and `imbalance` decrease after the update, EPLB generally has mitigated the hotspots. | ||
| 53 | -- If the hotspots remain concentrated on the same group of experts or the same ranks after the update, further investigate the EPLB configuration, expert mapping configuration, and request input distribution. | ||
| 54 | -- If the EPLB update itself takes excessive time, assess whether the update overhead negates the load-balancing benefits. | ||
| 55 | - | ||
| 56 | -This step determines whether to adjust EPLB parameters or investigate the expert mapping configuration, business input distribution, or routing strategy. | ||
| 57 | - | ||
| 58 | -### Step 5: Using the Offline Profiler to Verify Whether the Hotspots Have Caused Some Ranks to Run More Slowly | ||
| 59 | - | ||
| 60 | -Online metrics can indicate which experts are hot, but `msServiceProfiler` should also be used to collect MoE-related operator and communication data to verify whether the hotspots have already slowed execution: | ||
| 61 | - | ||
| 62 | -- Compare the `GroupedMatmul` execution durations across ranks/devices to verify whether hotspot ranks have longer computation durations. | ||
| 63 | -- Check the execution durations of `MoeDistributeDispatch` and `MoeDistributeCombine` to verify whether communication overhead is amplified by the hotspots. | ||
| 64 | -- Check the trace to determine whether a small number of ranks have longer execution durations in the MoE layer while other ranks wait for synchronization. | ||
| 65 | - | ||
| 66 | -Only when hotspot experts, hotspot ranks, and slow operators/communication occur within the same time window can the root cause be narrowed down to EP load imbalance. | ||
| 67 | - | ||
| 68 | -## Root Cause | ||
| 69 | - | ||
| 70 | -The expert load is unevenly distributed across EP, causing a small number of experts or ranks to continuously handle higher request loads and further making them performance bottlenecks for MoE computation or communication. Common root causes include concentrated business input distributions, EPLB being disabled or improperly configured, uneven expert mapping, concentration of hotspot experts, and abnormal execution performance of individual ranks/devices. | ||
| 71 | - | ||
| 72 | -## Resolution | ||
| 73 | - | ||
| 74 | -- **EPLB is disabled or ineffective:** Enable EPLB and adjust the update interval, window length, migration threshold, or expert remapping strategy. | ||
| 75 | -- **Hotspot experts are concentrated on a small number of ranks:** Adjust expert placement or mapping to distribute hotspot experts across more ranks. | ||
| 76 | -- **Input distribution causes routing concentration:** Analyze business request types based on request logs or load-testing datasets and, if necessary, segment traffic or isolate input distributions. | ||
| 77 | -- **Amplified communication overhead:** Check `dispatch` or `combine` communication duration and optimize the parallelism configuration or communication path to prevent hotspot ranks from simultaneously handling higher computation and communication loads. | ||
| 78 | -- **Individual ranks are abnormally slow:** First investigate device status, process load, and operator execution issues to avoid misidentifying device problems as routing imbalance. | ||
| 79 | - | ||
| 80 | -After the issue is addressed, observe whether the hotspot distribution is significantly mitigated, the execution durations of MoE operators/communications decrease, and decode latency and throughput recover. | ||
| 81 | - | ||
| 82 | -## Methodology Summary | ||
| 83 | - | ||
| 84 | -For EP load imbalance scenarios, first use `ms-service-metric` to monitor MoE-related execution durations, expert hotspot distribution, and changes in hotspot distribution before and after EPLB updates to verify whether persistent hotspot experts or ranks exist. After verifying the hotspots, use `msServiceProfiler` to collect MoE operator and communication data and compare the execution durations of operations such as `GroupedMatmul`, `dispatch`, and `combine` to determine whether the hotspots have actually created performance bottlenecks, avoiding misidentification of short-term input fluctuations or individual device anomalies as EP load imbalance. | ||
| 85 | - | ||
| 86 | -## Suggestions for Tool Improvements | ||
| 87 | - | ||
| 88 | -### `ms-service-metric` | ||
| 89 | - | ||
| 90 | -Currently, `ms-service-metric` can display hotspot distributions before and after EPLB updates and expert hotspot metrics. It is recommended to add top hotspot lists by layer, rank, and expert dimensions to directly show whether hotspot experts are concentrated on a small number of ranks. | ||
| 91 | - | ||
| 92 | -### `msServiceProfiler` | ||
| 93 | - | ||
| 94 | -Currently, `msServiceProfiler` can use MoE operator and communication durations to verify whether hotspots have created performance bottlenecks. It is recommended to add a correlation view linking "hotspot expert → rank/device → MoE operator execution duration" to offline reports. | ||
| @@ -1,225 +0,0 @@ | |||
| 1 | -# Troubleshooting Guide: Framework Scheduling and Dispatch Synchronization | ||
| 2 | - | ||
| 3 | -## Scenario Description | ||
| 4 | - | ||
| 5 | -In foundation model inference service scenarios, the framework typically needs to perform request queuing, batch scheduling, host-side task dispatch, device-side execution, and cross-node or cross-device synchronization. If task dispatch timing differs across nodes or devices, issues such as performance discrepancies among devices, abnormal synchronization wait duration, first-token latency fluctuations, and reduced throughput may occur. | ||
| 6 | - | ||
| 7 | -Using prefill/decode (PD) disaggregation and multi-node concurrent inference as an example, this document describes how to use `msServiceProfiler` to collect scheduling-path data, identify framework scheduling and dispatch synchronization issues, and select optimization solutions based on consistency requirements. | ||
| 8 | - | ||
| 9 | -## Symptoms | ||
| 10 | - | ||
| 11 | -**Typical Symptoms** | ||
| 12 | - | ||
| 13 | -- The model execution start time differs significantly across nodes. Some nodes have already started device execution, while others are still in host-side dispatch or scheduling wait. | ||
| 14 | -- Within the same iteration, the durations of `BatchSchedule`, `forward`, or custom spans differ significantly across devices, resulting in performance discrepancies among devices. | ||
| 15 | -- Long gaps exist before and after synchronization points, with more than 90 ms of synchronization wait in the end-to-end latency. | ||
| 16 | -- Significant P90/P99 fluctuations are observed in `Request_Latency_curve` or `First_Token_Latency_curve`, while average throughput does not meet expectations. | ||
| 17 | -- Under high concurrency, critical scheduling threads are preempted by non-critical threads, increasing the wait duration of the main thread. | ||
| 18 | - | ||
| 19 | -**Impact** | ||
| 20 | - | ||
| 21 | -| Item | Symptom | | ||
| 22 | -| --- | --- | | ||
| 23 | -| First-token latency | Scheduling wait increases during the prefill stage, resulting in higher first-token P90/P99 latency. | | ||
| 24 | -| Decode throughput | Some faster ranks wait for slower ranks, and decode steps are prolonged by synchronization points. | | ||
| 25 | -| Resource utilization | Device execution gaps increase, resulting in lower AI Core utilization. | | ||
| 26 | -| Stability | Tail latency increases with traffic fluctuations, and cross-node synchronization is more likely to be delayed by slower nodes. | | ||
| 27 | - | ||
| 28 | -## Data Collection | ||
| 29 | - | ||
| 30 | -### Function Description | ||
| 31 | - | ||
| 32 | -Use `msServiceProfiler` to collect `Span`, `Event`, `Metric`, and `Link` data for key stages, including framework scheduling, host-side dispatch, device execution, and synchronization wait. Combine these data with `BatchSchedule.csv`, `forward.csv`, and `Request_Latency_curve` to determine whether scheduling and dispatch are synchronized. | ||
| 33 | - | ||
| 34 | -### Precautions | ||
| 35 | - | ||
| 36 | -- Reproduce the issue in a stress-testing environment before enabling data collection to avoid affecting online services due to an excessive collection scope. | ||
| 37 | -- In multi-node scenarios, synchronize the system time across nodes before data collection. Otherwise, timeline alignment may be inaccurate. | ||
| 38 | -- To analyze the host-to-device dispatch duration, enable the ACL task duration-related collection options in the configuration. Note that this capability may introduce additional performance overhead. | ||
| 39 | -- If the dynamic collection capability of msProf is already enabled, do not enable collection options that conflict with it. | ||
| 40 | - | ||
| 41 | -### Configuration Example | ||
| 42 | - | ||
| 43 | -Create `ms_service_profiler_config.json` and enable service profile data collection. | ||
| 44 | - | ||
| 45 | -```json | ||
| 46 | -{ | ||
| 47 | - "enable": 1, | ||
| 48 | - "prof_dir": "${HOME}/.ms_server_profiler", | ||
| 49 | - "profiler_level": "INFO", | ||
| 50 | - "acl_task_time": 1, | ||
| 51 | - "acl_prof_task_time_level": "L0" | ||
| 52 | -} | ||
| 53 | -``` | ||
| 54 | - | ||
| 55 | -Set the environment variable and start the service. | ||
| 56 | - | ||
| 57 | -```bash | ||
| 58 | -export SERVICE_PROF_CONFIG_PATH=/path/to/ms_service_profiler_config.json | ||
| 59 | -``` | ||
| 60 | - | ||
| 61 | -### Instrumentation Recommendations | ||
| 62 | - | ||
| 63 | -Add span collection to key stages in the framework scheduling path. | ||
| 64 | - | ||
| 65 | -```C++ | ||
| 66 | -auto scheduleSpan = PROF(INFO, SpanStart("FrameworkSchedule")); | ||
| 67 | - | ||
| 68 | -// Request dequeue, batch construction, strategy selection, and other scheduling logic | ||
| 69 | - | ||
| 70 | -PROF(scheduleSpan.SpanEnd()); | ||
| 71 | - | ||
| 72 | -auto hostSubmitSpan = PROF(INFO, SpanStart("HostSubmit")); | ||
| 73 | - | ||
| 74 | -// Host-side task dispatch, stream binding, communication task submission, and other logic | ||
| 75 | - | ||
| 76 | -PROF(hostSubmitSpan.SpanEnd()); | ||
| 77 | - | ||
| 78 | -auto deviceExecSpan = PROF(INFO, SpanStart("DeviceExecute")); | ||
| 79 | - | ||
| 80 | -// Device-side computation or waiting for execution to complete | ||
| 81 | - | ||
| 82 | -PROF(deviceExecSpan.SpanEnd()); | ||
| 83 | -``` | ||
| 84 | - | ||
| 85 | -Add `Event` and `Metric` collection for synchronization points and queue backlog. | ||
| 86 | - | ||
| 87 | -```C++ | ||
| 88 | -PROF(INFO, Event("BeforeGlobalSync")); | ||
| 89 | -PROF(INFO, Metric("dispatchQueueSize", queueSize).MetricScope("scheduler", rankId).Launch()); | ||
| 90 | -PROF(INFO, Metric("syncWaitMs", syncWaitMs).MetricScope("rank", rankId).Launch()); | ||
| 91 | -PROF(INFO, Event("AfterGlobalSync")); | ||
| 92 | -``` | ||
| 93 | - | ||
| 94 | -For cross-thread or cross-module tracing, use `Link` to associate request IDs and avoid capturing only partial execution durations. | ||
| 95 | - | ||
| 96 | -```C++ | ||
| 97 | -PROF(INFO, Link("request_in_scheduler", "request_in_executor")); | ||
| 98 | -``` | ||
| 99 | - | ||
| 100 | -## Troubleshooting Method | ||
| 101 | - | ||
| 102 | -1. Observe the start time and durations of the same batch across different processes and devices in `BatchSchedule.csv`. | ||
| 103 | - - If the start time differs significantly, first investigate scheduling threads, host-side dispatch queues, cross-node clock synchronization, and load-balancing strategies. | ||
| 104 | - - If the start time is close but the end time differs significantly, first investigate device execution, uneven expert loads, communication wait, and differences in operator duration. | ||
| 105 | - | ||
| 106 | -2. Compare the `FrameworkSchedule`, `HostSubmit`, and `DeviceExecute` spans. | ||
| 107 | - - **Long `FrameworkSchedule` duration:** indicates a bottleneck in framework scheduling, which may be caused by synchronization queues, serialized transactions, lock contention, or batch processing strategies. | ||
| 108 | - - **Long `HostSubmit` duration:** indicates insufficient host-side dispatch capability, which may be caused by single-threaded submission, stream management blocking, or serialized communication task submission. | ||
| 109 | - - **A gap before `DeviceExecute`:** indicates that task scheduling has completed but the task has not entered device execution in a timely manner. Check the device queue, synchronization points, and upstream dispatch timing. | ||
| 110 | - | ||
| 111 | -3. Check the `syncWaitMs` and `dispatchQueueSize` metrics. | ||
| 112 | - - If `syncWaitMs` remains high on some ranks, this usually indicates that faster ranks are waiting for slower ranks. | ||
| 113 | - - If `dispatchQueueSize` periodically builds up, this usually indicates a mismatch between the production rate of scheduling threads and the consumption rate of execution threads. | ||
| 114 | - - If the queue size is not high but the wait duration is high, cross-node synchronization, communication, or strong-consistency barriers are usually the bottleneck. | ||
| 115 | - | ||
| 116 | -4. Combine `Request_Latency_curve` and `First_Token_Latency_curve` to determine the user-side impact. | ||
| 117 | - - If the average latency changes little but P99 increases significantly, the issue mainly affects tail latency. | ||
| 118 | - - If both the average latency and P99 increase, the scheduling and dispatch path has become an overall bottleneck. | ||
| 119 | - | ||
| 120 | -## Cause Analysis and Solutions | ||
| 121 | - | ||
| 122 | -### Distributed Scheduling Differences Causing Performance Discrepancies Among Devices | ||
| 123 | - | ||
| 124 | -**Cause** | ||
| 125 | - | ||
| 126 | -In PD disaggregation or multi-node deployment scenarios, model execution start time varies across nodes. Faster nodes reach synchronization points earlier and wait for slower nodes, resulting in significant synchronization wait. | ||
| 127 | - | ||
| 128 | -**Solution** | ||
| 129 | - | ||
| 130 | -- Adjust the scheduling strategy to use unified host-side dispatch and allow devices to execute tasks from their local queues, reducing differences in execution start time across nodes. | ||
| 131 | -- Add time-window constraints to cross-node request allocation to avoid splitting the same batch across nodes with significantly different states. | ||
| 132 | -- Monitor the `HostSubmit` start time by rank and trigger alerts or a degradation strategy when the difference exceeds a threshold. | ||
| 133 | -- Add lightweight alignment logic before strong synchronization stages to prevent individual nodes from entering the wait state too early. | ||
| 134 | - | ||
| 135 | -### Scheduling Serialization Causing Bottlenecks | ||
| 136 | - | ||
| 137 | -**Cause** | ||
| 138 | - | ||
| 139 | -The synchronized scheduling mode requires each partition or round of tasks to be completed strictly in sequence. If a partition contains thousands of tasks, the scheduling thread must process queues, transactions, locks, and state updates serially, amplifying dispatch latency. | ||
| 140 | - | ||
| 141 | -**Solution** | ||
| 142 | - | ||
| 143 | -- If the workload permits weak consistency, change synchronized scheduling to asynchronous scheduling to reduce unnecessary blocking. | ||
| 144 | -- If strong consistency is required, increase the number of scheduling partitions, M, and use additional scheduling resources to reduce queue wait duration within each partition. | ||
| 145 | -- Split scheduling state into request-level, batch-level, and device-level state to reduce the granularity of global locks. | ||
| 146 | -- Move duration statistics, log persistence, and low-priority state updates out of the critical path. | ||
| 147 | - | ||
| 148 | -### Asynchronous Scheduling Lacking Backpressure Control | ||
| 149 | - | ||
| 150 | -**Cause** | ||
| 151 | - | ||
| 152 | -Asynchronous scheduling can reduce blocking, but without queue limits, priority control, and result collection mechanisms, it may cause task accumulation, increased out-of-order execution, or degraded tail latency. | ||
| 153 | - | ||
| 154 | -**Solution** | ||
| 155 | - | ||
| 156 | -- Use a `Future` mechanism or dual-thread architecture to decouple the schedule thread from the generator thread. | ||
| 157 | -- The schedule thread handles batch decisions and task submission, while the generator thread handles result consumption, post-processing, and triggering of the next round. | ||
| 158 | -- Use a thread-safe queue to transfer tasks between threads, and use events, condition variables, or lightweight signals to control wake-up. | ||
| 159 | -- Set queue high-water marks and timeout policies to prevent asynchronous tasks from accumulating indefinitely. | ||
| 160 | - | ||
| 161 | -The example workflow is as follows: | ||
| 162 | - | ||
| 163 | -```text | ||
| 164 | -Request queuing -> Schedule thread constructs batches -> HostSubmit asynchronously dispatches tasks -> Generator thread consumes results -> Trigger next decode round | ||
| 165 | -``` | ||
| 166 | - | ||
| 167 | -### Mismatched Pipeline Scheduling Strategy | ||
| 168 | - | ||
| 169 | -**Cause** | ||
| 170 | - | ||
| 171 | -Synchronous pipelines provide better memory efficiency but can easily be delayed by slower stages. Asynchronous pipelines provide higher statistical efficiency but may introduce weight-version differences or discrepancy correction costs. | ||
| 172 | - | ||
| 173 | -**Solution** | ||
| 174 | - | ||
| 175 | -- For scenarios with high device memory pressure, prioritize synchronous pipelines and optimize memory scheduling through dynamic programming. | ||
| 176 | -- For training or generation scenarios where throughput is prioritized and some statistical differences are acceptable, use asynchronous pipelines together with learning rate scheduling, discrepancy correction, or inter-stage buffering. | ||
| 177 | -- For complex dependency graphs, use BSP superstep synchronization to control global consistency and use asynchronous execution within each superstep to improve resource utilization. | ||
| 178 | - | ||
| 179 | -### Improper Thread QoS Resource Allocation | ||
| 180 | - | ||
| 181 | -**Cause** | ||
| 182 | - | ||
| 183 | -Under high concurrency, critical scheduling threads, host-side dispatch threads, or result collection threads may be preempted by logging, monitoring, or low-priority post-processing threads, increasing the wait duration of the main thread. | ||
| 184 | - | ||
| 185 | -**Solution** | ||
| 186 | - | ||
| 187 | -- Increase the QoS level of the schedule thread, HostSubmit thread, and communication submission thread. | ||
| 188 | -- Lower the priority of non-critical threads such as logging, periodic monitoring, and statistical aggregation. | ||
| 189 | -- Bind critical threads to stable CPU cores to reduce thread migration. | ||
| 190 | -- Use Metric collection to monitor the queue length, wake-up interval, and synchronization wait duration of critical threads and evaluate the benefits of QoS adjustments. | ||
| 191 | - | ||
| 192 | -## Optimization Verification | ||
| 193 | - | ||
| 194 | -After optimization, collect profile data again under the same stress-testing traffic and compare the following metrics. | ||
| 195 | - | ||
| 196 | -| Metric | Expected Result | | ||
| 197 | -| --- | --- | | ||
| 198 | -| `FrameworkSchedule` duration | Average duration decreases, and P99 becomes more stable. | | ||
| 199 | -| HostSubmit start time difference | The difference in start time across ranks decreases. | | ||
| 200 | -| `syncWaitMs` | Synchronization wait decreases significantly, and the performance discrepancy between faster and slower ranks is reduced. | | ||
| 201 | -| `Request_Latency_curve` | End-to-end P90/P99 latency decreases. | | ||
| 202 | -| `First_Token_Latency_curve` | First-token tail latency decreases. | | ||
| 203 | -| Device utilization | Execution gaps decrease and utilization increases. | | ||
| 204 | - | ||
| 205 | -If synchronization wait remains high after optimization, continue investigating the following items. | ||
| 206 | - | ||
| 207 | -- Check whether the system time is synchronized across nodes. | ||
| 208 | -- Check whether network communication duration increases around synchronization points. | ||
| 209 | -- Check whether any devices have abnormal operator durations or uneven expert loads. | ||
| 210 | -- Check whether the number of scheduling partitions (`M`) is insufficient. | ||
| 211 | -- Check whether backpressure occurs in asynchronous queues or results are not collected in a timely manner. | ||
| 212 | - | ||
| 213 | -## Recommended Strategies | ||
| 214 | - | ||
| 215 | -| Workload Requirement | Recommended Solution | | ||
| 216 | -| -------------------- | ------------------- | | ||
| 217 | -| Weak consistency is acceptable | Prioritize asynchronous scheduling and use a Future mechanism or dual-thread architecture to reduce synchronization on the critical path. | | ||
| 218 | -| Strong consistency is required | Retain synchronization barriers, increase the number of scheduling partitions (`M`), and optimize unified host-side dispatch and device execution alignment. | | ||
| 219 | -| Significant performance discrepancies among devices across nodes | Prioritize optimization of the distributed scheduling strategy and reduce differences in `HostSubmit` and `DeviceExecute` start time across ranks. | | ||
| 220 | -| Complex dependency scenarios | Use BSP superstep synchronization to control consistency and combine work stealing or local asynchronous execution within each superstep. | | ||
| 221 | -| Abnormal tail latency under high concurrency | Adjust the QoS of critical threads, split global locks, and add queue backpressure and priority controls. | | ||
| 222 | - | ||
| 223 | -## Summary | ||
| 224 | - | ||
| 225 | -The core issue with framework scheduling and dispatch synchronization is the conflict between the strictness of synchronization mechanisms and performance requirements. During troubleshooting, first use `msServiceProfiler` to break down the scheduling path into stages such as `FrameworkSchedule`, `HostSubmit`, `DeviceExecute`, and `SyncWait`, and then combine `BatchSchedule`, `Request_Latency`, and `First_Token_Latency` to identify the bottleneck. During optimization, select a solution based on service consistency requirements: prioritize asynchronous scheduling in weak-consistency scenarios, while in strong-consistency scenarios, prioritize optimizing distributed dispatch, increasing scheduling partitions, and reducing differences in execution start time across ranks. | ||
| @@ -1,41 +1,41 @@ | |||
| 1 | # GIL Contention Analysis | 1 | # GIL Contention Analysis |
| 2 | 2 | ||
| 3 | -## Background | 3 | +## 1. Background |
| 4 | 4 | ||
| 5 | Python uses a core mechanism called the Global Interpreter Lock (GIL) that restricts Python bytecode execution to a single thread at any given time, preventing multithreaded applications from achieving true parallel execution of computational tasks. | 5 | Python uses a core mechanism called the Global Interpreter Lock (GIL) that restricts Python bytecode execution to a single thread at any given time, preventing multithreaded applications from achieving true parallel execution of computational tasks. |
| 6 | -The customer's service model is developed in Python and extensively uses a multithreaded architecture to perform high-frequency operations such as operator dispatch, memory copies, and task scheduling in parallel. In concurrent multithreaded scenarios, multiple application threads continuously compete for the single GIL, frequently resulting in lock contention, thread blocking, and context switching. In particular, a thread that holds the GIL for an extended period can further exacerbate uneven thread scheduling and reduce effective compute utilization, degrading overall model performance. | 6 | +The customer's business model in this case is developed based on Python, and the business logic extensively adopts a multithreaded architecture to execute high-frequency operations such as operator dispatch, memory data transfer, and task scheduling in parallel. In multithreaded concurrent scenarios, multiple business threads continuously compete for the single GIL, frequently triggering behaviors such as lock preemption, thread blocking, and context switching. In particular, when abnormal scenarios occur in which a thread holds the GIL for a long time without releasing it in a timely manner, the problems of uneven thread scheduling and reduced effective computing resource utilization are further aggravated, ultimately leading to overall performance degradation of the model. |
| 7 | 7 | ||
| 8 | -## Symptoms | 8 | +## 2. Symptoms |
| 9 | 9 | ||
| 10 | After the customer's existing Python model was migrated to and deployed on the Ascend platform, its overall performance failed to meet the expected targets, with long execution durations and insufficient task throughput. | 10 | After the customer's existing Python model was migrated to and deployed on the Ascend platform, its overall performance failed to meet the expected targets, with long execution durations and insufficient task throughput. |
| 11 | Preliminary investigation confirmed that the customer's service had no operator errors, data anomalies, or hardware resource bottlenecks. Further investigation based on the characteristics of the service code revealed extensive multithreaded concurrent operations in the core service path. This indicated a performance bottleneck caused by abnormal GIL contention in Python multithreading. | 11 | Preliminary investigation confirmed that the customer's service had no operator errors, data anomalies, or hardware resource bottlenecks. Further investigation based on the characteristics of the service code revealed extensive multithreaded concurrent operations in the core service path. This indicated a performance bottleneck caused by abnormal GIL contention in Python multithreading. |
| 12 | 12 | ||
| 13 | -## Troubleshooting Process | 13 | +## 3. Troubleshooting Process |
| 14 | 14 | ||
| 15 | -To accurately locate abnormal code paths and thread behavior related to GIL contention, holding, and release, the self-developed `gil_tracer` tool was used for dedicated data analysis. The complete troubleshooting process is as follows: | 15 | +To accurately locate abnormal code paths and thread behavior related to GIL lock preemption, holding, and release, the self-developed gil_tracer tool was used for dedicated data analysis. The complete troubleshooting process is as follows: |
| 16 | 16 | ||
| 17 | -1. **Data collection:** Use the [`gil_tracer` tool](../../../misc/gil_tracer/README_EN.md) to continuously capture data from the customer's process, recording comprehensive behavior data for GIL contention, holding, voluntary release, involuntary switching, blocking, and waiting across all service threads, and export standardized `gil_trace` log data. | 17 | +1. **Data collection:** Use the [gil_tracer](../../../misc/gil_tracer/README_EN.md) tool to continuously capture data from the customer's business process, recording comprehensive behavior data for all business threads, including GIL lock preemption, holding, active release, passive switching, and blocking waits, and export standardized `gil_trace` log data. |
| 18 | 2. **Joint data analysis:** Cross-reference and correlate the GIL behavior data in `gil_trace` with the service Profiler's profile data to determine the relationships among thread execution duration, CPU utilization, task blocking periods, and GIL status. | 18 | 2. **Joint data analysis:** Cross-reference and correlate the GIL behavior data in `gil_trace` with the service Profiler's profile data to determine the relationships among thread execution duration, CPU utilization, task blocking periods, and GIL status. |
| 19 | -3. **Abnormal code path identification:** Accurately identify abnormal behavior through data analysis. Some service threads hold the GIL for an extended period without voluntarily releasing it, causing other ready threads to remain blocked while waiting for the GIL and preventing them from being scheduled normally. This creates a severe thread scheduling bottleneck and identifies the core code logic responsible for the performance issue. | 19 | +3. **Abnormal code path identification:** Through data analysis, abnormal behaviors were accurately identified: in the execution logic of some business threads, the GIL lock was held for a long time without active release, causing the remaining ready threads to remain in a lock-waiting blocked state and unable to be scheduled for normal execution, forming a severe thread scheduling bottleneck. The core code logic causing the performance issue was ultimately located. |
| 20 | 20 | ||
| 21 | -## Root Causes | 21 | +## 4. Root Causes |
| 22 | 22 | ||
| 23 | 1. **Inherent mechanism-level bottleneck:** The fact that only one thread can execute Python bytecode under the GIL at a time prevents pure Python multithreading from utilizing multicore compute resources in parallel. Lock contention overhead is therefore inherent in highly concurrent multithreaded scenarios. | 23 | 1. **Inherent mechanism-level bottleneck:** The fact that only one thread can execute Python bytecode under the GIL at a time prevents pure Python multithreading from utilizing multicore compute resources in parallel. Lock contention overhead is therefore inherent in highly concurrent multithreaded scenarios. |
| 24 | 2. **Service code implementation defect (core root cause):** The customer's multithreaded service logic was not designed appropriately. Some worker threads held the GIL for an extended period while executing time-consuming logic without voluntarily releasing it, and no appropriate lock release or thread-yielding mechanism was provided. | 24 | 2. **Service code implementation defect (core root cause):** The customer's multithreaded service logic was not designed appropriately. Some worker threads held the GIL for an extended period while executing time-consuming logic without voluntarily releasing it, and no appropriate lock release or thread-yielding mechanism was provided. |
| 25 | 3. **Cascading performance impact:** Abnormal GIL holding causes other service threads to continuously contend for the GIL and remain blocked while waiting. This results in imbalanced thread scheduling and frequent context switching, with substantial compute resources wasted on lock contention and thread waiting. Consequently, overall model execution efficiency is significantly reduced, causing the migrated model to fail to meet its performance targets. | 25 | 3. **Cascading performance impact:** Abnormal GIL holding causes other service threads to continuously contend for the GIL and remain blocked while waiting. This results in imbalanced thread scheduling and frequent context switching, with substantial compute resources wasted on lock contention and thread waiting. Consequently, overall model execution efficiency is significantly reduced, causing the migrated model to fail to meet its performance targets. |
| 26 | 26 | ||
| 27 | -## Methodology Summary | 27 | +## 5. Methodology Summary |
| 28 | 28 | ||
| 29 | For Python-based model migration involving multithreaded services, performance degradation, and low throughput, a standardized troubleshooting process can be established to quickly identify GIL-related performance issues: | 29 | For Python-based model migration involving multithreaded services, performance degradation, and low throughput, a standardized troubleshooting process can be established to quickly identify GIL-related performance issues: |
| 30 | - | 30 | + |
| 31 | 1. **Initial screening:** Determine whether the service contains extensive multithreaded concurrent logic, and rule out common performance bottlenecks related to hardware, operators, data paths, and environment configuration. | 31 | 1. **Initial screening:** Determine whether the service contains extensive multithreaded concurrent logic, and rule out common performance bottlenecks related to hardware, operators, data paths, and environment configuration. |
| 32 | -2. **Dedicated data collection:** Prioritize the use of the `gil_tracer` tool to collect comprehensive data on GIL contention, holding, release, blocking, and waiting in the customer's process. | 32 | +2. **Dedicated data collection:** Prioritize the use of the gil_tracer tool to collect comprehensive data on GIL lock preemption, holding, release, and blocking in the customer's process. |
| 33 | -3. **Joint analysis:** Combine the data with the Profiler's profile data to correlate GIL behavior with execution bottlenecks and distinguish normal lock contention from abnormal lock holding and prolonged lock waiting. | 33 | +3. **Joint analysis:** Combine the data with the Profiler's profile data to correlate lock behavior with execution bottlenecks and distinguish normal lock contention from abnormal lock holding and deadlock waiting scenarios. |
| 34 | 4. **Precise identification:** Identify abnormal code segments involving prolonged lock holding, frequent lock contention, or severe thread blocking to guide service code optimization. | 34 | 4. **Precise identification:** Identify abnormal code segments involving prolonged lock holding, frequent lock contention, or severe thread blocking to guide service code optimization. |
| 35 | 35 | ||
| 36 | -## Suggestions for Tool Improvements | 36 | +## 6. Suggestions for Tool Improvement |
| 37 | 37 | ||
| 38 | -The `gil_tracer` tool can comprehensively collect GIL behavior data, but its thread identification capabilities are insufficient. To further improve troubleshooting efficiency, the following enhancements are recommended: | 38 | +The gil_tracer tool can comprehensively collect GIL behavior data, but its thread identification capabilities are insufficient. To further improve troubleshooting efficiency, the following enhancements are recommended: |
| 39 | 39 | ||
| 40 | -1. **Collecting and displaying thread names:** Add service thread names and thread IDs to trace logs and visualization results so that abnormal threads can be directly associated with their service functions, such as data transfer threads and operator dispatch threads. This eliminates the need for manual code tracing and enables rapid identification of abnormal functional threads. | 40 | +1. **Collect and display thread names:** Add service thread names and thread IDs to trace logs and visualization results so that abnormal threads can be directly associated with their service functions, such as data transfer threads and operator dispatch threads. This eliminates the need for manual code tracing and enables rapid identification of abnormal functional threads. |
| 41 | -2. **Optimizing abnormality aggregation and statistics:** Add statistics for prolonged GIL holding, frequent lock contention, and thread blocking time, and automatically aggregate data for abnormal threads to provide an intuitive view of bottlenecks and reduce the manual analysis effort. | 41 | +2. **Optimize abnormality aggregation and statistics:** Add statistics for prolonged GIL holding, frequent lock contention, and thread blocking time, and automatically aggregate data for abnormal threads to provide an intuitive view of bottlenecks and reduce the manual analysis effort. |
Mdocs/en/best_practices/irq_interruption.md+38-36File content is under review, please try again later
Mdocs/en/best_practices/kernel_thread_switching.md+22-20File content is under review, please try again later
| @@ -1,91 +0,0 @@ | |||
| 1 | -# Insufficient KV Blocks | ||
| 2 | - | ||
| 3 | -## Background | ||
| 4 | - | ||
| 5 | -KV blocks are used to hold the KV cache for requests. After a request enters the prefill or decode stage, the scheduler continuously needs to allocate KV blocks. If there are insufficient available KV blocks, a request may be queued, preempted, or recomputed because it cannot obtain the required KV cache resources, even when compute resources are still available. | ||
| 6 | - | ||
| 7 | -## Source | ||
| 8 | - | ||
| 9 | -Inference | ||
| 10 | - | ||
| 11 | -## Symptoms | ||
| 12 | - | ||
| 13 | -Users typically observe performance degradation rather than a direct indication of "insufficient KV blocks": | ||
| 14 | - | ||
| 15 | -- As test concurrency continues to increase, throughput stops increasing, while first-token latency and end-to-end latency increase significantly. | ||
| 16 | -- The service has a relatively large number of waiting/pending requests, and some requests remain unable to enter the decode stage for an extended period. | ||
| 17 | -- NPU utilization does not necessarily remain at full capacity, but request queue wait time continues to increase. | ||
| 18 | -- Monitoring shows that KV cache utilization remains high for an extended period, `free_kvcache_blocks` remains close to 0, or metrics related to preemption or allocation failures continue to increase. | ||
| 19 | - | ||
| 20 | -## Troubleshooting Process | ||
| 21 | - | ||
| 22 | -### Step 1: Verifying Whether the Issue Is Caused by Increased Queue Wait Time | ||
| 23 | - | ||
| 24 | -In the Grafana service overview or request latency dashboard, check the latency breakdown and first determine which stage accounts for the latency increase: | ||
| 25 | - | ||
| 26 | -- Whether first-token latency has increased. | ||
| 27 | -- Whether request queue/waiting time has increased. | ||
| 28 | -- Whether the number of running requests has not increased significantly while waiting/pending requests continue to accumulate. | ||
| 29 | - | ||
| 30 | -If the latency increase occurs primarily during model execution and NPU utilization remains high, investigate compute bottlenecks first. If the latency increase occurs primarily during the waiting stage, continue the investigation in the scheduling and KV cache areas. | ||
| 31 | - | ||
| 32 | -### Step 2: Verifying Whether the Waiting Is Caused by Insufficient KV Blocks | ||
| 33 | - | ||
| 34 | -In the KV cache, request status, and scheduling dashboards in Grafana, focus on whether the following phenomena occur simultaneously within the same time window: | ||
| 35 | - | ||
| 36 | -- `free_kvcache_blocks` remains low for an extended period, while KV cache utilization approaches the upper limit. | ||
| 37 | -- Waiting/pending requests, queue wait time, or first-token latency increases simultaneously. | ||
| 38 | -- Metrics related to preemption, recomputation, or allocation failures increase during the same period. | ||
| 39 | - | ||
| 40 | -If these three signals are aligned, the requests are likely bottlenecked by KV cache capacity rather than being compute-bound. | ||
| 41 | - | ||
| 42 | -### Step 3: Identifying the Source of Capacity Pressure | ||
| 43 | - | ||
| 44 | -The KV cache usage only indicates that the instance is approaching its capacity limit. To determine whether the pressure is caused by concurrency, request length, traffic distribution, or KV cache configuration, analyze the test configuration, service startup parameters, request logs, and Grafana monitoring data together: | ||
| 45 | - | ||
| 46 | -- Check the test configuration, service startup parameters, or change records to determine whether concurrency, `max_num_seqs`, `max_model_len`, maximum output length, or batch-related configuration has been increased. | ||
| 47 | -- Check request logs, test datasets, or request-length statistics to determine whether requests with long contexts or long outputs are concentrated on the instance. | ||
| 48 | -- Check instance-level monitoring in Grafana to determine whether only some instances are receiving more requests or tokens while other instances still have available capacity. | ||
| 49 | -- Check service startup parameters, device memory configuration, and the total/free KV blocks in Grafana to determine whether the total number of available KV blocks is too small. | ||
| 50 | - | ||
| 51 | -If test traffic is fixed but the proportion of long-input or long-output requests increases, the issue is usually that longer requests consume more blocks. If request lengths remain stable but concurrency increases, the concurrency on a single instance has exceeded the KV cache capacity available to that instance. If only some instances exhaust their blocks, uneven load distribution across instances should also be investigated. | ||
| 52 | - | ||
| 53 | -### Step 4: Using Offline Profiler Data to Identify the Affected Requests and Batches | ||
| 54 | - | ||
| 55 | -If online monitoring indicates insufficient KV blocks, use `msServiceProfiler` to collect `Schedule`, `KVCache`, and `Request` data. Focus on the following three files: | ||
| 56 | - | ||
| 57 | -- `request.csv`: Check whether `queue_wait_time(ms)` and `first_token_latency(ms)` have increased significantly and identify the requests with the longest wait time. | ||
| 58 | -- `batch.csv`: Check whether `used_blocks` and `kvcache_usage_rate` remain high and `free_blocks` remains low for an extended period across consecutive batches, and whether `decode_batch_size` is unable to increase steadily due to insufficient blocks. | ||
| 59 | -- `kvcache.csv`: Check `blocks_allocated` and `blocks_freed`. If `blocks_allocated` continues to exceed `blocks_freed` across multiple time windows and `free_blocks` is exhausted, the root cause can be narrowed down to insufficient KV cache capacity. | ||
| 60 | - | ||
| 61 | -The Profiler analysis should answer two questions: which requests consume the most blocks, and at which batches the scheduler begins queuing or preempting requests after the available blocks are exhausted. | ||
| 62 | - | ||
| 63 | -## Root Causes | ||
| 64 | - | ||
| 65 | -The number of available KV blocks is insufficient, preventing requests from promptly obtaining KV cache resources. Common root causes include excessive concurrency on a single instance, excessively long input or output sequences, insufficient device memory reserved for the KV cache, concentration of long requests on a small number of instances, or scheduling parameters that allow too many requests to enter the scheduler simultaneously. | ||
| 66 | - | ||
| 67 | -## Solutions | ||
| 68 | - | ||
| 69 | -Select an appropriate solution based on the troubleshooting results: | ||
| 70 | - | ||
| 71 | -- **Excessive concurrency:** Reduce per-instance concurrency, `max_num_seqs`, or the ingress traffic throttling threshold to avoid admitting too many requests at once. | ||
| 72 | -- **Requests are too long:** Limit the maximum input or output length, or route long-context requests to instances with greater KV cache capacity. | ||
| 73 | -- **Insufficient total KV blocks on a single instance:** Adjust KV cache-related device memory configuration or increase the proportion of device memory available for the KV cache. If no device memory remains available on a single device, add instances, increase the number of devices, or use devices with greater memory capacity. | ||
| 74 | -- **Uneven traffic distribution:** First address load imbalance across instances so that requests are distributed based on instance capacity and queue status, avoiding premature KV block exhaustion on a small number of instances. | ||
| 75 | -- **Significant preemption/recomputation:** Reduce the number of requests entering the scheduler or adjust the scheduling policy to avoid frequently swapping out requests that have already entered the decode stage. | ||
| 76 | - | ||
| 77 | -After the changes, recheck the same set of signals: whether `free_kvcache_blocks` has returned to a stable level, whether waiting/pending requests have decreased, whether first-token latency has decreased, and whether throughput resumes increasing with concurrency. | ||
| 78 | - | ||
| 79 | -## Methodology Summary | ||
| 80 | - | ||
| 81 | -For scenarios involving insufficient KV blocks, first use `ms-service-metric` to confirm whether the latency increase occurs primarily during queue waiting and the first-token stage, and observe whether KV cache utilization, `free_kvcache_blocks`, and waiting/pending requests become abnormal within the same time window. After online metrics indicate KV cache capacity pressure, use `msServiceProfiler` to collect `request.csv`, `batch.csv`, and `kvcache.csv` to determine whether the issue is caused by request length, concurrency, batch scheduling, or an imbalance between block allocation and release. | ||
| 82 | - | ||
| 83 | -## Suggestions for Tool Improvements | ||
| 84 | - | ||
| 85 | -### `ms-service-metric` | ||
| 86 | - | ||
| 87 | -Currently, `ms-service-metric` can display KV cache utilization, `free_kvcache_blocks`, the number of waiting/pending requests, and first-token latency. Add KV block shortage diagnostic prompts to the existing dashboards and automatically correlate these metrics within the same time window to help determine whether queueing is caused by KV cache capacity pressure. | ||
| 88 | - | ||
| 89 | -### `msServiceProfiler` | ||
| 90 | - | ||
| 91 | -Currently, `msServiceProfiler` can use `request.csv`, `batch.csv`, and `kvcache.csv` to analyze request waiting, batch scheduling, and KV cache allocation/freeing. Add a KV block shortage summary to offline reports to automatically identify time windows in which `free_blocks` remains low, `decode_batch_size` cannot increase, or `blocks_allocated` continuously exceeds `blocks_freed`. | ||
| @@ -1,121 +0,0 @@ | |||
| 1 | -# Impact of KV Cache Transfer on Model Performance | ||
| 2 | - | ||
| 3 | -## Background | ||
| 4 | - | ||
| 5 | -In prefill/decode (PD) disaggregation deployments, after the prefill node completes computing the KV cache for the input sequence, the KV cache must be transferred to the decode node for subsequent token-by-token generation. Cross-node KV cache transfer is a critical path in PD disaggregation, and its latency directly affects the time to first token on the decode node and overall request latency. In distributed KV cache pooling scenarios, loading and writing KV cache across nodes also involves substantial data transfer. Ascend uses the HIXL one-sided communication library and MemFabric's unified cross-node memory addressing technology to optimize the KV cache transfer path. However, insufficient network bandwidth, high communication protocol overhead, excessive memory copies, and insufficient overlap between data transfer and computation can still cause KV cache transfer to become a performance bottleneck in actual deployments. | ||
| 6 | - | ||
| 7 | -## Source | ||
| 8 | - | ||
| 9 | -Inference | ||
| 10 | - | ||
| 11 | -## Symptoms | ||
| 12 | - | ||
| 13 | -Users typically first observe extended request wait time on decode nodes rather than a direct indication of "KV cache transfer overhead." In PD disaggregation scenarios, `queue_wait_time` may be significantly higher, and the interval between the completion of prefill execution and the start of token generation on the decode node may be excessively long. Further observation of PD disaggregation metrics may reveal the following: | ||
| 14 | - | ||
| 15 | -- In `pd_split_communication.csv`, the time difference between `prefill_res_time` and `request_end_time` is excessively long, indicating that KV cache transfer may account for a substantial portion of the execution time. | ||
| 16 | -- In `pd_split_kvcache.csv`, `during_time(ms)`, which indicates the time required to transfer the KV cache from the prefill node to the decode node, is high and positively correlated with `seq_len`. The longer the sequence, the more KV cache data is transferred and the longer the transfer takes. | ||
| 17 | -- In the Timeline view, a noticeable gap can be observed between the end of the `ModelExecute` block on the prefill node and the start of decode execution on the decode node. decode starts only after KV cache transfer is complete. If data transfer and computation do not overlap, this waiting gap directly increases end-to-end latency. | ||
| 18 | -- In distributed KV cache pooling scenarios, the time required to load cached data from remote nodes increases prefill latency. Even when some cache data is available locally, the latency of remote loading may offset the benefits of cache hits. | ||
| 19 | - | ||
| 20 | -## Troubleshooting Process | ||
| 21 | - | ||
| 22 | -### Step 1: Collecting Communication and KV Cache Data with Profiler | ||
| 23 | - | ||
| 24 | -In a multi-node, multi-device PD disaggregation deployment, configure `ms_service_profiler_config.json` consistently on all nodes and set `domain` to `"Request; KVCache; Communication; Schedule; ModelExecute"` to ensure that `Communication` and `KVCache` domain data is collected. After collection is complete, run the following command to parse the data: | ||
| 25 | - | ||
| 26 | -```bash | ||
| 27 | -python3 -m ms_service_profiler.parse --input-path ${PATH}/prof_dir/ | ||
| 28 | -``` | ||
| 29 | - | ||
| 30 | -The parsing process generates files such as `pd_split_communication.csv`, `pd_split_kvcache.csv`, `request.csv`, `batch.csv`, and `chrome_tracing.json`. | ||
| 31 | - | ||
| 32 | -### Step 2: Analyzing KV Cache Transfer Duration in `pd_split_kvcache.csv` | ||
| 33 | - | ||
| 34 | -In `pd_split_kvcache.csv`, examine the KV cache transfer data for each request. Key fields include: | ||
| 35 | - | ||
| 36 | -- `seq_len`: request sequence length, which determines the amount of KV cache data transferred. | ||
| 37 | -- `during_time(ms)`: actual time required to transfer the KV cache from the prefill node to the decode node. | ||
| 38 | -- `block_tables`: information about the blocks being transferred. | ||
| 39 | - | ||
| 40 | -Group requests by `seq_len` and analyze the distribution of `during_time(ms)`, including the average, P90, and P99 values. Calculate the effective transfer bandwidth based on the KV cache data volume and `during_time(ms)`, and compare it with the theoretical network bandwidth. If the effective transfer bandwidth is substantially lower than the theoretical bandwidth, investigate network bandwidth, protocol overhead, memory copies, and other transfer efficiency issues. | ||
| 41 | - | ||
| 42 | -Group the data by `rank` (device ID) to determine whether transfer performance is abnormal on specific devices or links. | ||
| 43 | - | ||
| 44 | -### Step 3: Analyzing End-to-End Communication Timing in `pd_split_communication.csv` | ||
| 45 | - | ||
| 46 | -In `pd_split_communication.csv`, examine the following key timestamps: | ||
| 47 | - | ||
| 48 | -- `http_req_time(ms)`: time when the request arrives. | ||
| 49 | -- `send_request_time(ms)`: time when the prefill node starts sending the request to the decode node. | ||
| 50 | -- `send_request_succ_time(ms)`: time when the request is successfully sent. | ||
| 51 | -- `prefill_res_time(ms)`: time when prefill execution is completed. | ||
| 52 | -- `request_end_time(ms)`: time when request execution is completed. | ||
| 53 | - | ||
| 54 | -Calculate the duration of each stage: | ||
| 55 | - | ||
| 56 | -- Request forwarding duration = `send_request_succ_time(ms)` - `send_request_time(ms)` | ||
| 57 | -- Prefill execution duration = `prefill_res_time(ms)` - `send_request_succ_time(ms)` | ||
| 58 | -- KV cache transfer plus decode execution duration = `request_end_time(ms)` - `prefill_res_time(ms)` | ||
| 59 | - | ||
| 60 | -If the KV cache transfer plus decode execution duration accounts for an excessive proportion of the total duration and is strongly correlated with `seq_len`, further investigate KV cache transfer as a potential bottleneck. The `during_time(ms)` field in `pd_split_kvcache.csv` should be used to confirm whether KV cache transfer itself accounts for a substantial portion of this duration. | ||
| 61 | - | ||
| 62 | -### Step 4: Confirming Transfer and Computation Overlap in the Timeline View | ||
| 63 | - | ||
| 64 | -Open `chrome_tracing.json` and locate the KV cache transfer process for the PD disaggregation scenario in the Timeline view. Observe the gap between the end of the `ModelExecute` block on the prefill node and the start of execution on the decode node. If this gap is consistent with `during_time(ms)` in `pd_split_kvcache.csv`, KV cache transfer can be identified as a direct cause of decode-side waiting. | ||
| 65 | - | ||
| 66 | -Check whether KV cache transfer overlaps with computation in the Timeline. If transfer occurs entirely after prefill execution and before decode execution, transfer and computation do not overlap, indicating an optimization opportunity. | ||
| 67 | - | ||
| 68 | -### Step 5: Monitoring PD Disaggregation Metrics in Grafana | ||
| 69 | - | ||
| 70 | -In a PD disaggregation deployment, monitor the prefill and decode nodes separately. If `waiting_batch_size` remains high and `batch_size` remains low on the decode node while the prefill node is operating normally, the decode node may be waiting for KV cache transfer. Examine the waiting/running state transitions of the decode node in `request_status.csv` to determine whether the waiting time is correlated with KV cache transfer. | ||
| 71 | - | ||
| 72 | -### Step 6: Obtaining Request-Level Statistics with the Multidimensional Analysis Tool | ||
| 73 | - | ||
| 74 | -```bash | ||
| 75 | -msserviceprofiler analyze --input-path=/path/to/input | ||
| 76 | -``` | ||
| 77 | - | ||
| 78 | -Check the statistics for `first_token_latency(ms)` and `waiting_time(ms)` in `request_summary.csv` to determine the proportion of TTFT attributable to waiting time. | ||
| 79 | - | ||
| 80 | -## Root Causes | ||
| 81 | - | ||
| 82 | -Common causes of KV cache transfer affecting model performance include: | ||
| 83 | - | ||
| 84 | -1. **High communication protocol overhead**: When traditional two-sided communication protocols, such as HCCL collective communication, are used for KV cache transfer, the sender and receiver require multiple handshakes and confirmations. This protocol overhead is amplified in the high-frequency, small-packet, one-way communication pattern of PD disaggregation. | ||
| 85 | - | ||
| 86 | -2. **Excessive memory copies**: KV cache data may undergo multiple memory copies from the prefill-side computation buffer along the network transmission path to decode-side working memory. Each copy consumes DMA bandwidth and memory bus resources. Ascend HIXL uses zero-copy transfer, in which RDMA writes directly to remote memory, to eliminate intermediate copies. However, if HIXL is not enabled or is configured incorrectly, the traditional transfer path may still be used. | ||
| 87 | - | ||
| 88 | -3. **Insufficient network bandwidth or link congestion**: KV cache transfer in PD disaggregation requires substantial network bandwidth. Insufficient bandwidth or contention among multiple flows can significantly increase transfer latency. In distributed KV cache pooling scenarios, simultaneous remote-memory reads and writes across multiple nodes may also cause network congestion. | ||
| 89 | - | ||
| 90 | -4. **Insufficient overlap between transfer and computation**: KV cache transfer occurs serially after prefill execution and before decode execution rather than overlapping with computation. Ideally, KV cache transfer should run in parallel with subsequent prefill computation or decode initialization to hide transfer latency. | ||
| 91 | - | ||
| 92 | -5. **Excessive sequence length increasing the amount of transferred data**: In long-sequence scenarios, KV cache data volume increases proportionally with sequence length. For million-token contexts, the KV cache can reach tens of GB, and a single transfer may take several seconds. | ||
| 93 | - | ||
| 94 | -6. **Excessively long data paths in distributed cache pooling architectures**: Solutions such as Mooncake may involve long call chains, with each layer introducing additional latency. Ascend uses a KV Connector to connect directly to the backend, HIXL for zero-copy transfer, and MemFabric for unified memory addressing to shorten the data path. | ||
| 95 | - | ||
| 96 | -## Solutions | ||
| 97 | - | ||
| 98 | -- **High communication protocol overhead**: Enable the Ascend HIXL one-sided communication library instead of traditional two-sided communication protocols. | ||
| 99 | -- **Excessive memory copies**: Use MemFabric's unified cross-node memory addressing to reduce data movement and enable HIXL zero-copy transfer. | ||
| 100 | -- **Insufficient network bandwidth**: Increase network bandwidth or use a high-speed RDMA network. | ||
| 101 | -- **Insufficient overlap between transfer and computation**: Optimize the overlap between transfer and computation, such as through pipeline parallelism, so that transfer runs in parallel with subsequent prefill computation or decode initialization. | ||
| 102 | -- **Excessive data volume**: Quantize or compress the KV cache to reduce the amount of data transferred. | ||
| 103 | -- **Excessively long data path**: In distributed KV cache pooling scenarios, use the KV Connector to connect directly to the backend and shorten the call chain. | ||
| 104 | - | ||
| 105 | -After applying the changes, recheck `during_time(ms)` in `pd_split_kvcache.csv`, decode-node waiting time, and TTFT to determine whether performance has improved. | ||
| 106 | - | ||
| 107 | -## Methodology Summary | ||
| 108 | - | ||
| 109 | -The complete troubleshooting path for this scenario is as follows: first confirm whether the deployment uses PD disaggregation or distributed KV cache pooling; then use `msServiceProfiler` to collect Communication and KVCache domain data and obtain KV cache transfer duration directly from `pd_split_kvcache.csv`; next analyze end-to-end timing with `pd_split_communication.csv` and determine the proportion of the transfer stage in the total duration; finally, use the Timeline view to confirm whether transfer overlaps with computation. | ||
| 110 | - | ||
| 111 | -The core diagnostic logic is as follows: if `during_time(ms)` in `pd_split_kvcache.csv` is high and strongly correlated with `seq_len`, while `request_end_time(ms) - prefill_res_time(ms)` in `pd_split_communication.csv` accounts for an excessive proportion of the total duration, KV cache transfer is likely a bottleneck. If the effective transfer bandwidth is substantially lower than the theoretical bandwidth, investigate network, protocol, and data-transfer efficiency. If the effective transfer bandwidth is normal but the transfer duration remains long, investigate excessive KV cache data volume. | ||
| 112 | - | ||
| 113 | -## Suggestions for Tool Improvements | ||
| 114 | - | ||
| 115 | -### `msServiceProfiler` | ||
| 116 | - | ||
| 117 | -Currently, `msServiceProfiler` can analyze KV cache transfer duration through `pd_split_kvcache.csv` and `pd_split_communication.csv`. Add a transfer bandwidth field to `pd_split_kvcache.csv` to automatically calculate effective transfer bandwidth and facilitate comparison with theoretical bandwidth. Add a transfer-path identifier field, such as HIXL, MemFabric, HCCL, or TCP, to `pd_split_kvcache.csv` to help identify the transfer method currently in use. Add more granular communication-stage breakdowns to `pd_split_communication.csv`, such as "KV cache serialization duration," "network transfer duration," "KV cache deserialization duration," and "memory copy duration." Add a KV cache transfer track to the Timeline view to display the transfer process separately and facilitate analysis of transfer and computation overlap. | ||
| 118 | - | ||
| 119 | -### `ms-service-metric` | ||
| 120 | - | ||
| 121 | -Currently, `ms-service-metric` can display PD disaggregation metrics by node. Add a decode-node waiting-time metric for PD disaggregation scenarios and distinguish between "waiting for KV cache transfer" and "waiting for scheduling." Add an online KV cache transfer latency metric to facilitate real-time monitoring of transfer performance. | ||
| @@ -1,23 +1,23 @@ | |||
| 1 | -# Memory Fragmentation Analysis | 1 | +# Memory Fragmentation |
| 2 | 2 | ||
| 3 | -## Background | 3 | +## 1. Background |
| 4 | 4 | ||
| 5 | In service-based inference scenarios, device memory usage does not necessarily increase sharply over a short period. Instead, it may gradually increase over an extended period. Such issues may be caused by memory leaks at the code level or by the accumulation of memory fragmentation on the framework side or the GE side. | 5 | In service-based inference scenarios, device memory usage does not necessarily increase sharply over a short period. Instead, it may gradually increase over an extended period. Such issues may be caused by memory leaks at the code level or by the accumulation of memory fragmentation on the framework side or the GE side. |
| 6 | 6 | ||
| 7 | -This case summarizes the troubleshooting process for gradually increasing device memory usage based on `torch_npu.profiler` data. | 7 | +This case summarizes the process of locating the "gradually increasing device memory usage" issue based on `torch_npu.profiler` data. |
| 8 | 8 | ||
| 9 | <div align="center"><img src="../figures/profiler_case_frag_overview.png" /></div> | 9 | <div align="center"><img src="../figures/profiler_case_frag_overview.png" /></div> |
| 10 | <div align="center"><b>Figure 1</b> Overview of the troubleshooting process for gradually increasing device memory usage</div> | 10 | <div align="center"><b>Figure 1</b> Overview of the troubleshooting process for gradually increasing device memory usage</div> |
| 11 | 11 | ||
| 12 | -## Symptoms | 12 | +## 2. Symptoms |
| 13 | 13 | ||
| 14 | -During `qwen cosyvoice2` inference, device memory usage begins to increase gradually after several graph inference runs, increasing by more than 10 MB after each run and resulting in an OOM error after approximately 10 hours. The issue cannot be reproduced on GPUs and occurs only on NPUs. | 14 | +During qwen cosyvoice2 inference, device memory usage begins to increase gradually after several graph inference runs, increasing by more than 10 MB each time and eventually causing an OOM error after approximately 10 hours. This issue is not reproduced on GPU and occurs only on NPU. |
| 15 | 15 | ||
| 16 | Based on the symptoms, the issue appears to be a memory leak that occurs after long-term operation. However, according to user feedback, device memory usage continues to increase even after `empty_cache` is enabled. | 16 | Based on the symptoms, the issue appears to be a memory leak that occurs after long-term operation. However, according to user feedback, device memory usage continues to increase even after `empty_cache` is enabled. |
| 17 | 17 | ||
| 18 | -## Troubleshooting Process | 18 | +## 3. Troubleshooting Process |
| 19 | 19 | ||
| 20 | -### 1. Collecting Profile Data Across Steps and Checking Allocated and Reserved Trends | 20 | +### 3.1 Collecting Profile Data Across Steps and Checking Allocated and Reserved Trends |
| 21 | 21 | ||
| 22 | When the initial profiling covers only a single step, it is not possible to determine whether the increase occurs within a step or accumulates across steps. Therefore, expand the profiling range to cover multiple consecutive inference steps and enable memory statistics. | 22 | When the initial profiling covers only a single step, it is not possible to determine whether the increase occurs within a step or accumulates across steps. Therefore, expand the profiling range to cover multiple consecutive inference steps and enable memory statistics. |
| 23 | 23 | ||
| @@ -52,17 +52,17 @@ Analysis of profile data across multiple steps shows: | |||
| 52 | 52 | ||
| 53 | > `allocated` (memory actually used by operators) remains stable, ruling out continuous memory leaks on the operator side. `reserved` (physical memory held by the memory pool) continues to increase, indicating that the allocator is holding an increasing amount of memory but cannot release it. This is a **typical characteristic of memory fragmentation**. | 53 | > `allocated` (memory actually used by operators) remains stable, ruling out continuous memory leaks on the operator side. `reserved` (physical memory held by the memory pool) continues to increase, indicating that the allocator is holding an increasing amount of memory but cannot release it. This is a **typical characteristic of memory fragmentation**. |
| 54 | 54 | ||
| 55 | -### 2. Filtering `operator_memory.csv` to Distinguish GE-Side and Framework-Side Sources | 55 | +### 3.2 Filtering `operator_memory.csv` to Distinguish GE-Side and Framework-Side Sources |
| 56 | 56 | ||
| 57 | After confirming that the issue is related to memory fragmentation, further identify the source of the fragmentation through `operator_memory.csv`: | 57 | After confirming that the issue is related to memory fragmentation, further identify the source of the fragmentation through `operator_memory.csv`: |
| 58 | 58 | ||
| 59 | -- Use the `cann` keyword to filter GE-side memory. `reserved` gradually increases to approximately 800 MB. | 59 | +- Use the cann keyword to filter GE-side memory. reserved gradually increases to approximately 800 MB. |
| 60 | -- Use the `aten` keyword to filter PyTorch-side memory. `reserved` also gradually increases to approximately 800 MB. | 60 | +- Use the aten keyword to filter PyTorch-side memory. reserved also gradually increases to approximately 800 MB. |
| 61 | 61 | ||
| 62 | <div align="center"><img src="../figures/profiler_case_frag_filter.png" /></div> | 62 | <div align="center"><img src="../figures/profiler_case_frag_filter.png" /></div> |
| 63 | <div align="center"><b>Figure 3</b> Filtering GE-side and framework-side sources using keywords in operator_memory.csv</div> | 63 | <div align="center"><b>Figure 3</b> Filtering GE-side and framework-side sources using keywords in operator_memory.csv</div> |
| 64 | 64 | ||
| 65 | -### 3. Validating Fragmentation Characteristics Using Environment Variables | 65 | +### 3.3 Validating Fragmentation Characteristics Using Environment Variables |
| 66 | 66 | ||
| 67 | Enable fragmentation mitigation environment variables on the GE side and the framework side separately for validation: | 67 | Enable fragmentation mitigation environment variables on the GE side and the framework side separately for validation: |
| 68 | 68 | ||
| @@ -78,14 +78,14 @@ The results show that the increase in device memory usage is significantly mitig | |||
| 78 | 78 | ||
| 79 | > After both environment variables are enabled, the increase in `reserved` is significantly suppressed, with the increase reduced from approximately 600 MB to approximately 75 MB. | 79 | > After both environment variables are enabled, the increase in `reserved` is significantly suppressed, with the increase reduced from approximately 600 MB to approximately 75 MB. |
| 80 | 80 | ||
| 81 | -## Conclusions | 81 | +## 4. Conclusions |
| 82 | 82 | ||
| 83 | 1. In short-sequence scenarios, the issue is mainly caused by continuous accumulation of memory fragmentation rather than a traditional code-level memory leak. | 83 | 1. In short-sequence scenarios, the issue is mainly caused by continuous accumulation of memory fragmentation rather than a traditional code-level memory leak. |
| 84 | 2. When `allocated` remains largely unchanged while `reserved` continues to increase, memory fragmentation should be investigated first. | 84 | 2. When `allocated` remains largely unchanged while `reserved` continues to increase, memory fragmentation should be investigated first. |
| 85 | 3. Filtering `operator_memory.csv` allows GE-side and framework-side sources of the increase to be quickly distinguished. | 85 | 3. Filtering `operator_memory.csv` allows GE-side and framework-side sources of the increase to be quickly distinguished. |
| 86 | 4. After enabling `GE_USE_STATIC_MEMORY=3` and `PYTORCH_NPU_ALLOC_CONF=expandable_segments:True`, the increase in `reserved` memory in short-sequence scenarios can be significantly mitigated. | 86 | 4. After enabling `GE_USE_STATIC_MEMORY=3` and `PYTORCH_NPU_ALLOC_CONF=expandable_segments:True`, the increase in `reserved` memory in short-sequence scenarios can be significantly mitigated. |
| 87 | 87 | ||
| 88 | -## Methodology Summary | 88 | +## 5. Methodology Summary |
| 89 | 89 | ||
| 90 | <div align="center"><img src="../figures/profiler_case_frag_methodology.png" /></div> | 90 | <div align="center"><img src="../figures/profiler_case_frag_methodology.png" /></div> |
| 91 | <div align="center"><b>Figure 5</b> Decision flow for the memory fragmentation troubleshooting methodology</div> | 91 | <div align="center"><b>Figure 5</b> Decision flow for the memory fragmentation troubleshooting methodology</div> |
| @@ -95,7 +95,7 @@ The results show that the increase in device memory usage is significantly mitig | |||
| 95 | 3. Filter `operator_memory.csv` using relevant keywords to distinguish GE-side and framework-side sources. | 95 | 3. Filter `operator_memory.csv` using relevant keywords to distinguish GE-side and framework-side sources. |
| 96 | 4. Use environment variables for validation to quickly determine whether the issue can be mitigated by the corresponding environment variables. | 96 | 4. Use environment variables for validation to quickly determine whether the issue can be mitigated by the corresponding environment variables. |
| 97 | 97 | ||
| 98 | -## Suggestions for Tool Improvements | 98 | +## 6. Suggestions for Tool Improvement |
| 99 | 99 | ||
| 100 | - Add dedicated troubleshooting capabilities for GE-side memory fragmentation. | 100 | - Add dedicated troubleshooting capabilities for GE-side memory fragmentation. |
| 101 | - Provide a more intuitive way to distinguish the causes of increases in `allocated` and `reserved`. | 101 | - Provide a more intuitive way to distinguish the causes of increases in `allocated` and `reserved`. |
| @@ -1,14 +1,12 @@ | |||
| 1 | -# Memory Leak Analysis | 1 | +# Memory Leak |
| 2 | 2 | ||
| 3 | -## Background | 3 | +## 1. Background |
| 4 | 4 | ||
| 5 | -**Source** | 5 | +Source: CANN package version upgrade (from Version A to Version B), inference scenario. |
| 6 | -CANN package version upgrade (from Version A to Version B), inference scenario. | ||
| 7 | 6 | ||
| 8 | -**Symptoms** | 7 | +Symptoms: Reproducible consistently. After Version B has been running for approximately 12 hours, an OOM occurs at the 471st step. The issue does not occur on Version A, nor on GPU; it is reproduced only on the NPU with Version B. Virtual memory has been confirmed to be enabled. |
| 9 | -The issue can be reproduced consistently. After Version B has been running for approximately 12 hours, an OOM occurs at the 471st step. The issue does not occur on Version A or on the GPU. It is occurs only on the NPU with Version B. It has been confirmed that virtual memory is enabled. | ||
| 10 | 8 | ||
| 11 | -## Troubleshooting Process | 9 | +## 2. Troubleshooting Process |
| 12 | 10 | ||
| 13 | ### Step 1: Comparing Memory Profile Data for a Single Step Across the Two Versions | 11 | ### Step 1: Comparing Memory Profile Data for a Single Step Across the Two Versions |
| 14 | 12 | ||
| @@ -83,13 +81,13 @@ After filtering `operator_memory.csv`, the following was found: | |||
| 83 | 81 | ||
| 84 | Further code review revealed that the KV-cache implementation of `custom_attention_forward` in Version B has a reference counting issue: after the intermediate tensor is referenced internally by the cache, its reference count on the Python side is not decremented correctly. As a result, the tensor is not released by Python after the step ends and accumulates in the memory pool. | 82 | Further code review revealed that the KV-cache implementation of `custom_attention_forward` in Version B has a reference counting issue: after the intermediate tensor is referenced internally by the cache, its reference count on the Python side is not decremented correctly. As a result, the tensor is not released by Python after the step ends and accumulates in the memory pool. |
| 85 | 83 | ||
| 86 | -## Root Cause | 84 | +## 3. Root Cause |
| 87 | 85 | ||
| 88 | The KV-cache implementation of the `custom_attention_forward` operator in Version B has a reference counting error, causing the intermediate tensor generated in each step (approximately 47 MB) to remain unreleased and continuously accumulate in device memory. After 471 steps, the accumulated memory leak reaches approximately 22 GB, triggering an OOM. | 86 | The KV-cache implementation of the `custom_attention_forward` operator in Version B has a reference counting error, causing the intermediate tensor generated in each step (approximately 47 MB) to remain unreleased and continuously accumulate in device memory. After 471 steps, the accumulated memory leak reaches approximately 22 GB, triggering an OOM. |
| 89 | 87 | ||
| 90 | This issue is an operator bug: the KV-cache improperly manages references to intermediate tensors. This failure mode should be added to the failure mode library. | 88 | This issue is an operator bug: the KV-cache improperly manages references to intermediate tensors. This failure mode should be added to the failure mode library. |
| 91 | 89 | ||
| 92 | -## Summary of the Troubleshooting Methodology | 90 | +## 4. Summary of the Troubleshooting Methodology |
| 93 | 91 | ||
| 94 | <div align="center"><img src="../figures/profiler_case_leak_methodology.png" /></div> | 92 | <div align="center"><img src="../figures/profiler_case_leak_methodology.png" /></div> |
| 95 | <div align="center"><b>Figure 3</b> Methodology for locating memory leaks</div> | 93 | <div align="center"><b>Figure 3</b> Methodology for locating memory leaks</div> |
| @@ -98,8 +96,8 @@ This issue is an operator bug: the KV-cache improperly manages references to int | |||
| 98 | 2. After confirming a leak in a single step, expand the profiling range to verify the accumulation trend across steps and rule out a one-time anomaly. | 96 | 2. After confirming a leak in a single step, expand the profiling range to verify the accumulation trend across steps and rule out a one-time anomaly. |
| 99 | 3. Filter operators with mismatched allocation and release records in `operator_memory.csv`. Then, use call stacks recorded with `with_stack=True` to locate the specific code path. | 97 | 3. Filter operators with mismatched allocation and release records in `operator_memory.csv`. Then, use call stacks recorded with `with_stack=True` to locate the specific code path. |
| 100 | 98 | ||
| 101 | -## Suggestions for Improving the Tools | 99 | +## 5. Suggestions for Tool Improvement |
| 102 | 100 | ||
| 103 | -- `operator_memory.csv` currently requires manual comparison of allocation and release records to identify operators with memory leaks. Add automatic identification and annotation of "unreleased operators." | 101 | +- `operator_memory.csv` currently requires manually comparing allocation and release records to identify leaking operators. It is recommended to add automatic annotation capability for "unreleased operators". |
| 104 | -- Enhance the profiler to automatically generate an `allocated` trend chart across steps to make cumulative memory leaks easier to identify. | 102 | +- The profiling tool can add automatic generation of cross-step allocated trend charts to lower the identification threshold for leak accumulation. |
| 105 | -- Add operator-level memory lifecycle tracking to the profiler, automatically associate allocations with releases, and directly flag abnormal memory behavior. | 103 | +- It is recommended to add operator-level memory lifecycle tracking in the profiler, automatically associate allocation and release, and directly mark anomalies. |
| @@ -1,155 +0,0 @@ | |||
| 1 | -# Model Performance Degradation Causing SLO Degradation | ||
| 2 | - | ||
| 3 | -## Background | ||
| 4 | - | ||
| 5 | -In service-based inference scenarios, service level objectives (SLOs) are core metrics for measuring service quality and typically include metrics such as time to first token (TTFT), tokens per second (TPS), request end-to-end latency (E2E latency), and throughput. When model execution performance degrades, SLO metrics deteriorate directly, affecting user experience and business SLAs. Model performance degradation can be caused by various factors, including decreased operator execution efficiency, ineffective model computation graph compilation and optimization, insufficient NPU memory causing swap, performance regressions introduced by model version upgrades, changes in operator performance caused by CANN version changes, compilation cache misses in dynamic-shape scenarios, and imbalanced expert loads in MoE models. On Ascend NPUs, model performance may degrade after migration from GPUs due to differences in operator adaptation, graph compilation strategies, memory management mechanisms, and other factors. A systematic troubleshooting approach is required to identify the cause layer by layer. | ||
| 6 | - | ||
| 7 | -**Source** | ||
| 8 | - | ||
| 9 | -Inference. | ||
| 10 | - | ||
| 11 | -**Symptoms** | ||
| 12 | - | ||
| 13 | -Users typically first observe an overall deterioration in the inference service SLO metrics: increased TTFT, decreased TPS, increased P95/P99 end-to-end latency, and decreased overall throughput. When the metrics are broken down in Grafana, the following symptoms are commonly observed: | ||
| 14 | - | ||
| 15 | -- The P50, P90, and P99 values of the `first_token_latency` metric all increase. | ||
| 16 | -- `generate_token_speed` (token generation speed) decreases. | ||
| 17 | -- `request_latency` (request end-to-end latency) increases. | ||
| 18 | -- `batch_size` may remain normal, but `during_time(ms)` (model execution time) increases. | ||
| 19 | -- NPU utilization may remain normal or even increase, indicating that the NPU is busy executing inefficient operators. | ||
| 20 | - | ||
| 21 | -In `batch.csv`, the `during_time(ms)` of rows where `name` is `modelExec` increases significantly, while `batch_size` and `total_scheduled_tokens` remain similar to their values before the degradation. This indicates that model execution takes longer for the same amount of computation. In `forward.csv`, forward execution time (`during_time(ms)`) increases, while bubble time (`bubble_time(ms)`) may remain normal, indicating that the bottleneck is in the model forward computation itself rather than scheduling. In `request.csv`, both `execution_time(ms)` and `first_token_latency(ms)` increase, while `queue_wait_time(ms)` may remain normal, indicating that the request wait time in the queue has not increased and that the bottleneck is in the execution stage. | ||
| 22 | - | ||
| 23 | -Typical scenarios include performance regressions after a model version upgrade, changes in operator performance after a CANN version upgrade, performance below expectations after migrating a model from a GPU to an Ascend NPU, imbalanced expert loads in an MoE model causing some devices to become bottlenecks, and compilation cache misses in dynamic-shape scenarios causing repeated compilation. | ||
| 24 | - | ||
| 25 | -## Troubleshooting Process | ||
| 26 | - | ||
| 27 | -### Step 1: Confirming the Scope and Magnitude of SLO Degradation | ||
| 28 | - | ||
| 29 | -In Grafana, view the time-series changes in SLO metrics such as `first_token_latency`, `generate_token_speed`, and `request_latency` to identify when the degradation started and its magnitude. Compare metrics such as `batch_size`, `total_scheduled_tokens`, and NPU utilization before and after the degradation to determine whether the degradation is related to a change in workload. If the workload remains unchanged while the SLO metrics deteriorate, the issue is likely caused by performance degradation on the model execution side. | ||
| 30 | - | ||
| 31 | -### Step 2: Collecting Model Execution Data Using the Profiler | ||
| 32 | - | ||
| 33 | -Configure `ms_service_profiler_config.json`, set `domain` to `"Schedule; ModelExecute; Request; KVCache"`, and enable data collection. If an operator-level performance issue is suspected, set `acl_task_time` to 1 or 2 to enable operator execution time collection. Note that enabling operator collection introduces additional performance overhead and is recommended when the model execution time is abnormal. After collection is complete, perform parsing: | ||
| 34 | - | ||
| 35 | -```bash | ||
| 36 | -python3 -m ms_service_profiler.parse --input-path ${PATH}/prof_dir/ | ||
| 37 | -``` | ||
| 38 | - | ||
| 39 | -The parsing generates files such as `batch.csv`, `forward.csv`, `request.csv`, and `chrome_tracing.json`. | ||
| 40 | - | ||
| 41 | -### Step 3: Analyzing Model Execution Time in `batch.csv` and `forward.csv` | ||
| 42 | - | ||
| 43 | -In `batch.csv`, filter the rows where `name` is `modelExec` and observe the trend of `during_time(ms)` over time. If the model execution time suddenly increases after a certain point in time, the cause may be a configuration change or an environmental change. | ||
| 44 | - | ||
| 45 | -Group the data by `dp_rank` and calculate the model execution time for each DP domain. If the execution time of a specific DP domain is significantly higher than that of other DP domains, the corresponding device or process may be abnormal. | ||
| 46 | - | ||
| 47 | -Group the data separately by `batch_type` (`prefill`/`decode`). If prefill execution time increases, input processing or attention computation may have slowed down. If decode execution time increases, token-by-token generation efficiency may have decreased. | ||
| 48 | - | ||
| 49 | -In `forward.csv`, observe `during_time(ms)` and `bubble_time(ms)` by `dp_rank` and `forward_iter`. If `during_time(ms)` increases while `bubble_time(ms)` remains normal, the bottleneck is in model forward computation. If `bubble_time(ms)` also increases, the issue may be related to scheduling or communication. | ||
| 50 | - | ||
| 51 | -### Step 4: Performing Fine-Grained Decomposition of the Model Execution Stage Using the Service-Based Decomposition Tool | ||
| 52 | - | ||
| 53 | -```bash | ||
| 54 | -msserviceprofiler split --input-path /path/to/input --prefill-batch-size 1 --prefill-number 50 | ||
| 55 | -msserviceprofiler split --input-path /path/to/input --decode-batch-size 1 --decode-number 50 | ||
| 56 | -``` | ||
| 57 | - | ||
| 58 | -Examine the time distribution of each sub-stage in `prefill.csv` and `decode.csv` to identify the specific bottleneck sub-stage in model execution, such as data delivery, operator execution, or data reception. | ||
| 59 | - | ||
| 60 | -### Step 5: Locating Bottleneck Operators in the Timeline View | ||
| 61 | - | ||
| 62 | -Open `chrome_tracing.json`, zoom in on the model execution stage in the Timeline view, and observe the execution time of each operator. If `acl_task_time` collection is enabled, operator-level execution timelines are available in the Timeline, allowing you to identify the operators with the longest execution time. | ||
| 63 | - | ||
| 64 | -Compare the Timelines before and after the degradation, if historical data is available, and observe which operators have changed execution time. Use the service-based profile data comparison tool: | ||
| 65 | - | ||
| 66 | -```bash | ||
| 67 | -msserviceprofiler compare ./profiling_data/before ./profiling_data/after | ||
| 68 | -``` | ||
| 69 | - | ||
| 70 | -Compare the differences between the profile data collected at the two time points. | ||
| 71 | - | ||
| 72 | -### Step 6: Obtaining Overall Statistics Using the Multidimensional Analysis Tool | ||
| 73 | - | ||
| 74 | -```bash | ||
| 75 | -msserviceprofiler analyze --input-path=/path/to/input | ||
| 76 | -``` | ||
| 77 | - | ||
| 78 | -In `batch_summary.csv`, view the P50, P90, and P99 percentiles of prefill and decode execution time to determine whether long-tail latency exists. In `request_summary.csv`, view the distributions of `first_token_latency(ms)` and `exec_time(ms)`. In `service_summary.csv`, view `generate_token_speed` and `generate_all_token_speed` to determine whether overall throughput has decreased. | ||
| 79 | - | ||
| 80 | -### Step 7: Performing Operator-Level Performance Analysis Using msprof If an Operator-Level Issue Is Suspected | ||
| 81 | - | ||
| 82 | -Set the `acl_task_time` parameter to 3 during collection to ensure that the profile data directory contains operator data files with the `_ascend_pt` suffix. After parsing is complete, use msprof to export operator data: | ||
| 83 | - | ||
| 84 | -```bash | ||
| 85 | -msprof --export=on --output=/path/to/output | ||
| 86 | -``` | ||
| 87 | - | ||
| 88 | -Open the parsed profile data in MindStudio Insight. In the "Operator Duration" panel, view the top operators by execution time and identify the bottleneck operators. | ||
| 89 | - | ||
| 90 | -### Step 8: Collecting `eplb_observe` Domain Data If Imbalanced Expert Loads Are Suspected in an MoE Model | ||
| 91 | - | ||
| 92 | -Set `domain` to `"eplb_observe"` to collect expert hotspot information. After parsing, view the expert hotspot heatmap and load imbalance line chart to determine whether imbalanced expert loads are causing performance degradation. | ||
| 93 | - | ||
| 94 | -## Root Causes | ||
| 95 | - | ||
| 96 | -Common root causes of SLO degradation caused by model performance degradation include: | ||
| 97 | - | ||
| 98 | -1. **Operator performance regression**: An upgrade to the CANN version changes the implementation of certain operators and causes performance degradation; a model version upgrade changes the computation graph and introduces inefficient operators; or changes in operator fusion strategies cause fusion to be ineffective. | ||
| 99 | - | ||
| 100 | -2. **Insufficient model adaptation after migration from GPU to Ascend NPU**: The model contains a large number of operators such as `Pad` and `Strided_Slice` that have relatively low execution efficiency on Ascend due to array rearrangement; some operators are not supported on Ascend, causing the model to be split into multiple subgraphs and increasing data transfer time between subgraphs; or the model does not actually invoke the Ascend backend and automatically falls back to CPU execution. | ||
| 101 | - | ||
| 102 | -3. **Compilation cache misses in dynamic-shape scenarios**: Different input shapes for each inference request cause graph compilation cache misses, triggering repeated compilation. Execution time increases significantly during the first inference or when the shape changes. | ||
| 103 | - | ||
| 104 | -4. **NPU memory insufficiency causing swap**: Excessive KV cache usage or excessive model weight usage causes insufficient NPU memory, triggering request swap, which swaps the request's KV cache to CPU memory. Swap and recovery operations introduce significant latency. | ||
| 105 | - | ||
| 106 | -5. **Imbalanced expert loads in MoE models**: In MoE models such as DeepSeek, different experts are invoked at different frequencies. Some devices hosting frequently invoked experts become computational hotspots, while other devices remain idle and wait, resulting in fast and slow ranks. | ||
| 107 | - | ||
| 108 | -6. **Host Bound causing device idle time**: For small models or in the decode stage, the host cannot dispatch tasks fast enough to keep up with the device's execution speed, causing intermittent device idle time. CANN graph-mode scheduling or model sinking can be used to address this issue. | ||
| 109 | - | ||
| 110 | -7. **Communication bottlenecks**: In multi-device inference scenarios, collective communication such as AllReduce/AllGather accounts for a high proportion of the execution time; in PD disaggregation scenarios, KV cache transfer latency is high; or in EP (Expert Parallelism) scenarios, Dispatch-Combine communication becomes a bottleneck. | ||
| 111 | - | ||
| 112 | -8. **Improper model quantization or precision settings**: During inference with a quantized model, precision loss causes additional computation steps to be required, or improper quantization configurations cause some operators to fall back to higher-precision computation. | ||
| 113 | - | ||
| 114 | -## Solutions | ||
| 115 | - | ||
| 116 | -- **Operator performance regression**: Use AOE to automatically tune and optimize the model computation graph, or roll back to an earlier CANN version. | ||
| 117 | -- **Insufficient adaptation after GPU migration**: Replace inefficient operators with Ascend-affinity operators and confirm that the model invokes the Ascend backend. | ||
| 118 | -- **Compilation cache misses in dynamic-shape scenarios**: Fix the input shape or enable the compilation cache. | ||
| 119 | -- **NPU memory insufficiency causing swap**: Adjust the KV cache configuration to avoid swap, reduce concurrency per instance, or increase available memory. | ||
| 120 | -- **Imbalanced MoE expert loads**: Enable expert load balancing (EPLB) and adjust the expert placement strategy. | ||
| 121 | -- **Host Bound**: Enable CANN graph-mode scheduling or model sinking. | ||
| 122 | -- **Communication bottlenecks**: Optimize the communication strategy, such as using HIXL instead of HCCL, and adjust the parallelism configuration. | ||
| 123 | -- **Quantization precision issues**: Adjust the quantization configuration and ensure that the quantization parameters are correct. | ||
| 124 | - | ||
| 125 | -After the issue is addressed, check whether the SLO metrics have recovered, the model execution time has decreased, and NPU utilization is normal. | ||
| 126 | - | ||
| 127 | -## Summary of the Troubleshooting Methodology | ||
| 128 | - | ||
| 129 | -The complete troubleshooting flow for this scenario is as follows: First, use ms-service-metric to identify the specific SLO metrics that have degraded and quantify the magnitude of the degradation. Then, use msServiceProfiler to collect data from the ModelExecute domain and use `batch.csv` and `forward.csv` to determine whether model execution time has increased. Next, use the service-based decomposition tool to perform fine-grained analysis and locate the bottleneck sub-stage in model execution. Then, use the Timeline view and operator-level profiling to identify the specific bottleneck operators. Finally, apply targeted optimization based on the bottleneck type (operator, communication, scheduling, or memory). | ||
| 130 | - | ||
| 131 | -Core decision logic: | ||
| 132 | - | ||
| 133 | -- If `modelExec` `during_time(ms)` increases while `batch_size` remains unchanged → model execution efficiency has decreased. | ||
| 134 | -- If `bubble_time(ms)` also increases in `forward.csv` → the issue may be related to scheduling or communication. | ||
| 135 | -- If the execution time of a specific `dp_rank` is significantly higher → the corresponding device or process may be abnormal. | ||
| 136 | -- If `queue_wait_time(ms)` remains normal but `execution_time(ms)` is high in `request.csv` → the bottleneck is in the execution stage rather than the queue. | ||
| 137 | -- If the number of `swapped` requests in `request_status.csv` is greater than 0 → insufficient NPU memory has triggered swap. | ||
| 138 | - | ||
| 139 | -## Suggestions for Improving the Tools | ||
| 140 | - | ||
| 141 | -### `ms-service-metric` | ||
| 142 | - | ||
| 143 | -Currently, `ms-service-metric` can display SLO metrics such as TTFT, TPS, and E2E latency. Add automatic SLO degradation alerting so that an alert is automatically generated when metrics such as TTFT, TPS, and E2E latency continuously exceed baseline thresholds. Add monitoring of the ratio of model execution time to scheduling time to facilitate rapid differentiation between execution and scheduling bottlenecks. In addition, add a swap request count metric and trigger an alert when swap occurs. | ||
| 144 | - | ||
| 145 | -### `msServiceProfiler` | ||
| 146 | - | ||
| 147 | -Currently, `msServiceProfiler` can analyze model execution time through `batch.csv` and `forward.csv`. Add fields for decomposing the model execution stage into sub-stages in `batch.csv`, such as "data delivery time," "operator execution time," and "data reception time," to facilitate direct identification of bottleneck sub-stages. Add automatic comparison with historical data and automatically suggest possible causes of performance degradation when a significant increase in model execution time is detected. In addition, add an SLO impact assessment panel to the parsing results to automatically quantify the impact of increased model execution time on SLO metrics such as TTFT and TPS. | ||
| 148 | - | ||
| 149 | -### Service-Based Decomposition Tool | ||
| 150 | - | ||
| 151 | -Currently, the decomposition tool requires `batch_size` or `rid` to be specified manually. Add automatic decomposition of the model execution stage without requiring manual parameter specification, and automatically select batches with abnormal execution time for decomposition. Also add comparison with baseline data to the decomposition results and indicate the magnitude of changes in the execution time of each sub-stage. | ||
| 152 | - | ||
| 153 | -### Service-Based Expert Recommendation Tool | ||
| 154 | - | ||
| 155 | -Currently, the expert recommendation tool can provide parameter tuning recommendations based on benchmark results. Add automatic parameter tuning recommendations based on performance degradation data. When an increase in model execution time is detected, automatically analyze whether the degradation can be mitigated by adjusting parameters such as `maxBatchSize` and `maxPrefillBatchSize`. | ||
| @@ -1,86 +0,0 @@ | |||
| 1 | -# Analysis of Excessive Preprocessing and Postprocessing Time in Model Inference | ||
| 2 | - | ||
| 3 | -## Background | ||
| 4 | - | ||
| 5 | -A request in a foundation-model inference service can be divided into three stages: preprocessing (Tokenizer encoding), model inference (prefill + decode), and postprocessing (Detokenizer decoding). Preprocessing and postprocessing are performed on the CPU and involve text encoding/decoding, special token processing, chat template rendering, and other operations. When the input prompt is long (>10,000 tokens) or the service is handling a multi-turn conversation, CPU time spent on preprocessing and postprocessing may exceed model inference time and become the primary bottleneck for end-to-end latency. | ||
| 6 | - | ||
| 7 | -The user reported that a conversational model service was deployed on an A2, with a time to first token (TTFT) of approximately 450 ms. Model prefill took approximately 180 ms, suggesting that preprocessing was taking too long. Service-based profiling was required to locate the specific bottleneck. | ||
| 8 | - | ||
| 9 | -## Symptoms | ||
| 10 | - | ||
| 11 | -The issue can be reproduced consistently. For a single prompt containing 8,000 tokens: | ||
| 12 | - | ||
| 13 | -- TTFT is approximately 450 ms, significantly higher than the expected ~200 ms. | ||
| 14 | -- The NPU has a noticeable idle waiting period of approximately 250 ms after the request arrives, during which no computation activity occurs. | ||
| 15 | -- As the prompt length increases, the proportion of idle time in TTFT also increases: approximately 60 ms of idle time for a 2,000-token prompt and approximately 250 ms for an 8,000-token prompt. | ||
| 16 | -- Under concurrent requests, significant queuing occurs during preprocessing and postprocessing: preprocessing of subsequent requests must wait for postprocessing of preceding requests to complete before it can start. | ||
| 17 | - | ||
| 18 | -<div align="center"><img src="../figures/profiler_model_time_consume.png" /></div> | ||
| 19 | - | ||
| 20 | -> The actual TTFT is 450 ms, of which model prefill takes only 180 ms, preprocessing takes approximately 250 ms, and postprocessing takes approximately 20 ms. Preprocessing and postprocessing together account for 60% of TTFT. | ||
| 21 | - | ||
| 22 | -## Troubleshooting Process | ||
| 23 | - | ||
| 24 | -### 1. Collecting Global Profile Data Using `msServiceProfiler` | ||
| 25 | - | ||
| 26 | -Use **`msServiceProfiler`** to collect comprehensive profile data from the service and obtain the distribution of time spent across all stages of the end-to-end request flow. | ||
| 27 | - | ||
| 28 | -### 2. Performing Visual Analysis | ||
| 29 | - | ||
| 30 | -Use `MindStudio Insight` to import the parsed profile data. | ||
| 31 | - | ||
| 32 | -Key analysis steps: | ||
| 33 | - | ||
| 34 | -#### 2.1 Viewing the End-to-End Timeline of a Single Request | ||
| 35 | - | ||
| 36 | -View the complete process from request arrival to the output of the first token as a timeline. A CPU preprocessing interval is visible before model prefill and includes the following operations: | ||
| 37 | - | ||
| 38 | -- Chat template rendering: Applies the conversation template to the original text. | ||
| 39 | -- Tokenizer encoding: Converts the text into a sequence of token IDs. | ||
| 40 | -- Input tensor construction and transfer: Copies the token IDs to the device. | ||
| 41 | - | ||
| 42 | -A CPU postprocessing interval also exists after prefill is completed: | ||
| 43 | - | ||
| 44 | -- Detokenizer decoding: Converts the first output token ID into text. | ||
| 45 | - | ||
| 46 | -<div align="center"><img src="../figures/profiler_model_request_link.png" /></div> | ||
| 47 | - | ||
| 48 | -> Preprocessing takes 250 ms, accounting for 55.6% of TTFT, during which the NPU remains completely idle. Although postprocessing takes only 20 ms, the cumulative overhead can be significant in streaming output scenarios because detokenization is required for every token. | ||
| 49 | - | ||
| 50 | -#### 2.2 Analyzing the Time Spent on Each Preprocessing Stage | ||
| 51 | - | ||
| 52 | -Filter the preprocessing-related functions from the exported CSV files and sort them by execution time. | ||
| 53 | - | ||
| 54 | -<div align="center"><img src="../figures/profiler_model_time_usage.png" /></div> | ||
| 55 | - | ||
| 56 | -Key findings: | ||
| 57 | - | ||
| 58 | -- Tokenizer encoding accounts for the largest proportion of execution time (approximately 60%). An 8,000-token prompt requires approximately 150 ms for character-by-character encoding. | ||
| 59 | -- Chat template rendering takes approximately 55 ms (22%), involving string concatenation and special token insertion. | ||
| 60 | -- Tensor construction and host-to-device transfer take approximately 30 ms (12%). | ||
| 61 | -- Other operations, such as parameter validation and memory pinning, take approximately 15 ms (6%). | ||
| 62 | - | ||
| 63 | -Analyze further how preprocessing time varies with prompt length: | ||
| 64 | -<div align="center"><img src="../figures/profiler_model_prompt_length_trend.png" /></div> | ||
| 65 | - | ||
| 66 | -> Preprocessing time increases approximately linearly with prompt length, indicating that Tokenizer encoding is the primary bottleneck and that parallel tokenization or caching optimization has not been adopted. | ||
| 67 | - | ||
| 68 | -## Root Cause | ||
| 69 | - | ||
| 70 | -During preprocessing, Tokenizer encoding encodes the entire prompt character by character without caching. In multi-turn conversation scenarios, the fixed system prompt is re-encoded for every request, causing preprocessing time to increase linearly with prompt length. For an 8,000-token prompt, preprocessing takes approximately 250 ms, accounting for 55.6% of TTFT, while the NPU remains completely idle during this period. | ||
| 71 | - | ||
| 72 | -This issue is a **service pipeline configuration issue**: Tokenizer caching is not enabled, and preprocessing and postprocessing share CPU threads with model inference, blocking NPU scheduling. This failure mode should be added to the failure mode library. | ||
| 73 | - | ||
| 74 | -## Conclusion | ||
| 75 | - | ||
| 76 | -1. The root cause of excessive preprocessing time is that Tokenizer encoding does not use caching. The entire prompt is re-encoded for every request, taking approximately 150 ms for an 8,000-token prompt. | ||
| 77 | -2. The entire preprocessing and postprocessing flow runs on the CPU, causing the NPU to remain idle for approximately 270 ms (250 ms for preprocessing + 20 ms for postprocessing), accounting for 60% of TTFT. | ||
| 78 | -3. Preprocessing time increases linearly with prompt length. For a 16,000-token prompt, preprocessing takes approximately 480 ms, nearly matching the prefill time. | ||
| 79 | -4. Optimization directions: Enable Tokenizer caching so that the system prompt is encoded only once; use a Rust/C++-based Tokenizer to bypass the Python GIL; and deploy preprocessing and postprocessing on separate threads or processes from model inference to avoid blocking NPU scheduling. | ||
| 80 | - | ||
| 81 | -## Summary of the Troubleshooting Methodology | ||
| 82 | - | ||
| 83 | -1. When TTFT is abnormally high, first use `msServiceProfiler` to collect the end-to-end timeline and determine whether a CPU idle interval exists before prefill. | ||
| 84 | -2. Use MindStudio Insight to identify the proportion of execution time spent in each preprocessing stage, including Tokenizer encoding, chat template rendering, and tensor transfer. | ||
| 85 | -3. Compare preprocessing time at different prompt lengths to determine whether it increases linearly. | ||
| 86 | -4. Compare preprocessing time between cold and warm requests to determine whether Tokenizer caching is effective. | ||
| @@ -1,102 +0,0 @@ | |||
| 1 | -# Multi-Instance Load Imbalance | ||
| 2 | - | ||
| 3 | -## Background | ||
| 4 | - | ||
| 5 | -Inference services typically use multiple instances to handle traffic. Ideally, the number of requests, token volume, queue length, and KV cache utilization should be roughly balanced across instances. If the ingress routing, instance weights, health status, or request length distribution is abnormal, a small number of instances may become hotspots while other instances remain idle, causing overall throughput and latency to be constrained by the hotspot instances. | ||
| 6 | - | ||
| 7 | -## Source | ||
| 8 | - | ||
| 9 | -Inference | ||
| 10 | - | ||
| 11 | -## Symptoms | ||
| 12 | - | ||
| 13 | -Users typically first observe that overall throughput is lower than expected for the available multi-instance capacity, or that P95/P99 latency is significantly higher than average latency. When the metrics are broken down by instance, the following symptoms are commonly observed: | ||
| 14 | - | ||
| 15 | -- A small number of instances consistently have higher request counts, token throughput, or batch sizes than other instances. | ||
| 16 | -- Hotspot instances have more waiting/pending requests, higher time to first token, and longer queue wait time. | ||
| 17 | -- Hotspot instances have higher KV cache utilization and lower `free_kvcache_blocks`. | ||
| 18 | -- Other instances remain idle, but the overall service already exhibits long-tail latency. | ||
| 19 | - | ||
| 20 | -## Troubleshooting Process | ||
| 21 | - | ||
| 22 | -### Step 1: Verifying Whether Hotspot Instances Exist | ||
| 23 | - | ||
| 24 | -In the instance-level panels in Grafana, select the same load testing window or production time window and compare the following metrics across instances: | ||
| 25 | - | ||
| 26 | -- Request QPS and the number of running/waiting requests. | ||
| 27 | -- Prompt tokens, generated tokens, and total token throughput. | ||
| 28 | -- Time to first token, end-to-end latency, and queue wait time. | ||
| 29 | -- Batch size, KV cache utilization, and `free_kvcache_blocks`. | ||
| 30 | - | ||
| 31 | -Short-term fluctuations do not necessarily indicate a problem. If a small number of instances remain consistently higher across multiple consecutive windows while other instances remain consistently lower, this likely indicates a load imbalance across instances. | ||
| 32 | - | ||
| 33 | -### Step 2: Determining Whether the Imbalance Is Caused by Request Count or Request Size | ||
| 34 | - | ||
| 35 | -Analyze request count and token count separately: | ||
| 36 | - | ||
| 37 | -- If both the number of requests and the token volume are higher, prioritize checking ingress routing, instance weights, or connection stickiness based on gateway logs, load balancing configuration, service discovery status, and connection reuse. | ||
| 38 | -- If the number of requests is similar but the token volume is higher and the average input and output lengths are longer, use request logs, load testing datasets, or request length statistics to determine whether long requests are concentrated on hotspot instances. | ||
| 39 | -- If both the number of requests and the token volume are similar but hotspot instances have higher latency, use service startup parameters, device monitoring, process logs, and the Profiler to check instance configuration, device status, process status, and local resource contention. | ||
| 40 | - | ||
| 41 | -First determine the type of imbalance based on this analysis, and then select the corresponding troubleshooting direction. | ||
| 42 | - | ||
| 43 | -### Step 3: Checking Ingress Routing and Instance Status | ||
| 44 | - | ||
| 45 | -If the imbalance is determined to be caused by request count, check the ingress configuration based on information from the gateway, service discovery, or load balancing system: | ||
| 46 | - | ||
| 47 | -- Whether traffic weights are consistent across instances. | ||
| 48 | -- Whether any instance has failed health checks and is therefore not receiving traffic. | ||
| 49 | -- Whether long-lived connections, connection pools, or session stickiness are causing requests to be consistently routed to a small number of instances. | ||
| 50 | -- Whether some instances failed to properly join the load balancer after a canary deployment, scaling operation, or restart. | ||
| 51 | - | ||
| 52 | -If the imbalance is determined to be caused by request size, use request length statistics and the load balancing strategy to determine whether the current strategy distributes requests based only on request count without considering input length, output length, queue status, or KV cache utilization. | ||
| 53 | - | ||
| 54 | -### Step 4: Verifying Whether Hotspot Instances Are Constrained by Resources | ||
| 55 | - | ||
| 56 | -Continue checking the internal status of hotspot instances: | ||
| 57 | - | ||
| 58 | -- Whether the number of waiting/pending requests continues to increase. | ||
| 59 | -- Whether KV cache utilization remains high and free blocks are nearly exhausted. | ||
| 60 | -- Whether NPU utilization is saturated. If NPU utilization is not saturated but the queue is growing, KV cache or scheduling resources are more likely to be the bottleneck. | ||
| 61 | -- Whether the increase in end-to-end latency is primarily caused by queue wait time or the time to first token. | ||
| 62 | - | ||
| 63 | -If a hotspot instance simultaneously exhibits queue buildup and high KV cache utilization, continue investigating based on the "Insufficient KV Block Count" scenario. | ||
| 64 | - | ||
| 65 | -### Step 5: Comparing Hotspot and Idle Instances Using the Profiler | ||
| 66 | - | ||
| 67 | -Collect `Schedule`, `Request`, and `KVCache` data from hotspot and idle instances separately, and focus on the following comparisons: | ||
| 68 | - | ||
| 69 | -- `request.csv`: Compare the number of requests, input length, output length, `queue_wait_time(ms)`, and `first_token_latency(ms)`. | ||
| 70 | -- `batch.csv`: Compare `batch_size`, `prefill_batch_size`, `decode_batch_size`, `total_scheduled_tokens`, and `during_time(ms)`. | ||
| 71 | -- `kvcache.csv`: Compare `used_blocks`, `free_blocks`, and `kvcache_usage_rate`. | ||
| 72 | - | ||
| 73 | -If hotspot instances have more requests or higher token volume, and the Profiler shows higher queue wait time, larger batch sizes, and higher KV cache utilization, the issue can be traced to load imbalance across instances. | ||
| 74 | - | ||
| 75 | -## Root Causes | ||
| 76 | - | ||
| 77 | -The request count, request length distribution, or instance capabilities differ across instances. Common root causes include incorrect load balancing weights, health check or service discovery issues, long-lived connections or session stickiness, concentration of long requests on a small number of instances, inconsistent instance configurations, and load balancing strategies that do not account for token volume, queue length, or KV cache utilization. | ||
| 78 | - | ||
| 79 | -## Solutions | ||
| 80 | - | ||
| 81 | -- Incorrect routing weights: Correct the routing or instance weights and ensure that all healthy instances are included in load balancing. | ||
| 82 | -- Health check issues: Restore abnormal instances or remove unavailable instances from load balancing to prevent traffic from being routed only to a subset of instances. | ||
| 83 | -- Long-lived connections or session stickiness: Adjust the connection pool, gateway strategy, or load balancing algorithm to reduce the likelihood of repeatedly routing requests to the same instances. | ||
| 84 | -- Concentration of long requests: Schedule requests based on input/output token volume, queue length, or KV cache utilization, and isolate long and short requests when necessary. | ||
| 85 | -- Inconsistent instance capabilities: Standardize the model version, startup parameters, parallelism configuration, memory configuration, and hardware specifications. | ||
| 86 | -- KV cache exhaustion on hotspot instances: First throttle traffic or migrate traffic, and then adjust concurrency, request length, or KV cache capacity based on the insufficient KV block scenario. | ||
| 87 | - | ||
| 88 | -After the issue is addressed, check whether the number of requests, token volume, number of waiting requests, KV cache utilization, and P99 latency become balanced across instances. | ||
| 89 | - | ||
| 90 | -## Summary of the Troubleshooting Methodology | ||
| 91 | - | ||
| 92 | -For multi-instance load imbalance, first use ms-service-metric to compare the number of requests, token throughput, number of waiting requests, latency, and KV cache utilization across instances to determine whether only a small number of instances have consistently become hotspots. After confirming an imbalance across instances, use `msServiceProfiler` to separately collect `request.csv`, `batch.csv`, and `kvcache.csv` from hotspot and idle instances for comparison, and distinguish among abnormal ingress routing or instance weights, imbalanced request length distribution, inconsistent instance capabilities, and resource exhaustion within hotspot instances. | ||
| 93 | - | ||
| 94 | -## Suggestions for Improving the Tools | ||
| 95 | - | ||
| 96 | -### `ms-service-metric` | ||
| 97 | - | ||
| 98 | -Currently, `ms-service-metric` supports comparison of request volume, token volume, latency, queue status, and KV cache utilization across instances. It is recommended to add multi-instance load imbalance detection to automatically distinguish between "request count imbalance" and "request length/token volume imbalance" and prompt users to check ingress routing, instance weights, or request length distribution. | ||
| 99 | - | ||
| 100 | -### `msServiceProfiler` | ||
| 101 | - | ||
| 102 | -Currently, `msServiceProfiler` can separately collect `request.csv`, `batch.csv`, and `kvcache.csv` from hotspot and idle instances for manual comparison. It is recommended to add support for merging and analyzing profiling results from multiple instances and directly reporting differences between hotspot and idle instances in request volume, token volume, batch size, queue wait time, and KV cache utilization. | ||
Mdocs/en/best_practices/operator_compilation_latency.md+19-15File content is under review, please try again later
| @@ -1,102 +0,0 @@ | |||
| 1 | -# PrefixCache Misses | ||
| 2 | - | ||
| 3 | -## Background | ||
| 4 | - | ||
| 5 | -Long system prompts and multi-turn conversations are common scenarios in LLM inference applications. In long system prompt scenarios, the system prompt is the same across different requests, and the corresponding KV cache computation is also the same. In multi-turn conversation scenarios, each turn depends on the context of all previous turns, and the KV cache for previous turns must be recomputed for each subsequent turn. Prefix caching significantly reduces time to first token (TTFT) and prefill computation by caching and reusing the KV cache of previously computed common prefixes. Ascend-vLLM enables prefix caching by default. However, `PrefixCache` misses may still occur in practice due to unmet cache hit conditions, cache eviction caused by insufficient cache capacity, or an insufficient number of common prefix tokens across requests to fill a block. This can result in higher TTFT and longer prefill duration. | ||
| 6 | - | ||
| 7 | -## Source | ||
| 8 | - | ||
| 9 | -Inference | ||
| 10 | - | ||
| 11 | -## Symptoms | ||
| 12 | - | ||
| 13 | -Users typically first observe TTFT fluctuating or increasing, with some requests having significantly higher TTFT than similar requests. Further inspection of KV cache and request-related metrics may reveal the following: | ||
| 14 | - | ||
| 15 | -- The `cache_hit_rate` field in `request.csv` is low, while `first_token_latency(ms)` is high. | ||
| 16 | -- In `batch.csv`, `during_time(ms)` and `prefill_scheduled_tokens` are both high for prefill batches, indicating that a large number of prefix tokens are being recomputed rather than reused from the cache. | ||
| 17 | -- In KV cache-related metrics, `kvcache_usage_rate` fluctuates significantly and `free_blocks` changes frequently, indicating that the cache blocks are continuously being allocated and released rather than stably reused. | ||
| 18 | -- In `kvcache.csv`, frequent block allocation (`blocks_allocated`) and release (`blocks_freed`) operations can be observed. If `blocks_allocated` is close to the number of tokens in the request's full prefix, this indicates that a cache miss has caused the entire prefix to be reallocated. | ||
| 19 | - | ||
| 20 | -Typical scenarios include the following: In multi-turn conversations, the TTFT of the second and subsequent requests is almost the same as that of the first request, indicating no significant acceleration from prefix caching. In long system prompt scenarios, different requests with the same system prompt have similar TTFT. | ||
| 21 | - | ||
| 22 | -## Troubleshooting Process | ||
| 23 | - | ||
| 24 | -### Step 1: Checking KV Cache Usage and TTFT Changes | ||
| 25 | - | ||
| 26 | -In Grafana, check KV cache-related metrics such as `free_kvcache_blocks`, `allocated_kvcache_blocks`, and `kvcache_usage_rate`. If `kvcache_usage_rate` remains low for an extended period while `allocated_kvcache_blocks` fluctuates frequently, this indicates that the cache is repeatedly allocated and released rather than reused. Also monitor the TTFT metric (`first_token_latency`). If TTFT fluctuates significantly and correlates with changes in KV cache utilization, a `PrefixCache` hit rate issue may have occurred. | ||
| 27 | - | ||
| 28 | -### Step 2: Collecting Request and KV Cache Data Using the Profiler | ||
| 29 | - | ||
| 30 | -Configure `ms_service_profiler_config.json`, set `domain` to `"Request; KVCache; Schedule"`, and enable data collection. After collection is complete, run the following command to parse the data: | ||
| 31 | - | ||
| 32 | -```bash | ||
| 33 | -python3 -m ms_service_profiler.parse --input-path ${PATH}/prof_dir/ | ||
| 34 | -``` | ||
| 35 | - | ||
| 36 | -The parsing process generates files such as `request.csv`, `kvcache.csv`, and `batch.csv`. | ||
| 37 | - | ||
| 38 | -### Step 3: Analyzing Cache Hit Rate and TTFT in `request.csv` | ||
| 39 | - | ||
| 40 | -Check the `cache_hit_rate` field for each request in `request.csv`. Calculate the overall cache hit rate distribution, including the average, P50, and P90. A generally low hit rate indicates that `PrefixCache` is not working effectively. | ||
| 41 | - | ||
| 42 | -Sort requests by arrival time and observe changes in `cache_hit_rate` over time. Significant fluctuations in the hit rate may indicate frequent cache eviction caused by insufficient cache capacity. Compare requests with the same `recv_token_size` (input length). If requests with similar input lengths have significantly different `first_token_latency(ms)` values, and requests with lower latency have higher `cache_hit_rate`, it can be confirmed that the `PrefixCache` hit rate is a key factor affecting TTFT. | ||
| 43 | - | ||
| 44 | -### Step 4: Analyzing Cache Allocation Patterns in `kvcache.csv` | ||
| 45 | - | ||
| 46 | -Observe changes in `blocks_allocated` and `blocks_freed` over time in `kvcache.csv`. If `blocks_allocated` is close to the number of tokens in the request's full prefix each time a new request arrives, rather than only the incremental portion, this indicates a cache miss and full reallocation of the prefix. | ||
| 47 | - | ||
| 48 | -Analyze the trends of `total_blocks` and `free_blocks`. If `total_blocks` is sufficiently large but `free_blocks` fluctuates significantly, this indicates an issue with the cache management strategy, possibly because of an overly aggressive LRU eviction strategy or insufficient cache capacity. | ||
| 49 | - | ||
| 50 | -### Step 5: Analyzing Prefill Scheduling in `batch.csv` | ||
| 51 | - | ||
| 52 | -Filter the rows where `batch_type` is `prefill` and check `prefill_scheduled_tokens` and `during_time(ms)`. If the number of tokens scheduled for prefill is close to the full input length of the request rather than the incremental portion, this indicates that the prefix is not being reused from the cache. Compare the prefill duration of requests with the same input length at different times. If the duration varies significantly and correlates with the cache hit rate, the cache hit rate can be identified as a key factor. | ||
| 53 | - | ||
| 54 | -### Step 6: Obtaining Request-Dimension Statistics Using a Multidimensional Analysis Tool | ||
| 55 | - | ||
| 56 | -```bash | ||
| 57 | -msserviceprofiler analyze --input-path=/path/to/input | ||
| 58 | -``` | ||
| 59 | - | ||
| 60 | -Check the P50/P90/P99 percentiles of `first_token_latency(ms)` and the distribution of `input_token_num` in `request_summary.csv` to determine whether TTFT has a long tail. | ||
| 61 | - | ||
| 62 | -## Root Causes | ||
| 63 | - | ||
| 64 | -Common root causes of `PrefixCache` misses include: | ||
| 65 | - | ||
| 66 | -1. **Insufficient number of common prefix tokens across requests to fill a block**: Ascend-vLLM prefix caching is based on the block mechanism of PagedAttention. The KV cache of a common prefix is reused only when the number of common prefix tokens across requests is greater than or equal to the block size. If the common prefix is short, such as a short system prompt, cache reuse cannot be triggered. | ||
| 67 | - | ||
| 68 | -2. **Frequent eviction due to insufficient cache capacity**: The total number of KV cache blocks (`total_blocks`) is insufficient, or a large number of concurrent requests quickly fills the cache. When a new request arrives, the LRU policy evicts prefix caches that could otherwise be reused, preventing subsequent requests with the same prefix from achieving cache hits. | ||
| 69 | - | ||
| 70 | -3. **Prefix caching is not properly enabled**: Although Ascend-vLLM enables prefix caching by default, configuring `ascend_scheduler_config` at the same time causes a conflict and disables prefix caching. In addition, prefix caching is currently not supported for multimodal models. | ||
| 71 | - | ||
| 72 | -4. **Request prefix hash collisions or invalid cache indexing**: In distributed or multi-instance deployments, caches are isolated between instances. When requests are routed to different instances, they cannot reuse caches from other instances. In prefill/decode (PD) disaggregation scenarios, caches on prefill and decode nodes are managed independently, and cross-node cache sharing is not enabled. | ||
| 73 | - | ||
| 74 | -5. **Model limitations**: Currently, only the Qwen2.5 and Qwen3 series support prefix caching. The feature may not work with other models. | ||
| 75 | - | ||
| 76 | -6. **Interaction between chunked prefill and prefix caching**: When prefix caching is enabled, chunked prefill is also enabled. Chunked prefill may cause cache block boundaries to be misaligned with request prefix boundaries, affecting cache hits. | ||
| 77 | - | ||
| 78 | -## Solutions | ||
| 79 | - | ||
| 80 | -- Insufficient common prefix length: Ensure that the system prompt or conversation history is longer than the block size, or adjust the block size configuration. | ||
| 81 | -- Insufficient cache capacity: Increase the configured total number of KV cache blocks or reduce concurrency on a single instance. | ||
| 82 | -- Prefix caching not enabled: Check whether `ascend_scheduler_config` is configured. If there is a conflict, remove it and confirm that the model is on the supported list. | ||
| 83 | -- Distributed cache isolation: Enable cross-node KV cache pooling in distributed scenarios, such as an HIXL + MemFabric solution, to implement cache sharing. | ||
| 84 | -- Chunked prefill interaction: Adjust the chunk size for chunked prefill to align with the block size. | ||
| 85 | - | ||
| 86 | -After applying the changes, check whether `cache_hit_rate` increases, TTFT decreases, and `blocks_allocated` changes from full allocation to incremental allocation. | ||
| 87 | - | ||
| 88 | -## Summary of the Troubleshooting Methodology | ||
| 89 | - | ||
| 90 | -For this scenario, first use ms-service-metric to observe KV cache utilization fluctuations and TTFT trends. Then use `msServiceProfiler` to collect Request and KVCache domain data and directly confirm the cache hit rate using the `cache_hit_rate` field in `request.csv`. Next, analyze cache allocation and release patterns in `kvcache.csv` to determine whether the issue is caused by insufficient capacity or unmet cache hit conditions. Finally, use the number of tokens scheduled for prefill in `batch.csv` to confirm whether the prefix is being recomputed. | ||
| 91 | - | ||
| 92 | -The key diagnostic logic is as follows: If `cache_hit_rate` is low and `blocks_allocated` is close to the number of tokens in the full prefix, a `PrefixCache` miss has occurred. Further determine the cause as follows: If `free_blocks` remains close to 0 for an extended period, the cache capacity is insufficient. If `free_blocks` is sufficient but the hit rate remains low, check whether the common prefix length meets the block size requirement, whether prefix caching is properly enabled, and whether the model supports the feature. | ||
| 93 | - | ||
| 94 | -## Suggestions for Improving the Tools | ||
| 95 | - | ||
| 96 | -### `ms-service-metric` | ||
| 97 | - | ||
| 98 | -Currently, `ms-service-metric` can display KV cache utilization and TTFT metrics. It is recommended to add a `PrefixCache` hit rate metric that directly displays the `cache_hit_rate` time series for real-time monitoring of cache effectiveness. It is also recommended to add `PrefixCache` miss alerts to automatically provide risk notifications when the hit rate remains low. In addition, it is recommended to add statistics on the common prefix length distribution to help users determine whether request prefixes meet the block size requirement. | ||
| 99 | - | ||
| 100 | -### `msServiceProfiler` | ||
| 101 | - | ||
| 102 | -Currently, `msServiceProfiler` can use the `cache_hit_rate` field in `request.csv` to confirm the cache hit rate. It is recommended to add `cache_hit_blocks` and `cache_miss_blocks` fields to `request.csv` to distinguish between the number of hit and missed blocks for more precise analysis of cache effectiveness. It is also recommended to add a cache eviction reason field to `kvcache.csv`, such as LRU eviction, release upon request completion, or manual invalidation, to help identify the specific causes of cache misses. In addition, it is recommended to add a `PrefixCache` diagnostic report to the parsing results to automatically check whether the common prefix length meets the block size requirement and whether common configuration issues, such as a conflict with `ascend_scheduler_config`, exist. | ||
| @@ -1,16 +1,16 @@ | |||
| 1 | # Pthread Lock Wait | 1 | # Pthread Lock Wait |
| 2 | 2 | ||
| 3 | -## Background | 3 | +## 1. Background |
| 4 | 4 | ||
| 5 | In distributed training scenarios for large PyTorch models, the [`DataLoader` and `pin_memory`](https://docs.pytorch.org/docs/2.12/data.html#torch.utils.data.DataLoader) modules use a multithreaded producer-consumer model and rely on pthread mutexes (`pthread_mutex_t`) to protect concurrent access to shared queues. | 5 | In distributed training scenarios for large PyTorch models, the [`DataLoader` and `pin_memory`](https://docs.pytorch.org/docs/2.12/data.html#torch.utils.data.DataLoader) modules use a multithreaded producer-consumer model and rely on pthread mutexes (`pthread_mutex_t`) to protect concurrent access to shared queues. |
| 6 | 6 | ||
| 7 | The training runs on a multi-NPU server, with a data loading thread pool configured with 16 worker threads. The main thread retrieves data from the queue and feeds it to the NPU for computation. As the batch size increases and data preprocessing becomes more complex, training performance degrades. | 7 | The training runs on a multi-NPU server, with a data loading thread pool configured with 16 worker threads. The main thread retrieves data from the queue and feeds it to the NPU for computation. As the batch size increases and data preprocessing becomes more complex, training performance degrades. |
| 8 | 8 | ||
| 9 | -## Source | 9 | +## 2. Source |
| 10 | 10 | ||
| 11 | Training | 11 | Training |
| 12 | 12 | ||
| 13 | -## Symptoms | 13 | +## 3. Symptoms |
| 14 | 14 | ||
| 15 | The issue can be consistently reproduced. | 15 | The issue can be consistently reproduced. |
| 16 | 16 | ||
| @@ -33,17 +33,17 @@ For details, see the following figure. | |||
| 33 | 33 | ||
| 34 |  | 34 |  |
| 35 | 35 | ||
| 36 | -## Troubleshooting Process | 36 | +## 4. Troubleshooting Process |
| 37 | 37 | ||
| 38 | -1. Use the `perf` tool for process-level performance sampling. | 38 | +1. Use the perf tool for process-level performance sampling. |
| 39 | 39 | ||
| 40 | - - Run `perf record -g -p <pid> sleep 30` to collect profile data for the training process. | 40 | + - Run `perf record -g -p <pid> sleep 30` to collect performance hotspots of the training process. |
| 41 | - - The performance flame graph shows that `pthread_mutex_lock` accounts for a high proportion of the sampled CPU time. | 41 | + - The performance flame graph shows that `pthread_mutex_lock` accounts for a high proportion. |
| 42 | - - Lock contention mainly occurs during `push` and `pop` operations on the data queue. | 42 | + - Lock contention mainly occurs during push and pop operations on the data queue. |
| 43 | 43 | ||
| 44 | -2. Use the `strace` tool to trace system calls. | 44 | +2. Use the strace tool to perform system call tracking. |
| 45 | 45 | ||
| 46 | - - Run `strace -tt -T -e futex -p <pid>` to trace `futex` system calls. | 46 | + - Run `strace -tt -T -e futex -p <pid>` to track `futex` system calls. |
| 47 | - A large number of `futex(FUTEX_WAIT)` calls are observed, with individual wait durations exceeding 10 ms. | 47 | - A large number of `futex(FUTEX_WAIT)` calls are observed, with individual wait durations exceeding 10 ms. |
| 48 | 48 | ||
| 49 | 3. Use MSOSRT to collect the execution time of system library functions. | 49 | 3. Use MSOSRT to collect the execution time of system library functions. |
| @@ -56,48 +56,48 @@ For details, see the following figure. | |||
| 56 | 56 | ||
| 57 | **Usage:** | 57 | **Usage:** |
| 58 | 58 | ||
| 59 | - 1. Build the MSOSRT tool. | 59 | + 1. Build the MSOSRT tool. |
| 60 | 60 | ||
| 61 | - Download the source code repository to the local environment and run `bash build.sh` to generate the `libmsosrt_trace.so` library. | 61 | + Download the source code repository to the local environment and run `bash` `build.sh` to generate the `libmsosrt_trace.so` library. |
| 62 | 62 | ||
| 63 | - 2. Run `export LD_PRELOAD=./libmsosrt_trace.so:$LD_PRELOAD` to add `libmsosrt_trace.so` to the `LD_PRELOAD` environment variable. | 63 | + 2. Run `export LD_PRELOAD=./libmsosrt_trace.so:$LD_PRELOAD` to add `libmsosrt_trace.so` to the `LD_PRELOAD` environment variable. |
| 64 | 64 | ||
| 65 | - 3. Set the environment variables for the detection threshold and output method. Select either real-time printing or file export. | 65 | + 3. Set the environment variables for the detection threshold and export mode (real-time printing or file export; avoid enabling both modes simultaneously): |
| 66 | 66 | ||
| 67 | - ```bash | 67 | + ```bash |
| 68 | - # Detection threshold. A positive integer. Only library functions whose duration exceeds the threshold are recorded. Unit: ns. Default: 10000000. | 68 | + # Detection threshold. A positive integer. Only library functions whose duration exceeds the threshold are recorded. Unit: ns. Default: 10000000. |
| 69 | - export MSOSRT_TRACE_THRESHOLD=10000000 | 69 | + export MSOSRT_TRACE_THRESHOLD=10000000 |
| 70 | - # Real-time printing. A positive integer. Set to 1 to print detection results in real time without writing them to a file. Default: 0. | 70 | + # Real-time printing. A positive integer. Set to 1 to print detection results in real time without writing them to a file. Default: 0. |
| 71 | - export MSOSRT_REALTIME_PRINT=1 | 71 | + export MSOSRT_REALTIME_PRINT=1 |
| 72 | - # File export. A string specifying the directory for exporting detection results. Default: current directory. | 72 | + # File export. A string specifying the directory for exporting detection results. Default: current directory. |
| 73 | - export MSOSRT_EXPORT_PATH="./osrt_trace_result" | 73 | + export MSOSRT_EXPORT_PATH="./osrt_trace_result" |
| 74 | - ``` | 74 | + ``` |
| 75 | 75 | ||
| 76 | - 4. Run the training process. | 76 | + 4. Run the training process. |
| 77 | 77 | ||
| 78 | - 5. If real-time printing is selected, detection results are printed in real time while the user process is running, as shown below: | 78 | + 5. If real-time printing is selected, detection results are printed in real time while the user process is running, as shown in the following figure: |
| 79 | 79 | ||
| 80 | - ```text | 80 | + ```text |
| 81 | - Pid: 2328177, Tid: 2328280, Function: pthread_cond_wait, StartTime: 1725398310787080000, Duration: 3088062410 | 81 | + Pid: 2328177, Tid: 2328280, Function: pthread_cond_wait, StartTime: 1725398310787080000, Duration: 3088062410 |
| 82 | - Pid: 2328177, Tid: 2328282, Function: pthread_cond_wait, StartTime: 1725398310787170000, Duration: 3087994240 | 82 | + Pid: 2328177, Tid: 2328282, Function: pthread_cond_wait, StartTime: 1725398310787170000, Duration: 3087994240 |
| 83 | - Pid: 2328177, Tid: 2328480, Function: read, StartTime: 1725398318916180000, Duration: 100509970 | 83 | + Pid: 2328177, Tid: 2328480, Function: read, StartTime: 1725398318916180000, Duration: 100509970 |
| 84 | - Pid: 2328177, Tid: 2328440, Function: ioctl, StartTime: 1725398319218640000, Duration: 512040720 | 84 | + Pid: 2328177, Tid: 2328440, Function: ioctl, StartTime: 1725398319218640000, Duration: 512040720 |
| 85 | - Pid: 2328177, Tid: 2328177, Function: free, StartTime: 1725398330504550000, Duration: 56386880 | 85 | + Pid: 2328177, Tid: 2328177, Function: free, StartTime: 1725398330504550000, Duration: 56386880 |
| 86 | - ``` | 86 | + ``` |
| 87 | 87 | ||
| 88 | - 6. If file export is selected, detection results are generated in the directory specified by `MSOSRT_EXPORT_PATH` after the user process exits. The result file is named `msosrt_trace_{process_id}_{process_name}.csv`, such as `msosrt_trace_2328177_python3.csv`. The file contains information such as the process ID (PID), thread ID (TID), function name, start time, and duration, as shown in the following table. | 88 | + 6. If file export is selected, detection results are generated in the directory specified by `MSOSRT_EXPORT_PATH` after the user process exits. The result file is named `msosrt_trace_{process_id}_{process_name}.csv`, such as `msosrt_trace_2328177_python3.csv`. The file contains information such as the process ID (PID), thread ID (TID), function name, start time, and duration, as shown in the following table. |
| 89 | 89 | ||
| 90 | - | Pid | Tid | Function | StartTime(ns) | Duration(ns) | | 90 | + | Pid | Tid | Function | StartTime(ns) | Duration(ns) | |
| 91 | - | --- | --- | --- | --- | --- | | 91 | + | --- | --- | --- | --- | --- | |
| 92 | - | 2328177 | 2328280 | pthread_cond_wait | 1725398310787080000 | 3088062410 | | 92 | + | 2328177 | 2328280 | pthread_cond_wait | 1725398310787080000 | 3088062410 | |
| 93 | - | 2328177 | 2328282 | pthread_cond_wait | 1725398310787170000 | 3087994240 | | 93 | + | 2328177 | 2328282 | pthread_cond_wait | 1725398310787170000 | 3087994240 | |
| 94 | - | 2328177 | 2328480 | read | 1725398318916180000 | 100509970 | | 94 | + | 2328177 | 2328480 | read | 1725398318916180000 | 100509970 | |
| 95 | - | 2328177 | 2328440 | ioctl | 1725398319218640000 | 512040720 | | 95 | + | 2328177 | 2328440 | ioctl | 1725398319218640000 | 512040720 | |
| 96 | - | 2328177 | 2328177 | free | 1725398330504550000 | 56386880 | | 96 | + | 2328177 | 2328177 | free | 1725398330504550000 | 56386880 | |
| 97 | 97 | ||
| 98 | - The detection results show that `pthread_cond_wait` accounts for a high proportion of the execution time and is the primary cause of lock waits. Meanwhile, `read`, `ioctl`, and other functions also account for high proportions and are the primary contributors to the time spent on data preprocessing. Based on this information, the performance bottleneck in the data preprocessing logic can be identified. | 98 | + From the detection results, it can be observed that the `pthread_cond_wait` function accounts for a relatively high proportion, which is the main cause of lock waiting. At the same time, functions such as read and ioctl also account for a relatively high proportion, which is the main cause of the time consumed by the data preprocessing logic. Based on this information, we can locate the performance bottleneck in the data preprocessing logic. |
| 99 | 99 | ||
| 100 | -## Root Cause | 100 | +## 5. Root Cause |
| 101 | 101 | ||
| 102 | 1. Incorrect lock granularity: | 102 | 1. Incorrect lock granularity: |
| 103 | 103 | ||
| @@ -109,25 +109,25 @@ For details, see the following figure. | |||
| 109 | - The default `PTHREAD_MUTEX_TIMED_NP` type is used, resulting in significant performance degradation under high contention. | 109 | - The default `PTHREAD_MUTEX_TIMED_NP` type is used, resulting in significant performance degradation under high contention. |
| 110 | - `PTHREAD_MUTEX_ADAPTIVE_NP` adaptive locking is not enabled, resulting in excessive futex waits in kernel space. | 110 | - `PTHREAD_MUTEX_ADAPTIVE_NP` adaptive locking is not enabled, resulting in excessive futex waits in kernel space. |
| 111 | 111 | ||
| 112 | -## Summary of the Troubleshooting Methodology | 112 | +## 6. Troubleshooting Methodology Summary |
| 113 | 113 | ||
| 114 | For thread lock wait scenarios, prioritize the following troubleshooting steps: | 114 | For thread lock wait scenarios, prioritize the following troubleshooting steps: |
| 115 | 115 | ||
| 116 | -1. First, use the lock analysis capabilities of `perf`. | 116 | +1. First, use the lock analysis capabilities of perf. |
| 117 | 117 | ||
| 118 | - Run `perf record` to quickly determine whether lock contention exists and identify the lock objects experiencing the most severe contention. | 118 | - Run `perf record` to quickly determine whether lock contention exists and identify the lock objects experiencing the most severe contention. |
| 119 | - Generate a flame graph and examine the CPU proportions of `pthread_mutex_lock` and `pthread_cond_wait`. A high proportion may indicate a thread lock issue. | 119 | - Generate a flame graph and examine the CPU proportions of `pthread_mutex_lock` and `pthread_cond_wait`. A high proportion may indicate a thread lock issue. |
| 120 | 120 | ||
| 121 | -2. Use the `MSOSRT` tool for detailed analysis. | 121 | +2. Use the MSOSRT tool for detailed analysis. |
| 122 | 122 | ||
| 123 | - - Use the `MSOSRT` detection results to identify `pthread_cond_wait` as the primary cause of lock waits. | 123 | + - Use the MSOSRT detection results to identify `pthread_cond_wait` as the primary cause of lock waits. |
| 124 | - Analyze functions such as `read` and `ioctl`, which account for high proportions and are the primary contributors to the time spent on data preprocessing. | 124 | - Analyze functions such as `read` and `ioctl`, which account for high proportions and are the primary contributors to the time spent on data preprocessing. |
| 125 | 125 | ||
| 126 | -## Suggestions for Improving the Tools | 126 | +## 7. Suggestions for Tool Improvement |
| 127 | 127 | ||
| 128 | -1. Enhance `msprof` by integrating `perf`. | 128 | +1. Enhance msProf by integrating perf: |
| 129 | 129 | ||
| 130 | - - Integrate `perf` into `msprof` so that lock detection can directly output statistics on lock hold time, rather than only wait time. | 130 | + - Integrate perf into msProf so that lock detection can directly output statistics on lock hold time, rather than only wait time. |
| 131 | - Add call stack tracing for lock contention to directly show which function path holds the lock for the longest time. | 131 | - Add call stack tracing for lock contention to directly show which function path holds the lock for the longest time. |
| 132 | 132 | ||
| 133 | 2. Add a lock contention visualization tool. | 133 | 2. Add a lock contention visualization tool. |
| @@ -1,20 +1,20 @@ | |||
| 1 | # High Python GC Overhead | 1 | # High Python GC Overhead |
| 2 | 2 | ||
| 3 | -## Background | 3 | +## 1. Background |
| 4 | 4 | ||
| 5 | During GPT-like LLM training in a multi-node distributed environment, the customer observed frequent performance jitter. | 5 | During GPT-like LLM training in a multi-node distributed environment, the customer observed frequent performance jitter. |
| 6 | 6 | ||
| 7 | -## Source | 7 | +## 2. Source |
| 8 | 8 | ||
| 9 | Training | 9 | Training |
| 10 | 10 | ||
| 11 | -## Symptoms | 11 | +## 3. Symptoms |
| 12 | 12 | ||
| 13 | The issue can be reproduced consistently. Long-running analysis shows that the training step duration across nodes exhibits highly consistent fluctuation patterns and frequencies. The duration periodically fluctuates between approximately 2770 ms and 2900 ms, as shown in the following figure. | 13 | The issue can be reproduced consistently. Long-running analysis shows that the training step duration across nodes exhibits highly consistent fluctuation patterns and frequencies. The duration periodically fluctuates between approximately 2770 ms and 2900 ms, as shown in the following figure. |
| 14 | 14 | ||
| 15 |  | 15 |  |
| 16 | 16 | ||
| 17 | -## Troubleshooting Process | 17 | +## 4. Troubleshooting Process |
| 18 | 18 | ||
| 19 | 1. Use the Ascend PyTorch Profiler with GC detection enabled to collect and analyze model profile data. The analysis shows that, in the abnormal steps where training duration fluctuates, a significant `free` duration is observed on the timeline. This `free` operation occurs in a Python function call stack on the framework side and is not directly associated with NPU hardware execution or HCCL communication operators. After multiple profiling sessions and cross-validation, the abnormal `free` duration is consistently observed in the execution path of the same `nn.Module`, and a GC event is detected during the same period. | 19 | 1. Use the Ascend PyTorch Profiler with GC detection enabled to collect and analyze model profile data. The analysis shows that, in the abnormal steps where training duration fluctuates, a significant `free` duration is observed on the timeline. This `free` operation occurs in a Python function call stack on the framework side and is not directly associated with NPU hardware execution or HCCL communication operators. After multiple profiling sessions and cross-validation, the abnormal `free` duration is consistently observed in the execution path of the same `nn.Module`, and a GC event is detected during the same period. |
| 20 | 20 | ||
| @@ -26,9 +26,9 @@ The issue can be reproduced consistently. Long-running analysis shows that the t | |||
| 26 | profiler_level=torch_npu.profiler.ProfilerLevel.Level0, | 26 | profiler_level=torch_npu.profiler.ProfilerLevel.Level0, |
| 27 | aic_metrics=torch_npu.profiler.AiCMetrics.AiCoreNone, | 27 | aic_metrics=torch_npu.profiler.AiCMetrics.AiCoreNone, |
| 28 | data_simplification=False, | 28 | data_simplification=False, |
| 29 | - gc_detect_threshold=1, # Enable GC detection and set the GC detection threshold to 1 ms | 29 | + gc_detect_threshold=1, # Enable the GC detection option and set the GC detection threshold to 1 ms. |
| 30 | ) | 30 | ) |
| 31 | - | 31 | + |
| 32 | # Add the basic profiling configuration parameters. For details, see the parameter descriptions below. | 32 | # Add the basic profiling configuration parameters. For details, see the parameter descriptions below. |
| 33 | with torch_npu.profiler.profile( | 33 | with torch_npu.profiler.profile( |
| 34 | activities=[ | 34 | activities=[ |
| @@ -38,7 +38,7 @@ The issue can be reproduced consistently. Long-running analysis shows that the t | |||
| 38 | schedule=torch_npu.profiler.schedule(wait=0, warmup=0, active=1, repeat=1, skip_first=0), # Used together with prof.step() | 38 | schedule=torch_npu.profiler.schedule(wait=0, warmup=0, active=1, repeat=1, skip_first=0), # Used together with prof.step() |
| 39 | on_trace_ready=torch_npu.profiler.tensorboard_trace_handler("./result"), | 39 | on_trace_ready=torch_npu.profiler.tensorboard_trace_handler("./result"), |
| 40 | experimental_config=experimental_config) as prof: | 40 | experimental_config=experimental_config) as prof: |
| 41 | - | 41 | + |
| 42 | # Start profile data collection. | 42 | # Start profile data collection. |
| 43 | for step in range(steps): # Training iterations | 43 | for step in range(steps): # Training iterations |
| 44 | train_one_step() # Training function | 44 | train_one_step() # Training function |
| @@ -75,7 +75,7 @@ The issue can be reproduced consistently. Long-running analysis shows that the t | |||
| 75 | 75 | ||
| 76 | Result: The performance jitter is eliminated. | 76 | Result: The performance jitter is eliminated. |
| 77 | 77 | ||
| 78 | -4. Adjust the Python GC thresholds. | 78 | +4. Adjust the Python GC reclamation threshold. |
| 79 | 79 | ||
| 80 | Adjust the Python GC thresholds before starting model training. For details, see the [Python GC thresholds](https://docs.python.org/3/library/gc.html#gc.set_threshold) documentation. | 80 | Adjust the Python GC thresholds before starting model training. For details, see the [Python GC thresholds](https://docs.python.org/3/library/gc.html#gc.set_threshold) documentation. |
| 81 | 81 | ||
| @@ -86,18 +86,18 @@ The issue can be reproduced consistently. Long-running analysis shows that the t | |||
| 86 | 86 | ||
| 87 | Result: The performance jitter persists but occurs less frequently. | 87 | Result: The performance jitter persists but occurs less frequently. |
| 88 | 88 | ||
| 89 | -## Root Cause | 89 | +## 5. Root Cause |
| 90 | 90 | ||
| 91 | As an interpreted language, Python uses an interpreter implemented in C to parse and execute bytecode instructions. In Python's memory management mechanism, each object maintains a reference count to track whether it is referenced. When an object's reference count reaches 0, indicating that the object is no longer referenced, Python immediately reclaims the memory occupied by the object. | 91 | As an interpreted language, Python uses an interpreter implemented in C to parse and execute bytecode instructions. In Python's memory management mechanism, each object maintains a reference count to track whether it is referenced. When an object's reference count reaches 0, indicating that the object is no longer referenced, Python immediately reclaims the memory occupied by the object. |
| 92 | 92 | ||
| 93 | -However, when Python objects form circular references, such as when A references B and B references A, the reference counting mechanism alone cannot reduce the reference counts of these objects to 0. As a result, the memory occupied by these objects cannot be automatically reclaimed. To address memory leaks caused by circular references, Python provides an automatic garbage collection (GC) mechanism. When the allocation and deallocation counts for a generation exceed its configured threshold, Python automatically triggers a GC event and uses a mark-and-sweep algorithm to identify and release unreachable objects involved in circular references. | 93 | +However, when circular references form between Python objects (that is, a cyclic dependency where A references B and B references A), the reference counting mechanism alone cannot reduce the reference counts of these objects to zero, and this portion of memory cannot be reclaimed automatically. To address the memory leak caused by circular references, Python introduces an automatic Garbage Collection (GC) mechanism. When the number of accumulated objects that form circular references exceeds the configured reclamation threshold, Python automatically triggers a GC event, which scans and releases these useless objects involved in circular references through the `mark-and-sweep` algorithm. |
| 94 | 94 | ||
| 95 | It is important to note that GC is a compute-intensive operation that can incur significant execution overhead, and it can block the Python process during execution due to its Stop-the-World behavior. In foundation-model training scenarios, where performance stability is critical, the most typical external symptom of a GC event is a sudden increase in the duration of an individual training step, resulting in significant periodic performance fluctuations throughout the training process. | 95 | It is important to note that GC is a compute-intensive operation that can incur significant execution overhead, and it can block the Python process during execution due to its Stop-the-World behavior. In foundation-model training scenarios, where performance stability is critical, the most typical external symptom of a GC event is a sudden increase in the duration of an individual training step, resulting in significant periodic performance fluctuations throughout the training process. |
| 96 | 96 | ||
| 97 | -## Summary of the Troubleshooting Methodology | 97 | +## 6. Troubleshooting Methodology Summary |
| 98 | 98 | ||
| 99 | For this scenario, first use the Ascend PyTorch Profiler to collect model profile data and check whether GC events occur in the timeline. If a GC event is present, analyze its trigger conditions, impact, and duration, and adjust the Python GC thresholds to reduce the frequency of GC events. | 99 | For this scenario, first use the Ascend PyTorch Profiler to collect model profile data and check whether GC events occur in the timeline. If a GC event is present, analyze its trigger conditions, impact, and duration, and adjust the Python GC thresholds to reduce the frequency of GC events. |
| 100 | 100 | ||
| 101 | -## Suggestions for Improving the Tools | 101 | +## 7. Suggestions for Tool Improvement |
| 102 | 102 | ||
| 103 | None. | 103 | None. |
| @@ -1,253 +0,0 @@ | |||
| 1 | -# Troubleshooting Guide: Long Wait Time for Model Inference Requests | ||
| 2 | - | ||
| 3 | -## Scenario Description | ||
| 4 | - | ||
| 5 | -In foundation-model inference service scenarios, a request typically goes through multiple stages from entering the service to starting model inference, including gateway forwarding, request queueing, batch formation, prefill execution, decode scheduling, and result delivery. If a request waits too long, users may experience increased time to first token (TTFT), degraded end-to-end P99 latency, unstable response time under low load, or continuously growing queues under high load. | ||
| 6 | - | ||
| 7 | -This document uses long wait time for inference requests as an example to describe how to use `msServiceProfiler` to collect `Request` and `BatchSchedule` data, identify whether the waiting time is primarily caused by queueing at the service entry point, batch formation, prefill/decode resource contention, external dependency blocking, or system resource bottlenecks, and provide optimization approaches for batching, scheduling, resources, caching, and monitoring. | ||
| 8 | - | ||
| 9 | -## Symptoms | ||
| 10 | - | ||
| 11 | -**Typical Symptoms** | ||
| 12 | - | ||
| 13 | -- The number of requests in the `waiting` state in `Request_Status_curve` continues to increase and does not decrease for an extended period. | ||
| 14 | -- P90/P99 of `First_Token_Latency_curve` is significantly elevated, while individual model execution durations do not increase proportionally. | ||
| 15 | -- `Request_Latency_curve` shows significant fluctuations in end-to-end latency, and tail latency increases rapidly during peak traffic. | ||
| 16 | -- `Batch_Size_curve` shows that the batch size remains small or that batch formation takes too long, indicating that the batch formation strategy does not match the request workload. | ||
| 17 | -- Prefill and decode requests contend for resources, causing short requests to be blocked by long requests. | ||
| 18 | -- The service process has high CPU activity but low NPU utilization, indicating that requests may be blocked in I/O, scheduling, or preprocessing stages. | ||
| 19 | - | ||
| 20 | -**Impact** | ||
| 21 | - | ||
| 22 | -| Item | Symptom | | ||
| 23 | -| --- | --- | | ||
| 24 | -| Time to first token | Requests wait too long for batch formation or prefill resources, resulting in higher TTFT. | | ||
| 25 | -| End-to-end latency | Queueing time is amplified, resulting in degraded P90/P99 request latency. | | ||
| 26 | -| Throughput | Batches are not filled to the expected size or scheduling is too conservative, resulting in low NPU utilization. | | ||
| 27 | -| Stability | Queues continue to grow under peak traffic, resulting in timeouts or request failures. | | ||
| 28 | -| Resource utilization | CPU, memory, KV Cache, or NPU resources are allocated unevenly, resulting in local resource bottlenecks. | | ||
| 29 | - | ||
| 30 | -## Data Collection | ||
| 31 | - | ||
| 32 | -### Function Description | ||
| 33 | - | ||
| 34 | -Use `msServiceProfiler` to collect data from the `Request`, `BatchSchedule`, `ModelExecute`, `KVCache`, and `Communication` domains. Combine the collected data with `batch.csv`, `request.csv`, `BatchSchedule.csv`, `forward.csv`, and visualization curves to identify the sources of request waiting time. | ||
| 35 | - | ||
| 36 | -### Precautions | ||
| 37 | - | ||
| 38 | -- Collect profile data in a stress testing scenario that can reproduce the issue consistently. Record key parameters such as concurrency, input and output lengths, `maxBatchSize`, and `max_wait_time`. | ||
| 39 | -- If most of the waiting time occurs at the service entry point or in external dependencies, also collect logs from the service gateway, database, cache, and postprocessing paths. | ||
| 40 | -- In multi-instance or distributed cluster scenarios, ensure that the clocks of all nodes are synchronized to avoid deviations in Timeline analysis. | ||
| 41 | -- Enabling more domains increases the amount of collected data. It is recommended to collect `Request` and `BatchSchedule` data first, and then add `ModelExecute`, `KVCache`, and `Communication` data as needed. | ||
| 42 | - | ||
| 43 | -### Configuration Example | ||
| 44 | - | ||
| 45 | -Create `ms_service_profiler_config.json` to collect request status, batch scheduling, and model execution data. | ||
| 46 | - | ||
| 47 | -```json | ||
| 48 | -{ | ||
| 49 | - "enable": 1, | ||
| 50 | - "prof_dir": "${HOME}/.ms_server_profiler", | ||
| 51 | - "profiler_level": "INFO", | ||
| 52 | - "domain": "Request;BatchSchedule;ModelExecute;KVCache;Communication" | ||
| 53 | -} | ||
| 54 | -``` | ||
| 55 | - | ||
| 56 | -Set the configuration file path before starting the service. | ||
| 57 | - | ||
| 58 | -```bash | ||
| 59 | -export SERVICE_PROF_CONFIG_PATH=/path/to/ms_service_profiler_config.json | ||
| 60 | -``` | ||
| 61 | - | ||
| 62 | -When parsing the data, it is recommended to export the default span data and focus on `forward.csv` and `BatchSchedule.csv`. | ||
| 63 | - | ||
| 64 | -```bash | ||
| 65 | -ms_service_profiler_parse --input-path ${PROF_DIR} --output-path ${OUTPUT_DIR} --span | ||
| 66 | -``` | ||
| 67 | - | ||
| 68 | -### Instrumentation Recommendations | ||
| 69 | - | ||
| 70 | -If the framework already contains custom scheduling logic, add spans and metrics around request queueing, batch formation, external dependencies, and model execution. | ||
| 71 | - | ||
| 72 | -```C++ | ||
| 73 | -auto enqueueSpan = PROF(INFO, SpanStart("RequestEnqueue")); | ||
| 74 | - | ||
| 75 | -// Request queueing, authentication, parameter parsing, and other logic | ||
| 76 | - | ||
| 77 | -PROF(enqueueSpan.SpanEnd()); | ||
| 78 | - | ||
| 79 | -auto batchWaitSpan = PROF(INFO, SpanStart("BatchWait")); | ||
| 80 | - | ||
| 81 | -// Wait for batch formation or for max_wait_time to expire | ||
| 82 | - | ||
| 83 | -PROF(batchWaitSpan.SpanEnd()); | ||
| 84 | - | ||
| 85 | -auto modelReadySpan = PROF(INFO, SpanStart("ModelReady")); | ||
| 86 | - | ||
| 87 | -// Prefill/Decode scheduling is complete and the request is ready for model execution | ||
| 88 | - | ||
| 89 | -PROF(modelReadySpan.SpanEnd()); | ||
| 90 | -``` | ||
| 91 | - | ||
| 92 | -Collect the queue length, batch formation wait time, and external dependency duration. | ||
| 93 | - | ||
| 94 | -```C++ | ||
| 95 | -PROF(INFO, Metric("requestQueueSize", requestQueueSize).MetricScope("scheduler", instanceId).Launch()); | ||
| 96 | -PROF(INFO, Metric("batchWaitMs", batchWaitMs).MetricScope("batch", batchId).Launch()); | ||
| 97 | -PROF(INFO, Metric("externalIOMs", externalIOMs).MetricScope("request", reqId).Launch()); | ||
| 98 | -``` | ||
| 99 | - | ||
| 100 | -## Troubleshooting | ||
| 101 | - | ||
| 102 | -1. Check `Request_Status_curve`. | ||
| 103 | - - If the number of `waiting` requests continues to increase, the incoming traffic exceeds the service consumption capacity. Check the batching strategy, number of instances, and resource bottlenecks. | ||
| 104 | - - If the number of `waiting` requests periodically increases and then decreases, `max_wait_time` may be too long or the batch formation window may be too large. | ||
| 105 | - - If the number of `running` requests is low while the number of `waiting` requests is high, requests may be blocked in scheduling, I/O, or thread pool processing. | ||
| 106 | - | ||
| 107 | -2. Check `Batch_Size_curve` and `batch.csv`. | ||
| 108 | - - If the batch size remains below `maxBatchSize`, `max_wait_time` may be too short, concurrency may be insufficient, or scheduling conditions may be too restrictive. | ||
| 109 | - - If the batch size is close to `maxBatchSize` but waiting time remains high, model execution capacity may be insufficient. Consider scaling out or optimizing prefill/decode scheduling. | ||
| 110 | - - If `prefill_batch_size` and `decode_batch_size` fluctuate significantly, prefill and decode may be contending for resources. Consider adjusting the priority policy. | ||
| 111 | - | ||
| 112 | -3. Check `First_Token_Latency_curve`. | ||
| 113 | - - If TTFT increases while prefill execution time remains normal, the waiting time primarily occurs between request queueing and the start of prefill. | ||
| 114 | - - If both TTFT and prefill execution time increase, check `maxPrefillBatchSize`, `maxSeqLen`, KV Cache, and prefill operator performance. | ||
| 115 | - | ||
| 116 | -4. Check `Request_Latency_curve`. | ||
| 117 | - - If P99 end-to-end latency increases while average latency remains largely unchanged, a small number of requests may be delayed by long queues, long contexts, or external dependencies. | ||
| 118 | - - If both average latency and P99 latency increase, the overall service consumption capacity is insufficient. Prioritize scaling out or reducing the computation cost of individual requests. | ||
| 119 | - | ||
| 120 | -## Cause Analysis and Solutions | ||
| 121 | - | ||
| 122 | -### Mismatched Batching Parameters | ||
| 123 | - | ||
| 124 | -**Cause** | ||
| 125 | - | ||
| 126 | -A small `maxBatchSize` limits throughput. A long `max_wait_time` causes excessive waiting under low load, while a short `max_wait_time` makes it difficult to fill batches. If these parameters do not match the actual concurrency and request lengths, both waiting time and throughput are affected. | ||
| 127 | - | ||
| 128 | -**Solution** | ||
| 129 | - | ||
| 130 | -- Gradually increase `maxBatchSize` based on available hardware resources. For example, increase `voc_inference_max_bs` from `4` to `8` and observe NPU utilization and request latency. | ||
| 131 | -- Reduce the maximum wait time. For example, set `voc_inference_max_wait_ms` to 20 ms to reduce batch formation wait time under low load. | ||
| 132 | -- Implement dynamic batching: allow a longer wait under low load to improve batch utilization and shorten the wait window under high load to reduce tail latency. | ||
| 133 | -- Compare `Batch_Size_curve`, `Request_Status_curve`, `First_Token_Latency`, and throughput after each adjustment to avoid optimizing only a single metric. | ||
| 134 | - | ||
| 135 | -### Improper Prefill/Decode Scheduling Strategy | ||
| 136 | - | ||
| 137 | -**Cause** | ||
| 138 | - | ||
| 139 | -The prefill stage is typically compute-intensive, while the decode stage requires continuous iterations. If the scheduling policy is fixed or requests are processed only in arrival order, long prefill requests may block decode requests, while continuous decode execution may cause new requests to wait too long for their first token. | ||
| 140 | - | ||
| 141 | -**Solution** | ||
| 142 | - | ||
| 143 | -- Enable prefill/decode priority scheduling and dynamically select the scheduling policy based on `prefillTimeMsPerReq` and `decodeTimeMsPerReq`. | ||
| 144 | -- Assign higher scheduling priority to short requests to reduce the probability of short requests being blocked by requests with long contexts. | ||
| 145 | -- Limit the amount of resources that a single prefill round can consume under high concurrency to prevent decode from being starved for an extended period. | ||
| 146 | -- Place requests with long contexts or long outputs into separate buckets to prevent them from slowing down the normal request queue. | ||
| 147 | -- Use `BatchSchedule.csv` to analyze the time distribution of prefill and decode batches and verify whether scheduling changes reduce queueing time. | ||
| 148 | - | ||
| 149 | -### Synchronous Blocking or External Dependencies Slowing Down The Main Thread | ||
| 150 | - | ||
| 151 | -**Cause** | ||
| 152 | - | ||
| 153 | -The service path may include authentication, database queries, vector retrieval, log persistence, network calls, or postprocessing. If these operations are performed synchronously on the main or scheduling thread, requests cannot be queued or formed into batches in a timely manner. | ||
| 154 | - | ||
| 155 | -**Solution** | ||
| 156 | - | ||
| 157 | -- Adopt an asynchronous, non-blocking architecture. For example, use an asynchronous framework such as FastAPI for I/O operations. | ||
| 158 | -- Move database queries, cache access, log persistence, and postprocessing out of the critical scheduling path. | ||
| 159 | -- Set timeouts and fallback mechanisms for external dependencies to prevent a single slow dependency from blocking the entire request. | ||
| 160 | -- Use metrics to record `externalIOMs` and `requestQueueSize` to determine whether waiting is caused by external I/O. | ||
| 161 | - | ||
| 162 | -### Insufficient Instance Resources or Load Imbalance | ||
| 163 | - | ||
| 164 | -**Cause** | ||
| 165 | - | ||
| 166 | -When a single instance handles too many requests, its queue continues to grow. In a multi-instance deployment, a coarse-grained routing strategy may overload some instances while leaving others idle, resulting in higher overall P99 latency. | ||
| 167 | - | ||
| 168 | -**Solution** | ||
| 169 | - | ||
| 170 | -- Deploy a distributed inference cluster and use Kubernetes Service or a gateway for load balancing across instances. | ||
| 171 | -- Use HPA to automatically scale instances based on QPS, queue length, NPU utilization, or P99 latency. | ||
| 172 | -- Implement intelligent request routing using a two-stage scheduling strategy of "coarse-grained bucketing at the gateway + fine-grained prediction at the instance." | ||
| 173 | -- Route requests with different lengths, business priorities, or model versions to corresponding instance pools. | ||
| 174 | -- Set circuit breakers and queue length limits for overloaded instances to prevent tail latency from increasing without bound. | ||
| 175 | - | ||
| 176 | -### Prefill/Decode Resource Contention | ||
| 177 | - | ||
| 178 | -**Cause** | ||
| 179 | - | ||
| 180 | -The prefill and decode stages have different requirements for computation, memory, and KV Cache. When they share the same resource pool, they can easily contend for resources under long-context or high-concurrency workloads, resulting in request waiting and decode fluctuations. | ||
| 181 | - | ||
| 182 | -**Solution** | ||
| 183 | - | ||
| 184 | -- Adopt prefill/decode disaggregation (PD disaggregation) and deploy prefill and decode on different nodes or instance pools. | ||
| 185 | -- Use high-performance KV Cache transfer to reduce the overhead of transferring KV Cache between prefill and decode. | ||
| 186 | -- Configure different batch sizes, concurrency levels, and scaling policies for prefill and decode instances. | ||
| 187 | -- Collect data from the Communication domain for the PD disaggregation path to verify that KV Cache transfer does not become a new bottleneck. | ||
| 188 | - | ||
| 189 | -### Missing Caching or Preprocessing Optimization | ||
| 190 | - | ||
| 191 | -**Cause** | ||
| 192 | - | ||
| 193 | -If repeated requests, similar queries, fixed system prompts, and long conversation histories are fully processed each time, the prefill workload and request waiting time increase. | ||
| 194 | - | ||
| 195 | -**Solution** | ||
| 196 | - | ||
| 197 | -- Build a vector cache layer. For example, use Redis to cache embeddings or retrieval results for frequently requested queries and reduce repeated embedding model invocations. | ||
| 198 | -- Enable prefix caching for frequently used fixed prefixes to reuse the KV Cache of historical contexts and reduce prefill computation. | ||
| 199 | -- Cache request preprocessing results, such as template concatenation, tokenization, or routing decisions. | ||
| 200 | -- Monitor the cache hit rate and correlate it with TTFT and prefill execution time. | ||
| 201 | - | ||
| 202 | -### System-Level Performance Fluctuations | ||
| 203 | - | ||
| 204 | -**Cause** | ||
| 205 | - | ||
| 206 | -CPU scheduling fluctuations, memory paging overhead, thread migration, or KV Cache memory fragmentation may cause request waiting time to become unstable. The effects of memory paging and CPU scheduling may be more significant in streaming input or speech model scenarios. | ||
| 207 | - | ||
| 208 | -**Solution** | ||
| 209 | - | ||
| 210 | -- Pin critical threads to CPUs to reduce thread migration. | ||
| 211 | -- Evaluate the Transparent Huge Pages configuration based on system requirements to reduce memory management fluctuations. | ||
| 212 | -- Use PagedAttention-like techniques to manage KV Cache in blocks, improve memory utilization, and reduce fragmentation. | ||
| 213 | -- For streaming speech input scenarios, optimize memory page and buffer sizes to reduce frequent copying of small blocks of data. | ||
| 214 | - | ||
| 215 | -## Optimization Verification | ||
| 216 | - | ||
| 217 | -It is recommended to verify optimizations in the following order: batching parameters -> scheduling strategy -> asynchronous processing -> resource scaling -> caching and system optimization. | ||
| 218 | - | ||
| 219 | -| Optimization | Metrics | Expected Result | | ||
| 220 | -| --- | --- | --- | | ||
| 221 | -| Adjust `maxBatchSize` | `Batch_Size_curve`, throughput | The batch size is closer to the expected size, and NPU utilization increases. | | ||
| 222 | -| Adjust `max_wait_time` | `First_Token_Latency`, `Request_Status_curve` | TTFT decreases, and the `waiting` queue clears more quickly. | | ||
| 223 | -| Prefill/Decode priority | `BatchSchedule.csv`, decode latency | Mutual blocking between prefill and decode is reduced. | | ||
| 224 | -| Asynchronous I/O | `externalIOMs`, `requestQueueSize` | Main-thread blocking is reduced, and request queueing becomes more stable. | | ||
| 225 | -| Distributed scaling | P99 latency, instance load | The `waiting` queue no longer continues to grow during peak traffic. | | ||
| 226 | -| Prefix cache | Prefill execution time, TTFT | TTFT decreases for requests with repeated prefixes. | | ||
| 227 | -| PagedAttention | KV Cache utilization, concurrency | Memory utilization improves, allowing more requests to be served concurrently. | | ||
| 228 | - | ||
| 229 | -When the optimization is effective, the following results are typically observed: | ||
| 230 | - | ||
| 231 | -- The peak size of the `waiting` queue in `Request_Status_curve` decreases, and the queue clears more quickly. | ||
| 232 | -- P90/P99 of `First_Token_Latency` decreases. | ||
| 233 | -- P99 of `Request_Latency` becomes more stable, and the number of timeouts decreases during peak traffic. | ||
| 234 | -- `Batch_Size_curve` better matches the expected behavior, with limited waiting under low load and limited queue buildup under high load. | ||
| 235 | -- NPU utilization increases, while CPU or I/O blocking time decreases. | ||
| 236 | - | ||
| 237 | -When batched inference is effective, the total execution time can be reduced from the sum of the execution time of multiple serial single-request executions to a duration close to that of a single batched execution, while NPU utilization also increases significantly. If dynamic batching and an asynchronous architecture are both enabled, pay particular attention to TTFT, average inter-token latency, and tokens/s to determine whether they improve simultaneously. | ||
| 238 | - | ||
| 239 | -## Recommended Actions | ||
| 240 | - | ||
| 241 | -| Issue Type | Recommended Solution | | ||
| 242 | -| --- | --- | | ||
| 243 | -| High waiting time under low load | Reduce `max_wait_time` to shorten the batch formation wait window. | | ||
| 244 | -| Queue buildup under high load | Increase `maxBatchSize` or scale out instances, and enable dynamic batching. | | ||
| 245 | -| High TTFT but normal model execution time | Prioritize checking request queueing, batch formation wait time, external I/O, and prefill scheduling. | | ||
| 246 | -| Significant decode fluctuations | Optimize prefill/decode priorities and evaluate PD disaggregation and communication optimization. | | ||
| 247 | -| High proportion of repeated requests | Enable vector caching, result caching, or prefix caching. | | ||
| 248 | -| KV Cache close to its limit | Adjust `maxSeqLen`, limit concurrency, or enable PagedAttention-like management capabilities. | | ||
| 249 | -| High P99 latency across multiple instances | Optimize request routing and use HPA and fine-grained instance load prediction. | | ||
| 250 | - | ||
| 251 | -## Summary | ||
| 252 | - | ||
| 253 | -Long wait time for model inference requests is typically not caused solely by model execution. It can also occur in request queueing, batch formation, prefill/decode scheduling, external I/O, resource contention, and missing caching mechanisms in the service path. During troubleshooting, first use `msServiceProfiler` to collect `Request` and `BatchSchedule` data, and use `Request_Status_curve`, `Batch_Size_curve`, `First_Token_Latency`, and `Request_Latency` to determine where the waiting time occurs. For optimization, prioritize adjusting `maxBatchSize` and `max_wait_time`. Then introduce prefill/decode priority scheduling, asynchronous I/O, distributed scaling, PD disaggregation, prefix caching, and PagedAttention as needed to progressively reduce TTFT and end-to-end P99 latency. | ||
| @@ -1,95 +0,0 @@ | |||
| 1 | -# Analysis of Excessive Sampler Execution Time | ||
| 2 | - | ||
| 3 | -## Background | ||
| 4 | - | ||
| 5 | -In foundation-model inference, the Sampler is one of the core components in the generation stage. It is responsible for calculating the probability distribution from logits and sampling the next token after the model completes a single forward inference. The Sampler execution logic includes multiple steps, such as Softmax normalization, Top-K/Top-P filtering, temperature scaling, random sampling, and greedy selection. When the Sampler takes too long to execute, it directly increases the end-to-end latency of the entire decode stage. This impact is amplified over repeated iterations, especially in the frequently executed decode process, which is triggered in every iteration. | ||
| 6 | - | ||
| 7 | -## Source | ||
| 8 | - | ||
| 9 | -Inference | ||
| 10 | - | ||
| 11 | -## Symptoms | ||
| 12 | - | ||
| 13 | -This issue is consistently reproducible under high-concurrency or long-sequence scenarios. | ||
| 14 | -**Issue Type**: Compute bottleneck / host-NPU interaction overhead. | ||
| 15 | - | ||
| 16 | -1. **Sampler stage takes excessively long in the timeline**: In the MindStudio Insight timeline, the `sampler`-related operations occupy a significant time span within a request's model execution cycle after `modelExec` (model forward) ends. The execution time is comparable to or even longer than that of the model computation itself. | ||
| 17 | -2. **Execution hangs at the sampling step**: Logs or debugging shows that execution is stuck at code lines such as `sampled_token_ids = sampler_output.sampled_token_ids`, and the program remains unresponsive for an extended period. | ||
| 18 | -3. **Latency increases sharply under high concurrency**: As the number of concurrent requests increases, the token generation latency increases significantly, while the model forward execution time remains relatively stable. The bottleneck is concentrated in the Sampler stage. | ||
| 19 | -4. **NPU and CPU utilization show an inverse relationship**: NPU utilization is relatively low, while the CPU core running the Sampler has high utilization, indicating significant host-side computation or synchronization overhead. | ||
| 20 | - | ||
| 21 | -## Troubleshooting Process | ||
| 22 | - | ||
| 23 | -### Step 1: Collecting Service Execution Timelines Using `msServiceProfiler` | ||
| 24 | - | ||
| 25 | -Use **msServiceProfiler** to collect request-level timeline data, with a focus on the execution time of the Sampler stage. This tool is specifically designed for MindIE Service inference service scenarios and can collect the start and end timestamps of key processes. | ||
| 26 | - | ||
| 27 | -1. **Prepare the configuration**: Create `ms_service_profiler_config.json` and enable fine-grained event collection. | ||
| 28 | - | ||
| 29 | - ```json | ||
| 30 | - { | ||
| 31 | - "enable": 1, | ||
| 32 | - "prof_dir": "/path/to/profile_output", | ||
| 33 | - "record_op_detail": true | ||
| 34 | - } | ||
| 35 | - ``` | ||
| 36 | - | ||
| 37 | -2. **Start data collection**: | ||
| 38 | - | ||
| 39 | - ```bash | ||
| 40 | - export SERVICE_PROF_CONFIG_PATH=/path/to/ms_service_profiler_config.json | ||
| 41 | - # Start the MindIE Service | ||
| 42 | - ``` | ||
| 43 | - | ||
| 44 | -3. **Reproduce the load**: Use concurrent service requests for stress testing to reproduce the scenario in which the Sampler takes abnormally long to execute. | ||
| 45 | -4. **Parse the data**: | ||
| 46 | - | ||
| 47 | - ```bash | ||
| 48 | - python3 -m ms_service_profiler.parse --input-path=/path/to/profile_output | ||
| 49 | - ``` | ||
| 50 | - | ||
| 51 | -### Step 2: Performing Fine-grained Timeline Analysis Using MindStudio Insight | ||
| 52 | - | ||
| 53 | -Import the generated `chrome_tracing.json` into **MindStudio Insight** for visual analysis. MindStudio Insight presents the execution of the entire process in the timeline and supports fine-grained analysis of the inference process. | ||
| 54 | - | ||
| 55 | -1. **Locate the Sampler stage**: Locate the Sampler-related tracks in the timeline, such as the `Sampler`, `PostProcess`, or `Sampling` thread. | ||
| 56 | -2. **Observe the execution sequence**: Focus on the interval between `modelExec` and `sampler`, as well as the length of the execution span within the Sampler. | ||
| 57 | -3. **Identify implicit synchronization**: If there is a significant idle gap or wait marker in the Sampler stage, implicit synchronization between the host and device may be occurring. Experience from the vLLM community indicates that `sampler_output.sampled_token_ids` may involve synchronization or data copying from a GPU tensor to the CPU. This overhead can be amplified under high concurrency. | ||
| 58 | -4. **Perform comparative analysis**: Compare Sampler execution time across different `batch_size` values or sequence lengths and determine whether there is a linear growth relationship. | ||
| 59 | - | ||
| 60 | -### Step 3: Checking Sampling Parameters and Configuration | ||
| 61 | - | ||
| 62 | -Check request parameters and service-side configuration to rule out excessive Sampler computation caused by parameter configuration. | ||
| 63 | - | ||
| 64 | -1. **Check sampling parameters**: Check whether the request contains a complex combination of sampling parameters, such as `top_k`, `top_p`, `temperature`, and `repetition_penalty` being enabled simultaneously, or postprocessing parameters such as `logprobs` and `best_of` that require additional computation. | ||
| 65 | -2. **Check the vocabulary size**: Check the model vocabulary size. For large vocabularies, such as those with more than 50K tokens, the Softmax computation itself can be relatively expensive. | ||
| 66 | -3. **Check the quantization configuration**: Check whether Sampler-related operators are running with the appropriate data types. Mixed precision may introduce additional data type conversion overhead. | ||
| 67 | - | ||
| 68 | -## Root Cause | ||
| 69 | - | ||
| 70 | -**Implicit synchronization between the host and device or a serial bottleneck in the Sampler implementation** | ||
| 71 | -(These issues fall under the **framework adaptation issues** and **scheduling implementation defects** categories.) | ||
| 72 | - | ||
| 73 | -**Detailed explanation:** | ||
| 74 | - | ||
| 75 | -1. **GPU-to-CPU data synchronization is a major cause**: Experience from the vLLM community indicates that the seemingly simple assignment `sampled_token_ids = sampler_output.sampled_token_ids` may actually trigger implicit synchronization or data copying from a GPU tensor to the CPU. Under high concurrency or when GPU memory is constrained, PCIe bandwidth may become a bottleneck, causing the sampling step to remain blocked for an extended period. | ||
| 76 | - | ||
| 77 | -2. **Large-vocabulary Softmax computation overhead**: When the vocabulary size is large, such as 50K–100K, the computation required to perform Softmax and Top-K/Top-P filtering on logits is non-negligible. If the Sampler performs these operations on the CPU, a large amount of data must be copied from the device to the host. If they are performed on the NPU, they consume compute resources that could otherwise be used for the next decode iteration. | ||
| 78 | - | ||
| 79 | -3. **Overly complex sampling parameters**: Enabling multiple sampling parameters simultaneously, such as `top_k`, `top_p`, `temperature`, and `repetition_penalty`, significantly increases the computational complexity of the Sampler, and some processing logic may be serial. | ||
| 80 | - | ||
| 81 | -4. **Improper scheduling parameter configuration**: Experience from troubleshooting in the vLLM community indicates that setting `max_num_batched_tokens` too low increases the scheduling frequency, causing the sampling step to be triggered more frequently and amplifying the impact of the overhead from each sampling operation. In addition, when `max_num_seqs` is too large, a large number of sequences must be sampled within a single batch, and the sampling time increases linearly with `batch_size`. | ||
| 82 | - | ||
| 83 | -## Summary of the Troubleshooting Methodology | ||
| 84 | - | ||
| 85 | -For the **"excessive Sampler execution time"** scenario, the key to troubleshooting is to **distinguish between "actual sampling computation time" and "implicit data transfer/synchronization time"** and avoid misidentifying synchronization overhead as a compute bottleneck. | ||
| 86 | - | ||
| 87 | -1. **Do not focus only on average execution time and ignore the timeline pattern**: If only average data is considered, long Sampler execution time may be misidentified as an efficiency issue with the sampling algorithm. You must use MindStudio Insight to observe the specific timeline pattern. If there are significant gaps or wait markers in the Sampler stage, investigate host-device synchronization issues first. | ||
| 88 | - | ||
| 89 | -2. **Use pure-model testing to isolate scheduling interference**: According to the MindStudio official optimization guide, first use pure-model testing to evaluate the upper bound of inference performance and identify the bottleneck before analyzing service scheduling issues. You can directly invoke model execution for a single inference without going through the service framework and compare whether the Sampler overhead still occurs. This helps determine whether the issue originates from the Sampler implementation itself or the service scheduling layer. | ||
| 90 | - | ||
| 91 | -3. **Check sampling parameters in logs**: Some scenarios with excessively long execution time may be caused by request parameters, such as a request containing an extremely high `top_k` value. It is recommended to add logging for sampling parameters on the service side to facilitate retrospective analysis. | ||
| 92 | - | ||
| 93 | -4. **Adjust scheduling parameters for verification**: If you suspect that an excessively high scheduling frequency is amplifying the sampling overhead, try increasing `max_num_batched_tokens` and observe whether P99 latency improves. If it does, this indicates that the sampling step was triggered too frequently under the original configuration. | ||
| 94 | - | ||
| 95 | -5. **Use msProf for operator-level analysis**: If you need to further identify which specific operator within the Sampler, such as Softmax or TopK, takes the most time, use msProf to collect operator-level profile data and then use the operator execution time panel in MindStudio Insight to identify the operators with the longest execution time. | ||
| @@ -1,107 +0,0 @@ | |||
| 1 | -# Excessive Scheduler Execution Time | ||
| 2 | - | ||
| 3 | -## Background | ||
| 4 | - | ||
| 5 | -In inference service scenarios, the scheduler is responsible for grouping incoming inference requests into batches according to specific policies and dispatching them to the NPU for execution. When the scheduler itself accounts for an excessive proportion of the total execution time, the NPU may remain idle while waiting, resulting in lower overall throughput and longer request queueing time. This is especially significant in Host Bound scenarios, such as small-model inference and the decode stage, where the host dispatch time of a single operator may exceed its device execution time, making scheduling overhead a system bottleneck. Ascend CANN provides graph-mode scheduling and model sinking technologies to optimize this issue. However, improper scheduling policy configuration, dynamic scheduling priority switching, and complex batch formation logic may still result in excessive scheduler execution time in actual deployments. | ||
| 6 | - | ||
| 7 | -## Source | ||
| 8 | - | ||
| 9 | -Inference | ||
| 10 | - | ||
| 11 | -## Symptoms | ||
| 12 | - | ||
| 13 | -Users typically first observe that the overall inference service throughput is lower than expected, NPU utilization is relatively low, and the number of waiting requests continues to increase. After breaking down the scheduling metrics in Grafana, common symptoms include: | ||
| 14 | - | ||
| 15 | -- `waiting_batch_size` remains high, while the number of running requests (`batch_size`) does not reach the configured `maxBatchSize`. | ||
| 16 | -- A large number of requests remain in the waiting state for an extended period in `request_status.csv`, while the number of requests in the running state fluctuates significantly. | ||
| 17 | -- Intermittent idle periods appear on the NPU execution stream, and significant idle gaps (bubbles) exist between consecutive Schedule spans in the **Timeline** view. | ||
| 18 | - | ||
| 19 | -After data is collected using msServiceProfiler, `batch.csv` shows that the `during_time(ms)` of entries whose `name` is `batchFrameworkProcessing` (batch formation stage) is significantly higher than that of `modelExec` (model execution stage). A typical symptom is that batch formation accounts for an excessively high proportion of the total batch processing time, whereas this proportion is typically low under normal conditions. This is particularly noticeable for Host Bound models, such as small-parameter-count encoder models or small-batch scenarios in the decode stage. | ||
| 20 | - | ||
| 21 | -## Troubleshooting Process | ||
| 22 | - | ||
| 23 | -### Step 1: Confirming Whether a Scheduling Bottleneck Exists | ||
| 24 | - | ||
| 25 | -In Grafana, check scheduling-related metrics such as `batch_size`, `waiting_batch_size`, `num_running_reqs`, and `num_waiting_reqs`. If `waiting_batch_size` continues to increase while `batch_size` does not reach its upper limit, the scheduler is not grouping and dispatching waiting requests in a timely manner. Also check NPU utilization. If NPU utilization is low while the waiting queue is long, this might indicate a scheduling bottleneck. | ||
| 26 | - | ||
| 27 | -### Step 2: Collecting Scheduling Data Using the Profiler | ||
| 28 | - | ||
| 29 | -Configure `ms_service_profiler_config.json`, set `domain` to `"Schedule;Request;ModelExecute"`, and enable data collection. After collection is complete, run the following parsing command: | ||
| 30 | - | ||
| 31 | -```bash | ||
| 32 | -python3 -m ms_service_profiler.parse --input-path ${PATH}/prof_dir/ | ||
| 33 | -``` | ||
| 34 | - | ||
| 35 | -The parsing process generates files such as `batch.csv`, `request.csv`, `forward.csv`, and `chrome_tracing.json`. | ||
| 36 | - | ||
| 37 | -### Step 3: Analyzing Scheduling Time in `batch.csv` | ||
| 38 | - | ||
| 39 | -In `batch.csv`, filter the rows whose `name` is `batchFrameworkProcessing` and calculate the distribution of `during_time(ms)`, including the average, P90, and P99. Then filter the rows whose `name` is `modelExec` and calculate the ratio of batch formation time to model execution time. An excessively high proportion of batch formation time indicates a bottleneck in the scheduling stage. | ||
| 40 | - | ||
| 41 | -Calculate scheduling time separately for each DP domain based on `dp_rank` to determine whether scheduling is slow in a specific DP domain. Calculate the statistics separately for each `batch_type` (prefill/decode) to determine whether the bottleneck occurs in prefill scheduling or decode scheduling. | ||
| 42 | - | ||
| 43 | -### Step 4: Performing Fine-grained Analysis of the Batch Execution Stage Using the Inference Service Breakdown Tool | ||
| 44 | - | ||
| 45 | -```bash | ||
| 46 | -msserviceprofiler split --input-path /path/to/input --decode-batch-size 1 --decode-number 100 | ||
| 47 | -``` | ||
| 48 | - | ||
| 49 | -After the breakdown, check the execution time distribution of each substage in `decode.csv`, such as data dispatch, model execution, and data reception, to identify the specific substage responsible for the scheduling time bottleneck. | ||
| 50 | - | ||
| 51 | -### Step 5: Confirming the Bubble Location in the Timeline | ||
| 52 | - | ||
| 53 | -Open `chrome_tracing.json` and observe the timing relationship between the Schedule and ModelExecute spans in the **Timeline** view. If a large number of bubbles (idle gaps) exist and these bubbles occur during the batch formation stage rather than the model execution stage, the scheduler can be identified as the bottleneck. | ||
| 54 | - | ||
| 55 | -Combine this analysis with the `bubble_time(ms)` field in `forward.csv` to calculate the bubble time between forward executions. If bubble time accounts for a high proportion of the total time, the NPU is waiting because scheduling and dispatch are not being performed in a timely manner. | ||
| 56 | - | ||
| 57 | -### Step 6: Obtaining Overall Statistics Using the Multidimensional Analysis Tool | ||
| 58 | - | ||
| 59 | -```bash | ||
| 60 | -msserviceprofiler analyze --input-path=/path/to/input | ||
| 61 | -``` | ||
| 62 | - | ||
| 63 | -Check the batch count and execution time statistics for prefill and decode in `batch_summary.csv` to evaluate scheduling efficiency from the perspective of the overall service. | ||
| 64 | - | ||
| 65 | -## Root Cause | ||
| 66 | - | ||
| 67 | -Common causes of excessive scheduler execution time include: | ||
| 68 | - | ||
| 69 | -1. **Host Bound scenarios**: For small models or individual operators in the decode stage, device execution time may be extremely short, while the host dispatch process for each operator takes relatively long. This causes the device to frequently remain idle while waiting. This is an inherent issue with host scheduling on Ascend NPUs and can be addressed using graph-mode scheduling or model sinking provided by CANN. | ||
| 70 | - | ||
| 71 | -2. **Improper scheduling policy configuration**: A small `maxBatchSize` causes frequent batch formation. Dynamic scheduling priority switching introduces additional policy switching overhead under single-concurrency workloads. An unreasonable ratio between `maxPrefillBatchSize` and `maxBatchSize` causes prefill and decode scheduling to block each other. | ||
| 72 | - | ||
| 73 | -3. **Excessive batch formation complexity**: When the number of requests is large and request lengths vary significantly, the scheduler needs to traverse a large number of candidate requests to match and form batches, causing the complexity of the matching algorithm to increase with the number of requests. | ||
| 74 | - | ||
| 75 | -4. **Framework adaptation issues**: The scheduler is not sufficiently optimized for the Task dispatch mechanism of Ascend NPUs, and graph-mode scheduling or model sinking is not enabled. Instead, individual operators are still dispatched one by one. | ||
| 76 | - | ||
| 77 | -5. **Resource contention**: The scheduler thread competes for CPU resources with other service threads, resulting in scheduling latency fluctuations. | ||
| 78 | - | ||
| 79 | -## Solutions | ||
| 80 | - | ||
| 81 | -- Host Bound: Enable CANN graph-mode scheduling or model sinking to reduce host dispatch overhead. | ||
| 82 | -- Improper scheduling policy: Adjust the ratio between `maxBatchSize` and `maxPrefillBatchSize`, and disable unnecessary dynamic scheduling priority switching. | ||
| 83 | -- Complex batch formation logic: Optimize the batch formation algorithm and reduce the range of candidate requests that need to be traversed. | ||
| 84 | -- Framework adaptation: Ensure that graph-mode scheduling or model sinking is enabled to avoid individual-operator dispatch. | ||
| 85 | -- Resource contention: Ensure that the scheduler thread has sufficient CPU resources and avoid contention with other service threads. | ||
| 86 | - | ||
| 87 | -After applying the changes, check whether `waiting_batch_size` decreases, `batch_size` approaches the upper limit, the proportion of batch formation time decreases, and NPU utilization increases. | ||
| 88 | - | ||
| 89 | -## Summary of the Troubleshooting Methodology | ||
| 90 | - | ||
| 91 | -The complete troubleshooting path for this scenario is as follows: first, use ms-service-metric to verify that `waiting_batch_size` is high, `batch_size` has not reached its upper limit, and NPU utilization is low; then use msServiceProfiler to collect data from the Schedule and ModelExecute domains and compare batch formation time with model execution time using `batch.csv`; next, use the inference service breakdown tool to perform a fine-grained breakdown of the execution time of each batch substage; finally, use the **Timeline** view to confirm the location and duration of bubbles. | ||
| 92 | - | ||
| 93 | -The core decision logic is as follows: if batch formation accounts for a high proportion of the total time and a large number of scheduling gaps exist in the timeline, the bottleneck is in the scheduler; if model execution accounts for a high proportion of the total time, the bottleneck is on the model side. | ||
| 94 | - | ||
| 95 | -## Suggestions for Improving the Tools | ||
| 96 | - | ||
| 97 | -### `ms-service-metric` | ||
| 98 | - | ||
| 99 | -Currently, `ms-service-metric` can display scheduling metrics such as `waiting_batch_size` and `batch_size`. It is recommended to add scheduling efficiency metrics, such as the ratio of scheduling time to model execution time and average batch formation latency, to facilitate rapid identification of scheduling bottlenecks during online monitoring. A Host Bound risk alert should also be added. When low NPU utilization is continuously detected for small models or during the decode stage, the system can automatically indicate a potential Host Bound issue. | ||
| 100 | - | ||
| 101 | -### `msServiceProfiler` | ||
| 102 | - | ||
| 103 | -Currently, `msServiceProfiler` can compare batch formation time with model execution time using `batch.csv`. It is recommended to add scheduling substage breakdown fields to `batch.csv`, such as request matching time, token allocation time, and Task dispatch time, to facilitate direct identification of the specific substage responsible for the scheduling bottleneck. A scheduling efficiency panel can also be added to the **Timeline** view to automatically calculate and display key metrics such as the proportion of batch formation time and bubble time. | ||
| 104 | - | ||
| 105 | -### Inference Service Breakdown Tool | ||
| 106 | - | ||
| 107 | -The current breakdown tool requires `batch_size` or `rid` to be specified manually. It is recommended to add the capability to automatically identify batches with abnormal execution time and automatically select the Top-N batches with the longest execution time for breakdown analysis. | ||
| @@ -1,241 +0,0 @@ | |||
| 1 | -# Optimization Guide for Large Performance Gaps Between Serving and Pure-Model Inference | ||
| 2 | - | ||
| 3 | -## Scenario Description | ||
| 4 | - | ||
| 5 | -In foundation-model inference optimization, pure-model execution is typically used first to establish a performance baseline for a model with fixed input and output lengths and a fixed batch size. The model is then deployed in a serving framework to handle real-world requests. If throughput, time to first token, or decode latency in the serving scenario differs significantly from the pure-model baseline, common causes include misaligned service parameters, insufficient resource allocation, abnormal communication configuration, load imbalance, or an excessively large sequence length configuration. | ||
| 6 | - | ||
| 7 | -Using a serving inference scenario with lower performance than the pure-model baseline as an example, this document describes how to use msServiceProfiler to collect serving inference pipeline data, identify the source of the performance gap, and provide optimization solutions for parameters, resources, communication, and load balancing. | ||
| 8 | - | ||
| 9 | -## Symptoms | ||
| 10 | - | ||
| 11 | -### Typical Symptoms | ||
| 12 | - | ||
| 13 | -- Throughput is normal in pure-model testing. For example, with input/output lengths of 256/256 and `bs=128`, throughput can reach 1132.24 tokens/s, but throughput decreases significantly after deployment in the serving framework. | ||
| 14 | -- In the serving scenario, `Batch_Size_curve` remains consistently below the configured `maxBatchSize` or `maxPrefillBatchSize` limit. | ||
| 15 | -- `Prefill_Generate_Speed_Latency_curve` and `Decode_Generate_Speed_Latency_curve` are significantly worse than the pure-model baseline. | ||
| 16 | -- P90/P99 latency in `First_Token_Latency_curve` or `Request_Latency_curve` is high and increases rapidly as concurrency increases. | ||
| 17 | -- HCCL communication timeouts, rank connection failures, model loading hangs, or service process termination occur during startup. | ||
| 18 | -- During multi-device deployment of MoE models, some devices have significantly higher execution times, and `moe_analysis` or expert hotspot diagrams indicate load imbalance. | ||
| 19 | - | ||
| 20 | -### Impact | ||
| 21 | - | ||
| 22 | -| Item | Symptom | | ||
| 23 | -| --- | --- | | ||
| 24 | -| Throughput | Serving inference throughput is significantly lower than the pure-model baseline. | | ||
| 25 | -| Time to first token | Queueing, batch formation, or execution time increases during the prefill stage. | | ||
| 26 | -| Decode latency | Per-step latency increases due to communication waits, lack of compute-communication fusion, or load imbalance. | | ||
| 27 | -| Stability | Insufficient memory, insufficient permissions, or communication timeouts cause service startup failures. | | ||
| 28 | -| Resource utilization | Device utilization decreases because batches are not fully utilized, KVCache is over-allocated, or hotspot experts are concentrated on a small number of devices. | | ||
| 29 | - | ||
| 30 | -## Data Collection | ||
| 31 | - | ||
| 32 | -### Function Description | ||
| 33 | - | ||
| 34 | -Use msServiceProfiler to collect data related to `Request`, `BatchSchedule`, `ModelExecute`, `Communication`, `KVCache`, and expert load during serving inference. Compare the differences between the pure-model baseline and the serving inference pipeline using `batch.csv`, `request.csv`, `forward.csv`, `BatchSchedule.csv`, and visualization curves. | ||
| 35 | - | ||
| 36 | -### Precautions | ||
| 37 | - | ||
| 38 | -- Complete pure-model baseline testing before optimization to determine the maximum performance with fixed input/output lengths and batch size. | ||
| 39 | -- Reuse the input/output lengths, concurrency level, and model configuration from the pure-model baseline as much as possible during serving stress testing to ensure that the baseline remains comparable. | ||
| 40 | -- Before collecting data in multi-node, multi-device scenarios, verify that the system clocks are synchronized across nodes to avoid time offsets in the Timeline and load-balancing diagrams. | ||
| 41 | -- If communication, task dispatch, or operator execution time needs to be analyzed, enable ACL task-time-related data collection as required, but evaluate the additional overhead. | ||
| 42 | -- Configure the `eplb_observe` domain separately to collect expert hotspot information and avoid excessive data volume. | ||
| 43 | - | ||
| 44 | -### Configuration Example | ||
| 45 | - | ||
| 46 | -Create `ms_service_profiler_config.json` and collect the `Request`, `BatchSchedule`, `ModelExecute`, `Communication`, and `KVCache` domains as required. | ||
| 47 | - | ||
| 48 | -```json | ||
| 49 | -{ | ||
| 50 | - "enable": 1, | ||
| 51 | - "prof_dir": "${HOME}/.ms_server_profiler", | ||
| 52 | - "profiler_level": "INFO", | ||
| 53 | - "domain": "Request;BatchSchedule;ModelExecute;Communication;KVCache", | ||
| 54 | - "acl_task_time": 1, | ||
| 55 | - "acl_prof_task_time_level": "L0" | ||
| 56 | -} | ||
| 57 | -``` | ||
| 58 | - | ||
| 59 | -To collect MoE expert hotspot information, enable the `eplb_observe` domain separately and configure the MindIE environment variables for expert hotspot collection. | ||
| 60 | - | ||
| 61 | -```json | ||
| 62 | -{ | ||
| 63 | - "enable": 1, | ||
| 64 | - "prof_dir": "${HOME}/.ms_server_profiler", | ||
| 65 | - "profiler_level": "INFO", | ||
| 66 | - "domain": "eplb_observe" | ||
| 67 | -} | ||
| 68 | -``` | ||
| 69 | - | ||
| 70 | -Set the collection configuration path before starting the service. | ||
| 71 | - | ||
| 72 | -```bash | ||
| 73 | -export SERVICE_PROF_CONFIG_PATH=/path/to/ms_service_profiler_config.json | ||
| 74 | -``` | ||
| 75 | - | ||
| 76 | -## Baseline Alignment | ||
| 77 | - | ||
| 78 | -When serving performance is lower than the pure-model baseline, first verify that the two tests are comparable. | ||
| 79 | - | ||
| 80 | -| Check Item | Description | | ||
| 81 | -| --- | --- | | ||
| 82 | -| Input/output lengths | The input and output lengths used for pure-model testing and serving stress testing should be the same, such as 256/256. | | ||
| 83 | -| Batch size and concurrency | The pure-model `bs` should correspond to serving `maxBatchSize`, `maxPrefillBatchSize`, and `concurrency`. | | ||
| 84 | -| Model weights | The model version, quantization method, parallelization strategy, and rank configuration should be the same. | | ||
| 85 | -| Precision and operators | The precision, operator libraries, and graph optimization settings used for pure-model testing and serving inference should be the same. | | ||
| 86 | -| Hardware resources | The number of NPUs, number of machines, CPU resources, and memory resources should be the same or otherwise comparable. | | ||
| 87 | - | ||
| 88 | -If the baselines are not aligned, do not directly conclude that the serving framework is the bottleneck. Record the maximum pure-model performance first, and then enable optimization settings one by one on the serving side to verify the performance improvement from each change. | ||
| 89 | - | ||
| 90 | -## Troubleshooting Method | ||
| 91 | - | ||
| 92 | -1. Check `Batch_Size_curve` and `batch.csv`. | ||
| 93 | - - If `prefill_batch_size` or `decode_batch_size` remains consistently low, the serving batches are not fully utilized. Check `concurrency`, `maxPrefillBatchSize`, `maxBatchSize`, request distribution, and `supportSelectBatch`. | ||
| 94 | - - If the batch size is already close to its upper limit but throughput remains low, continue checking ModelExecute, Communication, and device utilization. | ||
| 95 | - | ||
| 96 | -2. Check `Request_Status_curve`. | ||
| 97 | - - If the waiting queue continues to accumulate, the service entry point, batch formation, or execution stage may have insufficient request processing capacity. | ||
| 98 | - - If the running queue is small but throughput is low, the scheduling policy may be too conservative, or serving parameters may be limiting the effective batch size. | ||
| 99 | - | ||
| 100 | -3. Check the prefill- and decode-related curves. | ||
| 101 | - - If `Prefill_Generate_Speed_Latency` is high, first check `maxPrefillBatchSize`, `maxSeqLen`, KVCache reservation, and input length distribution. | ||
| 102 | - - If `Decode_Generate_Speed_Latency` is high, first check communication configuration, LCCL, compute-communication fusion, MoE load balancing, and cross-device synchronization waits. | ||
| 103 | - | ||
| 104 | -4. Check `Kvcache_usage_percent_curve`. | ||
| 105 | - - If KVCache utilization remains low while `maxSeqLen` is configured to a large value, excessive reservation may be limiting the batch size and concurrency. | ||
| 106 | - - If KVCache utilization is close to the upper limit, concurrency or sequence length has reached a memory bottleneck. Reduce `maxSeqLen` or increase resources as appropriate. | ||
| 107 | - | ||
| 108 | -## Cause Analysis and Solutions | ||
| 109 | - | ||
| 110 | -### Inconsistent Parameter Configuration Between Serving Inference and the Pure-Model Baseline | ||
| 111 | - | ||
| 112 | -**Cause** | ||
| 113 | - | ||
| 114 | -If parameters such as `maxPrefillBatchSize`, `maxBatchSize`, `concurrency`, and `prefillBatchSize` are not configured according to the actual workload, batches may not be fully utilized, queue scheduling may be overly conservative, or resources may be allocated improperly between prefill and decode, resulting in lower throughput than the pure-model baseline. | ||
| 115 | - | ||
| 116 | -**Solution** | ||
| 117 | - | ||
| 118 | -- Use the pure-model baseline as the target and establish a correspondence between `bs`, serving concurrency, and `maxBatchSize`. | ||
| 119 | -- Adjust `maxPrefillBatchSize` and `prefillBatchSize` according to the request length distribution to avoid excessively small batches during prefill. | ||
| 120 | -- Gradually increase `concurrency` according to the stress-test concurrency level and observe whether `Batch_Size_curve` approaches the configured upper limit. | ||
| 121 | -- For throughput-oriented scenarios, enable `supportSelectBatch` so that the scheduler preferentially selects batch combinations that are more favorable for throughput. | ||
| 122 | -- Record `Batch_Size_curve`, `Prefill_Generate_Speed_Latency`, and `Request_Latency` before and after optimization to avoid evaluating the result based only on a single throughput measurement. | ||
| 123 | - | ||
| 124 | -### Resource Allocation and Insufficient Memory | ||
| 125 | - | ||
| 126 | -**Cause** | ||
| 127 | - | ||
| 128 | -Compared with pure-model execution, deployment in the serving framework typically requires additional framework processes, queues, KVCache, communication buffers, and monitoring components. Insufficient system memory may cause model loading to hang, processes to be terminated, or abnormally high latency for the first request. | ||
| 129 | - | ||
| 130 | -**Solution** | ||
| 131 | - | ||
| 132 | -- Before startup, verify that sufficient memory is available. It is recommended that `free_mem` be no less than `(weight size / number of machines) * 1.3`. | ||
| 133 | -- In test environments, release the system cache before starting the service. | ||
| 134 | - | ||
| 135 | -```bash | ||
| 136 | -sync | ||
| 137 | -echo 3 > /proc/sys/vm/drop_caches | ||
| 138 | -``` | ||
| 139 | - | ||
| 140 | -- For containerized deployment, verify privileged mode and path permissions to avoid failures when accessing models, rank tables, shared memory, or device files. | ||
| 141 | - | ||
| 142 | -```bash | ||
| 143 | -docker run --privileged=true | ||
| 144 | -``` | ||
| 145 | - | ||
| 146 | -- If KVCache utilization remains low while memory usage is high, check whether `maxSeqLen` is significantly greater than the maximum sequence length in the actual dataset. | ||
| 147 | -- If the service process terminates, first check system logs, container memory limits, and peak memory usage during weight loading. | ||
| 148 | - | ||
| 149 | -### Insufficient Communication and Environment Variable Configuration | ||
| 150 | - | ||
| 151 | -**Cause** | ||
| 152 | - | ||
| 153 | -Multi-node, multi-device deployment in the serving framework relies on HCCL or LCCL communication. If environment variables are inconsistent between the primary and secondary nodes, the rank table path is incorrect, the container IP is incorrectly configured, or the communication timeout is too short, service startup may fail, decode waits may increase, or cross-device synchronization may take excessively long. | ||
| 154 | - | ||
| 155 | -**Solution** | ||
| 156 | - | ||
| 157 | -Set the local IP address, rank table, and deterministic communication-related environment variables on the primary and secondary nodes as appropriate. | ||
| 158 | - | ||
| 159 | -```bash | ||
| 160 | -export MIES_CONTAINER_IP=<local IP address> | ||
| 161 | -export RANKTABLEFILE=/path/to/rank_table.json | ||
| 162 | -export HCCL_DETERMINISTIC=true | ||
| 163 | -``` | ||
| 164 | - | ||
| 165 | -For large-scale deployments or environments with slow network initialization, increase the communication connection timeout as appropriate and verify that `WORLD_SIZE` matches the actual number of ranks. | ||
| 166 | - | ||
| 167 | -```bash | ||
| 168 | -export HCCL_CONNECT_TIMEOUT=7200 | ||
| 169 | -export WORLD_SIZE=32 | ||
| 170 | -``` | ||
| 171 | - | ||
| 172 | -If decode latency is high, consider enabling the LCCL communication library and compute-communication fusion. | ||
| 173 | - | ||
| 174 | -```bash | ||
| 175 | -export ATB_LLM_LCOC_ENABLE=1 | ||
| 176 | -``` | ||
| 177 | - | ||
| 178 | -During verification, focus on comparing Communication-domain spans, `Decode_Generate_Speed_Latency`, and P90/P99 of `Request_Latency`. | ||
| 179 | - | ||
| 180 | -### MoE Load Imbalance | ||
| 181 | - | ||
| 182 | -**Cause** | ||
| 183 | - | ||
| 184 | -In MoE models, the access frequency of different experts may vary significantly. If hotspot experts are concentrated on a small number of devices or ranks, some devices may finish early and wait for slower devices, resulting in lower serving throughput than the ideal pure-model baseline. | ||
| 185 | - | ||
| 186 | -**Solution** | ||
| 187 | - | ||
| 188 | -- Use msServiceProfiler to collect the `eplb_observe` domain and observe expert hotspots and load imbalance curves. | ||
| 189 | -- Use the `msit elb` tool to generate the expert deployment file `expert_map_file`. | ||
| 190 | -- Configure expert load-balancing parameters in `config.json`. For example, set `"level": 1` to enable static load balancing. | ||
| 191 | -- After adjustment, collect `moe_analysis.csv` and the expert load imbalance line chart again to verify that the execution time gap between devices has decreased. | ||
| 192 | - | ||
| 193 | -### Excessive Sequence Length Configuration | ||
| 194 | - | ||
| 195 | -**Cause** | ||
| 196 | - | ||
| 197 | -If `maxSeqLen` is configured based on an extreme upper limit, such as 10,000, while the actual maximum length in the dataset is only 698, KVCache and memory reservations may be excessive. This can limit the available batch size and concurrency, thereby reducing serving throughput. | ||
| 198 | - | ||
| 199 | -**Solution** | ||
| 200 | - | ||
| 201 | -- Analyze the actual input and output length distribution in production or stress-test datasets, and use P99 or the actual maximum value as the basis for configuring `maxSeqLen`. | ||
| 202 | -- Reduce `maxSeqLen` from an excessively conservative value to one closer to the actual workload. For example, reduce it from 10,000 to 698. | ||
| 203 | -- After adjustment, observe `Kvcache_usage_percent_curve`, `Batch_Size_curve`, and service throughput to verify whether performance improves. | ||
| 204 | -- If a small number of requests may contain extremely long sequences, route those requests separately or handle them with a degraded service level to avoid affecting the main service instances. | ||
| 205 | - | ||
| 206 | -## Optimization Verification | ||
| 207 | - | ||
| 208 | -Adjust only one aspect at a time and recollect data under the same stress-test conditions. The following verification sequence is recommended. | ||
| 209 | - | ||
| 210 | -| Step | Verification Objective | Metrics to Observe | | ||
| 211 | -| --- | --- | --- | | ||
| 212 | -| Pure-model baseline | Determine the theoretical upper bound of model performance | tokens/s, bs, input/output lengths | | ||
| 213 | -| Parameter optimization | Verify whether serving batches are fully utilized | `Batch_Size_curve`, `batch.csv` | | ||
| 214 | -| Memory optimization | Verify whether resources are sufficient | `Kvcache_usage_percent`, process RSS, system `free_mem` | | ||
| 215 | -| Communication optimization | Verify whether decode waits decrease | Communication spans, `Decode_Generate_Speed_Latency` | | ||
| 216 | -| Load balancing | Verify whether the performance gap between fast and slow ranks decreases | `moe_analysis.csv`, expert hotspot diagrams | | ||
| 217 | -| End-to-end verification | Verify user-side performance improvements | `First_Token_Latency`, `Request_Latency`, throughput | | ||
| 218 | - | ||
| 219 | -When the optimization is effective, the following results are typically observed: | ||
| 220 | - | ||
| 221 | -- `Batch_Size_curve` approaches the configured upper limit of `maxBatchSize` or `maxPrefillBatchSize`. | ||
| 222 | -- Average token latency decreases during both prefill and decode. | ||
| 223 | -- The average, P90, and P99 of `Request_Latency_curve` decrease. | ||
| 224 | -- KVCache utilization better matches the actual workload, reducing memory waste. | ||
| 225 | -- In MoE scenarios, the execution time gap between devices decreases, and the performance gap between fast and slow ranks is reduced. | ||
| 226 | -- Serving throughput gradually approaches the pure-model baseline. | ||
| 227 | - | ||
| 228 | -## Recommended Handling Strategies | ||
| 229 | - | ||
| 230 | -| Problem Type | Recommended Solution | | ||
| 231 | -| --- | --- | | ||
| 232 | -| Serving batch size remains low | Adjust `concurrency`, `maxBatchSize`, and `maxPrefillBatchSize`, and enable `supportSelectBatch`. | | ||
| 233 | -| High prefill latency | Adjust `prefillBatchSize` and `maxSeqLen`, and check KVCache reservation and input length distribution. | | ||
| 234 | -| High decode latency | Optimize HCCL/LCCL configuration, enable compute-communication fusion, and check cross-device communication waits. | | ||
| 235 | -| Startup failure or process termination | Check `free_mem`, container privileged mode, path permissions, and memory limits. | | ||
| 236 | -| Multi-device load imbalance | Use `msit elb` to generate `expert_map_file` and enable static or dynamic expert load balancing. | | ||
| 237 | -| Large gap from the pure-model baseline persists | Return to baseline alignment and verify that the model version, parallelization strategy, input/output lengths, and hardware resources are consistent. | | ||
| 238 | - | ||
| 239 | -## Summary | ||
| 240 | - | ||
| 241 | -The key to addressing large performance gaps between serving and pure-model inference lies in baseline alignment, parameter configuration, resource allocation, and communication optimization. During optimization, first use pure-model testing to establish the maximum performance baseline, and then use msServiceProfiler to break down the serving inference pipeline, focusing on `BatchSchedule`, `Request`, `KVCache`, `Communication`, and MoE load-balancing data. For throughput-oriented workloads, prioritize fully utilizing batches and enabling throughput-oriented scheduling policies. If decode tail latency is high, prioritize checking the communication library, compute-communication fusion, and expert load balancing. If resources are insufficient, resolve memory, container permission, and sequence length configuration issues before continuing with serving parameter optimization. | ||
| @@ -1,46 +1,51 @@ | |||
| 1 | -# 1. Background | 1 | +# Frequent Calls to Synchronous APIs |
| 2 | 2 | ||
| 3 | -During NPU workload execution, the execution time does not meet expectations. Profiling data shows a large number of wait operations, such as stream synchronization, requiring further troubleshooting and performance optimization. | 3 | +## 1. Background |
| 4 | 4 | ||
| 5 | -# 2. Source | 5 | +During NPU service execution, the execution time falls short of expectations. Profiling data collection confirms that there are many waiting behaviors such as stream synchronization, which urgently require problem localization and performance optimization. |
| 6 | 6 | ||
| 7 | -Performance profiling | 7 | +## 2. Source |
| 8 | 8 | ||
| 9 | -# 3. Problem Symptoms | 9 | +Performance tuning. |
| 10 | 10 | ||
| 11 | -Open `msprof.json` or `trace_view.json` using the visualization tool. A large number of operator executions can be observed, often accompanied by synchronization APIs such as `aclrtSynchronizeStreamWithTimeout`. | 11 | +## 3. Symptoms |
| 12 | -When a synchronization API is called, no other operators are dispatched. That is, the operator blocks the dispatch of other operators, resulting in low overall NPU utilization and poor performance. For the workload as a whole, asynchronous dispatch allows operators to be continuously dispatched and keeps the workload busy on the device side, thereby making full use of hardware resources. However, a large number of synchronization API calls convert asynchronous operations into synchronous operations, resulting in discontinuous workload execution and lower hardware resource utilization. | ||
| 13 | 12 | ||
| 14 | - | 13 | +Open the `msprof.json` or `trace_view.json` file with a visualization tool. You will find that many operators are being executed, often accompanied by synchronous interfaces such as aclrtSynchronizeStreamWithTimeout. |
| 15 | 14 | ||
| 16 | -# 4. Troubleshooting Process | 15 | +When a synchronous interface is being called, no other operators are dispatched, meaning that this operator blocks the dispatch of the remaining operators. As a result, the overall NPU utilization is low and performance is poor. For the overall service, the asynchronous dispatch mode requires operators to be dispatched over a long period and keeps the device-side service busy executing, thereby making full use of hardware resources. However, a large number of synchronous interface calls convert asynchronous behavior into synchronous behavior, which in turn causes discontinuity in the service and reduces hardware resource utilization. |
| 17 | 16 | ||
| 18 | -Open `msprof.json` or `trace_view.json` using MindStudio Insight. A large number of synchronization APIs with names such as "Synchronize" can be observed. | 17 | + |
| 19 | 18 | ||
| 20 | -You can also view a large number of API calls in the `api_statistic.csv` output file. | 19 | +## 4. Troubleshooting Process |
| 20 | + | ||
| 21 | +Open `msprof.json` or `trace_view.json` in MindStudio Insight to observe a large number of synchronization APIs with names similar to "Synchronize". | ||
| 22 | + | ||
| 23 | +You can also see a large number of API calls in the `api_statistic.csv` deliverable. | ||
| 21 | 24 | ||
| 22 |  | 25 |  |
| 23 | 26 | ||
| 24 | -The above information indicates that the workload contains a large number of unexpected stream synchronization operations. | 27 | +Based on the preceding information, it can be confirmed that the service indeed contains many stream synchronization operations that do not meet expectations. |
| 25 | 28 | ||
| 26 | -Therefore, use the profiler's stack trace functionality to additionally collect data containing stack information. This allows you to determine, based on the timing information, where the relevant synchronization operations are introduced. | 29 | +Therefore, you can use the stack call stack feature of profiler to additionally collect a set of data with stack information, and confirm from a time perspective where the related synchronization operations are introduced. |
| 27 | 30 | ||
| 28 | -# 5. Root Cause | 31 | +## 5. Root Cause |
| 29 | 32 | ||
| 30 | 1. Most stream synchronization operations are introduced manually or by the application logic. Therefore, first check the workload code and evaluate the necessity of the API calls from the perspective of the workload logic. Remove unnecessary synchronization APIs as appropriate. | 33 | 1. Most stream synchronization operations are introduced manually or by the application logic. Therefore, first check the workload code and evaluate the necessity of the API calls from the perspective of the workload logic. Remove unnecessary synchronization APIs as appropriate. |
| 31 | 34 | ||
| 32 | -2. In addition, some stream synchronization operations may be introduced by environment variables. For example, [ASCEND_LAUNCH_BLOCKING](https://gitcode.com/Ascend/pytorch/blob/master/docs/en/api/environment_variable/op_execution/ASCEND_LAUNCH_BLOCKING.md) forces stream synchronization for each operator to facilitate problem troubleshooting. | 35 | +2. In addition, some stream synchronization services may be introduced by environment variables. For example, [ASCEND_LAUNCH_BLOCKING](https://gitcode.com/Ascend/pytorch/blob/v2.14.0-26.2.0/docs/en/api/environment_variable/op_execution/ASCEND_LAUNCH_BLOCKING.md) performs stream synchronization on each operator to locate problems. |
| 33 | 36 | ||
| 34 | -# 6. Summary of the Troubleshooting Method | 37 | +## 6. Troubleshooting Methodology Summary |
| 35 | 38 | ||
| 36 | -1. Open `msprof.json` or `trace_view.json` using MindStudio Insight to identify stream synchronization. | 39 | +1. Open `msprof.json` or `trace_view.json` through insight to identify the stream synchronization phenomenon. |
| 37 | 40 | ||
| 38 | -2. Use `api_statistic.csv` to determine the overall number of synchronization API calls and their total execution time, facilitating an assessment of the impact of synchronization APIs on the workload. | 41 | +2. Use `api_statistic.csv` to confirm the overall number of calls and total time consumed by synchronous interfaces, so as to evaluate the impact of synchronous interfaces on the service. |
| 39 | 42 | ||
| 40 | -3. Use the stack trace functionality to identify the dispatch points of the relevant stream synchronization APIs based on timing information, quickly locate the key code segments, and evaluate the necessity of the synchronization APIs from the perspective of the workload. | 43 | +3. Use the stack capability to locate the dispatch point of the corresponding stream synchronization interface from the time perspective, quickly identify the key code segment, and evaluate the reasonableness of the synchronous interface from the service perspective. |
| 41 | 44 | ||
| 42 | -4. Finally, use tools such as Advisor to perform a comprehensive check of the data and quickly rule out some less relevant environmental factors. | 45 | +4. Finally, use tools such as advisor to perform a comprehensive check of the data and quickly rule out some insensitive environment variable factors. |
| 43 | 46 | ||
| 44 | -# 7. Suggestions for Improving the Tools | 47 | +  |
| 45 | 48 | ||
| 46 | -None | 49 | +## 7. Suggestions for Tool Improvement |
| 50 | + | ||
| 51 | +None. | ||
| @@ -20,7 +20,7 @@ The specific symptoms are as follows: | |||
| 20 | 4. CPU utilization remains normal, with no obvious bottleneck. | 20 | 4. CPU utilization remains normal, with no obvious bottleneck. |
| 21 | 5. Network bandwidth utilization is low, ruling out a communication bottleneck. | 21 | 5. Network bandwidth utilization is low, ruling out a communication bottleneck. |
| 22 | 6. PyTorch Profiler shows that operator dispatch on the host side becomes significantly slower after the checkpoint is saved, indicating high host-side system-call latency. | 22 | 6. PyTorch Profiler shows that operator dispatch on the host side becomes significantly slower after the checkpoint is saved, indicating high host-side system-call latency. |
| 23 | -7. `strace` tracing shows a large number of `futex`, `ioctl`, `malloc`, and `free` system calls, with the latency of individual calls reaching 10 to 50 ms. | 23 | +7. strace tracing shows a large number of `futex`, `ioctl`, `malloc`, and `free` system calls, with the latency of individual calls reaching 10 to 50 ms. |
| 24 | 24 | ||
| 25 | For details, see the following figure. | 25 | For details, see the following figure. |
| 26 | 26 | ||
| @@ -28,7 +28,7 @@ For details, see the following figure. | |||
| 28 | 28 | ||
| 29 | ## 4. Troubleshooting Process | 29 | ## 4. Troubleshooting Process |
| 30 | 30 | ||
| 31 | -1. Use `strace` to trace system calls. | 31 | +1. Use strace to trace system calls. |
| 32 | 32 | ||
| 33 | - Command: `strace -T -tt -p <pid> -o trace.log`. | 33 | - Command: `strace -T -tt -p <pid> -o trace.log`. |
| 34 | - Statistics show that `futex`, `ioctl`, `malloc`, and `free` system calls account for more than 60% of all system calls. | 34 | - Statistics show that `futex`, `ioctl`, `malloc`, and `free` system calls account for more than 60% of all system calls. |
| @@ -40,14 +40,13 @@ For details, see the following figure. | |||
| 40 | 40 | ||
| 41 | ```python | 41 | ```python |
| 42 | import torch_npu | 42 | import torch_npu |
| 43 | - | ||
| 44 | experimental_config = torch_npu.profiler._ExperimentalConfig( | 43 | experimental_config = torch_npu.profiler._ExperimentalConfig( |
| 45 | profiler_level=torch_npu.profiler.ProfilerLevel.Level0, | 44 | profiler_level=torch_npu.profiler.ProfilerLevel.Level0, |
| 46 | aic_metrics=torch_npu.profiler.AiCMetrics.AiCoreNone, | 45 | aic_metrics=torch_npu.profiler.AiCMetrics.AiCoreNone, |
| 47 | data_simplification=False, | 46 | data_simplification=False, |
| 48 | host_sys=[torch_npu.profiler.HostSystem.OSRT], # Collect process-level system calls | 47 | host_sys=[torch_npu.profiler.HostSystem.OSRT], # Collect process-level system calls |
| 49 | ) | 48 | ) |
| 50 | - | 49 | + |
| 51 | # Add the basic profiling configuration parameters. For details, see the parameter descriptions below. | 50 | # Add the basic profiling configuration parameters. For details, see the parameter descriptions below. |
| 52 | with torch_npu.profiler.profile( | 51 | with torch_npu.profiler.profile( |
| 53 | activities=[ | 52 | activities=[ |
| @@ -57,48 +56,49 @@ For details, see the following figure. | |||
| 57 | schedule=torch_npu.profiler.schedule(wait=0, warmup=0, active=1, repeat=1, skip_first=0), # Used with prof.step() | 56 | schedule=torch_npu.profiler.schedule(wait=0, warmup=0, active=1, repeat=1, skip_first=0), # Used with prof.step() |
| 58 | on_trace_ready=torch_npu.profiler.tensorboard_trace_handler("./result"), | 57 | on_trace_ready=torch_npu.profiler.tensorboard_trace_handler("./result"), |
| 59 | experimental_config=experimental_config) as prof: | 58 | experimental_config=experimental_config) as prof: |
| 59 | + | ||
| 60 | # Start profile data collection. | 60 | # Start profile data collection. |
| 61 | for step in range(steps): # Training iterations | 61 | for step in range(steps): # Training iterations |
| 62 | train_one_step() # Training function | 62 | train_one_step() # Training function |
| 63 | prof.step() # Used with schedule | 63 | prof.step() # Used with schedule |
| 64 | ``` | 64 | ``` |
| 65 | 65 | ||
| 66 | -In the `trace_view.json` file generated by Profiler, data in the OS Runtime API track is as shown in the following figure. | 66 | + In the Profiler deliverable file `trace_view.json`, the OS Runtime API level data is shown in the following figure: |
| 67 | 67 | ||
| 68 | - | 68 | +  |
| 69 | 69 | ||
| 70 | -Field descriptions | 70 | + Field descriptions |
| 71 | 71 | ||
| 72 | -| Field | Description | | 72 | + | Field | Description | |
| 73 | -| --- | --- | | 73 | + | --- | --- | |
| 74 | -| Title | The name of the API selected for a component. In this example, `pthread_mutex_unlock` is selected. | | 74 | + | Title | The name of the API selected for a component. In this example, `pthread_mutex_unlock` is selected. | |
| 75 | -| Start | The timestamp displayed on the timeline. Chrome Trace automatically aligns the timestamps. The unit is ms. | | 75 | + | Start | The timestamp displayed on the timeline. Chrome Trace automatically aligns the timestamps. The unit is ms. | |
| 76 | -| Wall Duration | The duration of the current API call. The unit is ms. | | 76 | + | Wall Duration | The duration of the current API call. The unit is ms. | |
| 77 | 77 | ||
| 78 | -The `os_runtime_statistic_*.csv` file has the following format. | 78 | + The `os_runtime_statistic_*.csv` file has the following format. |
| 79 | 79 | ||
| 80 | -| Device_id | Process ID | Thread ID | Name | Time(%) | Time(us) | Count | Avg(us) | Max(us) | Min(us) | | 80 | + | Device_id | Process ID | Thread ID | Name | Time(%) | Time(us) | Count | Avg(us) | Max(us) | Min(us) | |
| 81 | -| --------- | ---------- | --------- | --------- | ----------- | --------- | ----- | --------- | ------- | ------- | | 81 | + | --------- | ---------- | --------- | --------- | ----------- | --------- | ----- | --------- | ------- | ------- | |
| 82 | -| host | 387972 | 3880228 | nanosleep | 0.9852596 | 102468352 | 97090 | 1055.3953 | 1217 | 165 | | 82 | + | host | 387972 | 3880228 | nanosleep | 0.9852596 | 102468352 | 97090 | 1055.3953 | 1217 | 165 | |
| 83 | -| host | 387972 | 3880215 | ioctl | 0.0095065 | 989102 | 54 | 18315.074 | 20066 | 388 | | 83 | + | host | 387972 | 3880215 | ioctl | 0.0095065 | 989102 | 54 | 18315.074 | 20066 | 388 | |
| 84 | -| host | 387972 | 3880211 | nanosleep | 0.00138659 | 144098 | 2 | 72049.8 | 143954 | 944 | | 84 | + | host | 387972 | 3880211 | nanosleep | 0.00138659 | 144098 | 2 | 72049.8 | 143954 | 944 | |
| 85 | -| host | 387972 | 3880212 | ioctl | 0.000701886 | 72995 | 25 | 2919.8 | 8195 | 82 | | 85 | + | host | 387972 | 3880212 | ioctl | 0.000701886 | 72995 | 25 | 2919.8 | 8195 | 82 | |
| 86 | -| host | 387972 | 3880213 | malloc | 0.00069822 | 65990 | 13 | 1919.8 | 6595 | 654 | | 86 | + | host | 387972 | 3880213 | malloc | 0.00069822 | 65990 | 13 | 1919.8 | 6595 | 654 | |
| 87 | 87 | ||
| 88 | -Field descriptions | 88 | + Field descriptions |
| 89 | 89 | ||
| 90 | -| Field | Description | | 90 | + | Field | Description | |
| 91 | -| --- | --- | | 91 | + | --- | --- | |
| 92 | -| Device_id | Device ID. `host` is displayed for host-side data. | | 92 | + | Device_id | Device ID. `host` is displayed for host-side data. | |
| 93 | -| Process ID | Process ID. | | 93 | + | Process ID | Process ID. | |
| 94 | -| Thread ID | Thread ID. | | 94 | + | Thread ID | Thread ID. | |
| 95 | -| Name | API interface name. | | 95 | + | Name | API interface name. | |
| 96 | -| Time | Proportion of the total time spent in the API. | | 96 | + | Time | Proportion of the total time spent in the API. | |
| 97 | -| Time(us) | Total time spent in the API. The unit is us. | | 97 | + | Time(us) | Total time spent in the API. The unit is us. | |
| 98 | -| Count | Number of calls to the API. | | 98 | + | Count | Number of calls to the API. | |
| 99 | -| Avg(us), Max(us), Min(us) | Average, maximum, and minimum latency of the API calls. The unit is us. | | 99 | + | Avg(us), Max(us), Min(us) | The average, maximum, and minimum duration of this API call, in us. | |
| 100 | 100 | ||
| 101 | -As shown above, system calls such as `futex`, `ioctl`, and `pthread_mutex_unlock` have relatively high latency and require further analysis. | 101 | + As shown above, system calls such as futex, ioctl, and `pthread_mutex_unlock` have relatively high latency and require further analysis. |
| 102 | 102 | ||
| 103 | ## 5. Root Cause | 103 | ## 5. Root Cause |
| 104 | 104 | ||
| @@ -110,10 +110,8 @@ For foundation-model cluster training with high memory usage, if the system alre | |||
| 110 | 110 | ||
| 111 | ## 6. Summary of the Troubleshooting Methodology | 111 | ## 6. Summary of the Troubleshooting Methodology |
| 112 | 112 | ||
| 113 | -Prioritize using the end-to-end performance analysis capabilities of msProf to collect profile data from the NPU, OS, and CPU levels and perform an end-to-end execution-time breakdown. If a bottleneck is confirmed at the system-call layer, use OS kernel tools such as `strace` and `perf` to trace and sample system calls. | 113 | +Prioritize using the end-to-end performance analysis capabilities of msProf to collect profile data from the NPU, OS, and CPU levels and perform an end-to-end execution-time breakdown. If a bottleneck is confirmed at the system-call layer, use OS kernel tools such as strace and perf to trace and sample system calls. |
| 114 | 114 | ||
| 115 | -## 7. Suggestions for Improving the Tools | 115 | +## 7. Suggestions for Tool Improvement |
| 116 | 116 | ||
| 117 | -1. Data integration and joint analysis | 117 | +Data integration and joint analysis: In this case, locating the high system call duration issue requires a comprehensive analysis that combines Ascend model performance data with OS kernel data. Currently, the tools operate independently, lacking data linkage and an end-to-end full-link perspective, which makes it difficult to support efficient analysis of complex issues. Multi-source data integration and joint analysis represent the future direction of performance diagnosis tools and must be strengthened in subsequent development. |
| 118 | - | ||
| 119 | - In this case, troubleshooting high system-call latency requires comprehensive analysis combining Ascend model profile data with OS kernel data. Currently, the tools operate independently and lack data integration and cross-tool analysis capabilities, making it difficult to efficiently troubleshoot complex issues from an end-to-end perspective. Integrating data from multiple sources and enabling joint analysis is an important direction for future performance diagnostic tools and should be strengthened in subsequent development. | ||
Mdocs/en/development_guide/development_guide.md+59-34File content is under review, please try again later
Mdocs/en/install_guide/msprof_install_guide.md+50-86File content is under review, please try again later
Mdocs/en/user_guide/extended_functions.md+125-63File content is under review, please try again later
Mdocs/en/user_guide/msprof_parsing_instruct.md+162-105File content is under review, please try again later
Mdocs/en/user_guide/profile_data_file_references_db.md+83-72File content is under review, please try again later