FilesLast commitLast update
README

Cube SpMM Operator

Operator Overview

The Cube SpMM operator performs multiplication of a sparse matrix in BCSR (Block Compressed Sparse Row) format and a dense matrix:

C = alpha * A * B + beta * C

where:

  • AA is the sparse matrix. Its input format is COO and is converted to the BCSR format after preprocessing by aclsparseCubeSpmmPreprocess (rwPtr is int64_t, colRef and coreInfo are int32_t, and vals is float16).
  • BB is the dense matrix, whose data type is ACL_FLOAT16 and shape is [K,N][K, N]. Currently, only NN values that are multiples of 16 are supported.
  • CC is the output matrix, whose data type is ACL_FLOAT and shape is [M,N][M, N].
  • computeType is fixed to ACL_FLOAT.
  • The kernel internally partitions in the NN direction by kNChunkSize = 512. The local buffers (B1/B2/CO1 and the zeroing buffer) are all allocated by min(N, 512) to control per-core memory usage. This partitioning is transparent to users and does not affect the NN constraint at the API level.

Dimension Value Restrictions

To prevent overflow of the TilingData from the host to the kernel and of the internal BCSR indexes, the current implementation imposes the following restrictions on MM, KK, and NN:

  • M>0M > 0, K>0K > 0, and N>0N > 0, and none of the three values may be greater than INT32_MAX (2,147,483,6472{,}147{,}483{,}647). This upper limit comes from the fact that the COO row/column indexes currently accepted by aclsparseCubeSpmmPreprocess are int32_t.
  • M×K≤M \times K \le INT64_MAX (approximately 9.2×10189.2 \times 10^{18}), ensuring that the BCSR block index products (numBlocks * 16 and numBlocks * 256) do not exceed the range of int64_t.
  • NN must be a multiple of 16 and N≤32,767N \le 32{,}767 (the effective upper limit is 32,75232{,}752 after 16-alignment), which is determined by DataCopyParams.blockLen of type uint16_t inside the kernel.
  • The number of bytes of dense BB (K×N×2K \times N \times 2) and the number of bytes of output CC (M×N×4M \times N \times 4) must fit into size_t.

If the values exceed the preceding ranges, the API returns ACL_SPARSE_STATUS_NOT_SUPPORTED or ACL_SPARSE_STATUS_INVALID_VALUE.

The invocation process consists of the following steps:

  1. CreateCubeSpmmMat: create the Cube SpMM sparse matrix descriptor.
  2. Preprocess: call aclsparseCubeSpmmPreprocess to convert COO to BCSR.
  3. PadDenseMatrixB: call aclsparseCubeSpmmPadDenseMatrixB to perform padding alignment on dense BB (when AA remains unchanged while BB changes, you can call this API separately and reuse the BCSR data).
  4. GetBufferSize: query the workspace size required by SpMM (the current implementation always returns 0: tiling is passed as a kernel launch parameter along with <<<>>>, so no device workspace is required).
  5. CubeSpmm: execute the matrix multiplication on the AICore.

This operator includes the following APIs:

API Brief Description
aclsparseCreateCubeSpmmMat Creates a Cube SpMM sparse matrix descriptor
aclsparseDestroyCubeSpmmMat Destroys a Cube SpMM sparse matrix descriptor
aclsparseCubeSpmmPreprocess COO -> BCSR conversion of sparse matrix AA
aclsparseCubeSpmmPadDenseMatrixB Padding alignment of dense matrix BB
aclsparseCubeSpmmGetBufferSize Queries the workspace size (bytes) required by Cube SpMM
aclsparseCubeSpmm Executes the multiplication of a BCSR sparse matrix and a dense matrix

Operator Execution APIs

aclsparseCreateCubeSpmmMat

Product support

  • Atlas A2 products: Supported
  • The corresponding chip is Ascend 910B.

Function prototype

aclsparseStatus_t aclsparseCreateCubeSpmmMat(
    aclsparseCubeSpmmMatDescr_t *descr,
    int64_t rows, int64_t cols, int64_t nnz,
    int64_t blockM, int64_t blockK, int32_t numCores);

Parameter description

Parameter Input/Output Type Description
descr Output aclsparseCubeSpmmMatDescr_t* Output sparse matrix descriptor, host memory
rows Input int64_t Number of rows MM of the sparse matrix, host memory
cols Input int64_t Number of columns KK of the sparse matrix, host memory
nnz Input int64_t Number of non-zero elements in COO, host memory
blockM Input int64_t BCSR block size in the row direction, currently fixed to 16, host memory
blockK Input int64_t BCSR block size in the column direction, currently fixed to 16, host memory
numCores Input int32_t Number of AICores used by subsequent SpMM, host memory

Constraints

  • descr cannot be nullptr.
  • rows > 0, cols > 0, and nnz >= 0.
  • blockM and blockK must be fixed to 1616 (a hard requirement of the current kernel).
  • numCores > 0.
  • Currently, 0-based int32 indexes and float16 values are fixed (at the COO input stage); inside BCSR, only rwPtr is upgraded to int64_t, while colRef and coreInfo remain int32_t.
  • rows and cols must not be greater than INT32_MAX (limited by the COO int32_t indexes), and rows * cols must not be greater than INT64_MAX (to keep BCSR block index products safe).
  • nnz cannot exceed rows * cols.

aclsparseDestroyCubeSpmmMat

Product support

  • Atlas A2 products: Supported
  • The corresponding chip is Ascend 910B.

Function prototype

aclsparseStatus_t aclsparseDestroyCubeSpmmMat(
    aclsparseConstCubeSpmmMatDescr_t descr);

Parameter description

Parameter Input/Output Type Description
descr Input aclsparseConstCubeSpmmMatDescr_t Cube SpMM sparse matrix descriptor to destroy, host memory

Constraints

  • If nullptr is passed in, the API directly returns ACL_SPARSE_STATUS_SUCCESS.
  • The API releases the device memory allocated in the descriptor by aclsparseCubeSpmmPreprocess (rwPtr, colRef, vals, and coreInfo).
  • The Preprocess, GetBufferSize, and CubeSpmm APIs and the destroy API accept only Cube SpMM descriptors created by this library and still registered; unregistered objects return ACL_SPARSE_STATUS_INVALID_VALUE. Calls on the same descriptor are serialized by an object lock. Destruction waits for calls that already hold the object lock to complete, and calls waiting after destruction return an invalid status. Different descriptors can be called concurrently.
  • You must still manage the handle lifecycle and stop using all aliases after destruction. Handles are raw pointers; if a new object reuses an old address, the registration table cannot distinguish old aliases from new handles, so the library does not guarantee recognition of all dangling handles. The dense B/C descriptors must also remain valid before the call completes, and must not be destroyed or modified concurrently.

aclsparseCubeSpmmPadDenseMatrixB

Product support

  • Atlas A2 products: Supported
  • The corresponding chip is Ascend 910B.

Function prototype

aclsparseStatus_t aclsparseCubeSpmmPadDenseMatrixB(
    aclsparseHandle_t handle,
    int64_t bRows, int64_t bCols, int64_t bLd, const void *bValues,
    aclDataType bType, aclsparseOrder_t bOrder,
    int64_t *nPadOut, void **bPadOut);

Parameter description

Parameter Input/Output Type Description
handle Input aclsparseHandle_t Context handle of the ops-sparse library, host memory
bRows Input int64_t Number of rows of dense BB, which should equal matA->cols, host memory
bCols Input int64_t Original number of columns NN of dense BB, host memory
bLd Input int64_t Leading dimension of dense BB, host memory
bValues Input const void* Host memory pointer (float16) of dense BB, host memory; the API completes padding internally and then copies data to the device in one pass
bType Input aclDataType Data type of dense BB, which must be ACL_FLOAT16, host memory
bOrder Input aclsparseOrder_t Storage order of dense BB, which must be ACL_SPARSE_ORDER_ROW, host memory
nPadOut Output int64_t* Outputs the NN size after padding, host memory
bPadOut Output void** Outputs the device memory pointer of BB after padding; you must release it by using aclrtFree, device memory

Constraints

  • handle, bValues, nPadOut, and bPadOut cannot be nullptr.
  • bRows > 0, bCols > 0, and bLd >= bCols.
  • bType must be ACL_FLOAT16, and bOrder must be ACL_SPARSE_ORDER_ROW.
  • bCols is recommended to be a multiple of 16; if it is not, the API internally pads it to the minimum value that satisfies the L0B / CopyInB alignment requirements.
  • The output bPadOut memory is allocated by this API through aclrtMalloc, and you are responsible for releasing it.
  • When sparse matrix AA remains unchanged while dense BB changes, you can repeatedly call this API separately and reuse the same BCSR data.

aclsparseCubeSpmmGetBufferSize

Product support

  • Atlas A2 products (Ascend 910B): Supported

Function prototype

aclsparseStatus_t aclsparseCubeSpmmGetBufferSize(
    aclsparseHandle_t handle,
    const void *alpha, aclsparseConstCubeSpmmMatDescr_t matA,
    aclsparseConstDnMatDescr_t matB, const void *beta,
    aclsparseDnMatDescr_t matC, aclDataType computeType,
    size_t *size);

Parameter description

Parameter Input/Output Type Description
handle Input aclsparseHandle_t Context handle of the ops-sparse library, host memory
alpha Input const void* Scalar alpha pointer, currently unused; nullptr can be passed, host memory
matA Input aclsparseConstCubeSpmmMatDescr_t Sparse matrix descriptor preprocessed by aclsparseCubeSpmmPreprocess, host memory
matB Input aclsparseConstDnMatDescr_t Descriptor of dense matrix BB (bPad after padding), host memory
beta Input const void* Scalar beta pointer, currently unused; nullptr can be passed, host memory
matC Input/Output aclsparseDnMatDescr_t Descriptor of dense matrix CC (cPad after padding), host memory
computeType Input aclDataType Computation precision type, which must be ACL_FLOAT, host memory
size Output size_t* Outputs the required workspace size (bytes), fixed to 0 in the current implementation, host memory

Constraints

  • size cannot be nullptr.
  • matA, matB, and matC cannot be nullptr.
  • computeType must be ACL_FLOAT.
  • The data type of matB must be ACL_FLOAT16, and the data type of matC must be ACL_FLOAT.
  • The storage orders of matB and matC must be ACL_SPARSE_ORDER_ROW.
  • Dimension matching: matA->cols == matB->rows, matA->rows == matC->rows, and matB->cols == matC->cols.
  • After padding, the product of matB->cols and Block_K must be a multiple of 512B.
  • The MM, KK, and NN ranges in Dimension Value Restrictions must be satisfied.
  • matB->ld >= matB->cols and matC->ld >= matC->cols; the case of ld > cols is now correctly handled, and the kernel internally computes GM offsets through bLd / cLd in the TilingData.
  • Both matB->ld and matC->ld must not be greater than INT32_MAX.
  • matB->values and matC->values cannot be nullptr.

aclsparseCubeSpmm

Product support

  • Atlas A2 products (Ascend 910B): Supported

Function prototype

aclsparseStatus_t aclsparseCubeSpmm(
    aclsparseHandle_t handle,
    const void *alpha, aclsparseConstCubeSpmmMatDescr_t matA,
    aclsparseConstDnMatDescr_t matB, const void *beta,
    aclsparseDnMatDescr_t matC, aclDataType computeType,
    void *buffer);

Parameter description

Parameter Input/Output Type Description
handle Input aclsparseHandle_t Context handle of the ops-sparse library, host memory
alpha Input const void* Scalar alpha pointer, currently unused; nullptr can be passed, host memory
matA Input aclsparseConstCubeSpmmMatDescr_t Sparse matrix descriptor after preprocessing, host memory
matB Input aclsparseConstDnMatDescr_t Descriptor of dense matrix BB (after padding), host memory
beta Input const void* Scalar beta pointer, currently unused; nullptr can be passed, host memory
matC Input/Output aclsparseDnMatDescr_t Descriptor of dense matrix CC (after padding), host memory
computeType Input aclDataType Computation precision type, which must be ACL_FLOAT, host memory
buffer Input void* Workspace buffer, unused in the current implementation (GetBufferSize returns 0); nullptr can be passed

Constraints

  • The constraints are the same as those of aclsparseCubeSpmmGetBufferSize.
  • buffer is currently unused; nullptr can be passed.
  • Before the call, you must call aclsparseCubeSpmmPreprocess to perform preprocessing and fill the internal BCSR data of matA.
  • Only opA = NON_TRANSPOSE and opB = NON_TRANSPOSE are supported.

Supported sparse formats

Format Supported Description
Cube-BCSR ✅ Sparse matrix AA supports the Cube-BCSR format, generated by aclsparseCubeSpmmPreprocess
COO ❌ Raw COO input must be preprocessed first
CSR ❌ Not supported

Host and Preprocessing Error Returns

API Return Value Scenario
aclsparseCubeSpmmPreprocess ACL_SPARSE_STATUS_HANDLE_IS_NULLPTR COO input data pointers are not empty while the sparse matrix handle matA is nullptr
aclsparseCubeSpmmPreprocess ACL_SPARSE_STATUS_INSUFFICIENT_RESOURCES COO input data pointers are empty
aclsparseCubeSpmmPreprocess ACL_SPARSE_STATUS_EXECUTION_FAILED D2H readback of COO input data fails
aclsparseCubeSpmmPreprocess ACL_SPARSE_STATUS_INTERNAL_ERROR No column mapping is found when constructing BCSR
aclsparseCubeSpmmPreprocess ACL_SPARSE_STATUS_ALLOC_FAILED Allocating the BCSR device buffer or uploading the generated BCSR data fails
aclsparseCubeSpmm ACL_SPARSE_STATUS_INSUFFICIENT_RESOURCES The BCSR buffer generated by preprocessing is missing
aclsparseCubeSpmm ACL_SPARSE_STATUS_EXECUTION_FAILED Obtaining or synchronizing the stream fails

The preceding preprocessing and execution errors are returned by the corresponding APIs, and aclsparseCubeSpmmGetBufferSize performs the workspace query.

Invocation example

The example code is for reference only. For details about compilation and execution, see Compiling and Running a Sample.

#include <cstdint>
#include <iostream>
#include <vector>

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

int main()
{
    // 1. Initialize ACL and create a stream
    aclInit(nullptr);
    int32_t deviceId = 0;
    aclrtSetDevice(deviceId);
    aclrtStream stream = nullptr;
    aclrtCreateStream(&stream);

    // 2. Create the ops-sparse handle
    aclsparseHandle_t handle = nullptr;
    aclsparseCreate(&handle);
    aclsparseSetStream(handle, stream);

    // 3. Prepare COO data (example: M=32, K=32, nnz=10)
    int64_t M = 32;
    int64_t K = 32;
    int64_t N = 128;
    int64_t nnz = 10;
    int32_t numCores = 8;

    std::vector<int32_t> hCooRows(nnz, 0);
    std::vector<int32_t> hCooCols(nnz, 0);
    std::vector<uint16_t> hCooVals(nnz, 0);
    // ... Fill COO data ...

    // 4. Upload COO data to the device
    void *dCooRows = nullptr;
    void *dCooCols = nullptr;
    void *dCooVals = nullptr;
    aclrtMalloc(&dCooRows, nnz * sizeof(int32_t), ACL_MEM_MALLOC_HUGE_FIRST);
    aclrtMalloc(&dCooCols, nnz * sizeof(int32_t), ACL_MEM_MALLOC_HUGE_FIRST);
    aclrtMalloc(&dCooVals, nnz * sizeof(uint16_t), ACL_MEM_MALLOC_HUGE_FIRST);
    aclrtMemcpy(dCooRows, nnz * sizeof(int32_t), hCooRows.data(),
                nnz * sizeof(int32_t), ACL_MEMCPY_HOST_TO_DEVICE);
    aclrtMemcpy(dCooCols, nnz * sizeof(int32_t), hCooCols.data(),
                nnz * sizeof(int32_t), ACL_MEMCPY_HOST_TO_DEVICE);
    aclrtMemcpy(dCooVals, nnz * sizeof(uint16_t), hCooVals.data(),
                nnz * sizeof(uint16_t), ACL_MEMCPY_HOST_TO_DEVICE);

    // 5. Create the Cube SpMM sparse matrix descriptor
    aclsparseCubeSpmmMatDescr_t matA = nullptr;
    aclsparseCreateCubeSpmmMat(&matA, M, K, nnz, 16, 16, numCores);

    // 6. Generate dense B (on the host)
    std::vector<uint16_t> hB(static_cast<size_t>(K) * N, 0);
    // ... Fill B ...

    // 7. Preprocessing: COO -> BCSR
    aclsparseCubeSpmmPreprocess(
        handle, nullptr, matA,
        static_cast<const int32_t *>(dCooRows),
        static_cast<const int32_t *>(dCooCols),
        static_cast<const uint16_t *>(dCooVals),
        ACL_FLOAT);

    // 8. Perform padding alignment on B: one-pass H2D copy from host to device
    int64_t nPad = 0;
    void *dBPad = nullptr;
    aclsparseCubeSpmmPadDenseMatrixB(
        handle, K, N, N, hB.data(),
        ACL_FLOAT16, ACL_SPARSE_ORDER_ROW,
        &nPad, &dBPad);

    // 9. Create the B/C dense descriptors after padding
    aclsparseDnMatDescr_t matB = nullptr;
    aclsparseDnMatDescr_t matC = nullptr;
    void *dC = nullptr;
    aclrtMalloc(&dC, M * nPad * sizeof(float), ACL_MEM_MALLOC_HUGE_FIRST);
    aclrtMemset(dC, M * nPad * sizeof(float), 0, M * nPad * sizeof(float));

    aclsparseCreateDnMat(&matB, K, nPad, nPad, dBPad,
                         ACL_FLOAT16, ACL_SPARSE_ORDER_ROW);
    aclsparseCreateDnMat(&matC, M, nPad, nPad, dC,
                         ACL_FLOAT, ACL_SPARSE_ORDER_ROW);

    // 10. Query the workspace (fixed to 0 in the current implementation) and execute SpMM
    size_t workspaceSize = 0;
    aclsparseCubeSpmmGetBufferSize(
        handle, nullptr, matA, matB, nullptr, matC,
        ACL_FLOAT, &workspaceSize);

    aclsparseCubeSpmm(
        handle, nullptr, matA, matB, nullptr, matC,
        ACL_FLOAT, nullptr);

    aclrtSynchronizeStream(stream);

    // 11. Clean up resources
    aclsparseDestroyDnMat(matC);
    aclsparseDestroyDnMat(matB);
    aclsparseDestroyCubeSpmmMat(matA);
    aclrtFree(dC);
    aclrtFree(dBPad);
    aclrtFree(dCooRows);
    aclrtFree(dCooCols);
    aclrtFree(dCooVals);
    aclsparseDestroy(handle);
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return 0;
}