| Files | Last commit | Last update |
|---|---|---|
SpMV Operator
Operator Overview
The SpMV (Sparse Matrix - Dense Vector Multiplication) operator implements the multiplication of a sparse matrix and a dense vector. The core operation is y = alpha * op(A) * x + beta * y, where A is a sparse matrix in CSR format, and x and y are dense vectors.
Mathematical expression:
y = alpha * op(A) * x + beta * y
Here op(A) is the operation of sparse matrix A (transpose/non-transpose), x is the input dense vector, and y is the input/output dense vector.
The repository contains two implementations: arch22 (Atlas A2 products and Atlas A3 products, DAV_2201) and arch35 (Ascend 950PR&950DT products), which share the same set of aclsparse interfaces.
It includes the following interfaces (three-stage invocation flow, with semantics matching cuSPARSE SpMV):
| Interface | Brief Function |
|---|---|
| aclsparseSpMVGetBufferSize | Queries the number of workspace bytes required for execution |
| aclsparseSpMVPreprocess | Optional preprocessing: arch22 performs one longest-row probe for the CUBE algorithm (rowPtr D2H + stream synchronization) and caches it into the matrix descriptor, and the other algorithms perform only parameter validation; arch35 builds a reusable deterministic CSR-to-CSC index for the transpose path |
| aclsparseSpMV | Executes the sparse matrix-dense vector multiplication y = alpha * op(A) * x + beta * y |
| aclsparseCsrSetStrides / GetStrides | Sets/obtains the element strides of CSR rowOffsets, colInd, and values (arch22/arch35) |
| aclsparseDnVecSetStride / GetStride | Sets/obtains the element stride of the dense vector (arch22/arch35) |
Operator Execution Interface
aclsparseSpMVGetBufferSize
Function prototype
aclsparseStatus_t aclsparseSpMVGetBufferSize(aclsparseHandle_t handle, aclsparseOperation_t opA, const void *alpha, aclsparseConstSpMatDescr_t matA, aclsparseConstDnVecDescr_t vecX, const void *beta, aclsparseDnVecDescr_t vecY, aclDataType computeType, aclsparseSpMVAlg_t alg, size_t *bufferSize)
Function Description
- Returns the exact number of workspace bytes required for execution:
- In general cases, it returns 0;
- arch22: for transpose (opA=TRANSPOSE) with FP32 computation (output FP32/FP16/BF16), it returns
groups * roundUp(cols, 8) * 2 * sizeof(float)(groups = min(number of AIV cores, max(rows, 1))): this path performs deterministic double-single (hi/lo two-plane) accumulation in the workspace, combines with the beta*y0 double word at the end, and writes back with a single rounding (the 16-bit output is converted through Cast round-to-nearest-even (RNE), with the rounding midpoint corrected by the low bits of the double word), ensuring precision in cancellation scenarios and cross-core determinism; - arch22: for transpose with COMPLEX64 output, it returns
groups * roundUp(2*cols, 8) * 2 * sizeof(float)(interleaved float2, same principle); - arch35 (Ascend 950PR&950DT products): always returns a non-zero size, including a 192-byte header and base-normalized row offsets; the transpose path also includes stable CSR-to-CSC metadata (column offsets, row indices, and original CSR value subscripts) and an accumulation area, with each area aligned to 64 bytes. The caller is responsible for allocating Device memory according to the returned number of bytes and must not hard-code the old size.
- arch22:
ACL_SPARSE_SPMV_CSR_ALG_CUBEreturns the workspace size required for segmented summation (gather product area + intra-block speculative scan result area); an empty matrix (nnz == 0) falls back to the vector implementation and returns 0.
- It performs only null-pointer and parameter validation (arch35 checks only descriptor metadata, allowing the CSR or x/y data pointers to be unbound yet), and produces no Host<->Device data synchronization.
aclsparseSpMVPreprocess
Function prototype
aclsparseStatus_t aclsparseSpMVPreprocess(aclsparseHandle_t handle, aclsparseOperation_t opA, const void *alpha, aclsparseConstSpMatDescr_t matA, aclsparseConstDnVecDescr_t vecX, const void *beta, aclsparseDnVecDescr_t vecY, aclDataType computeType, aclsparseSpMVAlg_t alg, void *externalBuffer)
Function Description
- Optional call; arch22 performs parameter validation + workspace lifecycle management (externalBuffer can be nullptr when bufferSize is 0; it must be non-empty when non-0), and the CUBE algorithm additionally performs the longest-row probe and caches it (see the interface table);
- When SpMV executes multiple times on the same sparsity pattern, the descriptor, workspace, and preprocessing results can be reused; after the pattern changes, query and preprocessing must be performed again.
- arch35 (Ascend 950PR&950DT products): it generates base-normalized row pointers in the workspace and records the pattern, attributes, and workspace of matA as an active plan, which subsequent
aclsparseSpMVcalls can reuse; the transpose path asynchronously builds a stable column-wise index on the calling stream — the row order and element order of the original CSR are strictly preserved within each column, and each subsequent output element is accumulated in a fixed order, avoiding the non-determinism introduced by floating-point atomic add. Preprocessing reads only rowOffsets (which must be bound when rows > 0) and descriptor metadata, and requires the workspace to be allocated; values, colInd, and x/y can be bound after preprocessing completes, and the execution stage still fully checks the data pointers. Subsequent pointer updates may invalidate the cached plan, but SpMV can be executed directly (falling back to reading the original CSR at execution time) without preprocessing again; however, after modifying the CSR structure in place (the contents of rowOffsets or colInd change, even if the pointer addresses do not), Preprocess must be called again — the Host does not read device-side index contents and cannot automatically discover such changes; otherwise, the old normalized row offsets may be reused; updating only values/x/y in place does not require re-preprocessing. Both preprocessing and execution enqueue Device tasks to the handle stream and do not synchronize to read back the CSR; asynchronous H2D on the same stream can be placed directly before the call, and the caller is responsible for synchronizing before reading results or reusing/releasing the related memory, and for keeping the memory valid during all asynchronous operations.
aclsparseSpMV
Product support
- Ascend 950PR&950DT products: Supported (arch35 / DAV_3510; see "Ascend 950PR&950DT product capabilities and invocation conventions" at the end of this document for the capability matrix)
- Atlas A3 products: Supported (arch22 / DAV_2201)
- Atlas A2 products: Supported (arch22 / DAV_2201)
Function prototype
aclsparseStatus_t aclsparseSpMV(aclsparseHandle_t handle, aclsparseOperation_t opA, const void *alpha, aclsparseConstSpMatDescr_t matA, aclsparseConstDnVecDescr_t vecX, const void *beta, aclsparseDnVecDescr_t vecY, aclDataType computeType, aclsparseSpMVAlg_t alg, void *externalBuffer)
Parameter description
| Parameter | Input/Output | Parameter Type | Description |
|---|---|---|---|
| handle | Input | aclsparseHandle_t | ops-sparse library context handle; aclsparseSetStream must be called first to bind the stream; Host memory |
| opA | Input | aclsparseOperation_t | Operation type of sparse matrix A: arch22 supports ACL_SPARSE_OP_NON_TRANSPOSE / ACL_SPARSE_OP_TRANSPOSE and does not support conjugate transpose; arch35 additionally supports ACL_SPARSE_OP_CONJUGATE_TRANSPOSE; Host memory |
| alpha | Input | const void* | Scalar alpha pointer; the type must match computeType (for complex64, pass the real/imaginary parts as interleaved float2). arch22 currently supports only the Host pointer mode; for arch35, the memory location is controlled by aclsparseSetPointerMode and supports Host/Device memory |
| matA | Input | aclsparseConstSpMatDescr_t | Descriptor of sparse matrix A; only CSR format is supported; arch22 uses I32 indices and base 0/1; Host memory |
| vecX | Input | aclsparseConstDnVecDescr_t | Descriptor of the input dense vector x; Host memory |
| beta | Input | const void* | Scalar beta pointer; the type must match computeType. The pointer mode is the same as alpha; when beta=0, the original value of y is not read |
| vecY | Input/Output | aclsparseDnVecDescr_t | Descriptor of the input/output dense vector y; updated in place; Host memory |
| computeType | Input | aclDataType | Computation precision type: arch22 supports ACL_INT32 / ACL_FLOAT / ACL_COMPLEX64; arch35 supports ACL_FLOAT / ACL_INT32 / ACL_COMPLEX64 |
| alg | Input | aclsparseSpMVAlg_t | Algorithm type, varying by product: arch22 (Atlas A2 products and Atlas A3 products) supports ACL_SPARSE_SPMV_ALG_DEFAULT / ACL_SPARSE_SPMV_CSR_ALG1 / ACL_SPARSE_SPMV_CSR_ALG2 (vector unit implementations) and ACL_SPARSE_SPMV_CSR_ALG_CUBE (cube segmented summation implementation); arch35 (Ascend 950PR&950DT products) supports ACL_SPARSE_SPMV_ALG_DEFAULT / ACL_SPARSE_SPMV_CSR_ALG1 / ACL_SPARSE_SPMV_CSR_ALG2 |
| externalBuffer | Input | void* | workspace; allocate the size according to the value returned by GetBufferSize; pass nullptr when 0 is returned (it must be allocated for arch22 transpose deterministic accumulation and the arch22 cube algorithm; arch35 always requires a non-empty, 64-byte aligned buffer; Device memory) |
Constraints (arch22: Atlas A2 products and Atlas A3 products)
- handle cannot be nullptr, and
aclsparseSetStreammust be called first to set the stream; computation executes asynchronously on the caller stream - matA, vecX, and vecY cannot be nullptr; alpha and beta cannot be nullptr
- matA supports only CSR format (
ACL_SPARSE_FORMAT_CSR); CSC/COO returnsACL_SPARSE_STATUS_NOT_SUPPORTED - The row offset and column index types of matA must both be
ACL_SPARSE_INDEX_32I;ACL_SPARSE_INDEX_64IreturnsACL_SPARSE_STATUS_NOT_SUPPORTED - The index base supports
ACL_SPARSE_INDEX_BASE_ZEROandACL_SPARSE_INDEX_BASE_ONE ACL_SPARSE_SPMV_CSR_ALG_CUBE(cube segmented summation) additional constraints: opA must beACL_SPARSE_OP_NON_TRANSPOSE, the index base must beACL_SPARSE_INDEX_BASE_ZERO, both computeType and the vecY value type must beACL_FLOAT, and the matA / vecX value types must beACL_FLOATorACL_FLOAT16(for fp16 input, cube accumulates in fp32 and outputs fp32); the longest row must not exceed the UB capacity upper bound. Because the reduction order differs, its results may have floating-point error differences from the default algorithm; degenerate inputs (such as empty matrices) automatically fall back to the vector implementation- Supports boundary inputs such as dynamic M/K/nnz, empty rows, long-tail rows (the non-zero element count of a single row is not limited by UB capacity and is processed with intra-row chunked loops), and nnz=0/1
- Duplicate coordinate and ordering constraints: duplicate column coordinates are allowed within the same row, and duplicates are accumulated according to mathematical semantics (consistent with cuSPARSE); column indices are not required to be ordered or unique
- Inputs A/X are read-only, and Y is updated in place; no CPU-side computation or needless Host synchronization occurs
- Dimension matching:
- Non-transpose mode: vecX size >= A.cols, and vecY size >= A.rows
- Transpose mode: vecX size >= A.rows, and vecY size >= A.cols
- The value type of vecX must be consistent with the value type of matA
- Descriptor element strides are fixed and processed as 1 (the strides set by
aclsparseCsrSetStrides/aclsparseDnVecSetStrideare not read) - Undeclared format/type combinations return
ACL_SPARSE_STATUS_NOT_SUPPORTED
Constraints (arch35: Ascend 950PR&950DT products)
- handle cannot be nullptr, and
aclsparseSetStreammust be called first to set the stream - matA, vecX, and vecY cannot be nullptr
- matA supports only CSR format (
ACL_SPARSE_FORMAT_CSR) - The Ascend 950PR&950DT products path supports positive element strides: CSR row offsets, column indices, values, and x/y each use the strides in the descriptors, and output gaps are not modified
- The row offset and column index types of matA must both be
ACL_SPARSE_INDEX_32I, and the two types must be identical
The following are Ascend 950PR&950DT products constraints; see the later sections for the Atlas A2 products and Atlas A3 products differences.
- Because the Kernel reads CSR indices as signed
int32_t,MandKdo not exceedINT32_MAX;nnzdoes not exceedINT32_MAX(base 0) orINT32_MAX - 1(base 1), avoiding row offset/column storage overflow - The index base of matA supports
ACL_SPARSE_INDEX_BASE_ZEROorACL_SPARSE_INDEX_BASE_ONE - opA supports
ACL_SPARSE_OP_NON_TRANSPOSE,ACL_SPARSE_OP_TRANSPOSE, andACL_SPARSE_OP_CONJUGATE_TRANSPOSE; complex values are conjugated entry by entry for conjugate transpose, and real values behave the same as ordinary transpose - alg supports
ACL_SPARSE_SPMV_ALG_DEFAULT,ACL_SPARSE_SPMV_CSR_ALG1, andACL_SPARSE_SPMV_CSR_ALG2 - computeType supports
ACL_INT32,ACL_FLOAT, orACL_COMPLEX64 - The value type of vecX must be consistent with the value type of matA
- Dimension matching:
- Non-transpose mode: the vecX size must equal A.cols, and the vecY size must equal A.rows
- Transpose mode: the vecX size must equal A.rows, and the vecY size must equal A.cols
- Supports M=0, N=0, and NNZ=0; when the output length is 0, it returns success, and when NNZ=0 the result is
beta * y - When M=0 or N=0, NNZ=0 must also be satisfied; otherwise, query, preprocessing, and execution all return
INVALID_VALUE. - Descriptors created by
aclsparseCreateCsrandaclsparseCreateDnVechave a default element stride of 1; throughaclsparseCsrSetStridesandaclsparseDnVecSetStride, positive-stride non-contiguous Tensors can be described natively - The strides of CSR rowOffsets, colInd, values, vecX, and vecY are all counted in elements and must be greater than 0; vecY is read and written in place according to its stride, and gap elements are not overwritten
- Non-contiguous strides currently take effect only on the Ascend 950PR&950DT products path; the Atlas A2 products and Atlas A3 products paths support only the default stride of 1
- The caller is responsible for ensuring that the CSR contents are valid: rowOffsets must start from base, end at NNZ+base, and be monotonically non-decreasing, and colInd must all lie within
[base, cols+base). SpMV and Preprocess do not synchronize to read back Device data and do not promise to return content validation errors - The INT8→INT32 path performs final INT32 saturation on the complete
alpha * dot(A, x) + beta * y, preserving positive-negative term cancellation; it uses pre-multiplication range checks and shifted saturation boundaries to avoid intermediate INT64 multiply-accumulate overflow. The contiguous, stride, and transpose paths have consistent semantics.
Supported Type Combinations
arch22 (Atlas A2 products and Atlas A3 products):
| matA/vecX Value Type | vecY Type | computeType | Description |
|---|---|---|---|
| ACL_INT8 | ACL_INT32 | ACL_INT32 | Element-wise exact match semantics |
| ACL_INT8 | ACL_FLOAT | ACL_FLOAT | |
| ACL_FLOAT16 | ACL_FLOAT | ACL_FLOAT | |
| ACL_BF16 | ACL_FLOAT | ACL_FLOAT | |
| ACL_FLOAT16 | ACL_FLOAT16 | ACL_FLOAT | FP32 computation, single rounding at the end |
| ACL_BF16 | ACL_BF16 | ACL_FLOAT | FP32 computation, single rounding at the end |
| ACL_FLOAT | ACL_FLOAT | ACL_FLOAT | |
| ACL_COMPLEX64 | ACL_COMPLEX64 | ACL_COMPLEX64 | Complex scalars alpha/beta are passed in as interleaved float2 |
| ACL_FLOAT | ACL_COMPLEX64 | ACL_COMPLEX64 | Real vectors/matrices are promoted to complex computation |
| ACL_INT32 | ACL_INT32 | ACL_INT32 | Existing in-repo combination, retained |
| ACL_INT32 | ACL_FLOAT | ACL_FLOAT | Existing in-repo combination, retained |
Value type combinations supported by arch35 (Ascend 950PR&950DT products):
- matA=ACL_FLOAT, vecX=ACL_FLOAT, vecY=ACL_FLOAT, computeType=ACL_FLOAT
- matA=ACL_FLOAT16, vecX=ACL_FLOAT16, vecY=ACL_FLOAT or ACL_FLOAT16, computeType=ACL_FLOAT
- matA=ACL_BF16, vecX=ACL_BF16, vecY=ACL_FLOAT or ACL_BF16, computeType=ACL_FLOAT
- matA=ACL_INT8, vecX=ACL_INT8, vecY=ACL_INT32, computeType=ACL_INT32
- matA=ACL_INT8, vecX=ACL_INT8, vecY=ACL_FLOAT, computeType=ACL_FLOAT
- matA=ACL_COMPLEX64, vecX=ACL_COMPLEX64, vecY=ACL_COMPLEX64, computeType=ACL_COMPLEX64
- matA=ACL_FLOAT, vecX=ACL_FLOAT, vecY=ACL_COMPLEX64, computeType=ACL_COMPLEX64
Returns
| Return Value | Description |
|---|---|
ACL_SPARSE_STATUS_SUCCESS |
Success |
ACL_SPARSE_STATUS_HANDLE_IS_NULLPTR |
handle is null or has no bound stream |
ACL_SPARSE_STATUS_INVALID_VALUE |
Descriptor/scalar/bufferSize pointers are null, vector length is insufficient, externalBuffer is empty when workspace is required, data pointers used in the current arch35 stage are unbound, and so on |
ACL_SPARSE_STATUS_NOT_SUPPORTED |
Format is not CSR, index type is not I32, invalid opA/alg/indexBase, undeclared dtype combinations |
ACL_SPARSE_STATUS_INSUFFICIENT_RESOURCES |
For arch35 transpose with NNZ>0, the workspace is empty or insufficient |
ACL_SPARSE_STATUS_EXECUTION_FAILED |
arch22 kernel launch or stream synchronization fails |
ACL_SPARSE_STATUS_INTERNAL_ERROR |
The arch35 common GetAivCoreCount returns 0; no fixed core count fallback is used |
Supported sparse formats
| Format | Supported | Description |
|---|---|---|
| CSR | ✅ | Sparse matrix A supports the CSR format |
| COO | ❌ | Not supported |
| CSC | ❌ | Not supported |
Invocation example
Three-stage invocation flow:
size_t bufferSize = 0;
aclsparseSpMVGetBufferSize(handle, op, alpha, matA, vecX, beta, vecY, computeType, alg, &bufferSize);
void *workspace = nullptr;
if (bufferSize > 0) {
aclrtMalloc(&workspace, bufferSize, ACL_MEM_MALLOC_NORMAL_ONLY);
}
aclsparseSpMVPreprocess(handle, op, alpha, matA, vecX, beta, vecY, computeType, alg, workspace);
aclsparseSpMV(handle, op, alpha, matA, vecX, beta, vecY, computeType, alg, workspace);
For the specific compilation, three-stage invocation, and self-test commands, refer to SPMV Test Description; for the general project build method, see Compilation and Running Sample.
For non-contiguous Tensors (arch35), set the element strides after creating ordinary descriptors; the SpMV three-stage interfaces remain unchanged:
aclsparseCsrSetStrides(matA, rowOffsetsStride, colIndStride, valuesStride);
aclsparseDnVecSetStride(vecX, xStride);
aclsparseDnVecSetStride(vecY, yStride);
When the stride setting interfaces are not called, compatible behavior is maintained and all strides are 1. After updating CSR pointers or strides, the transpose path must call
aclsparseSpMVPreprocess again.
Python/ATen Interface
ops-sparse also delivers the Python/torch layer adaptation (sparse/spmv/torch_extension/, based on the unified cann_ops_sparse torch_extension framework in the repository):
- Public entry
torch.mv(mat, vec), internally mapped to theSparseCsrPrivateUse1dispatch key ofaten::mv: it covers only a 2D CSR sparse matrix × 1D dense vector on NPU, executes on NPU, and does not perform CPU fallback; unsupported combinations (layout/dtype/shape/device mismatch) raise errors explicitly. - The ATen path calls the underlying interface with fixed
alpha=1andbeta=0; for other alpha/beta combinations, use the aclsparse C++ three-stage interfaces. - INT8 input produces INT32 output, and the other output dtypes match the input; int64 indices are automatically converted to int32 on NPU.
- The adaptation layer validates parameters, dtype, shape, layout, stride, and device, with exception and stream asynchronous semantics aligned with PyTorch.
The workspace is held by the caller, and aclsparseSpMV only queues asynchronous tasks on it without stream synchronization;
therefore, before reusing the same buffer, you need to ensure yourself that the previous SpMV has completed.
- Atlas A2 products and Atlas A3 products
ACL_SPARSE_SPMV_ALG_DEFAULT(vector version): all intermediate quantities reside in UB, it returns 0, andexternalBuffercan benullptr. - Atlas A2 products and Atlas A3 products
ACL_SPARSE_SPMV_CSR_ALG_CUBE: it returns the workspace size required for segmented summation (gather product area + intra-block speculative scan result area). The caller must request device memory of this size and pass it as theexternalBufferofaclsparseSpMV; when not provided, it falls back to the workspace on the handle (an error is reported when capacity is insufficient). An empty matrix (nnz == 0) falls back to the vector implementation and returns 0.
Ascend 950PR&950DT Product Capabilities and Invocation Conventions
The arch35 implementation is located in sparse/spmv/arch35/, with target architecture dav-3510. All declared combinations use 2D
CSR, I32 row pointer/column index, and index base 0/1, and support NON_TRANSPOSE, TRANSPOSE, and
CONJUGATE_TRANSPOSE:
| A values / x | y | computeType |
|---|---|---|
| INT8 | INT32 | INT32 |
| INT8 | FP32 | FP32 |
| FP16 | FP32 | FP32 |
| BF16 | FP32 | FP32 |
| FP16 | FP16 | FP32 (converted after FP32 accumulation) |
| BF16 | BF16 | FP32 (converted after FP32 accumulation) |
| FP32 | FP32 | FP32 |
| complex64 | complex64 | complex64 |
| FP32 | complex64 | complex64 (FP32 embedded as a real number) |
For non-transpose, x.size == A.cols and y.size == A.rows; for transpose/conjugate transpose, x.size == A.rows and
y.size == A.cols. It supports dynamic shapes, empty rows, nnz=0/1, uneven long tails, and unsorted/duplicate
columns per row; contributions of duplicate coordinates are all counted, and ALG2 accumulates in the original entry order. The caller should ensure that rowPtr is monotonic and that the first and last values match base/nnz,
and that each column lies within [0, A.cols) after base subtraction. The Host validates the visible descriptor metadata; status feedback for device CSR
structure errors still needs to be completed in an Ascend 950PR&950DT products environment and pass dedicated testing, and it must not be advertised as a
supported asynchronous parameter error until that decision gate is closed.
The algorithms support ACL_SPARSE_SPMV_ALG_DEFAULT (mapped to CSR ALG1), ACL_SPARSE_SPMV_CSR_ALG1,
and ACL_SPARSE_SPMV_CSR_ALG2. The ALG2 transpose path uses one GM accumulator and completes deterministic reduction with a single traversal in fixed
row/entry order, O(nnz + cols). For matrices with
0 < rows <= kSpmvTransposeGatherRowsMax, ALG1/DEFAULT first checks on the device side whether the columns of each row are ordered; when ordered, each output column is located by an exclusive warp
through binary search and reduced, and when unordered, it falls back to the atomic-free path in original entry order. Larger matrices use row-by-row traversal and
workspace atomic accumulation. The floating-point/complex results of ALG1/DEFAULT are not promised to be bit-wise deterministic.
The path thresholds are defined uniformly in spmv_tiling_data.h, shared by the Host launch logic and
Kernel dispatch: kSpmvTransposeGatherRowsMax is currently 4095 (upper bound inclusive); with zero rows or beyond
this upper bound, the ALG1/DEFAULT transpose uses the atomic path; the non-transpose path with FP32 input/output/computation uses
the small-matrix implementation when rows <= kSpmvFloatSmallRowsMax, which is currently 64 (upper bound inclusive).
alpha/beta can use a Host or Device pointer according to aclsparseSetPointerMode; in Device mode,
the Host does not dereference the scalars. When beta == 0, the kernel does not read the old y; when beta != 0, it writes back according to
alpha * op(A) * x + beta * y. The workspace must be caller-allocated Device memory satisfying
64-byte alignment; you must not release or modify the workspace, descriptor, CSR, scalar, x, or y before asynchronous execution ends.
The interface does not carry the actual workspace size, and the caller must use the result of GetBufferSize; undersized allocation is not guaranteed to be
reliably detected by the interface.
COO/CSC/SELL, I64, batch/broadcast, FP64/complex128, and undeclared
dtype/computeType/algorithm are not supported; these combinations return
ACL_SPARSE_STATUS_NOT_SUPPORTED (parameter structure errors return ACL_SPARSE_STATUS_INVALID_VALUE).
The SpMV preprocessing record uses an independent activeSpmvBuffer. Reusing the same descriptor/workspace
between SpMV and SpMM/SDDMM invalidates the old layout; after CSR stride or vector stride changes, the old plan is not reused.
The row offsets generated by preprocessing are always contiguous, and other inputs and outputs are still accessed according to their own physical strides. The workspace header is
192 bytes, and the caller should call GetBufferSize again to query and must not hard-code the old size.
Python/ATen Adaptation Requirements
The Python entry is torch.mv(mat, vec), internally mapped to the NPU Dispatcher of aten::mv, accepting only a 2D
CSR sparse matrix and a 1D dense vector. The bridging layer must complete device/layout/shape/stride/dtype/
index/alias validation, SpMat/DnVec descriptor and NPU output Tensor construction, and call the underlying standard SpMV with fixed alpha=1 and
beta=0; CPU fallback is not allowed. The target versions are PyTorch 2.7+ and
torch_npu 26.0+, and the asynchronous stream, allocator, exception, and output dtype semantics must be consistent with the target versions.
The bridging target is the optionally built ops_sparse_torch (see BUILD_TORCH_ADAPTER in the root directory), which registers:
torch.ops.ops_sparse.spmv(mat, vec), plus theSparseCsrPrivateUse1path ofaten::mv, for real CSRtorch.mvcalls; it does not override the genericPrivateUse1densemvregistration, avoiding interference with the existing dense implementation of torch_npu;torch.ops.ops_sparse_test.spmv_npu(row_ptr, col_ind, values, x, y, alpha, beta, trans, base), used by the task-package ATK, performance, and memory scripts. This entry updatesyin place and returns the same Tensor.
Build example (the CANN, PyTorch, and torch_npu environments must be loaded first):
cmake -S . -B build -DSOC_VERSION=ascend950 -DBUILD_TORCH_ADAPTER=ON
cmake --build build --target ops_sparse ops_sparse_torch -j
OPS_SPARSE_TORCH_LIBRARY=build/torch_npu/libops_sparse_torch.so \
python3 torch_npu/test_spmv_npu.py
The bridging uses the current NPU stream and calls NPUCachingAllocator::recordStream to ensure that the temporary workspace
is not reused by the caching allocator before the asynchronous Kernel completes; when torch_npu is not installed, the device is not NPU, or the dispatcher
does not match, it reports an error directly and provides no CPU reference fallback.
Ascend 950PR&950DT Product Testing and Acceptance
The arch35 C++ GTest/CSV tests are placed in test/spmv/arch35/ and integrated through
ops_sparse_add_gtest_tests(spmv ${OPS_SPARSE} EIGEN). Existing tests cover scenarios such as three-stage invocation, workspace
reuse, stride, base, transpose, deferred binding, INT8→INT32 positive/negative overflow, and FP16 rounding.
The existing in-repo GTests cannot be regarded as complete coverage of the nine dtype groups: BF16, input read-only/alias assertions, and
ALG2 bit-wise determinism still lack corresponding regression cases. The operator capability matrix is not equivalent to the test coverage matrix. The dedicated
SpMV950/test_cases/ must also execute 200 ATK accuracy cases, fixed P-01/P-02/P-03 GPU/NPU performance
cases, and memory comparison; the report performs at least 10 warmup runs and at least 30 samples, and records median/P90, workspace,
peak memory, and NPU Dispatch/Profiler evidence. Without a CANN/NPU environment, only static checks are possible, and acceptance cannot be claimed.
Atlas A2 products and Atlas A3 products: CSR and vector element strides
arch22 supports the rowOffsets/colInd/values strides of aclsparseCsrSetStrides and the
X/Y strides of aclsparseDnVecSetStride, with units of elements of the corresponding types; strides must be positive.
This path retains all of the preceding type combinations, base 0/1, N/T, and DEFAULT/CSR_ALG1/CSR_ALG2.
When all five strides are 1, the original computation kernel, original workspace size, and original launch sequence are used.
Non-contiguous arrays are packed into a contiguous workspace with native bytes on each aclsparseSpMV call,
reusing the same numeric kernel; only when Y is non-contiguous is one exact element scatter added.
Therefore, this path has extra data-movement kernel overhead, and performance collection should count the complete kernel sequence of the public API.
The data movement performs no low-precision conversion; FP16/BF16 accumulation, beta compensation, and the final RNE are still completed by the original numeric kernel.
The gap and the guard bytes before/after Y are not written; when beta=0, the original Y is neither packed nor read.
The scatter divides inter-core ownership by the physical 64-byte cache lines of the real Y address and does not traverse the physical holes in the strides;
Y with unnatural element alignment uses a single-core fallback. Extra-large byte gaps that the DMA stride field cannot express use element-by-element movement,
preserving 64-bit address offsets and avoiding truncation.
The ACL_SPARSE_SPMV_CSR_ALG_CUBE of non-contiguous layouts falls back to the vector implementation after retaining the original N, base 0, FP32 compute/output,
and FP32/FP16 input constraints, consistent with the fallback semantics for unusable CUBE layouts such as empty input.
This fallback does not probe, cache, or reuse CUBE longest-row metadata; the original path and restrictions of contiguous CUBE remain unchanged.
The non-contiguous workspace simultaneously holds the required contiguous arrays, the original transpose double-single area, and an alignment margin of up to 63 bytes for the
start address, with all areas aligned to 64 bytes. Allocation must follow the value returned by this GetBufferSize call;
this path allows externalBuffer to be at any byte-offset address, and the caller does not need to align it first.
External pointer parameters have no capacity field, and the actual allocation size is guaranteed by the caller; when using the handle workspace, capacity is checked,
and ACL_SPARSE_STATUS_INSUFFICIENT_RESOURCES is returned when insufficient. Span, pointer arithmetic, and workspace layout overflow return
ACL_SPARSE_STATUS_INVALID_VALUE. Only external/handle workspace is used, and no extra temporary device allocations are created.
The Preprocess of the arch22 ordinary vector path and the non-contiguous CUBE fallback validates only metadata and does not cache device contents.
After updating the contents of rowOffsets, colInd, values, X, or Y at the same addresses, the next execution repacks them,
and re-preprocessing is not needed for content changes. After dimensions, types, or strides change, the workspace size should be queried again.
Each data-movement and computation kernel uses the current handle stream; the caller should keep the inputs and workspace valid before asynchronous tasks complete,
and is responsible for cross-stream dependencies. The Host scalar vector path does not perform extra synchronization or read back device data; Device scalar mode follows
the existing scalar read/synchronization conventions. For contiguous CUBE, changing the CSR row structure in place still requires re-preprocessing according to the existing conventions.
Verification entry: SPARSE_TEST_STRIDES_ONLY=1 ./spmv_test runs the new stride regression; when the variable is not set, the
original full SpMV tests continue to run. The stride regression covers 11 type combinations, N/T, base 0/1, each of the five strides individually and mixed,
ALG1/ALG2, NaN Y with beta=0, guard/gap, unnatural Y alignment, workspace byte offsets 1/63,
in-place updates of all five arrays, CUBE fallback, wide transpose, and an INT64_MAX stride of length 1.
Among them, the Host layout check covers span/address/alignment addition overflow, and the device regression also checks the error code for insufficient handle workspace capacity.
When the output is non-empty, both the contiguous and non-contiguous paths of arch22 require that rows/cols be representable by uint32_t,
and that nnz + indexBase <= INT32_MAX, so that the numeric tiling and I32 CSR row offsets can represent the input.
When the representable range is exceeded, query/preprocess/execute consistently return ACL_SPARSE_STATUS_INVALID_VALUE.
When the output is empty, query returns 0 and execution is a direct no-op, neither building a packing plan
nor applying the preceding new range restrictions; with nnz=0 but non-empty Y, beta * Y is still executed.