README

SpGEMM Operator

Product support

Product Supported
Ascend 950PR&950DT products (the current support scope is the Ascend 950PR products) √
Atlas A3 products √
Atlas A2 products √
Atlas 200I/500 A2 inference products ×
Atlas inference products ×
Atlas training products ×

Function Description

SpGEMM (Sparse General Matrix-Matrix Multiplication) computes the product of two CSR sparse matrices:

C' = alpha * op(A) * op(B) + beta * C

Here A has the shape M×K, B has the shape K×N, and the output C has the shape M×N. The current version only supports op(A)=A and op(B)=B. When multiple intermediate products land on the same coordinate, they are merged; the column indices of the output CSR are in strictly ascending order per row, and contain no duplicate coordinates. Explicit zeros produced by numerical cancellation remain in the output structure.

The operator adopts a multi-stage Generic API: it first counts intermediate products and queries the workspace, then computes the output structure and values, and finally writes the internal results into caller-allocated dynamic outputs. The Python adaptation calls the same aclsparseSpGEMM* implementation through the public interface torch.sparse.mm(mat1, mat2).

Interfaces and Responsibilities

Interface Brief Function
aclsparseSpGEMMCreateDescr Creates an SpGEMM descriptor reused across stages
aclsparseSpGEMMWorkEstimation Queries or executes the work-amount statistics to obtain the per-row and total intermediate product counts
aclsparseSpGEMMGetNumProducts Queries the total number of intermediate products obtained by WorkEstimation
aclsparseSpGEMMEstimateMemory Queries the ALG2/ALG3 memory plan and the Compute workspace size
aclsparseSpGEMMCompute Queries or executes the structure and value computation, writes rowOffsets, and updates nnz(C)
aclsparseSpGEMMCopy Writes the internal column indices and values into the C pointers set by the caller
aclsparseSpGEMMDestroyDescr Destroys the Host descriptor and does not release the caller workspace
aclsparseSpGEMMSetCInValid Supports legacy calls that mark the validity of the C input
aclsparseSpGEMMGetBufferSize Queries the shared workspace of the legacy three-stage compatible interfaces
aclsparseSpGEMMPreprocess Executes structure preprocessing of the legacy three-stage compatible interfaces
aclsparseSpGEMM Executes value computation of the legacy three-stage compatible interfaces

Interface description

Descriptor Creation and Destruction

Function prototype

aclsparseStatus_t aclsparseSpGEMMCreateDescr(
    aclsparseSpGEMMDescr_t *descr);

aclsparseStatus_t aclsparseSpGEMMDestroyDescr(
    aclsparseSpGEMMDescr_t descr);

Parameter description

Parameter Input/Output Parameter Type Description
descr Output/Input aclsparseSpGEMMDescr_t* / aclsparseSpGEMMDescr_t Opaque Host descriptor; before Create, *descr must be nullptr

Constraints

  • You must create the descriptor before the other SpGEMM stages, and destroy it after all asynchronous work completes.
  • aclsparseSpGEMMDestroyDescr(nullptr) returns success.
  • Destroy releases only the Host descriptor; it does not synchronize the stream and does not release externalBuffer1/2/3.

Common Parameters

The following parameters are shared by WorkEstimation, EstimateMemory, Compute, and Copy.

Parameter Input/Output Parameter Type Memory Location Description
handle Input aclsparseHandle_t Host ops-sparse context handle, which must be bound to a stream through aclsparseSetStream
opA Input aclsparseOperation_t Host Only ACL_SPARSE_OP_NON_TRANSPOSE is supported
opB Input aclsparseOperation_t Host Only ACL_SPARSE_OP_NON_TRANSPOSE is supported
alpha Input const void* Host/Device Scalar alpha; its address space is determined by the handle pointer mode, and its dtype equals computeType
matA Input aclsparseConstSpMatDescr_t Host descriptor, Device data M×K CSR input matrix A
matB Input aclsparseConstSpMatDescr_t Host descriptor, Device data K×N CSR input matrix B
beta Input const void* Host/Device Scalar beta; its address space is determined by the handle pointer mode, and its dtype equals computeType
matC Input/Output aclsparseSpMatDescr_t Host descriptor, Device data M×N CSR input/output matrix C; Compute updates nnz
computeType Input aclDataType Host ACL_FLOAT16, ACL_BF16, ACL_FLOAT, or ACL_COMPLEX64
alg Input aclsparseSpGEMMAlg_t Host DEFAULT, ALG1, ALG2, or ALG3; it cannot be changed for the same descriptor across the whole flow
spgemmDescr Input/Output aclsparseSpGEMMDescr_t Host Stores the stage state, problem snapshot, workspace plan, numProds, and nnz(C)

aclsparseSpGEMMWorkEstimation

Queries and executes the intermediate-product work-amount statistics. The first call passes externalBuffer1=nullptr to query the size; after the Device workspace is allocated, the second call executes the statistics.

Function prototype

aclsparseStatus_t aclsparseSpGEMMWorkEstimation(
    aclsparseHandle_t handle,
    aclsparseOperation_t opA, aclsparseOperation_t opB,
    const void *alpha,
    aclsparseConstSpMatDescr_t matA,
    aclsparseConstSpMatDescr_t matB,
    const void *beta,
    aclsparseSpMatDescr_t matC,
    aclDataType computeType,
    aclsparseSpGEMMAlg_t alg,
    aclsparseSpGEMMDescr_t spgemmDescr,
    size_t *bufferSize1, void *externalBuffer1);

Stage-Specific Parameters

Parameter Input/Output Parameter Type Memory Location Description
bufferSize1 Input/Output size_t* Host Writes back the required number of bytes for a query; passes in the actual available number of bytes for execution
externalBuffer1 Input void* Device nullptr for the first call, or a workspace of at least bufferSize1 bytes for the second call

After successful execution, externalBuffer1 must be retained until Copy completes. If the input CSR is invalid, the workspace is insufficient, or the number of intermediate products exceeds INT32_MAX, the corresponding error code is returned.

aclsparseSpGEMMGetNumProducts

Function prototype

aclsparseStatus_t aclsparseSpGEMMGetNumProducts(
    aclsparseSpGEMMDescr_t spgemmDescr,
    int64_t *numProds);

Parameter description

Parameter Input/Output Parameter Type Description
spgemmDescr Input aclsparseSpGEMMDescr_t Descriptor that has successfully executed WorkEstimation
numProds Output int64_t* Total number of intermediate products, which does not equal the final deduplicated nnz(C)

aclsparseSpGEMMEstimateMemory

Used to query the Compute workspace. The chunkFraction of ALG2/ALG3 must lie in (0, 1]. The current deterministic implementation of Ascend 950PR products returns bufferSize3=0, and externalBuffer3 is reserved for compatibility with the multi-stage interface.

Function prototype

aclsparseStatus_t aclsparseSpGEMMEstimateMemory(
    aclsparseHandle_t handle,
    aclsparseOperation_t opA, aclsparseOperation_t opB,
    const void *alpha,
    aclsparseConstSpMatDescr_t matA,
    aclsparseConstSpMatDescr_t matB,
    const void *beta,
    aclsparseSpMatDescr_t matC,
    aclDataType computeType,
    aclsparseSpGEMMAlg_t alg,
    aclsparseSpGEMMDescr_t spgemmDescr,
    float chunkFraction,
    size_t *bufferSize3, void *externalBuffer3,
    size_t *bufferSize2);

Stage-Specific Parameters

Parameter Input/Output Parameter Type Memory Location Description
chunkFraction Input float Host For ALG2/ALG3 it must be in (0,1]; DEFAULT/ALG1 reserve this parameter
bufferSize3 Output size_t* Host The current implementation writes back 0
externalBuffer3 Input void* Device Reserved in the current implementation; nullptr can be passed
bufferSize2 Output size_t* Host Number of workspace bytes required by Compute

aclsparseSpGEMMCompute

The first call passes externalBuffer2=nullptr to directly query the size; the second call executes the structure and value computation. Compute writes matC.rowOffsets and updates nnz(C) in the descriptor, but does not allocate memory for the output column indices and values.

Function prototype

aclsparseStatus_t aclsparseSpGEMMCompute(
    aclsparseHandle_t handle,
    aclsparseOperation_t opA, aclsparseOperation_t opB,
    const void *alpha,
    aclsparseConstSpMatDescr_t matA,
    aclsparseConstSpMatDescr_t matB,
    const void *beta,
    aclsparseSpMatDescr_t matC,
    aclDataType computeType,
    aclsparseSpGEMMAlg_t alg,
    aclsparseSpGEMMDescr_t spgemmDescr,
    size_t *bufferSize2, void *externalBuffer2);

Stage-Specific Parameters

Parameter Input/Output Parameter Type Memory Location Description
bufferSize2 Input/Output size_t* Host Writes back the required number of bytes for a query; passes in the actual available number of bytes for execution
externalBuffer2 Input void* Device Can be nullptr for the first call; for execution, a workspace of at least bufferSize2 bytes

Before Compute, matC must be bound to Device rowOffsets of length at least M+1. If beta=0, you can allocate the output colIndices and values after Compute succeeds and nnz(C) is obtained through aclsparseSpMatGetSize; if beta!=0, the input C must provide the same CSR pattern and valid values as the result in advance.

For compatibility with existing source code, aclsparseSpGEMMSetCInValid is retained. The new multi-stage interface determines valid C_in based on beta!=0 and the matC CSR pattern/values bound before Compute; legacy callers do not need to remove the SetCInValid call, and the accumulation semantics remain C' = alpha * A * B + beta * C_in.

The legacy three-stage interfaces aclsparseSpGEMMGetBufferSize, aclsparseSpGEMMPreprocess, and aclsparseSpGEMM are also retained and internally reuse the preceding multi-stage implementation. The compatible workspace holds both the work-amount statistics and value computation areas, and its lifecycle requirements are consistent with the legacy interfaces.

aclsparseSpGEMMCopy

Function prototype

aclsparseStatus_t aclsparseSpGEMMCopy(
    aclsparseHandle_t handle,
    aclsparseOperation_t opA, aclsparseOperation_t opB,
    const void *alpha,
    aclsparseConstSpMatDescr_t matA,
    aclsparseConstSpMatDescr_t matB,
    const void *beta,
    aclsparseSpMatDescr_t matC,
    aclDataType computeType,
    aclsparseSpGEMMAlg_t alg,
    aclsparseSpGEMMDescr_t spgemmDescr);

After Compute, call aclsparseSpMatGetSize to obtain nnz(C), allocate Device memory for colIndices and values, and then update matC through aclsparseCsrSetPointers. Copy asynchronously writes the final CSR; you must synchronize the stream bound to the handle before reading the results or releasing the workspace.

Legacy Three-Stage Compatible Interfaces

The following three interfaces internally reuse the preceding multi-stage implementation, allowing legacy callers to use the "query size → allocate → execute once" approach; the compatible workspace holds both the work-amount statistics and value computation areas.

Function prototype

aclsparseStatus_t aclsparseSpGEMMGetBufferSize(aclsparseHandle_t handle, aclsparseOperation_t opA,
                                               aclsparseOperation_t opB, const void* alpha,
                                               aclsparseConstSpMatDescr_t matA, aclsparseConstSpMatDescr_t matB,
                                               const void* beta, aclsparseSpMatDescr_t matC, aclDataType computeType,
                                               aclsparseSpGEMMAlg_t alg, size_t* size);

aclsparseStatus_t aclsparseSpGEMMPreprocess(aclsparseHandle_t handle, aclsparseOperation_t opA,
                                            aclsparseOperation_t opB, const void* alpha,
                                            aclsparseConstSpMatDescr_t matA, aclsparseConstSpMatDescr_t matB,
                                            const void* beta, aclsparseSpMatDescr_t matC, aclDataType computeType,
                                            aclsparseSpGEMMAlg_t alg, void* buffer);

aclsparseStatus_t aclsparseSpGEMM(aclsparseHandle_t handle, aclsparseOperation_t opA, aclsparseOperation_t opB,
                                  const void* alpha, aclsparseConstSpMatDescr_t matA, aclsparseConstSpMatDescr_t matB,
                                  const void* beta, aclsparseSpMatDescr_t matC, aclDataType computeType,
                                  aclsparseSpGEMMAlg_t alg, void* buffer);

Parameter description

Parameter Input/Output Parameter Type Description
size Output size_t* GetBufferSize writes back the number of bytes required by the compatible workspace; it cannot be nullptr
buffer Input void* Device workspace; it is not used for GetBufferSize, and for Preprocess/SpGEMM execution it must be non-empty and no smaller than the queried result
Other parameters Input — Consistent with the common parameters of WorkEstimation/Compute/Copy

Constraints

  • When buffer is nullptr, Preprocess/SpGEMM returns ACL_SPARSE_STATUS_INSUFFICIENT_RESOURCES; if the internal layout during execution is inconsistent with the value queried by GetBufferSize, ACL_SPARSE_STATUS_INTERNAL_ERROR is returned.
  • Before calling Preprocess/SpGEMM, matC must already be bound to Device rowOffsets of length number of A rows + 1; because the legacy interface completes Copy internally, colIndices and values must also be bound before the call, with a capacity no smaller than nnz(C). The implementation verifies only that the output pointers are non-empty and performs no capacity verification; insufficient capacity causes out-of-bounds writes to device memory.
  • After Preprocess succeeds, the legacy descriptor and the passed-in buffer are attached to matC (including activeBuffer); subsequently, calling SpGEMM with the same buffer and the same problem (A/B/C/computeType/alg) hits the cache directly and skips preprocessing.
  • The cache hit check (ProblemMatches) compares only the matA/matB/matC descriptor objects, shape, nnz, computeType, and alg, and does not compare CSR contents; after rewriting the input CSR structure in place (even if nnz does not change), you must call aclsparseSpGEMMPreprocess again (or switch to a different buffer to force re-preprocessing); otherwise, stale row-product statistics are reused, causing incorrect results.
  • When matC has no cached legacy descriptor, the passed-in buffer is inconsistent with the cache, or the problem (A/B/C/computeType/alg) does not match, SpGEMM automatically performs one full preprocessing pass (including the ProblemMatches check); that is, SpGEMM can be used independently of an explicit Preprocess call, but this cold path synchronously executes all preprocessing stages.
  • Switching to a different buffer or changing the problem triggers the preceding implicit re-preprocessing; callers should not assume that SpGEMM performs no preprocessing.
  • The lifecycle requirements of the compatible workspace are consistent with the legacy interfaces: you must synchronize the stream before reading the results or releasing it.

Supported Specifications

Specification Item Supported Value Description
Input/output format CSR A, B, and C are all 2D CSR; COO, CSC, batch, and broadcasting are not supported
Data type FP16, BF16, FP32, Complex64 The values types of A, B, and C must exactly match computeType
Index type ACL_SPARSE_INDEX_32I rowOffsets and colIndices must both be int32
Index base ACL_SPARSE_INDEX_BASE_ZERO one-based CSR is not supported
opA / opB ACL_SPARSE_OP_NON_TRANSPOSE Transpose or conjugate transpose is not supported
Algorithm DEFAULT, ALG1, ALG2, ALG3 DEFAULT and ALG1 use the deterministic full-candidate path; the four algorithms have consistent output semantics
scalar pointer mode Host, Device alpha and beta must both conform to the current handle pointer mode
Output structure Column indices in strictly ascending order per row, no duplicate coordinates Structural items with zero values are still retained
Size limit shape, nnz, and the number of intermediate products do not exceed INT32_MAX Also limited by size_t and the actual Device memory

Constraints

  • The number of columns of A must equal the number of rows of B; the shape of C must be A.rows × B.cols.
  • A, B, and C must use the same value dtype, int32 index type, and zero-based index.
  • The rowOffsets of the input CSR of A and B must be monotonically non-decreasing, and the column indices must be within the valid range and non-decreasing per row.
  • alpha, beta, each matrix descriptor, the SpGEMM descriptor, and the size pointers required by stages cannot be nullptr.
  • You must not change matrix descriptors, shape, nnz, dtype, or algorithm across stages for the same descriptor; after structural changes, WorkEstimation must be executed again.
  • Both WorkEstimation and Compute adopt the two-call convention of "querying the size with an empty buffer, then executing with a Device buffer".
  • The lifecycles of externalBuffer1 and externalBuffer2 must extend until Copy completes; the number of bytes passed in during execution must not be smaller than the queried result.
  • Copy is submitted asynchronously; callers must synchronize the stream before reading outputs, destroying input data, or reusing the workspace.
  • aclsparseSpGEMMDestroyDescr does not release matrix descriptors or Device memory created by the caller.

Invocation Flow

The recommended flow is as follows. The unified return code checks and Device allocation helper functions are omitted; for the complete runnable path, see ../../test/spgemm/arch35/spgemm_test.cpp.

aclsparseSpGEMMDescr_t descr = nullptr;
aclsparseSpGEMMCreateDescr(&descr);

// A and B are complete CSR; C has shape, dtype, and rowOffsets of length M+1 set.
size_t size1 = 0;
aclsparseSpGEMMWorkEstimation(handle, opA, opB, alpha, matA, matB, beta,
    matC, computeType, alg, descr, &size1, nullptr);
void *buffer1 = DeviceMalloc(size1);
aclsparseSpGEMMWorkEstimation(handle, opA, opB, alpha, matA, matB, beta,
    matC, computeType, alg, descr, &size1, buffer1);

int64_t numProducts = 0;
aclsparseSpGEMMGetNumProducts(descr, &numProducts);

size_t size2 = 0;
if (alg == ACL_SPARSE_SPGEMM_ALG2 || alg == ACL_SPARSE_SPGEMM_ALG3) {
    size_t size3 = 0;
    aclsparseSpGEMMEstimateMemory(handle, opA, opB, alpha, matA, matB, beta,
        matC, computeType, alg, descr, 1.0F, &size3, nullptr, &size2);
} else {
    aclsparseSpGEMMCompute(handle, opA, opB, alpha, matA, matB, beta,
        matC, computeType, alg, descr, &size2, nullptr);
}

void *buffer2 = DeviceMalloc(size2);
aclsparseSpGEMMCompute(handle, opA, opB, alpha, matA, matB, beta,
    matC, computeType, alg, descr, &size2, buffer2);

int64_t rowsC = 0;
int64_t colsC = 0;
int64_t nnzC = 0;
aclsparseSpMatGetSize(matC, &rowsC, &colsC, &nnzC);
void *colIndicesC = DeviceMalloc(static_cast<size_t>(nnzC) * sizeof(int32_t));
void *valuesC = DeviceMalloc(static_cast<size_t>(nnzC) * ValueSize(computeType));
aclsparseCsrSetPointers(matC, rowOffsetsC, colIndicesC, valuesC);

aclsparseSpGEMMCopy(handle, opA, opB, alpha, matA, matB, beta,
    matC, computeType, alg, descr);
aclrtSynchronizeStream(stream);

aclsparseSpGEMMDestroyDescr(descr);
DeviceFree(buffer2);
DeviceFree(buffer1);

Compilation and Testing

cmake -S . -B build \
  -DSOC_VERSION=ascend950 \
  -DCMAKE_BUILD_TYPE=Release \
  -DBUILD_TEST=ON \
  -DOP_LIST=spgemm
cmake --build build --target spgemm_test spgemm_perf --parallel
./build/test/spgemm/spgemm_test --gtest_color=no

PyTorch interface registration is provided through the torch_extension framework; for the build and load methods, see ../../torch_extension/README_en.md, and for the SpGEMM-side interface description, see ../../torch_extension/cann_ops_sparse/docs/en/spgemm.md.

Directory structure

sparse/spgemm/
├── README.md
├── common/
│   ├── spgemm_common.h        # Type and specification definitions shared across archs
│   └── spgemm_validate.cpp    # Common parameter validation
├── arch22/                    # Atlas A2 products, Atlas A3 products
│   ├── README.md
│   ├── spgemm.h
│   ├── spgemm_host.cpp
│   ├── spgemm_count_kernel.cpp
│   ├── spgemm_symbolic_kernel.cpp
│   ├── spgemm_numeric_kernel.cpp
│   ├── spgemm_merge.h
│   ├── spgemm_merge_emit.h
│   ├── spgemm_merge_row.h
│   └── spgemm_value.h
├── arch35/                    # arch35 implementation
│   ├── spgemm.h
│   ├── spgemm_host.cpp
│   ├── spgemm_kernel.cpp
│   ├── spgemm_kernel.h
│   ├── spgemm_csr_mat.cpp
│   ├── spgemm_csr_mat.h
│   └── spgemm_tiling_data.h
└── torch_extension/           # PyTorch interface registration (compiled separately by PyTorch JIT)
    ├── __init__.py
    ├── spgemm.py
    └── csrc/
        └── spgemm.cpp

The test code is located in test/spgemm/.