| Files | Last commit | Last update |
|---|---|---|
aclsparseSparseToDense Operator
This document is intended for users of the
ops-sparseAPIs.
Function Description
SparseToDense converts a sparse matrix in CSR, CSC, or COO format to a dense matrix. The API semantics align with cusparseSparseToDense_bufferSize and cusparseSparseToDense of the cuSPARSE Generic API. It is recommended that you call the APIs in two phases: querying the workspace and executing the conversion.
The operator computes the following expression:
Bij={Aijif (i,j)∈nnz(A)0otherwiseB_{ij} = \begin{cases} A_{ij} & \text{if } (i,j) \in \text{nnz}(A) \\ 0 & \text{otherwise} \end{cases}
where:
- AA is an m×nm \times n sparse matrix (CSR / CSC / COO format)
- BB is an m×nm \times n dense matrix (output, row-major or column-major)
Main features:
- Pure data movement: the kernel only performs the scatter write operation
B[idx] = A.val[p], with no arithmetic operations and no type conversion, and the input and output have the same dtype, so there is zero precision loss (bit-exact) - Three-format support: three sparse formats, CSR, CSC, and COO, automatically routed by the
formatfield of the descriptor - Reg first (asc-devkit): arch35 uses
AscendC::Reg::Scatter/Duplicateto write back discretely within UB strips and thenDataCopyPad; mixing with SIMT is forbidden - Multi-core parallelism: AI Cores are split by the primary axis of the output layout (ROW→rows / COL→columns), and the secondary axis splits UB strips by
tileLen - Output of the same type for all dtypes: data is read and written directly in the original dtype without float intermediate conversion, including COMPLEX64 (bit-copy by uint64)
- Asynchronous execution support: both APIs return asynchronously, and the caller is responsible for synchronization through the stream
- Zero workspace:
bufferSizealways returns 0 - Row/column-major output support: specified through
aclsparseOrder_t, and any leading dimension (ld) is supported
Architecture Support
| Architecture | Hardware | Implementation Directory | Description |
|---|---|---|---|
| arch35 | Ascend 950PR&950DT products | arch35/ |
Reg-first scatter; memset zeroing; no data-level verification |
| arch22 | Atlas A2 products (training products, 910B3/910B4) and Atlas A3 products (training products, 910_93), DAV_2201 | arch22/ |
Zeroing + scatter dual kernels; host verification chain (CheckMeta → coordinate verification → FillTiling). Out-of-range coordinates or invalid offsets are rejected, and duplicate coordinates are legal (the result takes any written value) |
For both architectures, bufferSize always returns 0 (zero workspace protocol). aclsparse API layer: duplicate (row, col) pairs (direct duplicates in COO and expanded duplicates within segments in CSR/CSC) are legal, and the result takes any written value (the write order is non-deterministic in a parallel environment; this implementation explicitly defines this convention, and cuSPARSE does not promise correctness for duplicate indexes). Out-of-range coordinates still return ACL_SPARSE_STATUS_INVALID_VALUE, and unordered coordinates are acceptable. torch_extension layer: following the summation semantics of PyTorch Tensor.to_dense for duplicate coordinates in uncoalesced COO, all SoCs are pre-merged before entering the native operator (see torch_extension/sparse2dense.py). Duplicates within CSR/CSC segments likewise take any written value at the torch layer. arch22 natively accepts uncoalesced COO tensors (a C API capability; the torch_extension layer pre-merges uniformly before entering).
Interface Prototype
aclsparseStatus_t aclsparseSparseToDense_bufferSize(
aclsparseHandle_t handle,
aclsparseConstSpMatDescr_t matA,
aclsparseDnMatDescr_t matB,
aclsparseSparseToDenseAlg_t alg,
size_t *bufferSize);
aclsparseStatus_t aclsparseSparseToDense(
aclsparseHandle_t handle,
aclsparseConstSpMatDescr_t matA,
aclsparseDnMatDescr_t matB,
aclsparseSparseToDenseAlg_t alg,
void *buffer);
matA is a read-only sparse matrix descriptor, and matB is a mutable dense matrix descriptor. The APIs do not modify matA
or its data.
Parameter Description
The common parameters of the two APIs are as follows.
| Parameter | Memory Location | Direction | Type | Description |
|---|---|---|---|---|
handle |
Host | Input | aclsparseHandle_t |
ops-sparse context handle, carrying the execution stream; cannot be empty |
matA |
Host descriptor; data on device | Input | aclsparseConstSpMatDescr_t |
Sparse matrix A, containing the format, row/column counts, index type, indexBase, value type, and data pointers |
matB |
Host descriptor; data on device | Input/Output | aclsparseDnMatDescr_t |
Dense matrix B, containing the row count, column count, ld, layout, data type, and data pointer; written during execution |
alg |
Host | Input | aclsparseSparseToDenseAlg_t |
Only ACL_SPARSE_SPARSETODENSE_ALG_DEFAULT is supported |
The specific parameters of each API are as follows.
| API | Parameter | Memory Location | Direction | Description |
|---|---|---|---|---|
bufferSize |
bufferSize |
Host | Output | Workspace size in bytes; cannot be empty. Currently, it always returns 0 |
execute |
buffer |
Device | Input | workspace; can be empty when bufferSize == 0 |
Recommended Invocation Process
- Create the handle, the sparse matrix descriptor
matA, and the dense matrix descriptormatB. - Call
aclsparseSparseToDense_bufferSizeand allocate the device workspace by the returned size (currently always 0, so this step can be skipped). - Call
aclsparseSparseToDenseto execute the conversion. - Synchronize the stream bound to the handle, and read the result.
Sparse Format Semantics
| Format | matA Descriptor Fields |
Description |
|---|---|---|
| CSR | ptrs=rowOffsets(m+1), idxs=colInd(nnz) |
Compressed by row; the kernel splits multi-cores by row |
| CSC | ptrs=colOffsets(n+1), idxs=rowInd(nnz) |
Compressed by column; the kernel splits multi-cores by column |
| COO | ptrs=cooRowInd(nnz), idxs=cooColInd(nnz) |
Coordinate format; the kernel splits by nnz in grid-stride mode |
Both ptrType and IdxType of CSR/CSC must be ACL_SPARSE_INDEX_32I. The cooIdxType
of COO must be ACL_SPARSE_INDEX_32I. All formats support ACL_SPARSE_INDEX_BASE_ZERO and
ACL_SPARSE_INDEX_BASE_ONE.
Duplicate (row, col) pairs (direct duplicates in COO and expanded duplicates within segments in CSR/CSC) are legal, and the result is any one of the values (the write order is non-deterministic in a parallel environment; this implementation explicitly defines this convention, and cuSPARSE does not promise correctness for duplicate indexes). After base conversion, coordinates must still fall within [0, rows) × [0, cols). Out-of-range coordinates return a parameter error in the host verification chain, and no kernel is launched. The torch_extension layer pre-merges duplicate coordinates of uncoalesced COO by the summation semantics of PyTorch to_dense (see torch_extension/sparse2dense.py); duplicates within CSR/CSC segments likewise take any written value at the torch layer.
Supported Data Types
The arch35 implementation supports the following value types, and the value types of matA and matB must be the same.
| Data Type | Enum | Element Size |
|---|---|---|
| float32 | ACL_FLOAT |
4B |
| float16 | ACL_FLOAT16 |
2B |
| bfloat16 | ACL_BF16 |
2B |
| int32 | ACL_INT32 |
4B |
| int8 | ACL_INT8 |
1B |
| complex64 | ACL_COMPLEX64 |
8B (bit-copy by uint64_t on the Reg path) |
The arch22 implementation supports the following value types (no int32, including complex64), and the value types of matA and matB must be the same.
| Data Type | Enum | Element Size |
|---|---|---|
| float32 | ACL_FLOAT |
4B |
| float16 | ACL_FLOAT16 |
2B |
| bfloat16 | ACL_BF16 |
2B |
| int8 | ACL_INT8 |
1B |
| complex64 | ACL_COMPLEX64 |
8B |
Neither architecture supports float64, and passing an unsupported type returns ACL_SPARSE_STATUS_NOT_SUPPORTED.
Numerical, Layout, and Boundary Semantics
- Both
ACL_SPARSE_ORDER_ROW(row-major) andACL_SPARSE_ORDER_COL(column-major) are supported. Row-major requiresld >= n, and column-major requiresld >= m. - The leading dimension (ld) can be greater than the minimum value (that is, stride padding is allowed) to satisfy alignment requirements.
- The value types of matA and matB must be consistent, and cross-type conversion is not supported. The kernel reads and writes in the original dtype, ensuring bit-exact results without precision loss.
- The device memory of matB is zeroed internally by the operator (arch35: the hot path is SIMT uint64 grid-stride, and
nnz=0/empty matrices useaclrtMemsetAsync; arch22: the zeroing kernel covers all storage buffers including ld padding). The caller does not need to zero it beforehand. - NaN (including its payload),
+Inf,-Inf,+0,-0, and ordinary finite non-zero values are all copied bit-wise, and no numerical computation or type conversion is performed. - Zero-dimension matrices, all-zero matrices, and all-non-zero matrices are supported. When
nnz=0, the output is zeroed and the API returns directly (arch35 does not launch a kernel; arch22 defines the output by the zeroing kernel). - The matrix row count and column count must not exceed
INT32_MAX.
workspace and Lifecycle
- The workspace is temporary scratch used by each call and does not keep cross-call state.
bufferSizealways returns 0, andnullptrcan be passed asbuffer. - Execution is asynchronous on the stream of the handle, and the caller must synchronize that stream before reading or releasing the output, descriptors, and handle.
- The descriptor only borrows device pointers and does not own their memory. Synchronize the stream first, then destroy the descriptor and release the device memory it references.
Returns / Error Codes
| Return Value | Meaning |
|---|---|
ACL_SPARSE_STATUS_SUCCESS |
Success |
ACL_SPARSE_STATUS_HANDLE_IS_NULLPTR |
handle is NULL |
ACL_SPARSE_STATUS_INVALID_VALUE |
matA/matB is NULL; bufferSize is NULL; the stream is not set; dimensions do not match; matB.values is NULL during execute; nnz>0 but idxs/values is NULL |
ACL_SPARSE_STATUS_NOT_SUPPORTED |
The format is not CSR/CSC/COO; the index type is not I32; the value type is not in the supported list; the value types of matA/matB are inconsistent; alg is not DEFAULT; m/n exceeds INT32_MAX |
ACL_SPARSE_STATUS_INTERNAL_ERROR |
During execute, obtaining the AIV core count fails or the result is 0 (Atlas A2/A3, Ascend 950); in the empty matrix or nnz=0 path of Ascend 950, the output zeroing aclrtMemsetAsync fails |
ACL_SPARSE_STATUS_EXECUTION_FAILED |
The Ascend 950 execute detects that kernel enqueue fails |
Invocation example
#include <cstdio>
#include <memory>
#include "cann_ops_sparse.h"
#include "acl/acl.h"
#define LOG_PRINT(fmt, ...) do { printf(fmt, ##__VA_ARGS__); } while (0)
#define CHECK_RET(cond, msg) do { \
if (!(cond)) { LOG_PRINT("ERROR: %s at line %d\n", msg, __LINE__); return ret; } \
} while (0)
class AclContext {
public:
explicit AclContext(int32_t deviceId) : deviceId_(deviceId) {}
~AclContext() {
if (stream_) { aclrtDestroyStream(stream_); stream_ = nullptr; }
if (deviceSet_) { aclrtResetDevice(deviceId_); deviceSet_ = false; }
if (aclInited_) { aclFinalize(); aclInited_ = false; }
}
aclError Init() {
auto ret = aclInit(nullptr);
CHECK_RET(ret == ACL_SUCCESS, "aclInit failed");
aclInited_ = true;
ret = aclrtSetDevice(deviceId_);
CHECK_RET(ret == ACL_SUCCESS, "aclrtSetDevice failed");
deviceSet_ = true;
ret = aclrtCreateStream(&stream_);
CHECK_RET(ret == ACL_SUCCESS, "aclrtCreateStream failed");
return ACL_SUCCESS;
}
aclrtStream Stream() const { return stream_; }
private:
int32_t deviceId_;
aclrtStream stream_ = nullptr;
bool aclInited_ = false;
bool deviceSet_ = false;
};
static void *AllocAndCopyDevice(const void *hostPtr, size_t sizeBytes) {
void *dPtr = nullptr;
aclrtMalloc(&dPtr, sizeBytes, ACL_MEM_MALLOC_HUGE_FIRST);
if (hostPtr != nullptr && sizeBytes > 0)
aclrtMemcpy(dPtr, sizeBytes, hostPtr, sizeBytes, ACL_MEMCPY_HOST_TO_DEVICE);
return dPtr;
}
int main() {
AclContext ctx(0);
aclError ret = ctx.Init();
CHECK_RET(ret == ACL_SUCCESS, "AclContext init failed");
// CSR matrix data (4x4, nnz=5, 0-based)
int32_t hRowOff[] = {0, 2, 3, 5, 5};
int32_t hColInd[] = {0, 2, 1, 0, 2};
float hValues[] = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f};
int64_t rows = 4, cols = 4, nnz = 5;
// Allocate device memory and copy CSR data
std::unique_ptr<int32_t, decltype(&aclrtFree)> dRowOff(
static_cast<int32_t *>(AllocAndCopyDevice(hRowOff, sizeof(hRowOff))), &aclrtFree);
std::unique_ptr<int32_t, decltype(&aclrtFree)> dColInd(
static_cast<int32_t *>(AllocAndCopyDevice(hColInd, sizeof(hColInd))), &aclrtFree);
std::unique_ptr<float, decltype(&aclrtFree)> dValues(
static_cast<float *>(AllocAndCopyDevice(hValues, sizeof(hValues))), &aclrtFree);
std::unique_ptr<float, decltype(&aclrtFree)> dDnMat(
static_cast<float *>(AllocAndCopyDevice(nullptr, rows * cols * sizeof(float))), &aclrtFree);
CHECK_RET(dRowOff && dColInd && dValues && dDnMat, "device alloc failed");
// Create the handle
aclsparseHandle_t rawHandle = nullptr;
auto st = aclsparseCreate(&rawHandle);
CHECK_RET(st == ACL_SPARSE_STATUS_SUCCESS, "aclsparseCreate failed");
std::unique_ptr<aclsparseContext, aclsparseStatus_t (*)(aclsparseHandle_t)> handle(rawHandle, aclsparseDestroy);
aclsparseSetStream(handle.get(), ctx.Stream());
// Create the CSR sparse matrix descriptor matA
aclsparseConstSpMatDescr_t rawMatA = nullptr;
st = aclsparseCreateConstCsr(&rawMatA, rows, cols, nnz,
dRowOff.get(), dColInd.get(), dValues.get(),
ACL_SPARSE_INDEX_32I, ACL_SPARSE_INDEX_32I,
ACL_SPARSE_INDEX_BASE_ZERO, ACL_FLOAT);
CHECK_RET(st == ACL_SPARSE_STATUS_SUCCESS, "createConstCsr failed");
std::unique_ptr<aclsparseSpMatDescr, aclsparseStatus_t (*)(aclsparseConstSpMatDescr_t)> matA(
const_cast<aclsparseSpMatDescr *>(reinterpret_cast<const aclsparseSpMatDescr *>(rawMatA)),
aclsparseDestroySpMat);
// Create the dense matrix descriptor matB (row-major, ld=cols)
aclsparseDnMatDescr_t rawMatB = nullptr;
st = aclsparseCreateDnMat(&rawMatB, rows, cols, cols, dDnMat.get(),
ACL_FLOAT, ACL_SPARSE_ORDER_ROW);
CHECK_RET(st == ACL_SPARSE_STATUS_SUCCESS, "createDnMat failed");
std::unique_ptr<aclsparseDnMatDescr, aclsparseStatus_t (*)(aclsparseConstDnMatDescr_t)> matB(
rawMatB, aclsparseDestroyDnMat);
// Query the workspace (always 0)
size_t bufferSize = 0;
st = aclsparseSparseToDense_bufferSize(handle.get(), matA.get(), matB.get(),
ACL_SPARSE_SPARSETODENSE_ALG_DEFAULT, &bufferSize);
CHECK_RET(st == ACL_SPARSE_STATUS_SUCCESS, "bufferSize failed");
// Execute the CSR → Dense conversion
st = aclsparseSparseToDense(handle.get(), matA.get(), matB.get(),
ACL_SPARSE_SPARSETODENSE_ALG_DEFAULT, nullptr);
CHECK_RET(st == ACL_SPARSE_STATUS_SUCCESS, "execute failed");
// Synchronize and retrieve the result
ret = aclrtSynchronizeStream(ctx.Stream());
CHECK_RET(ret == ACL_SUCCESS, "sync failed");
float hDnMat[16] = {0};
ret = aclrtMemcpy(hDnMat, sizeof(hDnMat), dDnMat.get(), sizeof(hDnMat),
ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, "D2H failed");
// Print the result
printf("Dense matrix (%lld x %lld, row-major):\n", (long long)rows, (long long)cols);
for (int64_t i = 0; i < rows; ++i) {
for (int64_t j = 0; j < cols; ++j)
printf("%6.1f ", hDnMat[i * cols + j]);
printf("\n");
}
return 0;
}
Expected output:
Dense matrix (4 x 4, row-major):
1.0 0.0 2.0 0.0
0.0 3.0 0.0 0.0
4.0 0.0 5.0 0.0
0.0 0.0 0.0 0.0
Test Coverage
The test files are located in test/sparse2dense/ and use the GTest + CSV parameterized testing framework.
- Physical arch35 devices: all 50 test cases (32 correctness + 16 negative + 2 skipped) pass.
- Physical arch22 devices (Atlas A2 products and Atlas A3 products): full ST 123 OK + 3 SKIP (L2_001/L2_016/MultiDevice skipped under the single-card policy), Host UT 73 PASS + 1 SKIP, Python e2e 133/133, and official ATK precision 200/200.
arch35 Test Structure
| File | Description |
|---|---|
sparse2dense_param.h |
CSV parameter structure |
sparse2dense_golden.h |
CPU golden computation (three formats: CSR/CSC/COO) |
arch35/sparse2dense_test.csv |
L0/L1 correctness cases (32 cases) |
arch35/sparse2dense_l2_cases.csv |
L2 negative cases (16 cases) |
arch35/sparse2dense_npu_wrapper.h |
NPU input generation / type mapping / execution wrapper |
arch35/sparse2dense_test.cpp |
GTest main tests |
arch35 L0/L1 Correctness Tests (32 cases)
| Level | Coverage Dimension |
|---|---|
| L0 | Basic functions: CSR/CSC/COO × FP32/FP16/BF16/INT8/INT32 × row/col × base 0/1 |
| L0 | Boundaries: empty matrix / single element / fully dense / ld padding / wide matrix / tall matrix |
| L1 | Medium scale: 128×128 ~ 512×512 × three formats × five dtypes |
| L1 | indexBase=1 coverage |
| L1 | Three-format consistency (the CSR/CSC/COO outputs of the same matrix must be consistent) |
arch35 L2 Negative Tests (16 cases)
| Test Category | Coverage |
|---|---|
| Null pointer | handle / matA / matB / bufferSize is NULL |
| Dimension mismatch | The row/column counts of matA and matB are inconsistent |
| Type mismatch | The value types of matA and matB are inconsistent |
| Invalid ld | row-major ld < cols |
| Invalid format | The format enum is out of range |
| Invalid algorithm | The alg enum is out of range |
| Unsupported dtype | FP64 |
| Null pointer when nnz>0 | ptrs / idxs is NULL |
| INT32 overflow | m > INT32_MAX |
| Unsupported index type | I64 |
arch22 Test Structure
| File | Description |
|---|---|
arch22/sparse2dense_test.cpp |
GTest main tests (L0/L1/L2 + multi-card + negative cases of the coordinate verification chain) |
arch22/sparse2dense_test.csv |
Three-level cases in a single file (L0 12 + L1 85 + L2 37 = 134 cases, loaded at test runtime; L2_001/016 are mock-only SKIPs; L2_029~037 are dual-entry public API negative cases from the tenth review rectification) |
arch22/ut/ |
Host-side unit tests (including aclrt mock) |
python/test_sparse2dense_torch.py |
torch_extension end-to-end (aten::_to_dense takeover / format×dtype bit-wise / error paths / multi-card) |
Supported Chips
| Chip | Support |
|---|---|
| Ascend 950PR&950DT products | Supported (arch35 / dav-3510) |
| Atlas A2 products (training products, Ascend 910B3 / 910B4) | Supported (arch22 / dav-2201) |
| Atlas A3 products (training products, Ascend 910_93) | Supported (arch22 / dav-2201) |
PyTorch / Torch Extension
The PyTorch adaptation uses the unified in-repo torch_extension framework (the same as SpGEMM), registers the standard
aten::_to_dense, and users call Tensor.to_dense(). Source code directory:
sparse/sparse2dense/torch_extension/
├── __init__.py
├── sparse2dense.py
└── csrc/sparse2dense.cpp
For building, installation, and pytest commands, see
../../test/sparse2dense/python/README_en.md,
../../torch_extension/README_en.md, and
../../torch_extension/cann_ops_sparse/docs/en/sparse2dense.md.