torch_npu (Ascend PyTorch)

repository·master·Indexed 20 days ago

https://github.com/ascend/pytorch

A 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.

Tokens
46.8K
Snippets
133
Records
183
Agent score
67%

What's inside torch_npu

  1. Overview of TorchNPU

    master
    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.
  2. Overview of SimpleV1SparseDrive architecture

    master

    SimpleV1SparseDrive is a model structure implemented for Ascend NPU. The architecture consists of the following modules:

    • data_preprocessor: Uses BaseDataPreprocessor().
    • img_backbone: ResNet (contains extensive BatchNorm2d).
    • 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.
  3. Overview of Ascend PyTorch Profiler

    master

    The 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.

  4. Overview of TorchNPU Key Modules

    master

    TorchNPU 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.
  5. Understand the output MLIR fused operator code

    master

    When using run_and_get_code, the returned codes contains the captured MLIR output code snippets. These snippets typically include a call function and a benchmark_compiled_model function.

    The call function encapsulates the MLIR-compiled operator logic. Within this function, you will find the core execution interface, such as mlir_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, )
  6. Understand TorchNPU Docker Image Tag Specifications

    master

    TorchNPU 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.11
    • 2.10.0-910b-ubuntu22.04-py3.11
    • 2.10.0-a3-openeuler24.03-py3.11
    2.10.0-310p-ubuntu22.04-py3.11
  7. Profiling modes in Ascend PyTorch Profiler

    master

    The 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.
  8. HCCL AllReduce Workflow in Libtorch

    master

    The HCCL AllReduce example demonstrates the standard lifecycle for performing collective communication on NPU devices using Libtorch:

    1. NPU Device Initialization: Initialize the device using torch_npu::init_npu("npu:X").
    2. Create ProcessGroupHCCL: Instantiate the process group specifically for NPU collective communication.
    3. Tensor Creation: Create tensors directly on the NPU device.
    4. Execute AllReduce: Perform the global reduction operation on the tensors.
    5. Verification: Validate that the reduction results match expected mathematical outcomes.
    6. 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.
  9. Understand TorchNPU Docker Tag Naming Convention

    master

    TorchNPU 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, or a3.
    • Operating System: The base OS distribution, e.g., ubuntu22.04 or openeuler24.03.
    • Python Version: The major Python version included, e.g., py3.11.
  10. Understand the purpose of the torch_npu/csrc/libs directory

    master

    The torch_npu/csrc/libs directory is specifically used to export interfaces related to the NPU, including operators and device initialization.

    Important Constraint: This component is built into libtorch_npu without Python support. It is intended exclusively for NPU-based inference scenarios where a C++ environment is used rather than a Python runtime.

  11. Understand TorchNPU branch support and maintenance lifecycle

    master

    TorchNPU 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

    StatusDurationDescription
    Planned (计划)1~3 monthsPlanned feature development.
    Development (开发)6~12 monthsActive 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/AThe branch no longer accepts any modifications or fixes.