1. 项目概述

1.1 项目简介

torch_npu 是面向昇腾 NPU(Neural Processing Unit)的 PyTorch 后端实现,旨在为 PyTorch 开发者提供在昇腾 AI 处理器上进行深度学习训练与推理的完整能力。通过接入 PyTorch 生态,torch_npu 使现有 PyTorch 代码能够无缝迁移至昇腾平台,享受 NPU 带来的高性能计算体验。

1.2 设计目标

  • 兼容性:最大程度兼容 PyTorch 原生 API,用户仅需最小代码改动即可完成迁移
  • 高性能:充分利用昇腾 NPU 计算能力,支持算子融合与数据格式优化
  • 易用性:提供简洁一致的使用体验,降低开发者学习与迁移成本
  • 可扩展:支持自定义算子、分布式训练、混合精度等高级特性

1.3 代码规模

torch_npu 采用 C++ 与 Python 双语言实现,覆盖算子实现、核心运行时、分布式通信、性能分析、编译优化以及文档与测试等模块,整体工程规模较大。


2. 整体架构

2.1 架构层次图

在这里插入图片描述

2.2 目录结构

torch_npu/
├── torch_npu/              # 核心源代码目录
│   ├── csrc/               # C++ 源代码
│   │   ├── aten/           # ATen 算子实现
│   │   ├── core/           # 核心运行时
│   │   ├── framework/      # 算子框架
│   │   ├── distributed/    # 分布式通信
│   │   ├── profiler/       # 性能分析
│   │   ├── npu/            # NPU 设备接口
│   │   ├── inductor/       # Inductor 后端
│   │   └── ...
│   ├── npu/                # Python NPU API
│   ├── distributed/        # Python 分布式 API
│   ├── profiler/           # Python 分析器 API
│   ├── optim/              # 融合优化器
│   ├── contrib/            # 扩展功能
│   └── ...
├── third_party/            # 第三方依赖
├── test/                   # 测试代码
├── docs/                   # 文档
└── cmake/                  # CMake 构建脚本

3. 核心模块设计

3.1 设备管理模块

3.1.1 模块位置
  • C++ 实现:torch_npu/csrc/core/npu/
  • Python 接口:torch_npu/npu/utils.py、torch_npu/npu/__init__.py
3.1.2 核心类与接口

系统控制器(NpuSysCtrl)

// 文件: torch_npu/csrc/core/npu/sys_ctrl/npu_sys_ctrl.h
class NpuSysCtrl {
public:
    static NpuSysCtrl& GetInstance();     // 单例模式

    SysStatus Initialize(int device_id);   // 初始化设备
    SysStatus LazyInitialize(int device);  // 延迟初始化
    SysStatus ExchangeDevice(int device);  // 切换设备
    SysStatus Finalize();                  // 释放资源

    void RegisterReleaseFn(ReleaseFn fn,   // 注册资源释放回调
                           ReleasePriority priority);
};

设备函数(NPUFunctions)

// 文件: torch_npu/csrc/core/npu/NPUFunctions.h
namespace c10_npu {
    c10::DeviceIndex device_count() noexcept;  // 获取设备数量
    c10::DeviceIndex current_device();          // 获取当前设备
    void set_device(c10::DeviceIndex device);   // 设置当前设备
    void device_synchronize();                  // 设备同步
    int ExchangeDevice(int device);             // 交换设备
}

Python API

# 文件: torch_npu/npu/__init__.py
# 设备管理 API
torch_npu.npu.is_available()          # 检查 NPU 是否可用
torch_npu.npu.device_count()          # 获取设备数量
torch_npu.npu.current_device()        # 获取当前设备
torch_npu.npu.set_device(device)      # 设置当前设备
torch_npu.npu.synchronize()           # 同步设备
torch_npu.npu.get_device_name()       # 获取设备名称
torch_npu.npu.get_device_properties() # 获取设备属性
3.1.3 设备属性结构
// 文件: torch_npu/csrc/npu/Module.cpp
struct NPUDeviceProp {
    std::string name;           // 设备名称
    size_t totalGlobalMem;      // 全局内存大小
    int64_t cube_core_num;      // Cube 核心数
    int64_t vector_core_num;    // Vector 核心数
    int64_t L2_cache_size;      // L2 缓存大小
    std::optional major;   // 主版本号
    std::optional minor;   // 次版本号
};

3.2 内存管理模块

3.2.1 模块位置
  • C++ 实现:torch_npu/csrc/core/npu/NPUCachingAllocator.h
  • Python 接口:torch_npu/npu/memory.py
3.2.2 核心设计

缓存分配器架构

在这里插入图片描述

内存统计结构

// 文件: torch_npu/csrc/core/npu/NPUCachingAllocator.h
struct Stat {
    int64_t current = 0;    // 当前分配量
    int64_t peak = 0;       // 峰值分配量
    int64_t allocated = 0;  // 总分配量
    int64_t freed = 0;      // 总释放量
};

struct DeviceStats {
    StatArray allocation;          // 分配统计
    StatArray reserved_bytes;      // 预留字节数
    int64_t num_alloc_retries;     // 分配重试次数
    int64_t num_ooms;              // OOM 次数
};

Python API

# 文件: torch_npu/npu/memory.py
torch_npu.npu.memory_allocated(device)     # 已分配内存
torch_npu.npu.max_memory_allocated(device) # 峰值已分配内存
torch_npu.npu.memory_reserved(device)      # 已预留内存
torch_npu.npu.max_memory_reserved(device)  # 峰值已预留内存
torch_npu.npu.memory_stats(device)         # 内存统计详情
torch_npu.npu.empty_cache()                # 清空缓存
torch_npu.npu.set_per_process_memory_fraction(fraction)  # 设置内存使用比例
3.2.3 存储实现
// 文件: torch_npu/csrc/core/NPUStorageImpl.h
struct NPUStorageDesc {
    c10::SmallVector base_sizes_;      // 基础尺寸
    c10::SmallVector base_strides_;    // 基础步长
    c10::SmallVector storage_sizes_;   // 存储尺寸
    aclFormat origin_format_;                       // 原始格式
    aclFormat npu_format_;                          // NPU 格式
    caffe2::TypeMeta data_type_;                    // 数据类型
};

struct NPUStorageImpl : public c10::StorageImpl {
    NPUStorageDesc npu_desc_;
    uint64_t unique_id_{0};
};

3.3 流与事件管理模块

3.3.1 模块位置
  • C++ 实现:torch_npu/csrc/core/npu/NPUStream.h、torch_npu/csrc/npu/Event.h
  • Python 接口:torch_npu/npu/streams.py
3.3.2 流管理设计
// 文件: torch_npu/csrc/core/npu/NPUStream.h
class NPUStream {
public:
    explicit NPUStream(c10::Stream stream);

    // 类型转换
    operator aclrtStream() const { return stream(); }
    operator c10::Stream() const { return unwrap(); }

    // 属性访问
    c10::DeviceIndex device_index() const;
    c10::Device device() const;

    // 同步操作
    bool query() const;
    void synchronize() const;
    aclrtStream stream() const;
};

// 流管理全局函数
NPUStream getDefaultNPUStream(c10::DeviceIndex device_index = -1);
NPUStream getCurrentNPUStream(c10::DeviceIndex device_index = -1);
NPUStream getStreamFromPool(bool isHighPriority, c10::DeviceIndex device);
bool npuSynchronizeDevice(bool check_error = true);

流内部结构

struct LeakyStreamInternals {
    c10::DeviceIndex device_index;
    int32_t stream_id;
    aclrtStream stream;
    std::unique_ptr repo;     // 任务队列
    bool is_data_preprocess_stream;
    bool is_sync_launch;
};
3.3.3 任务队列
// 文件: torch_npu/csrc/core/npu/NPUQueue.h
class NPUQueueBase {
public:
    virtual RepoStatus GetStatus() const = 0;
    virtual void Enqueue(void* cur_paras) = 0;
    virtual void Dequeue() = 0;
    virtual NPUStatus MakeSureQueueEmpty(bool check_error = true) = 0;
};

enum RepoStatus {
    INIT = 0,
    RUN = 1,
    NEED_EXIT = 2,
    CAN_EXIT = 3,
    ERROR_EXIT = 4
};
3.3.4 Python API
# 文件: torch_npu/npu/streams.py
class Stream(torch_npu._C._NPUStreamBase):
    """NPU 流包装器"""
    def wait_event(self, event)
    def wait_stream(self, stream)
    def record_event(self, event=None)
    def synchronize()

class Event(torch_npu._C._NPUEventBase):
    """NPU 事件"""
    def record(self, stream=None)
    def wait(self, stream=None)
    def synchronize()
    def elapsed_time(self, end_event)

# 上下文管理器
class StreamContext:
    """流选择上下文"""
    def __enter__(self)
    def __exit__(self)

3.4 算子框架模块

3.4.1 模块位置
  • C++ 实现:torch_npu/csrc/framework/
3.4.2 OpCommand 设计

OpCommand 是 torch_npu 算子调用的核心抽象,提供统一的算子构建和执行接口。

// 文件: torch_npu/csrc/framework/OpCommand.h
class OpCommand {
public:
    // 设置算子名称
    OpCommand& Name(const string& name);

    // 输入管理
    OpCommand& Input(const at::Tensor& input,
                     const string& descName = "",
                     const c10::optional& sensitive_format = c10::nullopt);
    OpCommand& InputWithoutContiguous(const at::Tensor& input);
    OpCommand& Inputs(const at::TensorList& inputs);
    OpCommand& Input(const c10::IntArrayRef& dimListRef, at::ScalarType toType);
    OpCommand& Input(const c10::Scalar& input, const at::ScalarType type);

    // 输出管理
    OpCommand& Output(at::Tensor& output, const string& descName = "");

    // 属性设置
    template
    OpCommand& Attr(const string& name, dataType value);

    // 执行
    void Run();
    OpCommand& Sync();

private:
    c10::SmallVector storage;
    OpCommandImpl* aclCmd = nullptr;
};
3.4.3 参数生成器
// 文件: torch_npu/csrc/framework/OpParamMaker.h
class OpAttrMaker {
public:
    static void Set(aclopAttr* attr, const string& name, bool value);
    static void Set(aclopAttr* attr, const string& name, int64_t value);
    static void Set(aclopAttr* attr, const string& name, float value);
    static void Set(aclopAttr* attr, const string& name, c10::IntArrayRef value);
};

class AclTensorDescMaker {
public:
    AclTensorDescMaker& Create(aclDataType dataType,
                               torch_npu::NPUStorageDesc storageDesc);
    AclTensorDescMaker& SetFormat(aclFormat format);
    AclTensorDescMaker& SetPlacement(aclMemType memType);
};
3.4.4 格式转换
// 文件: torch_npu/csrc/framework/FormatHelper.cpp

// 支持的格式
ACL_FORMAT_NC1HWC0    // 4D 分形格式
ACL_FORMAT_ND         // N 维通用格式
ACL_FORMAT_NCHW       // 标准 NCHW 格式
ACL_FORMAT_NHWC       // 标准 NHWC 格式
ACL_FORMAT_FRACTAL_NZ // NZ 分形格式
ACL_FORMAT_FRACTAL_Z  // Z 分形格式
ACL_FORMAT_NCDHW      // 5D 格式
ACL_FORMAT_NDC1HWC0   // 5D 分形格式

// 格式辅助函数
bool FormatHelper::IsPadded(const at::Tensor* tensor);
aclFormat FormatHelper::GetBaseFormat(const at::Tensor& tensor);
aclFormat FormatHelper::GetFormat(const at::Tensor& tensor);

3.5 ATen 算子注册模块

3.5.1 模块位置
  • C++ 实现:torch_npu/csrc/aten/
  • 配置文件:torch_npu/csrc/aten/npu_native_functions.yaml
3.5.2 算子注册机制

算子定义(YAML)

# 文件: torch_npu/csrc/aten/npu_native_functions.yaml
supported:
  - func: clone
    op_api: True          # 使用高层 OpAPI 实现
  - func: copy_
    op_api: True
  - func: empty.memory_format
  - func: contiguous
  - func: add.Tensor
    op_api: True
  - func: matmul
    op_api: True
  # ... 更多算子定义

算子实现示例

// 文件: torch_npu/csrc/aten/ops/op_api/CopyKernelOpApi.cpp
void copy_between_host_and_device_opapi(
    at::Tensor& dst,
    const at::Tensor& src,
    aclrtMemcpyKind kind,
    bool non_blocking)
{
    // 实现主机与设备之间的数据复制
}

自动混合精度注册

// 文件: torch_npu/csrc/aten/AutoCastOps.cpp
TORCH_LIBRARY_IMPL(aten, AutocastPrivateUse1, m) {
    // 低精度算子
    KERNEL_PRIVATEUSEONE(conv2d, lower_precision_fp)
    KERNEL_PRIVATEUSEONE(matmul, lower_precision_fp)
    KERNEL_PRIVATEUSEONE(bmm, lower_precision_fp)

    // 保持 FP32 精度的算子
    KERNEL_PRIVATEUSEONE(layer_norm, fp32)
    KERNEL_PRIVATEUSEONE(softmax, fp32)
    KERNEL_PRIVATEUSEONE(log_softmax, fp32)
}
3.5.3 代码生成

通过 generate_code.sh 自动生成以下文件:

生成文件用途
RegisterNPU.cppNPU 算子注册代码
RegisterCPU.cppCPU 算子注册代码
RegisterAutogradNPU.cpp自动求导注册
NPUNativeFunctions.h函数声明头文件
CustomRegisterSchema.cpp自定义算子 Schema
ForeachRegister.cppForeach 算子注册

3.6 分布式训练模块

3.6.1 模块位置
  • C++ 实现:torch_npu/csrc/distributed/
  • Python 接口:torch_npu/distributed/
3.6.2 支持的后端
后端说明使用场景
HCCL华为集合通信库NPU 集群分布式训练
LCCL本地集合通信库单机多卡通信
3.6.3 后端注册
# 文件: torch_npu/__init__.py
def _register_distributed_backend_for_npu():
    # 注册 HCCL 后端
    torch.distributed.Backend.register_backend(
        "hccl",
        lambda dist_backend_opts, pg_options:
            _new_process_group_hccl_helper(...),
        extended_api=True,
        devices=["npu"]
    )

    # 注册 LCCL 后端
    torch.distributed.Backend.register_backend(
        "lccl",
        lambda dist_backend_opts, pg_options:
            _new_process_group_lccl_helper(...),
        extended_api=True,
        devices=["npu"]
    )
3.6.4 分布式 API
# 文件: torch_npu/distributed/distributed_c10d.py

# 检查后端可用性
def is_hccl_available() -> bool

# 进程组管理
def reinit_process_group(group=None, rebuild_link=True)

# 扩展集合操作
def _batch_isend_irecv(p2p_op_list)
def _gather(tensor, gather_list=None, dst=0, group=None, async_op=False)
def _reduce_scatter_tensor_uneven(output, input, input_split_sizes=None, ...)
def _all_gather_into_tensor_uneven(...)
3.6.5 FSDP 支持
# 文件: torch_npu/distributed/fsdp/_add_fsdp_patch.py
# 针对 NPU 的完全分片数据并行优化
# - 自定义梯度收集和 reduce-scatter
# - AllGather 事件同步
# - NPU 特定的内存优化
3.6.6 RPC 支持
# 文件: torch_npu/distributed/rpc/
backend_registry.py  # 后端注册
options.py           # RPC 选项配置

3.7 自动混合精度模块

3.7.1 模块位置
  • Python 接口:torch_npu/npu/amp/
3.7.2 核心组件

autocast 上下文管理器

# 文件: torch_npu/npu/amp/autocast_mode.py
class autocast(torch.amp.autocast_mode.autocast):
    """NPU 自动混合精度上下文"""
    def __init__(self,
                 enabled=True,
                 dtype=torch.float16,
                 cache_enabled=True):
        super().__init__("npu", enabled, dtype, cache_enabled)

# 支持的精度类型
supported_dtype = [torch.float16, torch.bfloat16]

GradScaler 梯度缩放器

# 文件: torch_npu/npu/amp/grad_scaler.py
class GradScaler(BaseGradScaler):
    """NPU 梯度缩放器,支持 fp16/bf16"""

    def scale(self, outputs)           # 缩放损失
    def unscale_(self, optimizer)      # 反缩放梯度
    def step(self, optimizer)          # 优化器步进
    def update()                       # 更新缩放因子
3.7.3 使用示例
import torch
import torch_npu

# 创建模型和优化器
model = Model().npu()
optimizer = torch.optim.Adam(model.parameters())
scaler = torch_npu.npu.amp.GradScaler()

# 训练循环
for data, target in dataloader:
    data, target = data.npu(), target.npu()

    with torch_npu.npu.amp.autocast():
        output = model(data)
        loss = loss_fn(output, target)

    scaler.scale(loss).backward()
    scaler.step(optimizer)
    scaler.update()
    optimizer.zero_grad()

3.8 性能分析模块

3.8.1 模块位置
  • C++ 实现:torch_npu/csrc/profiler/
  • Python 接口:torch_npu/profiler/
3.8.2 分析器架构

在这里插入图片描述

3.8.3 使用方式
import torch_npu
from torch_npu.profiler import profile, ProfilerActivity

with profile(
    activities=[ProfilerActivity.CPU, ProfilerActivity.NPU],
    on_trace_ready=torch.profiler.tensorboard_trace_handler('./log')
) as prof:
    for step, (data, target) in enumerate(dataloader):
        # 训练代码
        prof.step()

3.9 编译优化模块

3.9.1 模块位置
  • C++ 实现:torch_npu/csrc/inductor/
  • Python 接口:torch_npu/dynamo/、torch_npu/_inductor/
3.9.2 Dynamo 支持
# 文件: torch_npu/dynamo/__init__.py

# NPU 编译后端
def _get_global_npu_backend(name, config=None)

# NPUGraph 扩展后端
def _get_npugraph_ex_backend()

# 使用示例
model = torch.compile(model, backend="npu")
3.9.3 Inductor 后端
# 文件: torch_npu/_inductor/
codegen/           # 代码生成
fx_passes/         # FX 图变换
aoti_runtime/      # AOT Inductor 运行时
3.9.4 NPUGraph 支持
# 文件: torch_npu/npu/graphs.py
class NPUGraph:
    """NPU 计算图捕获和回放"""

    def capture_begin(self)
    def capture_end(self)
    def replay(self)
    def reset(self)

# 使用示例
g = torch_npu.npu.NPUGraph()
with torch_npu.npu.graph(g):
    output = model(input)

# 回放
g.replay()

4. Python 接口层设计

4.1 模块结构

torch_npu/
├── __init__.py              # 主入口,初始化和补丁
├── npu/                     # NPU 设备 API
│   ├── __init__.py          # 公共 API 导出
│   ├── utils.py             # 设备工具函数
│   ├── memory.py            # 内存管理
│   ├── streams.py           # 流和事件
│   ├── graphs.py            # 计算图
│   ├── npu_config.py        # 配置选项
│   └── amp/                 # 自动混合精度
├── distributed/             # 分布式训练
│   ├── distributed_c10d.py  # C10D 后端
│   ├── fsdp/                # FSDP 补丁
│   └── rpc/                 # RPC 支持
├── optim/                   # 融合优化器
│   ├── npu_fused_adam.py
│   ├── npu_fused_adamw.py
│   └── ...
├── contrib/                 # 扩展功能
│   ├── function/            # 优化函数
│   └── module/              # 优化模块
├── profiler/                # 性能分析
├── dynamo/                  # Dynamo 支持
├── _inductor/               # Inductor 后端
├── jit/                     # JIT 编译
└── onnx/                    # ONNX 导出

4.2 核心 API 汇总

模块主要 API
torch_npu.npuis_available(), set_device(), synchronize(), memory_allocated()
torch_npu.npu.ampautocast(), GradScaler()
torch_npu.distributedis_hccl_available(), reinit_process_group()
torch_npu.optimNpuFusedAdam, NpuFusedSGD, NpuFusedLamb
torch_npu.profilerprofile(), ProfilerActivity

4.3 融合优化器

# 文件: torch_npu/optim/
class NpuFusedOptimizerBase      # 基类
class NpuFusedAdam               # Adam 融合版
class NpuFusedAdamW              # AdamW 融合版
class NpuFusedAdamP              # AdamP 融合版
class NpuFusedLamb               # LAMB 融合版
class NpuFusedSGD                # SGD 融合版
class NpuFusedRMSprop            # RMSprop 融合版
# ... 共 9 个融合优化器

5. 与 PyTorch 集成机制

5.1 后端注册

# 文件: torch_npu/__init__.py

# 1. 注册 NPU 为 PrivateUse1 后端
torch.utils.rename_privateuse1_backend("npu")

# 2. 注册设备模块
torch._register_device_module('npu', torch_npu.npu)

# 3. 生成设备方法
torch.utils.generate_methods_for_privateuse1_backend(
    for_tensor=True,
    for_module=True,
    for_storage=True,
    unsupported_dtype=[torch.quint8, torch.quint4x2, ...]
)

5.2 Monkey-Patch 机制

# 文件: torch_npu/__init__.py

def _apply_class_patches():
    # 1. 存储方法补丁
    _add_storage_methods()

    # 2. 张量方法补丁
    _add_tensor_methods()

    # 3. 序列化方法补丁
    _add_serialization_methods()

    # 4. 分布式方法补丁
    _apply_distributed_methods_patch()

    # 5. nn.functional 补丁
    all_monkey_patches = [
        ["nn.functional", npu_functional],
        ["nn", npu_modules],
    ]

5.3 模块设备转换

# 文件: torch_npu/utils/_module.py

# 支持 model.npu() 方法
def npu(self, device=None):
    return self._apply(lambda t: t.npu(device))

# NPU 特定的权重格式转换
def cast_weight(self, device):
    # BatchNorm: NC1HWC0 格式
    # Conv2d: FRACTAL_Z 格式
    # Conv3d: FRACTAL_Z_3D 格式

5.4 初始化流程

# 初始化顺序
1. import torch_npu
2. 加载 C++ 扩展 (_C)
3. 注册 NPU 后端
4. 应用 monkey-patches
5. 注册分布式后端 (HCCL/LCCL)
6. 注册 Dynamo/Inductor 支持
7. 注册退出清理钩子 (atexit)

6. 构建系统

6.1 构建架构

在这里插入图片描述

6.2 编译命令

# 标准编译
python setup.py build bdist_wheel

# 调试模式
DEBUG=1 python setup.py build bdist_wheel

# 启用 LTO 优化
ENABLE_LTO=TRUE python setup.py build bdist_wheel

# 并行编译
MAX_JOBS=8 python setup.py build bdist_wheel

6.3 CMake 配置

配置项说明默认值
CMAKE_BUILD_TYPE构建类型Release
ENABLE_LTO链接时优化OFF
PGO_MODEPGO 模式0
BUILD_TENSORPIPETensorpipe 支持OFF
BUILD_TORCHAIRTorchAIR 支持OFF
GLIBCXX_USE_CXX11_ABIC++11 ABI0

6.4 环境变量

变量说明
PYTORCH_INSTALL_DIRPyTorch 安装目录
PYTHON_INCLUDE_DIRPython 头文件目录
CANN_INSTALL_PATHCANN 安装路径
DEBUG调试模式开关
MAX_JOBS并行编译数

7. 第三方依赖

7.1 核心依赖

依赖来源用途
op-pluginGit 子模块算子实现库
ACLCANN SDK昇腾计算库
HCCLCANN SDK集合通信库
torchairGit 子模块动态编译框架
TensorpipeGit 子模块RPC 通信库

7.2 工具库

依赖用途
fmt字符串格式化
nlohmannJSON 处理
googletestC++ 单元测试
dlpack张量交换协议

7.3 运行时库依赖

PyTorch:
├── libc10.so
├── libtorch.so
├── libtorch_cpu.so
└── libtorch_python.so

CANN:
├── libhccl.so
├── libascendcl.so
├── libacl_op_compiler.so
├── libge_runner.so
└── libgraph.so

torch_npu:
├── libtorch_npu.so
└── libnpu_profiler.so

8. 附录

8.1 快速开始

import torch
import torch_npu

# 检查 NPU 可用性
print(f"NPU available: {torch_npu.npu.is_available()}")
print(f"NPU count: {torch_npu.npu.device_count()}")

# 创建 NPU 张量
x = torch.randn(3, 3).npu()
y = torch.randn(3, 3).npu()
z = x + y

# 使用模型
model = MyModel().npu()
output = model(input.npu())

8.2 配置选项

# 内存配置
torch_npu.npu.set_per_process_memory_fraction(0.8)

# 同步模式
torch_npu.npu.set_sync_debug_mode(1)  # 0=禁用, 1=警告, 2=错误

# 编译配置
torch_npu.npu.config.aoe_config.aoe_mode = "1"

8.3 错误码系统

# 文件: torch_npu/utils/_error_code.py
class ErrCode:
    NOT_FOUND = "ERR00001"
    NOT_SUPPORT = "ERR00007"
    INTERNAL = "ERR00005"
    PARAM = "ERR00003"
    VALUE = "ERR00004"
    TYPE = "ERR00008"

9. 总结与展望

torch_npu 作为面向昇腾 NPU 的 PyTorch 后端实现,通过设备管理、内存管理、流与事件、算子框架、ATen 算子注册、分布式训练、自动混合精度、性能分析与编译优化等核心模块,为 PyTorch 开发者提供了昇腾 AI 处理器上的完整训练与推理能力。

在架构设计上,torch_npu 采用分层解耦的组织方式:底层由 C++ 核心运行时对接 ACL、HCCL 等昇腾计算库,上层通过 PrivateUse1 后端注册与 Monkey-Patch 机制无缝融入 PyTorch 生态,使现有 PyTorch 代码能够以较小的改动迁移至昇腾平台,并支持算子融合、混合精度、分布式训练与编译优化等高级特性。

展望后续,torch_npu 将持续跟进 PyTorch 生态的演进,深化 Dynamo/Inductor 编译优化、分布式训练与自动混合精度等方向的适配能力,为开发者提供更稳定、更高效的使用体验,进一步降低昇腾平台的迁移与使用成本。

Logo

作为“人工智能6S店”的官方数字引擎,为AI开发者与企业提供一个覆盖软硬件全栈、一站式门户。

更多推荐