README

CANN Ops Sparse

cann_ops_sparse is a PyTorch extension library of sparse operators for the Ascend NPU. Through Just-In-Time (JIT) compilation, it connects the PyTorch interfaces to the ACLSparse C API of ops-sparse; the extension does not modify the torch_npu package itself, but at import time registers backend implementations of the standard ATen sparse operators for the operators collected in the wheel.

The framework does not depend on the registration implementation of any specific operator. The following uses the spgemm operator as an example to describe the build, invocation, and development flow; after other operators follow the same directory conventions, they can be independently packaged, installed, and registered.

Build and Installation

Prerequisites

  • Operating system: Linux
  • Python: 3.9+
  • Compiler: GCC 9.4.0+
  • Framework:
    • PyTorch >= 2.6.0
    • torch_npu matching the PyTorch version
  • Toolchain: Ascend CANN Toolkit

Installation steps

  1. Install the dependencies.

    cd <ops-sparse *repository root directory*>
    python3 -m pip install -r torch_extension/requirements.txt
    
  2. Build the wheel. This step requires only the Python build dependencies, and no CANN environment variables need to be set. You can use the build script in the repository root; --ops only puts the Torch Extension source code of the specified operators into the wheel and does not compile the main library or AscendC kernels. The following uses the spgemm operator as an example; replacing it with another operator name yields a minimal wheel that does not depend on the spgemm registration.

    bash build.sh --torch_extension --ops=spgemm
    
  3. Install the wheel.

    python3 -m pip install build_out/cann_ops_sparse-*.whl --force-reinstall --no-deps
    

Building the self-contained source package (sdist)

The source package contains the Python registration code, C++ wrapper source code, common header files, and license of the selected operators. After extraction, you can build a wheel with the same content without accessing the sparse/ or include/ directories in the Git repository. The existing in-repo wheel build method remains unchanged.

# Only Python build dependencies are required; this step does not compile CANN kernels and does not import torch_npu.
python3 -m pip install "setuptools>=70.1" wheel build
cd torch_extension
TORCH_EXTENSION_OPS=spgemm python3 -m build --sdist --no-isolation

# Extract outside the repository and build the wheel. You can replace archive with the actual generated file name.
archive="$PWD/dist/cann_ops_sparse-0.1.0.tar.gz"
mkdir -p /tmp/ops-sparse-source-build
tar -xf "$archive" -C /tmp/ops-sparse-source-build
cd /tmp/ops-sparse-source-build/cann_ops_sparse-0.1.0
python3 -m build --wheel --no-isolation

When TORCH_EXTENSION_OPS is not set, the source package contains all available operators; when a comma-separated operator list is set, only the extension source code of these operators is collected. The extracted source package builds all operators it contains by default, and you can also use the same variable to further filter a subset; requesting an operator that is not archived raises an error. _sdist_sources/ stores the out-of-repo sources required for archiving, and its LICENSE is the original repository license; the source package root directory also keeps the same LICENSE, and the .dist-info of the wheel carries the license text with the package. _sdist_sources/ is generated by the sdist command only in the release staging directory, and is not written to the working tree.

External dependencies are not distributed with the source package: building the wheel requires Python and the preceding build tools; installation and actual JIT/NPU execution still require matching PyTorch, torch_npu, the CANN Toolkit, a C++ compiler, ninja, and the libops_sparse.so containing the target operators. The CPU regression from source package to wheel does not mean that these run dependencies or the NPU have been verified.

Quick start

Taking the spgemm operator as an example, the standard ATen operator it registers is aten::_sparse_sparse_matmul, and it also adapts aten::_sparse_addmm used internally by the PyTorch CSR path. Users use torch.sparse.mm instead of calling cann_ops_sparse.spgemm; torch_npu.sparse is a Python facade created by this package at import time. Before creation, it checks that the namespace is not occupied by another module; if it is already occupied, the import fails and does not overwrite the existing implementation.

import torch
import torch_npu
import cann_ops_sparse

out = torch.sparse.mm(matrix, matrix)
# The equivalent torch_npu facade:
out = torch_npu.sparse.mm(matrix, matrix)

When cann_ops_sparse is imported, the common framework collects the MATMUL_CAPABILITIES declared by the operators and uniformly registers the SparsePrivateUse1 / SparseCsrPrivateUse1 implementations of mm, mm.out, addmm, addmm.out, _sparse_addmm, and _sparse_sparse_matmul. dense×dense keeps the existing dense backend; sparse×dense selects SpMM; dense×sparse reuses SpMM after a normal transpose; sparse×sparse selects SpGEMM. Operator packages do not register these entries repeatedly, and torch_npu.sparse.mm/addmm is declared uniformly by the common framework.

When an unregistered operator capability is requested, the unified routing reports an explicit error.

The wheel built with the spgemm operator contains its Torch Extension source code. The first NPU call of torch.sparse.mm triggers JIT compilation and loads the NPU implementation. Before running, you must first build the libops_sparse.so containing spgemm. The library directories are searched in the order of OPS_SPARSE_LIB_DIR, ${ASCEND_HOME_PATH}/lib64, and ${ASCEND_HOME_PATH}/<arch>-linux/lib64, where <arch> is the architecture of the running host machine. When built from source or installed to another directory, you can use OPS_SPARSE_LIB_DIR to specify the library directory with priority; when that directory lacks libops_sparse.so, the library already installed in the CANN directory is used, and an error is reported when no candidate directory contains the library.

For the specific interface semantics, supported scope, constraints, and invocation examples, see the SpGEMM interface description. For SparseToDense (aten::_to_dense), see the SparseToDense interface description.

Reproducible build and invocation

The following commands use the spgemm operator as an example and run in the repository root; replace the CANN path with the actual installation path of the local machine. For other operators, only replace spgemm with the target operator name and use their own test files.

source /path/to/ascend-toolkit/set_env.sh
# Compile the ACLSparse main library; building the Torch Extension wheel does not compile this main library or kernels.
CMAKE_BUILD_TYPE=Release bash build.sh --ops=spgemm --soc=<*your SOC model*>

python3 -m pip install -r torch_extension/requirements.txt
bash build.sh --torch_extension --ops=spgemm
python3 -m pip install --force-reinstall --no-deps build_out/cann_ops_sparse-*.whl

# The libops_sparse.so built from source is in build/, so specify its path explicitly.
# If the run package has been installed to ${ASCEND_HOME_PATH}/lib64, this variable does not need to be set.
export OPS_SPARSE_LIB_DIR="$PWD/build"
export TORCH_EXTENSIONS_DIR="$PWD/.torch_extensions"
python3 -m pytest -q test/spgemm/python/test_spgemm_torch_extension.py

Taking the spgemm operator as an example, the test cases call torch.sparse.mm and cover CSR/COO, the supported data types, int64 index conversion, empty outputs, and non-default streams; the first run generates cann_ops_sparse_spgemm in TORCH_EXTENSIONS_DIR.

Developer guide: adding a new operator

The Torch Extension source code of an operator belongs to <category>/<op>/torch_extension/. Taking the spgemm operator as an example, its files are in sparse/spgemm/torch_extension/; when adding other operators, use their own directories, and do not modify or depend on the registration files of spgemm. ops-sparse currently uses the sparse category uniformly; the root torch_extension directory is only responsible for the common builder and wheel packaging, and automatically extracts the registration source code of each operator at build time.

ops-sparse/
├── sparse/
│   └── <op>/                         # original operator implementation
│       ├── archXX/                   # original host / kernel code (not modified)
│       └── torch_extension/          # operator-side extension source code
│           ├── __init__.py           # exports the Python interfaces
│           ├── <op>.py               # ATen dispatch, Meta, and PrivateUse1 registration
│           └── csrc/
│               └── <op>.cpp          # bridge from at::Tensor to the ACLSparse C API
└── torch_extension/                  # wheel build entry point
    ├── setup.py
    └── cann_ops_sparse/
        ├── op_builder/
        │   └── builder.py            # common JIT builder
        └── ops/
            └── __init__.py           # discovers the operators extracted in the wheel

At build time, setup.py extracts the preceding files to cann_ops_sparse/ops/<category>/<op>/ and cann_ops_sparse/csrc/<category>/<op>/ in the wheel. When adding a new operator, the Python file should inherit from OpBuilder and implement the following:

  1. sources(): declares csrc/sparse/<op>/<op>.cpp;
  2. Registers Meta implementations for existing ATen schemas when necessary; new ATen operators must not define schemas repeatedly;
  3. Registers implementations for PrivateUse1 and the dispatch keys corresponding to sparse layouts;
  4. Implements the call of builder.load(), loading the C++ wrapper and executing the underlying ACLSparse API.
  5. To provide an equivalent entry such as torch_npu.sparse, declare TORCH_NPU_SPARSE_FACADE_APIS = {"*interface name*": public_pytorch_api} in the operator registration module; it is automatically collected and installed at package import. Do not modify torch_npu_sparse.py.
Component Responsibility
OpBuilder Compiles and loads the C++ wrapper using JIT/ninja.
ATen Dispatch Routes torch.sparse.addmm to the NPU aten::_sparse_addmm implementation.
PrivateUse1 The dispatch key with which PyTorch dispatches NPU Tensors to the custom backend.

The old python/ops_sparse adapter of Gather has been merged into this framework, and the registration and JIT loading are managed by sparse/gather/torch_extension. After importing cann_ops_sparse, you can call torch.index_select or the retained torch.ops.ops_sparse.gather(values, indices, base=0); the latter supports base=0/1. The convenience functions are imported from cann_ops_sparse.ops.sparse.gather. The PYTHONPATH of the old Python directory is no longer needed, and the tests are unified in test/gather/python/.