FilesLast commitLast update
README

aclsparseSpSM

Product support

Product Supported
Ascend 950PR&950DT products √
Atlas A3 products √
Atlas A2 products √
Atlas 200I/500 A2 inference products ×
Atlas inference products ×
Atlas training products ×

Function Description

  • Operator function: aclsparseSpSM (Sparse Triangular Solve with Multiple Right-Hand Sides) solves the sparse triangular linear system op(A)·C = α·op(B). Here A is a sparse triangular square matrix (m×m) in CSR, CSC, or COO format, B is a dense right-hand-side matrix, C is a dense solution matrix that can share the Device address with B, and α is a scalar coefficient. This operator targets cusparseSpSM in the cuSPARSE Generic API, adopts the BufferSize, Analysis, and Solve three-stage model, and supports updating matrix values after Analysis.
  • Target platforms: Ascend 950PR&950DT products (arch35 / DAV_3510), and the training and inference series of Atlas A2 products and Atlas A3 products (arch22 / DAV_2201).
  • Programming model: Ascend C Vector API. Format normalization, value updates, and triangular solving execute on NPU; see the corresponding interface descriptions for the synchronization and Host read-back scope of Analysis/Update.

Mathematical Principle

Problem Definition

It solves the sparse triangular linear system:

op(A) · C = α · op(B)
Symbol Meaning Dimension/Type
A CSR, CSC, or COO sparse triangular square matrix m×m, FP32 or complex64
B Dense right-hand-side matrix op(B) is m×nrhs, FP32 or complex64
C Dense solution matrix (can share the Device address with B) m×nrhs, FP32 or complex64
α Scalar coefficient Consistent with computeType, Host or Device pointer mode
op(A) / op(B) Original matrix, transpose, or conjugate transpose N / T / H
fillMode The triangular part of A that participates in the computation LOWER / UPPER
diagType Diagonal type UNIT (uses implicit 1, ignores stored values) / NON_UNIT (actual values)

The transposes of A and B are handled independently. For real input, H is equivalent to T; for complex64 input, H performs both transpose and conjugation. B/C can each use the ROW or COL layout.

General Row-Update Formula

For each row i, traverse along the solving direction; the solved rows form the dependency set deps(i):

             α·op(B)[i, :] − Σ_{j∈deps(i)} op(A)[i,j] · C[j, :]
C[i, :] = ─────────────────────────────────────────────────────  (NON_UNIT)
                                  op(A)[i,i]

C[i, :] = α·op(B)[i, :] − Σ_{j∈deps(i)} op(A)[i,j] · C[j, :]    (UNIT)

Key points:

  • Division scope: /op(A)[i,i] applies to the entire numerator (α·op(B)[i,:] − Σ ...), not only the summation terms.
  • UNIT is a special case: when A[i,i]≡1.0, the division is omitted; the design takes the NON_UNIT general formula as the basis and UNIT as the fast path.
  • Duplicate coordinates: stably sorted by (row, col, originalSlot) and merged in a fixed order, producing deterministic results for the same device and input.

Four (opA, fillMode) Dependency Modes

deps(i) is determined by (opA, fillMode):

opA fillMode Substitution Mode Traversal Direction deps(i)
N LOWER forward i=0→m−1 {j<i | A[i,j]≠0}
N UPPER backward i=m−1→0 {j>i | A[i,j]≠0}
T/H LOWER backward i=m−1→0 {j>i | op(A)[i,j]≠0}
T/H UPPER forward i=0→m−1 {j<i | op(A)[i,j]≠0}

On NPU, Analysis normalizes CSR, CSC, or COO into an ordered base-0 representation of op(A) and saves the plan required for value updates and subsequent solving. See aclsparseSpSMAnalysis for the read-back scope on different platforms.

Division and Boundary Handling

  • NON_UNIT division: missing diagonals or diagonals summing to zero return errors at Analysis or Update; Atlas A2 products and Atlas A3 products return ACL_SPARSE_STATUS_INVALID_VALUE, and Ascend 950PR&950DT products return ACL_SPARSE_STATUS_NOT_SUPPORTED.
  • UNIT diag: the division is omitted (A[i,i]≡1.0).
  • Singular matrix detection: the Analysis stage detects diagonal zeros (explicit zeros or missing diagonal entries), and returns an error code when a zero diagonal element is detected (aligned with the cuSPARSE zeroPivot mechanism).
  • Numerical stability: both FP32 and complex64 save the high and low parts of intermediate values, using FMA residuals, compensated summation, and division correction to reduce error propagation. The output type remains FP32/complex64; when the true solution exceeds the representable range, infinity may be output.
  • Zero-dimension input: Atlas A2 products and Atlas A3 products accept m=0 or nrhs=0 inputs that satisfy the other interface constraints, and Solve performs no numeric computation; Ascend 950PR&950DT products return ACL_SPARSE_STATUS_INVALID_VALUE.
  • Asynchronous execution: Solve is submitted asynchronously, and the caller must synchronize the handle stream before reading outputs or releasing inputs/workspace.
  • In-place correctness: when B/C share the same Device address, B is saved first, and then solving and layout conversion execute.

Interface description

aclsparseSpSM uses the SpSM descriptor to save plan state across the BufferSize, Analysis, Solve, and UpdateMatrix stages.

aclsparseSpSMCreateDescr

Function prototype

aclsparseStatus_t aclsparseSpSMCreateDescr(aclsparseSpSMDescr_t *spsmDescr);

Parameter description

Parameter Input/Output Parameter Type Description
spsmDescr Output aclsparseSpSMDescr_t* Host pointer that receives the newly created SpSM descriptor; do not use it to overwrite a descriptor that has not been destroyed

Constraints

  • spsmDescr cannot be nullptr; otherwise, ACL_SPARSE_STATUS_INVALID_VALUE is returned.
  • The descriptor is shared across the BufferSize, Analysis, Solve, and UpdateMatrix stages, and must be created before calling these interfaces.

aclsparseSpSMDestroyDescr

Function prototype

aclsparseStatus_t aclsparseSpSMDestroyDescr(aclsparseSpSMDescr_t spsmDescr);

Parameter description

Parameter Input/Output Parameter Type Description
spsmDescr Input aclsparseSpSMDescr_t SpSM descriptor handle to destroy; Host memory

Constraints

  • When spsmDescr is nullptr, Atlas A2 products and Atlas A3 products return ACL_SPARSE_STATUS_INVALID_VALUE, and Ascend 950PR&950DT products return ACL_SPARSE_STATUS_SUCCESS.
  • Destruction does not implicitly wait for asynchronous Solve; the caller must first ensure that the related stream work completes.
  • The handle should not be used after successful destruction; on all supported platforms, after successful destruction, calling DestroyDescr again directly without re-creating the descriptor returns ACL_SPARSE_STATUS_INVALID_VALUE.

aclsparseSpSMBufferSize

Queries the workspace size (in bytes) required by SpSM.

Function prototype

aclsparseStatus_t aclsparseSpSMBufferSize(
    aclsparseHandle_t handle, aclsparseOperation_t opA, aclsparseOperation_t opB,
    const void *alpha, aclsparseConstSpMatDescr_t matA,
    aclsparseConstDnMatDescr_t matB, aclsparseDnMatDescr_t matC,
    aclDataType computeType, aclsparseSpSMAlg_t alg,
    aclsparseSpSMDescr_t spsmDescr, size_t *bufferSize);

Parameter description

Parameter Input/Output Parameter Type Description
handle Input aclsparseHandle_t ops-sparse context, carrying device, stream, and pointer mode
opA Input aclsparseOperation_t Operation type of sparse matrix A; supports N/T/H
opB Input aclsparseOperation_t Operation type of dense matrix B; supports N/T/H
alpha Input const void* Scalar consistent with computeType; supports Host/Device pointer mode
matA Input aclsparseConstSpMatDescr_t CSR/CSC/COO sparse triangular square matrix descriptor
matB Input aclsparseConstDnMatDescr_t Dense right-hand-side descriptor; the shape after op matches A
matC Output aclsparseDnMatDescr_t Dense solution matrix descriptor; sharing the Device address with B is allowed
computeType Input aclDataType ACL_FLOAT or ACL_COMPLEX64
alg Input aclsparseSpSMAlg_t Algorithm type; only ACL_SPARSE_SPSM_ALG_DEFAULT is supported; Host memory
spsmDescr Input/Output aclsparseSpSMDescr_t Valid SpSM descriptor; Ascend 950PR&950DT products store the parameter signature and workspace plan here, and Atlas A2 products and Atlas A3 products bind the plan at Analysis
bufferSize Output size_t* Outputs the required workspace size (in bytes); Host memory

The BufferSize of Atlas A2 products and Atlas A3 products depends on the current device core count, and must be queried on the device used by the subsequent Analysis; on failure, *bufferSize is not modified. The values of B/C can be bound later.

aclsparseSpSMAnalysis

SpSM analysis stage: completes format normalization, index validation, diagonal checking, dependency analysis, and Update slot mapping on NPU, and binds the workspace used by subsequent Solve.

Function prototype

aclsparseStatus_t aclsparseSpSMAnalysis(
    aclsparseHandle_t handle, aclsparseOperation_t opA, aclsparseOperation_t opB,
    const void *alpha, aclsparseConstSpMatDescr_t matA,
    aclsparseConstDnMatDescr_t matB, aclsparseDnMatDescr_t matC,
    aclDataType computeType, aclsparseSpSMAlg_t alg,
    aclsparseSpSMDescr_t spsmDescr, void *buffer);

Parameter description

Parameter Input/Output Parameter Type Description
handle Input aclsparseHandle_t Carries the current device, stream, and pointer mode; for Ascend 950PR&950DT products, it must be the same as the BufferSize stage
opA / opB Input aclsparseOperation_t Supports N/T/H; for Ascend 950PR&950DT products, it must be consistent with the BufferSize stage, and Atlas A2 products and Atlas A3 products bind it at Analysis
alpha Input const void* The address location must conform to the pointer mode; for Ascend 950PR&950DT products, the address and pointer mode must be consistent with the BufferSize stage; Atlas A2 products and Atlas A3 products do not read its value
matA Input aclsparseConstSpMatDescr_t Valid sparse matrix; for Ascend 950PR&950DT products, it must be consistent with the BufferSize stage; Atlas A2 products and Atlas A3 products bind the format, structure, array addresses, and attributes at this stage
matB / matC Input/Output Dense matrix descriptors The shape, layout, and ld must satisfy the formula; the descriptors of Ascend 950PR&950DT products must be consistent with the BufferSize stage; Analysis does not read the B/C values
computeType Input aclDataType ACL_FLOAT or ACL_COMPLEX64, consistent with the matrices
alg Input aclsparseSpSMAlg_t Algorithm type; only ACL_SPARSE_SPSM_ALG_DEFAULT is supported; Host memory
spsmDescr Input/Output aclsparseSpSMDescr_t Stores the analyzed state and the NPU plan
buffer Input void* Device workspace aligned to 64 bytes and no smaller than the bytes returned by BufferSize; Atlas A2 products and Atlas A3 products require explicit passing, and Ascend 950PR&950DT products use the current handle workspace when it is empty

Analysis synchronizes the handle stream. Ascend 950PR&950DT products read back a fixed 64-byte verification digest; Atlas A2 products and Atlas A3 products read back per-core verification status, normalized row offsets, and a small amount of scheduling metadata, and also read back the corresponding column indices when checking pure-diagonal structures; numeric solving still executes on NPU.

The values of B/C can be bound later through the common setters after descriptor creation, but a valid Device address must be restored before the first non-zero-dimension Solve. Atlas A2 products and Atlas A3 products bind non-empty B/C addresses at Analysis; addresses that were empty at that time are bound by the first successful Solve. For Atlas A2 products and Atlas A3 products, Host parameter validation failure does not submit work and retains the old plan; Device data validation or read-back failure invalidates the plan, and Analysis must be performed again after the data is corrected.

aclsparseSpSM

SpSM solving stage: asynchronously executes op(A)·C = α·op(B), reusing the execution plan generated by Analysis.

Function prototype

aclsparseStatus_t aclsparseSpSM(
    aclsparseHandle_t handle, aclsparseOperation_t opA, aclsparseOperation_t opB,
    const void *alpha, aclsparseConstSpMatDescr_t matA,
    aclsparseConstDnMatDescr_t matB, aclsparseDnMatDescr_t matC,
    aclDataType computeType, aclsparseSpSMAlg_t alg,
    aclsparseSpSMDescr_t spsmDescr);

Parameter description

Parameter Input/Output Parameter Type Description
handle Input aclsparseHandle_t Must be consistent with the handle, device, and stream bound to the analyzed plan
opA / opB Input aclsparseOperation_t Must be consistent with the analyzed plan; supports N/T/H
alpha Input const void* The pointer mode must be consistent with the analyzed plan; the HOST value is copied at this call, and the DEVICE value is read when the kernel executes. Ascend 950PR&950DT products additionally require the address to be consistent with the plan; Atlas A2 products and Atlas A3 products allow replacing the alpha address that satisfies the location and lifecycle constraints
matA Input aclsparseConstSpMatDescr_t The sparse structure and descriptor identity must be consistent with the Analysis stage
matB Input aclsparseConstDnMatDescr_t Dense RHS; Device values are valid until the asynchronous work completes
matC Output aclsparseDnMatDescr_t Dense result; sharing the Device address with B is allowed
computeType Input aclDataType ACL_FLOAT or ACL_COMPLEX64
alg Input aclsparseSpSMAlg_t Algorithm type; only ACL_SPARSE_SPSM_ALG_DEFAULT is supported; Host memory
spsmDescr Input aclsparseSpSMDescr_t SpSM descriptor; the Analysis stage must be completed; Host memory

aclsparseSpSMUpdateMatrix

It updates the values of A after Analysis without changing the sparse pattern; after success, Solve can continue to be called.

Function prototype

aclsparseStatus_t aclsparseSpSMUpdateMatrix(
    aclsparseHandle_t handle, aclsparseSpSMDescr_t spsmDescr,
    const void *newValues, aclsparseSpSMUpdate_t updatePart);

Parameter description

Parameter Input/Output Parameter Type Description
handle Input aclsparseHandle_t Must be consistent with the handle, device, and stream bound to the analyzed plan
spsmDescr Input/Output aclsparseSpSMDescr_t Analysis must have completed successfully
newValues Input const void* Device array consistent with the Analysis computeType; GENERAL is nnz values in the original storage order. DIAGONAL: Atlas A2 products and Atlas A3 products likewise require the complete nnz array; Ascend 950PR&950DT products require m values ordered by the original A row numbers
updatePart Input aclsparseSpSMUpdate_t ACL_SPARSE_SPSM_UPDATE_GENERAL or ACL_SPARSE_SPSM_UPDATE_DIAGONAL

Constraints

  • Update does not change the sparse structure or the value array of matA; the indices of A must remain consistent with Analysis. GENERAL refreshes all values in the original storage order, and a subsequent GENERAL overwrites the preceding DIAGONAL update. When opA=H, the values of A itself are still passed.
  • The DIAGONAL of Atlas A2 products and Atlas A3 products uses only the row == col entries in the complete newValues array, and the other entries retain the current plan values. The input must be 4-byte aligned memory on the current device and must not overlap the workspace.
  • Every Update of Atlas A2 products and Atlas A3 products synchronizes the stream and reads back the Device verification status. Value validation failure returns ACL_SPARSE_STATUS_INVALID_VALUE and invalidates the plan; subsequent Solve returns ACL_SPARSE_STATUS_NOT_INITIALIZED, and Analysis must be performed again. Host parameter validation failure retains the old plan and does not submit work.
  • The NON_UNIT Update of Ascend 950PR&950DT products first validates the candidate diagonal values and synchronously reads back the digest, retaining the old plan when validation fails. UNIT ignores diagonal values, and DIAGONAL is a successful no-op.
  • newValues and the bound A indices and workspace must remain valid until the related stream work completes.

Matrix Attribute Interfaces

SpSM sets the fillMode and diagType of the triangular matrix through the sparse matrix descriptor attribute interface aclsparseSpMatSetAttribute, which must be set before calling BufferSize/Analysis.

aclsparseStatus_t aclsparseSpMatSetAttribute(aclsparseSpMatDescr_t spMatDescr,
                                             aclsparseSpMatAttribute_t attribute,
                                             const void *data, size_t dataSize);
aclsparseStatus_t aclsparseSpMatGetAttribute(aclsparseConstSpMatDescr_t spMatDescr,
                                             aclsparseSpMatAttribute_t attribute,
                                             void *data, size_t dataSize);
  • attribute=ACL_SPARSE_SPMAT_FILL_MODE: data points to aclsparseFillMode_t, dataSize must be sizeof(aclsparseFillMode_t), and the value is ACL_SPARSE_FILL_MODE_LOWER (lower triangular) or ACL_SPARSE_FILL_MODE_UPPER (upper triangular).
  • attribute=ACL_SPARSE_SPMAT_DIAG_TYPE: data points to aclsparseDiagType_t, dataSize must be sizeof(aclsparseDiagType_t), and the value is ACL_SPARSE_DIAG_TYPE_UNIT (uses implicit diagonal 1 and ignores stored values) or ACL_SPARSE_DIAG_TYPE_NON_UNIT (actual diagonal values must be provided by the sparse matrix data).

Return Codes

Return Code Description
ACL_SPARSE_STATUS_SUCCESS Operation succeeded; Solve only indicates that the work has been submitted
ACL_SPARSE_STATUS_INVALID_VALUE Null descriptor/alpha, invalid enumeration or index, dimension/ld/stage mismatch, wrong device, invalid address, or workspace overlap; after successful destruction, calling DestroyDescr again directly without re-creating the descriptor returns this code on all supported platforms; for Ascend 950PR&950DT products, calling Solve/Update after Analysis is incomplete or the plan is invalidated also returns this code
ACL_SPARSE_STATUS_NOT_SUPPORTED Unsupported computation type or index width; Ascend 950PR&950DT products also use it for unsupported algorithms, sizes, and NON_UNIT missing diagonals/diagonals summing to zero
ACL_SPARSE_STATUS_MATRIX_TYPE_NOT_SUPPORTED matA is not CSR, CSC, or COO
ACL_SPARSE_STATUS_INSUFFICIENT_RESOURCES For Ascend 950PR&950DT products, workspace computation overflow or insufficient handle workspace capacity; for Atlas A2 products and Atlas A3 products, invalid workspace layout or parameters return INVALID_VALUE
ACL_SPARSE_STATUS_HANDLE_IS_NULLPTR handle is nullptr
ACL_SPARSE_STATUS_EXECUTION_FAILED For Ascend 950PR&950DT products, stream synchronization or digest read-back fails
ACL_SPARSE_STATUS_INTERNAL_ERROR For Atlas A2 products and Atlas A3 products, Analysis/Update status read-back, structure/scheduling processing, or HOST alpha copy fails
ACL_SPARSE_STATUS_NOT_INITIALIZED The current device or handle context is unavailable; Atlas A2 products and Atlas A3 products also use it for calling Solve/Update after Analysis is incomplete or the plan is marked as not analyzed (analyzed == false) (for Ascend 950PR&950DT products, stage mismatch returns ACL_SPARSE_STATUS_INVALID_VALUE)
ACL_SPARSE_STATUS_ALLOC_FAILED Descriptor memory allocation failed

Failure Classification (Ascend 950PR&950DT products)

Category Typical Scenario Return Code
Invalid parameter Zero-dimension input (m = 0), leading dimension too small, invalid enumeration or index ACL_SPARSE_STATUS_INVALID_VALUE
Stage mismatch Calling Solve/Update after Analysis is incomplete or the plan is invalidated ACL_SPARSE_STATUS_INVALID_VALUE
Invalid layout Dense matrix order/ld does not satisfy constraints, or the byte span exceeds the INT64_MAX representable range (DenseValid returns false) ACL_SPARSE_STATUS_INVALID_VALUE
Size limit exceeded With a valid common matrix descriptor and other parameters valid, m equals INT32_MAX or nnz + base exceeds INT32_MAX ACL_SPARSE_STATUS_NOT_SUPPORTED
Algorithm or diagonal not satisfied Unsupported algorithm, or NON_UNIT diagonal missing or summing to zero ACL_SPARSE_STATUS_NOT_SUPPORTED

The common aclsparseCreateDnMat rejects inputs with rows or cols greater than INT32_MAX at creation time and returns ACL_SPARSE_STATUS_INVALID_VALUE; therefore, m > INT32_MAX or nrhs > INT32_MAX cannot create the valid B/C descriptors required by SpSM through the common interfaces, and does not belong to the runtime size limit exceeded in the preceding table.

On Atlas A2 products and Atlas A3 products, both invalid layout and size limit exceeded return ACL_SPARSE_STATUS_INVALID_VALUE; calling Solve/Update after Analysis is incomplete or the plan is marked as not analyzed (analyzed == false) returns ACL_SPARSE_STATUS_NOT_INITIALIZED. After successful destruction, calling DestroyDescr again directly without re-creating the descriptor returns ACL_SPARSE_STATUS_INVALID_VALUE on both platform generations.

Supported Specifications

Specification Item Supported Value Description
Data type (computeType) ACL_FLOAT, ACL_COMPLEX64 The value types of matA/matB/matC are consistent with computeType
Sparse format CSR, CSC, COO Supports unsorted indices and duplicate coordinates
opA / opB N, T, H Real H is equivalent to T, and complex H performs conjugate transpose
fillMode ACL_SPARSE_FILL_MODE_LOWER, ACL_SPARSE_FILL_MODE_UPPER Both are supported
diagType ACL_SPARSE_DIAG_TYPE_UNIT, ACL_SPARSE_DIAG_TYPE_NON_UNIT UNIT uses implicit 1 and ignores stored diagonal entries; NON_UNIT sums duplicate diagonal entries, and the sum must be non-zero
order (B/C layout) ACL_SPARSE_ORDER_ROW, ACL_SPARSE_ORDER_COL B/C can be combined independently
pointer mode HOST, DEVICE The alpha address type must match the handle pointer mode
indexBase ACL_SPARSE_INDEX_BASE_ZERO, ACL_SPARSE_INDEX_BASE_ONE Both are supported; ONE is normalized internally to ZERO
Index type ACL_SPARSE_INDEX_32I The row offset and column index types must both be 32I; 64I is not supported
in-place Supported matB.values and matC.values can point to the same Device address, including different layouts
Update GENERAL, DIAGONAL Keeps the pattern after Analysis unchanged
alg ACL_SPARSE_SPSM_ALG_DEFAULT Only the default algorithm
Matrix size Atlas A2 products and Atlas A3 products: 0 ≤ m, nrhs ≤ INT32_MAX; Ascend 950PR&950DT products: 0 < m < INT32_MAX, 0 < nrhs ≤ INT32_MAX nnz + base ≤ INT32_MAX; when m=0, nnz must be 0; the actual size is also constrained by address strides, byte-count overflow checks, and available workspace capacity

Constraints

  • Descriptor and types: A must be a square matrix, and A/B/C/computeType use consistent FP32 or complex64; ptr/idx are I32, and base is ZERO or ONE.
  • Operations and layout: opA/opB support N/T/H, and B/C can each use ROW/COL; the shapes of op(A), op(B), and C must satisfy the formula.
  • Zero-dimension input: Atlas A2 products and Atlas A3 products accept m (matA.rows) or nrhs (matC.cols) of 0, but valid descriptor, alpha, workspace, and stage validation must still be completed; when m=0, nnz must be 0, and Solve does not submit numeric computation. Ascend 950PR&950DT products reject zero-dimension inputs.
  • Leading dimension constraints: the leading dimensions (ldb/ldc) of matB/matC must satisfy the layout constraints — for row-major (ACL_SPARSE_ORDER_ROW), ld >= cols; for column-major (ACL_SPARSE_ORDER_COL), ld >= rows; otherwise, ACL_SPARSE_STATUS_INVALID_VALUE is returned.
  • Singular matrix detection: when diagType=NON_UNIT, missing diagonals or diagonals summing to zero are checked; Atlas A2 products and Atlas A3 products return ACL_SPARSE_STATUS_INVALID_VALUE, and Ascend 950PR&950DT products return ACL_SPARSE_STATUS_NOT_SUPPORTED. UNIT uses implicit diagonal 1.
  • Matrix size and layout limits: see Supported Specifications. Invalid layout (ld does not satisfy constraints or the byte span exceeds the INT64_MAX representable range) returns ACL_SPARSE_STATUS_INVALID_VALUE on all platforms. The common aclsparseCreateDnMat returns ACL_SPARSE_STATUS_INVALID_VALUE at creation time for inputs with rows or cols greater than INT32_MAX, so the valid B/C descriptors required by m > INT32_MAX or nrhs > INT32_MAX cannot be created. With a valid common matrix descriptor and other parameters valid, Ascend 950PR&950DT products return ACL_SPARSE_STATUS_NOT_SUPPORTED for m == INT32_MAX or nnz + base > INT32_MAX; Atlas A2 products and Atlas A3 products return ACL_SPARSE_STATUS_INVALID_VALUE for nnz + base > INT32_MAX.
  • Stage consistency: the same plan binds handle, device, stream, pointer mode, the identities of the three matrix descriptors, the array addresses of A, and structure attributes; Ascend 950PR&950DT products additionally bind the alpha address. After modifying bound items, the workspace must be queried and Analysis performed again; the BufferSize of Atlas A2 products and Atlas A3 products only queries the size, and Analysis binds the plan.
  • Empty values: the common CreateDnMat requires non-empty values. BufferSize/Analysis do not read the B/C values; they can be temporarily emptied through the common setters after descriptor creation, and valid addresses must be restored before the first non-zero-dimension Solve. For Atlas A2 products and Atlas A3 products, bound non-empty B/C addresses cannot be replaced, and Analysis must be performed again.
  • buffer lifecycle: Atlas A2 products and Atlas A3 products require explicitly passing a non-empty external buffer; Ascend 950PR&950DT products use the current handle workspace when the parameter is empty. The workspace must be 64-byte aligned memory on the current device, with a capacity no smaller than the value returned by BufferSize, and must not overlap A/B/C, Device alpha, or Update inputs until the stream completes.
  • Asynchronous execution: Solve does not synchronize or read back. The caller must synchronize the handle stream before reading C, releasing A/B/C/workspace, or destroying the descriptor.
  • unsorted indices: unsorted and duplicate coordinates of CSR/CSC/COO are supported; all stored indices must still be valid.
  • In-place layout: any orderB/orderC combination supports B/C sharing the same Device address, and B is saved before solving. Atlas A2 products and Atlas A3 products reject B/C addresses that differ but partially overlap, and C overlapping the A arrays.
  • Address check boundaries: raw void* cannot prove logical dtype, sub-array length, or allocation generation, and the caller must still ensure the real type, capacity, and lifecycle. Atlas A2 products and Atlas A3 products require the A indices/values, non-zero-dimension B/C values, and Device alpha to be 4-byte aligned memory on the current device; destroyed handles or matrix descriptors are not detected.
  • Concurrency: multiple independent plans can execute on different streams; concurrent calls on the same plan are not allowed.
  • Attribute setting timing: fillMode and diagType must be set through aclsparseSpMatSetAttribute before calling BufferSize/Analysis (the attributes are ACL_SPARSE_SPMAT_FILL_MODE and ACL_SPARSE_SPMAT_DIAG_TYPE respectively).

Invocation Description

The invocation flow is the three-stage method (Generic API Descriptor pattern):

  1. BufferSize: queries the required workspace size and allocates Device memory.
  2. Analysis: normalizes the format, validates indices and diagonals, prepares the solving and Update plans on NPU, and binds the active buffer.
  3. Solve / Update: asynchronously executes the triangular solving; if only values are updated, UpdateMatrix can be called and the plan reused to continue Solve.

The sample code is as follows and is for reference only. For the specific compilation and execution process, refer to Compilation and Running Sample.

#include <cstdio>
#include <memory>
#include <vector>

#include "acl/acl.h"
#include "cann_ops_sparse.h"

#define CHECK_RET(cond, return_expr) \
    do {                             \
        if (!(cond)) {               \
            return_expr;             \
        }                            \
    } while (0)

#define LOG_PRINT(message, ...)         \
    do {                                \
        printf(message, ##__VA_ARGS__); \
    } while (0)

class AclContext {
public:
    explicit AclContext(int32_t deviceId) : deviceId_(deviceId) {}

    ~AclContext()
    {
        if (stream_ != nullptr) {
            aclrtDestroyStream(stream_);
            stream_ = nullptr;
        }
        if (deviceSet_) {
            aclrtResetDevice(deviceId_);
            deviceSet_ = false;
        }
        if (aclInited_) {
            aclFinalize();
            aclInited_ = false;
        }
    }

    int Init()
    {
        auto ret = aclInit(nullptr);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret);
        aclInited_ = true;

        ret = aclrtSetDevice(deviceId_);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret);
        deviceSet_ = true;

        ret = aclrtCreateStream(&stream_);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret);
        return ACL_SUCCESS;
    }

    aclrtStream Stream() const { return stream_; }

private:
    int32_t deviceId_;
    aclrtStream stream_ = nullptr;
    bool aclInited_ = false;
    bool deviceSet_ = false;
};

// Helper: allocates Device memory and copies Host data
static void* AllocAndCopyDevice(const void *hostPtr, size_t sizeBytes)
{
    void *dPtr = nullptr;
    if (aclrtMalloc(&dPtr, sizeBytes, ACL_MEM_MALLOC_HUGE_FIRST) != ACL_SUCCESS) {
        return nullptr;
    }
    if (hostPtr != nullptr && sizeBytes > 0) {
        if (aclrtMemcpy(dPtr, sizeBytes, hostPtr, sizeBytes, ACL_MEMCPY_HOST_TO_DEVICE) != ACL_SUCCESS) {
            aclrtFree(dPtr);
            return nullptr;
        }
    }
    return dPtr;
}

// All return paths first wait for asynchronous tasks, then destroy the descriptor and release device memory.
struct ExampleResources {
    explicit ExampleResources(aclrtStream value) : stream(value) {}
    ExampleResources(const ExampleResources&) = delete;
    ExampleResources& operator=(const ExampleResources&) = delete;
    ~ExampleResources()
    {
        aclrtSynchronizeStream(stream);
        aclsparseSpSMDestroyDescr(spsmDescr);
        if (matA != nullptr) { aclsparseDestroySpMat(matA); }
        if (matB != nullptr) { aclsparseDestroyDnMat(matB); }
        if (matC != nullptr) { aclsparseDestroyDnMat(matC); }
        for (void *ptr : {dRowPtrA, dColIndA, dValA, dB, dC, dBuffer}) {
            if (ptr != nullptr) { aclrtFree(ptr); }
        }
    }
    aclrtStream stream = nullptr;
    aclsparseSpMatDescr_t matA = nullptr;
    aclsparseDnMatDescr_t matB = nullptr, matC = nullptr;
    aclsparseSpSMDescr_t spsmDescr = nullptr;
    void *dRowPtrA = nullptr, *dColIndA = nullptr, *dValA = nullptr;
    void *dB = nullptr, *dC = nullptr, *dBuffer = nullptr;
};

int aclsparseSpSMTest(AclContext& ctx)
{
    aclrtStream stream = ctx.Stream();

    // 1. Create the ops-sparse handle
    aclsparseHandle_t rawHandle = nullptr;
    auto sparseRet = aclsparseCreate(&rawHandle);
    CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("aclsparseCreate failed. ERROR: %d\n", sparseRet);
              return sparseRet);
    std::unique_ptr<aclsparseContext, aclsparseStatus_t (*)(aclsparseHandle_t)> handlePtr(rawHandle, aclsparseDestroy);
    ExampleResources resources(stream);

    sparseRet = aclsparseSetStream(static_cast<aclsparseHandle_t>(handlePtr.get()), stream);
    CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("aclsparseSetStream failed. ERROR: %d\n", sparseRet);
              return sparseRet);

    // 2. Set PointerMode
    sparseRet = aclsparseSetPointerMode(static_cast<aclsparseHandle_t>(handlePtr.get()), ACL_SPARSE_POINTER_MODE_HOST);
    CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("aclsparseSetPointerMode failed. ERROR: %d\n", sparseRet);
              return sparseRet);

    // 3. Prepare the Host-side CSR data
    //    A (3x3, lower triangular, NON_UNIT, nnz=6):     B (3x2):
    //    [2.0  0.0  0.0]      [2.0  4.0]
    //    [1.0  3.0  0.0]      [4.0  8.0]
    //    [4.0  5.0  6.0]      [6.0 12.0]
    //
    //    CSR (with diagonal, NON_UNIT):
    //      rowOff = [0, 1, 3, 6]
    //      colInd = [0, 0, 1, 0, 1, 2]
    //      values = [2.0, 1.0, 3.0, 4.0, 5.0, 6.0]
    //
    //    Solve A * X = 1.0 * B (lower triangular, forward substitution, NON_UNIT):
    //      X[0] = B[0] / A[0,0]                         = [1.0,  2.0]
    //      X[1] = (B[1] - A[1,0]*X[0]) / A[1,1]         = [1.0,  2.0]
    //      X[2] = (B[2] - A[2,0]*X[0] - A[2,1]*X[1]) / A[2,2] = [-0.5, -1.0]
    int64_t m = 3, n = 2;
    int64_t nnzA = 6;
    float hAlpha = 1.0f;

    std::vector<int> hRowPtrA = {0, 1, 3, 6};
    std::vector<int> hColIndA = {0, 0, 1, 0, 1, 2};
    std::vector<float> hValA  = {2.0f, 1.0f, 3.0f, 4.0f, 5.0f, 6.0f};

    // B: row-major 3x2
    int64_t ldb = n, ldc = n;
    aclsparseOrder_t orderB = ACL_SPARSE_ORDER_ROW;
    aclsparseOrder_t orderC = ACL_SPARSE_ORDER_ROW;
    std::vector<float> hB(static_cast<size_t>(m) * n, 0.0f);
    hB[0 * n + 0] = 2.0f; hB[0 * n + 1] = 4.0f;
    hB[1 * n + 0] = 4.0f; hB[1 * n + 1] = 8.0f;
    hB[2 * n + 0] = 6.0f; hB[2 * n + 1] = 12.0f;

    std::vector<float> hC(static_cast<size_t>(m) * n, 0.0f);

    // 4. Copy the data to the Device
    auto &dRowPtrA = resources.dRowPtrA;
    dRowPtrA = AllocAndCopyDevice(hRowPtrA.data(), (m + 1) * sizeof(int));
    auto &dColIndA = resources.dColIndA;
    dColIndA = AllocAndCopyDevice(hColIndA.data(), nnzA * sizeof(int));
    auto &dValA = resources.dValA;
    dValA = AllocAndCopyDevice(hValA.data(),    nnzA * sizeof(float));
    auto &dB = resources.dB;
    dB = AllocAndCopyDevice(hB.data(),       static_cast<size_t>(m) * n * sizeof(float));
    auto &dC = resources.dC;
    dC = AllocAndCopyDevice(hC.data(),       static_cast<size_t>(m) * n * sizeof(float));

    if (dRowPtrA == nullptr || dColIndA == nullptr || dValA == nullptr || dB == nullptr || dC == nullptr) {
        LOG_PRINT("*Failed to allocate or copy device data*\n");
        return ACL_SPARSE_STATUS_ALLOC_FAILED;
    }

    // 5. Create the sparse matrix descriptor and set the triangular attributes
    auto &matA = resources.matA;
    sparseRet = aclsparseCreateCsr(&matA, m, m, nnzA, dRowPtrA, dColIndA, dValA,
                                   ACL_SPARSE_INDEX_32I, ACL_SPARSE_INDEX_32I,
                                   ACL_SPARSE_INDEX_BASE_ZERO, ACL_FLOAT);
    CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("aclsparseCreateCsr failed. ERROR: %d\n", sparseRet);
              return sparseRet);

    // 5.1 Set the triangular matrix attributes: fillMode=LOWER, diagType=NON_UNIT
    aclsparseFillMode_t fillMode = ACL_SPARSE_FILL_MODE_LOWER;
    aclsparseDiagType_t diagType = ACL_SPARSE_DIAG_TYPE_NON_UNIT;
    sparseRet = aclsparseSpMatSetAttribute(matA, ACL_SPARSE_SPMAT_FILL_MODE, &fillMode, sizeof(fillMode));
    CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("aclsparseSpMatSetAttribute(FILL_MODE) failed. ERROR: %d\n", sparseRet);
              return sparseRet);
    sparseRet = aclsparseSpMatSetAttribute(matA, ACL_SPARSE_SPMAT_DIAG_TYPE, &diagType, sizeof(diagType));
    CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("aclsparseSpMatSetAttribute(DIAG_TYPE) failed. ERROR: %d\n", sparseRet);
              return sparseRet);

    auto &matB = resources.matB;
    auto &matC = resources.matC;
    sparseRet = aclsparseCreateDnMat(&matB, m, n, ldb, dB, ACL_FLOAT, orderB);
    CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("aclsparseCreateDnMat B failed. ERROR: %d\n", sparseRet);
              return sparseRet);
    sparseRet = aclsparseCreateDnMat(&matC, m, n, ldc, dC, ACL_FLOAT, orderC);
    CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("aclsparseCreateDnMat C failed. ERROR: %d\n", sparseRet);
              return sparseRet);

    // 6. Create the SpSM descriptor
    auto &spsmDescr = resources.spsmDescr;
    sparseRet = aclsparseSpSMCreateDescr(&spsmDescr);
    CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("aclsparseSpSMCreateDescr failed. ERROR: %d\n", sparseRet);
              return sparseRet);

    // 7. Step 1 — BufferSize
    size_t bufferSize = 0;
    sparseRet = aclsparseSpSMBufferSize(
        static_cast<aclsparseHandle_t>(handlePtr.get()),
        ACL_SPARSE_OP_NON_TRANSPOSE, ACL_SPARSE_OP_NON_TRANSPOSE,
        &hAlpha, matA, matB, matC, ACL_FLOAT,
        ACL_SPARSE_SPSM_ALG_DEFAULT, spsmDescr, &bufferSize);
    CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("SpSMBufferSize failed. ERROR: %d\n", sparseRet);
              return sparseRet);
    LOG_PRINT("bufferSize = %zu bytes\n", bufferSize);

    auto &dBuffer = resources.dBuffer;
    auto aclRet = aclrtMalloc(&dBuffer, bufferSize, ACL_MEM_MALLOC_HUGE_FIRST);
    CHECK_RET(aclRet == ACL_SUCCESS, LOG_PRINT("aclrtMalloc for buffer failed. ERROR: %d\n", aclRet); return aclRet);

    // 8. Step 2 — Analysis (NPU normalization, topological layering, and singularity detection)
    sparseRet = aclsparseSpSMAnalysis(
        static_cast<aclsparseHandle_t>(handlePtr.get()),
        ACL_SPARSE_OP_NON_TRANSPOSE, ACL_SPARSE_OP_NON_TRANSPOSE,
        &hAlpha, matA, matB, matC, ACL_FLOAT,
        ACL_SPARSE_SPSM_ALG_DEFAULT, spsmDescr, dBuffer);
    CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("SpSMAnalysis failed. ERROR: %d\n", sparseRet);
              return sparseRet);

    // 9. Step 3 — Solve (asynchronous start, no stream synchronization inside the operator)
    sparseRet = aclsparseSpSM(
        static_cast<aclsparseHandle_t>(handlePtr.get()),
        ACL_SPARSE_OP_NON_TRANSPOSE, ACL_SPARSE_OP_NON_TRANSPOSE,
        &hAlpha, matA, matB, matC, ACL_FLOAT,
        ACL_SPARSE_SPSM_ALG_DEFAULT, spsmDescr);
    CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("SpSM failed. ERROR: %d\n", sparseRet);
              return sparseRet);

    // 10. Wait for asynchronous Solve to complete (synchronized by the caller; Analysis / NON_UNIT Update performs synchronized verification)
    aclRet = aclrtSynchronizeStream(stream);
    CHECK_RET(aclRet == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", aclRet); return aclRet);

    // 11. Copy the result back to the Host and print it
    aclRet = aclrtMemcpy(hC.data(), static_cast<size_t>(m) * n * sizeof(float),
                         dC, static_cast<size_t>(m) * n * sizeof(float),
                         ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_RET(aclRet == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", aclRet);
              return aclRet);

    for (int64_t i = 0; i < m; i++) {
        LOG_PRINT("C[%lld] = %.1f, %.1f\n", static_cast<long long>(i), hC[i * n + 0], hC[i * n + 1]);
    }

    // resources cleans up resources at return, before handlePtr is destructed.
    return ACL_SPARSE_STATUS_SUCCESS;
}

int main()
{
    AclContext ctx(0);
    auto ret = ctx.Init();
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    ret = aclsparseSpSMTest(ctx);
    CHECK_RET(ret == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("aclsparseSpSMTest failed. ERROR: %d\n", ret); return ret);
    return 0;
}

The expected output is as follows:

bufferSize = <*subject to the actual query result*> bytes
C[0] = 1.0, 2.0
C[1] = 1.0, 2.0
C[2] = -0.5, -1.0

In-place usage: change dC in the preceding example to reuse dB (that is, aclsparseCreateDnMat(&matC, m, n, ldc, dB, ...)). The implementation saves the values of B before computing and supports independent B/C layouts; the caller must ensure that the capacity of the shared memory covers both, and resources.dC in the example should remain independently allocated or be set to nullptr, ensuring that the same address is released only once at destruction.

Reference Resources

  • Target interface: cuSPARSE cusparseSpSM (Generic API, three-stage execution).