Ascend NPU Bridge for PyTorch

2.9.0 · active · verified Tue Apr 14

torch-npu is a PyTorch extension that serves as an NPU bridge, adapting the Ascend Neural Network Processing Unit (NPU) to the PyTorch framework. It enables developers to leverage the powerful computational capabilities of Huawei Ascend AI Processors for deep learning training and inference within the PyTorch ecosystem. The current version is 2.9.0, with regular updates aligning with PyTorch releases and Ascend software stacks.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to check for NPU availability and perform a basic matrix multiplication on an Ascend NPU. It's crucial to first set up the CANN environment variables before running any NPU-accelerated code.

# Ensure CANN environment variables are sourced (e.g., from .bashrc or executed directly)
# source /usr/local/Ascend/ascend-toolkit/set_env.sh

import torch
import torch_npu # Essential for initializing NPU backend

# Check NPU availability
if torch.npu.is_available():
    print(f"NPU is available. Device count: {torch.npu.device_count()}")
    device = torch.device("npu:0")
    # Example tensor operations on NPU
    x = torch.randn(2, 2).to(device)
    y = torch.randn(2, 2).to(device)
    z = x.mm(y)
    print(f"Tensor on NPU:\n{x}")
    print(f"Result of matrix multiplication on NPU:\n{z}")
else:
    print("NPU is not available, using CPU.")
    device = torch.device("cpu")
    x = torch.randn(2, 2).to(device)
    y = torch.randn(2, 2).to(device)
    z = x.mm(y)
    print(f"Tensor on CPU:\n{x}")
    print(f"Result of matrix multiplication on CPU:\n{z}")

view raw JSON →