torch_npu (Ascend PyTorch)
repository·master·Indexed 20 days ago
https://github.com/ascend/pytorchA PyTorch adapter plugin designed for Huawei Ascend AI processors. It enables the PyTorch framework to leverage Ascend NPU compute capabilities through deep adaptation and optimization, including support for torch.compile with mlir and dvm backends and MFusion graph fusion.
What's inside torch_npu
- TorchNPU is a deep learning adaptation plugin designed for Ascend NPUs. It allows the PyTorch framework to directly call Ascend NPU hardware, providing high-performance computing capabilities for AI applications. It inherits most features from upstream PyTorch while providing deep optimizations for Ascend hardware.
Overview of SimpleV1SparseDrive architecture
masterSimpleV1SparseDrive is a model structure implemented for Ascend NPU. The architecture consists of the following modules:
data_preprocessor: UsesBaseDataPreprocessor().img_backbone: ResNet (contains extensiveBatchNorm2d).img_neck: FPN.head:V1SparseDriveHead, which includes:det_head:Sparse4DHeadLike(includes DeformableFeatureAggregation, FlashAttention, and Refinement).map_head:Sparse4DHeadLike.motion_plan_head: Motion & Planning (includes multi-layer FlashAttention, FFN, and refinement).
depth_branch:DenseDepthNetLike(consists of 3 depth layers).grid_mask: GridMask.
Overview of lintrunner adapters
masterThelintrunneradapters are specialized files designed to bridge various linters with thelintrunnerframework. They allow different linting tools to be integrated into thelintrunnerexecution model, ensuring they can be invoked and interpreted correctly by the runner.Overview of Ascend PyTorch Profiler
masterThe Ascend PyTorch Profiler is a performance analysis tool designed for PyTorch training and online inference on Ascend hardware. It captures a full spectrum of performance data, including:
- PyTorch layer operator information
- CANN layer operator information
- Underlying NPU operator information
- Operator memory usage information
By integrating the profiler into your scripts, it automatically generates visualized performance data files upon task completion, facilitating efficient performance analysis.
Overview of TorchNPU Key Modules
masterTorchNPU is a deep learning adapter plugin that enables PyTorch to invoke Ascend NPUs. Its architecture consists of several key functional modules:
- Basic Compute: Provides support for PyTorch native and custom APIs for mainstream AI scenarios.
- Distributed: Accelerates distributed training via FSDP2 and supports DTensor, collective communication (AllGather, AllReduce, AllToAll), and point-to-point primitives (Send, Recv).
- Graph Mode: Accelerates training/inference via dynamic graph capture, static graph optimization, and efficient code generation. Supports offloading via NPUGraph (v2.6.0+).
- Debug & Tuning: Provides profiling for compute, communication, and memory, plus real-time anomaly monitoring via WatchDog.
- TorchNPU Core: Manages virtual memory to reduce fragmentation, optimizes cross-stream memory reuse in distributed settings, and integrates resources via
PrivateUse1.
Understand the output MLIR fused operator code
masterWhen using
run_and_get_code, the returnedcodescontains the captured MLIR output code snippets. These snippets typically include acallfunction and abenchmark_compiled_modelfunction.The
callfunction encapsulates the MLIR-compiled operator logic. Within this function, you will find the core execution interface, such asmlir_fused_xxx.run. This interface is responsible for executing the fused operator on a specific NPU device and compute stream, taking input tensors and writing results to the output tensor.def call(args): arg0_1, arg1_1 = args args.clear() with torch.npu.utils.device(0): torch.npu.set_device(0) buf0 = empty_strided((3, ), (1, ), device='npu', dtype=torch.float32) stream0 = get_raw_stream(0) # This is the core execution interface for the fused operator mlir_fused_mul_0.run(arg0_1, arg1_1, buf0, stream=stream0) del arg0_1 del arg1_1 return (buf0, )Understand TorchNPU Docker Image Tag Specifications
masterTorchNPU Docker images use a specific tagging format to identify the compatible environment. Tags follow this pattern:
<TorchNPU_version>-<chip>-<os>-<python_version>Field Definitions
- TorchNPU Version: The version of the TorchNPU plugin (e.g.,
2.10.0). - Chip: The chip model identifier (e.g.,
310p,910b,a3). Specific values can be found in the CANN mirror. - OS: The operating system distribution (e.g.,
ubuntu22.04,openeuler24.03). - Python Version: The pre-installed major Python version (e.g.,
py3.11).
Example Tags
2.10.0-310p-ubuntu22.04-py3.112.10.0-910b-ubuntu22.04-py3.112.10.0-a3-openeuler24.03-py3.11
2.10.0-310p-ubuntu22.04-py3.11- TorchNPU Version: The version of the TorchNPU plugin (e.g.,
Profiling modes in Ascend PyTorch Profiler
masterThe profiler offers different modes for data collection. Note: You cannot use two or more modes simultaneously in the same process.
Data Profiling Modes
torch_npu.profiler.profile(Recommended): Provides complete profiling APIs. You manually add these APIs to your code to freely choose specific content to profile.dynamic_profile(Recommended): Supports starting profiling at any time during training and allows starting profiling without modifying user code, offering higher flexibility.
Extended Profiling (Optional)
If you need to profile additional data, the following functions are available:
- Profile MSTX data
- Profile environment variables
- Mark performance data profiling process
- Device memory visualization
- Create Profiler sub-thread profiling
Data Parsing
- Automatic Parsing: The standard profiling APIs perform automatic parsing during the profiling process.
- Offline Parsing: Use this if you have unparsed raw performance data that needs to be processed after the fact.
HCCL AllReduce Workflow in Libtorch
masterThe HCCL AllReduce example demonstrates the standard lifecycle for performing collective communication on NPU devices using Libtorch:
- NPU Device Initialization: Initialize the device using
torch_npu::init_npu("npu:X"). - Create ProcessGroupHCCL: Instantiate the process group specifically for NPU collective communication.
- Tensor Creation: Create tensors directly on the NPU device.
- Execute AllReduce: Perform the global reduction operation on the tensors.
- Verification: Validate that the reduction results match expected mathematical outcomes.
- Resource Cleanup: Crucial step—you must call
torch_npu::finalize_npu()to release NPU resources after use.
Important Requirements:
- Ensure NPU devices are available and CANN is correctly installed.
- All participating processes must be started simultaneously for the collective communication to function.
- NPU Device Initialization: Initialize the device using
Understand TorchNPU Docker Tag Naming Convention
masterTorchNPU Docker images follow a specific naming convention to identify the compatible software and hardware stack. The format is:
<TorchNPU版本号>-<硬件信息(芯片)>-<操作系统>-<Python版本>Field Definitions
- TorchNPU Version: e.g.,
2.10.0 - Hardware (Chip): Identifiers for Ascend chips, such as
910b,310p, ora3. - Operating System: The base OS distribution, e.g.,
ubuntu22.04oropeneuler24.03. - Python Version: The major Python version included, e.g.,
py3.11.
- TorchNPU Version: e.g.,
Understand the purpose of the torch_npu/csrc/libs directory
masterThe
torch_npu/csrc/libsdirectory is specifically used to export interfaces related to the NPU, including operators and device initialization.Important Constraint: This component is built into
libtorch_npuwithout Python support. It is intended exclusively for NPU-based inference scenarios where a C++ environment is used rather than a Python runtime.Understand TorchNPU branch support and maintenance lifecycle
masterTorchNPU uses different maintenance strategies depending on the branch type (Regular, Long-Term Support, or Long-Term). Understanding these lifecycles helps in planning upgrades and ensuring stability for production environments.
Maintenance Phases
Status Duration Description Planned (计划) 1~3 months Planned feature development. Development (开发) 6~12 months Active development of new features and bug fixes. Regular branches typically have a 6-month development cycle, while Long-Term Support (LTS) branches have a 12-month cycle. Maintenance (维护) 1 year (Regular) / 3.5 years (LTS) Focuses on critical bug fixes only. No new features are added. Patch versions may be released based on bug impact. End of Life (EOL) N/A The branch no longer accepts any modifications or fixes.