| Files | Last commit | Last update |
|---|---|---|
SDDMM Operator
Operator Overview
SDDMM (Sampled Dense-Dense Matrix Multiplication) computes the product of two dense matrices only at the pattern positions of the sparse matrix C and writes the result back in place to the values array of C. The API semantics refer to cusparseSDDMM of the cuSPARSE Generic API.
This directory contains the implementations of Atlas A2 products and Atlas A3 products (arch22/) and Ascend 950PR&950DT products (arch35/).
The following text describes the arch35 implementation in detail. For the support matrix, preprocessing, and stream conventions of Atlas A2 products and Atlas A3 products, see
arch22 description. Both architectures support CSR/BSR, base 0/1,
host/device scalars, complex numbers, empty matrices, and BSR strided batch, and specific restrictions follow the description of each architecture.
The mathematical expression:
C_out = (alpha * op(X) * op(Y) + beta * C) ∘ spy(C)
where:
op(X)is m×k andop(Y)is k×n. X/Y support ROW/COL layouts and NON_TRANSPOSE/TRANSPOSE. The original descriptor shapes are determined by the operation flags: whenopX=NON_TRANSPOSE, X is m×k; whenopX=TRANSPOSE, X is k×m. WhenopY=NON_TRANSPOSE, Y is k×n; whenopY=TRANSPOSE, Y is n×k- C is an m×n CSR or square-block BSR sparse matrix, and spy(C) is the fixed sparse pattern
- ∘ denotes the Hadamard product (element-wise multiplication), that is, the computation result is stored only at the non-zero positions of C
- alpha and beta are computeType scalars, and their memory locations are determined by the pointer mode of the handle
For each non-zero element of CSR and each element within a non-zero block of BSR (logical row i and column j), the operator computes the K-dimensional dot product of op(X)[i,:] and op(Y)[:,j], and the result is alpha * dot + beta * old_value, written back in place to the corresponding values. When beta=0, the old values are not read.
The invocation process is a three-step method:
- BufferSize: query the required workspace size
- Preprocess (optional): verify row offsets/column indices on the device, and bind the complete pattern state to the matC descriptor
- Execute: execute the sampled matrix multiplication, and the result updates the values array of C in place
This operator includes the following APIs:
| API | Brief Description |
|---|---|
| aclsparseSDDMMBufferSize | Queries the workspace size (bytes) required by SDDMM |
| aclsparseSDDMMPreprocess | Verifies the pattern and establishes the descriptor-local prepared state |
| aclsparseSDDMM | Executes the sampled matrix multiplication C_out = (alpha * op(X) * op(Y) + beta * C) ∘ spy(C), and automatically preprocesses when the prepared state is not hit |
| aclsparseCreateBsr / aclsparseCreateConstBsr | Creates mutable/const BSR descriptors |
| aclsparseBsrSetStridedBatch | Sets the structure and value batch strides of BSR |
| aclsparseDnMatGetStridedBatch / aclsparseDnMatSetStridedBatch | Queries or sets the batch attributes of a dense matrix |
Implementation directory
The arch35 implementation is organized by host, device, and sparse format:
arch35/
├── host/
│ ├── sddmm_host.cpp # Three-phase APIs, parameter verification, and execution planning
│ └── sddmm_pattern_host.h # Verification core-splitting planning and host result merging
├── kernels/
│ ├── csr/
│ │ ├── sddmm_csr_cube_kernel.cpp
│ │ ├── sddmm_csr_cube_kernel.h
│ │ ├── sddmm_csr_cube_gather_kernel.h
│ │ ├── sddmm_csr_cube_traits.h
│ │ ├── sddmm_column_vector_kernel.h
│ │ └── sddmm_packed_vector_kernel.h
│ ├── bsr/
│ │ ├── sddmm_bsr_cube_kernel.cpp
│ │ ├── sddmm_complex_bsr_cube_kernel.cpp
│ │ └── sddmm_bsr8_vector_kernel.h
│ └── shared/
│ ├── sddmm_kernel.cpp # Common CSR/BSR scheduling, verification, packing, and SIMT computation
│ ├── sddmm_complex_row_kernel.cpp
│ ├── sddmm_device_math.h
│ ├── sddmm_pattern_validator.h # Pattern verification sharded by row, column, and batch
│ └── sddmm_simt_convert.h
├── sddmm.h # Compatibility entry
├── sddmm_kernel.h # Launch declarations shared by host/device
├── sddmm_tiling_data.h # Common data layout and constants
├── sddmm_bsr8_common.h
├── sddmm_bsr_cube_common.h
├── sddmm_complex_bsr_cube_common.h
├── sddmm_complex_row_common.h
└── sddmm_csr_cube_common.h # Planning, constraints, and launch declarations shared by all paths
The *_common.h files in the root directory are shared by the host and device and do not contain independent computation kernel implementations.
The build system recursively collects .cpp files of the current architecture, and implementation files reference cross-directory header files through relative paths.
PyTorch Interface
On Ascend 950PR&950DT products, use torch.sparse.sampled_addmm through the unified cann_ops_sparse wheel:
import torch
import torch_npu
import cann_ops_sparse
result = torch.sparse.sampled_addmm(pattern, mat1, mat2, alpha=1.0, beta=0.0)
# Write the result into the specified CSR tensor:
torch.sparse.sampled_addmm(pattern, mat1, mat2, out=result)
pattern is an NPU CSR tensor, and mat1 and mat2 are dense tensors on the same device and of the same type.
FP16, FP32, complex64, and int32/int64 indexes are supported, and the output retains the CSR pattern.
The default entry returns an independent result, and out=pattern updates values in place.
import cann_ops_sparse completes the public API registration, and the C++ wrapper is JIT compiled at the first NPU call.
For building and API specifications, see Torch Extension Interface Description,
and for function test steps, see SDDMM Test Description.
Operator Execution APIs
aclsparseSDDMMBufferSize
Product support
- Ascend 950PR&950DT products: Supported
- Atlas A3 products: Supported
- Atlas A2 products: Supported
Function prototype
aclsparseStatus_t aclsparseSDDMMBufferSize(
aclsparseHandle_t handle, aclsparseOperation_t opX, aclsparseOperation_t opY,
const void *alpha, aclsparseConstDnMatDescr_t matX, aclsparseConstDnMatDescr_t matY,
const void *beta, aclsparseSpMatDescr_t matC, aclDataType computeType,
aclsparseSDDMMAlg_t alg, size_t *size)
Parameter description
| Parameter | Input/Output | Type | Description |
|---|---|---|---|
| handle | Input | aclsparseHandle_t | Context handle of the ops-sparse library, carrying the stream, host memory |
| opX | Input | aclsparseOperation_t | Operation type of dense matrix X, supporting ACL_SPARSE_OP_NON_TRANSPOSE or ACL_SPARSE_OP_TRANSPOSE; conjugate transpose is not supported, host memory |
| opY | Input | aclsparseOperation_t | Operation type of dense matrix Y, supporting ACL_SPARSE_OP_NON_TRANSPOSE or ACL_SPARSE_OP_TRANSPOSE; conjugate transpose is not supported, host memory |
| alpha | Input | const void* | Scalar alpha pointer whose type must match computeType. The memory location is controlled by aclsparseSetPointerMode, host/device memory |
| matX | Input | aclsparseConstDnMatDescr_t | Descriptor of dense matrix X: m×k when opX=NON_TRANSPOSE, and k×m when opX=TRANSPOSE, host memory |
| matY | Input | aclsparseConstDnMatDescr_t | Descriptor of dense matrix Y: k×n when opY=NON_TRANSPOSE, and n×k when opY=TRANSPOSE, host memory |
| beta | Input | const void* | Scalar beta pointer whose type must match computeType. The memory location is controlled by aclsparseSetPointerMode, host/device memory |
| matC | Input/Output | aclsparseSpMatDescr_t | Mutable CSR/BSR descriptor of sparse matrix C, with a read-only pattern and values updated in place, host memory |
| computeType | Input | aclDataType | Accumulation and alpha/beta type. arch35 supports only ACL_FLOAT or ACL_COMPLEX64; passing other types such as ACL_FLOAT16 returns ACL_SPARSE_STATUS_NOT_SUPPORTED (matC values can be FP16/BF16; see the combinations in the following table), host memory |
| alg | Input | aclsparseSDDMMAlg_t | Algorithm type, supporting only ACL_SPARSE_SDDMM_ALG_DEFAULT, host memory |
| size | Output | size_t* | Outputs the required workspace size (bytes), host memory |
Constraints
- handle cannot be nullptr
- None of alpha, beta, or size can be nullptr
- None of matX, matY, or matC can be nullptr
- matC supports CSR or square-block BSR, and both row offsets and column indices must be
ACL_SPARSE_INDEX_32I - For arch35 CSR, the element strides of row offsets, column indices, and values must all be 1. Non-contiguous CSR returns
ACL_SPARSE_STATUS_NOT_SUPPORTED - The index base supports
ACL_SPARSE_INDEX_BASE_ZEROandACL_SPARSE_INDEX_BASE_ONE - The BSR block height and block width must be equal, supporting 2/4/8/16/32/64/128, and the intra-block layout supports ROW/COL
- opX supports
ACL_SPARSE_OP_NON_TRANSPOSEorACL_SPARSE_OP_TRANSPOSEand does not support conjugate transpose. Passing conjugate transpose returnsACL_SPARSE_STATUS_NOT_SUPPORTED - opY supports
ACL_SPARSE_OP_NON_TRANSPOSEorACL_SPARSE_OP_TRANSPOSEand does not support conjugate transpose. Passing conjugate transpose returnsACL_SPARSE_STATUS_NOT_SUPPORTED - The arch35 data type combinations are shown in the following table. The types of X and Y must be the same, and combinations not in the table return
ACL_SPARSE_STATUS_NOT_SUPPORTED
| matC Format | X/Y | C values | computeType |
|---|---|---|---|
| CSR/BSR | ACL_FLOAT | ACL_FLOAT | ACL_FLOAT |
| CSR/BSR | ACL_COMPLEX64 | ACL_COMPLEX64 | ACL_COMPLEX64 |
| CSR/BSR | ACL_FLOAT16 | ACL_FLOAT16 | ACL_FLOAT |
| CSR/BSR | ACL_FLOAT16 | ACL_FLOAT | ACL_FLOAT |
| CSR | ACL_BF16 | ACL_FLOAT | ACL_FLOAT |
| BSR | ACL_BF16 | ACL_BF16 | ACL_FLOAT |
| BSR | ACL_BF16 | ACL_FLOAT | ACL_FLOAT |
- The dimensions must satisfy
op(X).shape=[m,k],op(Y).shape=[k,n], andC.shape=[m,n]. Therefore, whenopX=NON_TRANSPOSE, X is m×k; whenopX=TRANSPOSE, X is k×m. WhenopY=NON_TRANSPOSE, Y is k×n; whenopY=TRANSPOSE, Y is n×k. - The scale upper limits and return codes are distinguished by descriptor type, platform, and verification phase:
- Descriptor creation phase:
aclsparseCreateDnMatreturnsACL_SPARSE_STATUS_INVALID_VALUEforrows/cols > INT32_MAX.aclsparseCreateBsrreturns this code forblockRows > INT32_MAX - 1,blockCols > INT32_MAX, orblockNnz > INT32_MAX - indexBase.aclsparseCreateCsrdoes not verify these I32 upper limits at the creation phase. - The host input parameter verification shared by the three SDDMM phases (BufferSize / Preprocess / Execute) handles CSR overflow per the following table. Each item in the table assumes that other parameters are valid.
- Descriptor creation phase:
| Platform | CSR Upper Limit | Overflow Return Code |
|---|---|---|
| Atlas A2 products and Atlas A3 products (arch22) | rows ≤ INT32_MAX - 1, cols ≤ INT32_MAX, nnz ≤ INT32_MAX - 1 |
ACL_SPARSE_STATUS_INVALID_VALUE |
| Ascend 950PR&950DT products (arch35) | rows/cols ≤ INT32_MAX, nnz ≤ INT32_MAX - indexBase |
ACL_SPARSE_STATUS_NOT_SUPPORTED |
- The dimensions of X/Y (including k), the leading dimensions, and the byte spans must also pass the dense descriptor verification of each platform. When X/Y dimensions beyond the I32 range are passed through the public creation APIs,
ACL_SPARSE_STATUS_INVALID_VALUEis returned first at the descriptor creation phase. - arch35 supports dynamic shapes, empty rows, and zero nnz. When m or n is 0, the pattern must be empty and all three phases return successfully. When k is 0, the output is beta * C (the old values are not read when beta is 0). arch22 returns
ACL_SPARSE_STATUS_INVALID_VALUEfor inputs where any dimension of X/Y/C is 0 - The workspace requires 64-byte alignment. When m or n is 0, it is 0 bytes. When both m and n are greater than 0 (including k being 0), the regular path is a 64-byte pattern verification area. When reuse conditions are met, such as contiguous ROW/ROW, opX/opY=N, CSR FP32/FP16, or single-batch BSR b8/K128, BufferSize additionally returns the dynamic scratch required for transposed packing of Y. The packed-Y reserved size does not exceed 64 MiB including the prefix and alignment. The execution branches of CSR packed-Y and CSR Cube scratch are mutually exclusive and share the same private offset. Only when CSR Cube needs more space than the generic path does BufferSize check the actual device pattern and first-column alignment on the handle stream. On a hit, it reserves the maximum of the two; on a fallback, it returns only the generic capacity. This check uses the AIV core count obtained at runtime for parallel determination, and each active core exclusively owns a 64-byte temporary result slot, with a total size of
64 × min(*AIV core count*, m)bytes. Results are merged after one synchronous readback, and no workspace of other operators is occupied, nor does it replace the complete pattern verification of the subsequent Preprocess. The real BSR Cube and complex64 split-real Cube use their own bounded private layouts. All areas are aligned upward to 64 bytes. The private area upper limits of the real BSR Cube and CSR Cube remain 64 MiB, and the private area upper limit of the complex64 BSR path is 128 MiB minus 64 bytes, with the additional constraint that the total common workspace including the verification prefix and alignment does not exceed 128 MiB - The complex64 BSR Cube queries the L0A/L0B byte capacity of the platform on the host and checks the space requirements of the current tile (including the B16/K128 grouped path). When the capacity is insufficient or a valid capacity cannot be obtained, the generic path is used. This check is performed in the shared planning of BufferSize, Preprocess, and Execute, and the Cube private area is not reserved on the first query fallback.
- Each successful BufferSize query of arch35 replaces the capacity plan of matC and invalidates the old prepared state. The buffer passed in afterwards must satisfy the size of this query. You must query again after metadata changes such as shape, layout, dtype, base, or batch. The allocated capacity can be reused only when the pattern is modified in place or index pointers of the same specification are replaced, but re-preprocessing is required. Even if the new pattern fits the Cube, it is enabled only when the original capacity is sufficient. Changes to alpha/beta or the pointer mode do not expand the capacity. The pattern check of BufferSize does not replace the re-verification of the current index content by Preprocess.
- When parallel pattern checking is needed and no AIV core is available,
ACL_SPARSE_STATUS_INSUFFICIENT_RESOURCESis returned. Temporary area allocation failure returnsACL_SPARSE_STATUS_ALLOC_FAILED, and verification synchronization, readback, or release failure returnsACL_SPARSE_STATUS_EXECUTION_FAILED. A failed query does not replace the existing capacity plan. When synchronization fails, the descriptor retains the temporary area, and subsequent SDDMM calls first attempt to synchronize and release it. When synchronization still cannot complete at descriptor destruction, the allocation is retained to avoid releasing space still being written by the device. - The arch35 Preprocess (including cold Execute automatic preprocessing) trims the verification core count by the runtime AIV core count and the index count, and small tasks use a single core. offsets are checked for adjacent boundaries by row ranges, columns are checked by independent index ranges, and non-shared batch patterns also participate in sharding. When both offsets/columns are broadcast, only one structure is checked. Each core writes to an independent 64-byte temporary result slot, and the host merges the state and pattern attributes after the synchronous readback and then updates the original workspace prefix, without increasing the user workspace capacity already queried by BufferSize. Errors are still determined by the earliest failing batch and, within that batch, by the order of endpoints, offsets, and columns. The prepared state is not established on failure.
- The DnMat/BSR batchCount range is 1..65535. X/Y can be batch 1 broadcast or the same as the C batch. A BSR offsets/columns stride of 0 indicates a shared pattern, and values do not allow cross-batch broadcast
Semantic mapping with cuSPARSE opB (migration note)
The formula of this operator is
C = (α·op(X)·op(Y) + βC) ∘ spy(C).opXandopYdetermine the original shapes of the X and Y descriptors and the effective shapes participating in the product respectively: whenopX=NON_TRANSPOSE, X is m×k; whenopX=TRANSPOSE, X is k×m. WhenopY=NON_TRANSPOSE, Y is k×n; whenopY=TRANSPOSE, Y is n×k. The semantics of op(A)/op(B) in cuSPARSEcusparseSDDMMare consistent with opX/opY of this API respectively, and the mapping of opY is as follows:
opY of This API Actually Computed Product Equivalent cuSPARSE opB ACL_SPARSE_OP_NON_TRANSPOSEop(X)·Y (Y descriptor k×n) CUSPARSE_OPERATION_NON_TRANSPOSEACL_SPARSE_OP_TRANSPOSEop(X)·Y^T (Y descriptor n×k) CUSPARSE_OPERATION_TRANSPOSEWhen migrating from cuSPARSE, the operation flag semantics of the second dense matrix are consistent and can be passed in directly: for scenarios where cuSPARSE uses
opB=NON_TRANSPOSE, passopY=NON_TRANSPOSEto this API; for scenarios where cuSPARSE usesopB=TRANSPOSE, passopY=TRANSPOSEto this API.
Supported sparse formats
| Format | Supported | Description |
|---|---|---|
| CSR | ✅ | I32 index, base 0/1 |
| BSR | ✅ | Square-block BSR, ROW/COL intra-block layouts, and strided batch. For constraints of Atlas A2 products and Atlas A3 products, see the arch22 description |
| COO | ❌ | Not supported. arch35 returns ACL_SPARSE_STATUS_MATRIX_TYPE_NOT_SUPPORTED, and Atlas A2/A3 return ACL_SPARSE_STATUS_NOT_SUPPORTED |
| CSC | ❌ | Not supported. arch35 returns ACL_SPARSE_STATUS_MATRIX_TYPE_NOT_SUPPORTED, and Atlas A2/A3 return ACL_SPARSE_STATUS_NOT_SUPPORTED |
aclsparseSDDMMPreprocess
Product support
- Ascend 950PR&950DT products: Supported
- Atlas A3 products: Supported
- Atlas A2 products: Supported
Function prototype
aclsparseStatus_t aclsparseSDDMMPreprocess(
aclsparseHandle_t handle, aclsparseOperation_t opX, aclsparseOperation_t opY,
const void *alpha, aclsparseConstDnMatDescr_t matX, aclsparseConstDnMatDescr_t matY,
const void *beta, aclsparseSpMatDescr_t matC, aclDataType computeType,
aclsparseSDDMMAlg_t alg, void *buffer)
Parameter description
| Parameter | Input/Output | Type | Description |
|---|---|---|---|
| handle | Input | aclsparseHandle_t | Context handle of the ops-sparse library, carrying the stream, host memory |
| opX | Input | aclsparseOperation_t | Operation type of dense matrix X, supporting ACL_SPARSE_OP_NON_TRANSPOSE or ACL_SPARSE_OP_TRANSPOSE; conjugate transpose is not supported, host memory |
| opY | Input | aclsparseOperation_t | Operation type of dense matrix Y, supporting ACL_SPARSE_OP_NON_TRANSPOSE or ACL_SPARSE_OP_TRANSPOSE, host memory |
| alpha | Input | const void* | Scalar alpha pointer. The memory location is controlled by aclsparseSetPointerMode, host/device memory |
| matX | Input | aclsparseConstDnMatDescr_t | Descriptor of dense matrix X: m×k when opX=NON_TRANSPOSE, and k×m when opX=TRANSPOSE, host memory |
| matY | Input | aclsparseConstDnMatDescr_t | Descriptor of dense matrix Y: k×n when opY=NON_TRANSPOSE, and n×k when opY=TRANSPOSE, host memory |
| beta | Input | const void* | Scalar beta pointer. The memory location is controlled by aclsparseSetPointerMode, host/device memory |
| matC | Input/Output | aclsparseSpMatDescr_t | Mutable CSR/BSR descriptor of sparse matrix C, host memory |
| computeType | Input | aclDataType | Accumulation and alpha/beta type. arch35 supports ACL_FLOAT or ACL_COMPLEX64, host memory |
| alg | Input | aclsparseSDDMMAlg_t | Algorithm type, supporting only ACL_SPARSE_SDDMM_ALG_DEFAULT, host memory |
| buffer | Input | void* | Workspace buffer (allocated by the size returned by BufferSize), device memory |
Constraints
- The constraints are the same as those of aclsparseSDDMMBufferSize (including return codes for unsupported combinations and overflow; see above for the phase each return code belongs to)
- When BufferSize is non-zero, buffer cannot be nullptr, must be allocated by the query result, and must satisfy 64-byte alignment
- Preprocessing verifies the endpoints and monotonicity of CSR/BSR offsets and the range of column indices on the calling stream, and caches the pattern flags and first-column information used for path selection
- The prepared state belongs to the matC descriptor, and the complete key contains the pattern pointer, structure generation, shape, base, block/layout, batch, X/Y metadata, algorithm, and workspace
- Values-only updates do not invalidate the pattern state, while actual changes to structure pointers or structure attributes invalidate it. If the caller modifies the offsets/columns content in place, Preprocess must be called again
- The caller manages the lifecycles of both matC and the workspace, and the implementation does not allocate or release the caller's workspace
Supported sparse formats
| Format | Supported | Description |
|---|---|---|
| CSR | ✅ | I32 index, base 0/1 |
| BSR | ✅ (Ascend 950PR&950DT products) | Square-block BSR, ROW/COL intra-block layouts, and strided batch |
| COO | ❌ | Not supported. arch35 returns ACL_SPARSE_STATUS_MATRIX_TYPE_NOT_SUPPORTED, and Atlas A2/A3 return ACL_SPARSE_STATUS_NOT_SUPPORTED |
| CSC | ❌ | Not supported. arch35 returns ACL_SPARSE_STATUS_MATRIX_TYPE_NOT_SUPPORTED, and Atlas A2/A3 return ACL_SPARSE_STATUS_NOT_SUPPORTED |
aclsparseSDDMM
Product support
- Ascend 950PR&950DT products: Supported
- Atlas A3 products: Supported
- Atlas A2 products: Supported
Function prototype
aclsparseStatus_t aclsparseSDDMM(
aclsparseHandle_t handle, aclsparseOperation_t opX, aclsparseOperation_t opY,
const void *alpha, aclsparseConstDnMatDescr_t matX, aclsparseConstDnMatDescr_t matY,
const void *beta, aclsparseSpMatDescr_t matC, aclDataType computeType,
aclsparseSDDMMAlg_t alg, void *buffer)
Parameter description
| Parameter | Input/Output | Type | Description |
|---|---|---|---|
| handle | Input | aclsparseHandle_t | Context handle of the ops-sparse library, carrying the stream, host memory |
| opX | Input | aclsparseOperation_t | Operation type of dense matrix X, supporting ACL_SPARSE_OP_NON_TRANSPOSE or ACL_SPARSE_OP_TRANSPOSE; conjugate transpose is not supported, host memory |
| opY | Input | aclsparseOperation_t | Operation type of dense matrix Y, supporting ACL_SPARSE_OP_NON_TRANSPOSE or ACL_SPARSE_OP_TRANSPOSE, host memory |
| alpha | Input | const void* | Scalar alpha pointer. The memory location is controlled by aclsparseSetPointerMode, host/device memory |
| matX | Input | aclsparseConstDnMatDescr_t | Descriptor of dense matrix X: m×k when opX=NON_TRANSPOSE, and k×m when opX=TRANSPOSE, host memory |
| matY | Input | aclsparseConstDnMatDescr_t | Descriptor of dense matrix Y: k×n when opY=NON_TRANSPOSE, and n×k when opY=TRANSPOSE, host memory |
| beta | Input | const void* | Scalar beta pointer. The memory location is controlled by aclsparseSetPointerMode, host/device memory |
| matC | Input/Output | aclsparseSpMatDescr_t | Mutable CSR/BSR descriptor of sparse matrix C, with values updated in place, host memory |
| computeType | Input | aclDataType | Accumulation and alpha/beta type. arch35 supports ACL_FLOAT or ACL_COMPLEX64, host memory |
| alg | Input | aclsparseSDDMMAlg_t | Algorithm type, supporting only ACL_SPARSE_SDDMM_ALG_DEFAULT, host memory |
| buffer | Input | void* | Workspace buffer (allocated by the size returned by BufferSize), device memory |
Constraints
- The constraints are the same as those of aclsparseSDDMMBufferSize
- When BufferSize is non-zero, buffer cannot be nullptr and must be consistent with the workspace in the prepared key
- Preprocess is an optional call. When Execute does not hit the prepared state, it automatically completes one preprocessing. This cold path synchronizes the current stream to return the structure verification state
- When the prepared state is hit, Execute does not perform host/device state movement or host synchronization. The regular path asynchronously launches the computation kernel, the contiguous-Y fast path asynchronously launches the packing and computation kernels in sequence, and the Cube fast path launches the preparation, Cube computation, and AIV epilogue kernels in sequence. The caller must synchronize the same stream before reading C values, and performance statistics must include all kernels issued by the same Execute call
- X/Y and the C pattern are read-only, and C values are updated in place. The caller serializes concurrent Preprocess/Execute on the same matC. Different matC objects can run independently in concurrency only when they use non-overlapping workspaces. Different streams must also use independent handles and satisfy their own stream ordering
Supported sparse formats
| Format | Supported | Description |
|---|---|---|
| CSR | ✅ | I32 index, base 0/1 |
| BSR | ✅ (Ascend 950PR&950DT products) | Square-block BSR, ROW/COL intra-block layouts, and strided batch |
| COO | ❌ | Not supported. arch35 returns ACL_SPARSE_STATUS_MATRIX_TYPE_NOT_SUPPORTED, and Atlas A2/A3 return ACL_SPARSE_STATUS_NOT_SUPPORTED |
| CSC | ❌ | Not supported. arch35 returns ACL_SPARSE_STATUS_MATRIX_TYPE_NOT_SUPPORTED, and Atlas A2/A3 return ACL_SPARSE_STATUS_NOT_SUPPORTED |
Invocation example
The example code is for reference only. For details about compilation and execution, see Compiling and Running a 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: allocate device memory and copy host data
static void* AllocAndCopyDevice(const void *hostPtr, size_t sizeBytes)
{
void *dPtr = nullptr;
aclError ret = aclrtMalloc(&dPtr, sizeBytes, ACL_MEM_MALLOC_HUGE_FIRST);
if (ret != ACL_SUCCESS) {
return nullptr;
}
if (hostPtr != nullptr && sizeBytes > 0) {
aclrtMemcpy(dPtr, sizeBytes, hostPtr, sizeBytes, ACL_MEMCPY_HOST_TO_DEVICE);
}
return dPtr;
}
int aclsparseSDDMMTest(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);
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 host-side data
// X (4x2): Y (3x2):
// [1.0 2.0] [1.0 0.0]
// [3.0 4.0] [0.0 1.0]
// [5.0 6.0] [1.0 1.0]
// [7.0 8.0]
//
// C (4x3, nnz=5), non-zero positions: (0,0)(0,2)(1,1)(2,0)(3,2), all initial values are 0
// C = 1.0 * X * Y^T ∘ spy(C) (beta=0):
// C[0,0]=X[0]·Y[0]=1.0 C[0,2]=X[0]·Y[2]=3.0
// C[1,1]=X[1]·Y[1]=4.0 C[2,0]=X[2]·Y[0]=5.0
// C[3,2]=X[3]·Y[2]=15.0
int64_t m = 4, n = 3, k = 2;
int64_t nnzC = 5;
float hAlpha = 1.0f;
float hBeta = 0.0f;
std::vector<int> hRowPtrC = {0, 2, 3, 4, 5};
std::vector<int> hColIndC = {0, 2, 1, 0, 2};
std::vector<float> hValC = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f};
// This example uses opX=NON_TRANSPOSE and opY=TRANSPOSE, so X is m×k (4x2) and Y is n×k (3x2).
// If the operation types are switched, the original descriptor shapes must also be switched accordingly: when opX=TRANSPOSE, X is k×m,
// and when opY=NON_TRANSPOSE, Y is k×n.
int64_t ldx = k, ldy = k;
aclsparseOrder_t orderX = ACL_SPARSE_ORDER_ROW;
aclsparseOrder_t orderY = ACL_SPARSE_ORDER_ROW;
std::vector<float> hX(static_cast<size_t>(m) * k, 0.0f);
hX[0 * k + 0] = 1.0f; hX[0 * k + 1] = 2.0f;
hX[1 * k + 0] = 3.0f; hX[1 * k + 1] = 4.0f;
hX[2 * k + 0] = 5.0f; hX[2 * k + 1] = 6.0f;
hX[3 * k + 0] = 7.0f; hX[3 * k + 1] = 8.0f;
std::vector<float> hY(static_cast<size_t>(n) * k, 0.0f);
hY[0 * k + 0] = 1.0f; hY[0 * k + 1] = 0.0f;
hY[1 * k + 0] = 0.0f; hY[1 * k + 1] = 1.0f;
hY[2 * k + 0] = 1.0f; hY[2 * k + 1] = 1.0f;
// 4. Copy data to the device
void *dRowPtrC = AllocAndCopyDevice(hRowPtrC.data(), (m + 1) * sizeof(int));
void *dColIndC = AllocAndCopyDevice(hColIndC.data(), nnzC * sizeof(int));
void *dValC = AllocAndCopyDevice(hValC.data(), nnzC * sizeof(float));
void *dX = AllocAndCopyDevice(hX.data(), static_cast<size_t>(m) * k * sizeof(float));
void *dY = AllocAndCopyDevice(hY.data(), static_cast<size_t>(n) * k * sizeof(float));
// 5. Create the descriptors
aclsparseSpMatDescr_t matC = nullptr;
sparseRet = aclsparseCreateCsr(&matC, m, n, nnzC, dRowPtrC, dColIndC, dValC,
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);
aclsparseDnMatDescr_t matX = nullptr, matY = nullptr;
sparseRet = aclsparseCreateDnMat(&matX, m, k, ldx, dX, ACL_FLOAT, orderX);
CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("aclsparseCreateDnMat X failed. ERROR: %d\n", sparseRet);
return sparseRet);
sparseRet = aclsparseCreateDnMat(&matY, n, k, ldy, dY, ACL_FLOAT, orderY);
CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("aclsparseCreateDnMat Y failed. ERROR: %d\n", sparseRet);
return sparseRet);
// 6. Step 1 — BufferSize
size_t bufferSize = 0;
sparseRet = aclsparseSDDMMBufferSize(
static_cast<aclsparseHandle_t>(handlePtr.get()),
ACL_SPARSE_OP_NON_TRANSPOSE, ACL_SPARSE_OP_TRANSPOSE,
&hAlpha, matX, matY, &hBeta, matC, ACL_FLOAT,
ACL_SPARSE_SDDMM_ALG_DEFAULT, &bufferSize);
CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("SDDMMBufferSize failed. ERROR: %d\n", sparseRet);
return sparseRet);
LOG_PRINT("bufferSize = %zu bytes\n", bufferSize);
void *dBuffer = nullptr;
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);
// 7. Step 2 — Preprocess
sparseRet = aclsparseSDDMMPreprocess(
static_cast<aclsparseHandle_t>(handlePtr.get()),
ACL_SPARSE_OP_NON_TRANSPOSE, ACL_SPARSE_OP_TRANSPOSE,
&hAlpha, matX, matY, &hBeta, matC, ACL_FLOAT,
ACL_SPARSE_SDDMM_ALG_DEFAULT, dBuffer);
CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("SDDMMPreprocess failed. ERROR: %d\n", sparseRet);
return sparseRet);
// 8. Step 3 — Execute (the result is written back in place to the values array of C)
sparseRet = aclsparseSDDMM(
static_cast<aclsparseHandle_t>(handlePtr.get()),
ACL_SPARSE_OP_NON_TRANSPOSE, ACL_SPARSE_OP_TRANSPOSE,
&hAlpha, matX, matY, &hBeta, matC, ACL_FLOAT,
ACL_SPARSE_SDDMM_ALG_DEFAULT, dBuffer);
CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("SDDMM failed. ERROR: %d\n", sparseRet);
return sparseRet);
// 9. Synchronize and wait for the computation to complete
aclRet = aclrtSynchronizeStream(stream);
CHECK_RET(aclRet == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", aclRet); return aclRet);
// 10. Copy the result back to the host and print it
aclRet = aclrtMemcpy(hValC.data(), static_cast<size_t>(nnzC) * sizeof(float),
dValC, static_cast<size_t>(nnzC) * 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 p = 0; p < nnzC; p++) {
LOG_PRINT("C_values[%lld] = %.1f\n", static_cast<long long>(p), hValC[p]);
}
// 11. Clean up resources
aclsparseDestroySpMat(matC);
aclsparseDestroyDnMat(matX);
aclsparseDestroyDnMat(matY);
if (dRowPtrC) aclrtFree(dRowPtrC);
if (dColIndC) aclrtFree(dColIndC);
if (dValC) aclrtFree(dValC);
if (dX) aclrtFree(dX);
if (dY) aclrtFree(dY);
if (dBuffer) aclrtFree(dBuffer);
return ACL_SPARSE_STATUS_SUCCESS;
}
int main()
{
AclContext ctx(0);
auto ret = ctx.Init();
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = aclsparseSDDMMTest(ctx);
CHECK_RET(ret == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("aclsparseSDDMMTest failed. ERROR: %d\n", ret); return ret);
return 0;
}
The expected output is as follows:
bufferSize = 64 bytes
C_values[0] = 1.0
C_values[1] = 3.0
C_values[2] = 4.0
C_values[3] = 5.0
C_values[4] = 15.0
Precision Standard
The precision verification of the SDDMM operator uses the framework MIXED_TOLERANCE mode (test/frame/verify.h::applyMixedTolerance + Verifier::verifyVector), which automatically selects atol/rtol and maxAbsErrLimit by data type:
- Per-element pass condition:
|actual - golden| ≤ max(atol + rtol * |golden|, maxAbsErrLimit), wheremaxAbsErrLimit = max(fixedValue, 32 * ULP(golden))andULP(x) = 2^(floor(log2|x|) - mantissaBits). - Overall pass condition:
matchedRatio ≥ 0.99.
| Data Type | rtol (relative tolerance) | atol (absolute tolerance) | maxAbsErrLimit fixedValue |
|---|---|---|---|
| FLOAT16 | 1.953125e-3 (2^-9) | 1.953125e-3 (2^-9) | 1e-1 |
| BFLOAT16 | 1.5625e-2 (2^-6) | 1.5625e-2 (2^-6) | 1.0 |
| FLOAT32 | 9.765625e-4 (2^-10) | 1.52587890625e-5 (2^-23) | 1e-2 |
The real and imaginary parts of complex64 are compared separately by the FLOAT32 rules. The CPU golden result uses complex128. FP16/BF16 inputs use FP32 computation and accumulation, and FP32 inputs use the FP64 golden result.
Description: FP16 write-back follows IEEE conversion semantics. When a finite FP32 result exceeds the FP16 range, a signed Inf is obtained, and 65504 saturation truncation is not performed. Inf/NAN values are accepted by the ecosystem operator precision standard.
Supported Chips
- Ascend 950PR&950DT products (architecture arch35 / DAV_3510)
- Atlas A3 products: Supported
- Ascend 910B (architecture arch22 / DAV_2201): corresponding to Atlas A2 products