| Files | Last commit | Last update |
|---|---|---|
DenseToSparse Operator
Product support
| Product | Supported |
|---|---|
| Ascend 950PR&950DT products | √ (arch35) |
| Atlas A3 products | √ (arch22) |
| Atlas A2 products | √ (arch22) |
| Atlas 200I/500 A2 inference products | × |
| Atlas inference products | × |
| Atlas training products | × |
Function Description
DenseToSparse converts a two-dimensional dense matrix to a CSR, CSC, COO, or Blocked-ELL
(referred to as BELL below) sparse matrix. The API semantics align with
cusparseDenseToSparse_bufferSize, cusparseDenseToSparse_analysis, and
cusparseDenseToSparse_convert of the cuSPARSE Generic API. It is recommended that you call the APIs in the three
phases: querying the workspace, analyzing the structure, and executing the conversion, so that the structure information in the target canonical descriptor is automatically generated from Dense.
For CSR and CSC, Analysis counts non-zero elements, writes offsets, and updates the nnz of matB;
COO Analysis publishes the actual number of non-zero elements through matB.nnz; Convert trusts the structure published by
Analysis (which must use the same workspace as Analysis) and writes only indexes and values. The structure and
storage capacity of BELL are preset by the caller, and Convert extracts only the dense blocks covered by the fixed pattern, without discovering or
expanding the structure; BELL uses a rounded-up block grid, and out-of-range logical elements of tail blocks output positive zero of the dtype,
the values payload is allocated by the padding grid (ceil(rows/b)*b x ellCols), and the block column index of an
empty slot is -1 (a value less than the index base is considered empty).
The API semantics align with the
cusparseDenseToSparse_bufferSize, cusparseDenseToSparse_analysis, and
cusparseDenseToSparse_convert of the cuSPARSE Generic API, and it is recommended that you call the APIs in the
three phases: querying the workspace, analyzing the structure, and executing the conversion.
Interfaces and Responsibilities
| API | Brief Description |
|---|---|
aclsparseDenseToSparseGetBufferSize |
Queries the device workspace bytes required by Analysis/Convert (pure query, no phase side effects) |
aclsparseDenseToSparseAnalysis |
Analyzes the structure: CSR/CSC counts non-zero elements, writes offsets, and updates nnz; COO publishes nnz; BELL verifies the geometry and pattern |
aclsparseDenseToSparseConvert |
Executes the conversion: CSR/CSC/COO writes indices/values (trusting the Analysis prefix); BELL extracts block values by pattern |
Sparse Format Semantics
| Format | Required before Analysis | Bound after Analysis | Output Semantics |
|---|---|---|---|
| CSR | rowOffsets[m + 1] |
colIndices[nnz], values[nnz] |
Compressed by row; column indexes increase within each row |
| CSC | colOffsets[n + 1] |
rowIndices[nnz], values[nnz] |
Compressed by column; row indexes increase within each column |
| COO | No structure array requirement | rowIndices[nnz], colIndices[nnz], values[nnz] |
Outputs coordinates in logical row-major order |
| BELL | ellColInd[ceil(ellCols / blockSize) * ceil(m / blockSize)], ellValue[blockRows * b * slots * b] |
None | Extracts block values by the preset block-column pattern |
You need to distinguish the descriptor creation capability for CSR/CSC from the execution capability of DenseToSparse:
aclsparseCreateCsr and aclsparseCreateCsc accept four offset/index combinations: I32/I32, I32/I64, I64/I32, and
I64/I64. However, to keep consistent with the actual operator behavior of cuSPARSE, DenseToSparse
can execute only the combinations whose offset type is the same as the element index type.
| CSR/CSC Offset Type | CSR/CSC Element Index Type | DenseToSparse Support |
|---|---|---|
| I32 | I32 | Supported |
| I32 | I64 | Not supported |
| I64 | I32 | Not supported |
| I64 | I64 | Supported |
For created CSR/CSC descriptors with I32/I64 or I64/I32,
aclsparseDenseToSparseGetBufferSize, aclsparseDenseToSparseAnalysis, and
aclsparseDenseToSparseConvert all return ACL_SPARSE_STATUS_NOT_SUPPORTED.
The row/column index of COO shares the index type specified by the descriptor. All formats support
ACL_SPARSE_INDEX_BASE_ZERO and ACL_SPARSE_INDEX_BASE_ONE.
Blocked-ELL (BELL)
BELL conversion uses the fixed pattern that the caller determines before the call, instead of discovering the structure from the dense matrix.
Each item in ellColInd represents a block column index and is encoded in 0-based or 1-based form according to the
indexBase of the descriptor. Neither Analysis nor Convert modifies
ellColInd. Dense non-zero elements not covered by the pattern are ignored, and the pattern is neither expanded nor reordered,
nor is insufficient capacity reported.
Geometry and Storage Capacity
Let rows = m, cols = n, and ellBlockSize = b. The following conditions must be satisfied:
b > 0;0 <= ellCols <= cols.
rows, cols, and ellCols are not required to be divisible by b; if they are not divisible, the last block row or
block column is a tail block. Geometry quantities are computed by rounding up:
blockRows = ceil(rows / b)
slots = ceil(ellCols / b)
| Array/Field | Number of Elements or Semantics |
|---|---|
ellColInd |
blockRows * slots I32 or I64 block-column indices |
ellValue |
blockRows * b * slots * b value scalars |
aclsparseSpMatGetSize(..., &nnz) |
nnz = blockRows * b * slots * b, that is, the storage scalar capacity |
Capacity is computed by the padded block grid, so each slot always occupies b * b scalars, and the intra-block addressing formula of tail blocks
is the same as that of non-tail blocks. When both rows and ellCols are divisible by b, this capacity exactly equals
rows * ellCols, which is fully identical to the behavior when tail blocks are not supported.
The nnz here is neither the actual number of non-zero elements in Dense nor the actual
number of non-zero elements within the effective pattern coverage. Before creating the BELL descriptor, you must allocate ellColInd and ellValue by the preceding element counts;
none of the three DenseToSparse phases changes this capacity.
Pattern, Padding, and Out-of-Range Items
For a pattern item encoded with base base, the item is valid only when
base <= encoded < base + ceil(cols / b), and the corresponding 0-based block column is
encoded - base. -1, any value less than base, and any value beyond the block-column range
are treated as padding; the corresponding entire b * b slot is written in ellValue as
positive zero of the value type. This also applies to 0 in a 1-based pattern.
Logical elements out of range within a tail block are also written as positive zero: for the logical position (row, col) in a slot,
data is copied from Dense only when row < rows && col < cols; otherwise, positive zero is written. Therefore, when
rows or cols is not divisible, the padded rows and columns neither read Dense nor access out of range.
ellColInd is located on the device. The APIs do not synchronize the pattern to the host and then verify its content item by item,
so GetBufferSize and Analysis do not report an error because a pattern item is out of range; the result semantics of such an item in Convert
are the preceding padding. The caller must still guarantee that the device pointers, element types, and allocated capacity
are correct.
Three-Phase Invocation and Lifecycle
BELL can also follow the recommended
GetBufferSize -> Analysis -> Convert sequence. Its GetBufferSize returns
bufferSize == 0, so nullptr can be passed as buffer for both Analysis and Convert.
Analysis does not scan Dense, does not read the pattern, and does not start device kernels; Convert directly
consumes the fixed pattern and storage in the current BELL descriptor, without depending on private phase states or historical snapshots.
ellColInd and ellValue must be prepared and bound before creating the BELL descriptor, and the addresses and capacity must
remain valid until the stream where Convert resides completes execution. The descriptor only borrows these device pointers and does not own
their memory. You can destroy the descriptor or release the arrays only after the stream is synchronized.
Values Layout and Dense Reading
Task numbers are arranged by block row first:
task = blockRow * slots + slot
valuePos = task * b * b + innerCol * b + innerRow
Therefore, ellValue is first arranged by task (that is, the slot order of ellColInd), and within each
b * b block, elements are arranged in column-major order. Dense reading follows the order of matA:
ROW: dense[row * ld + col]
COL: dense[col * ld + row]
The two Dense orders produce the same logical BELL values, and only the physical addressing of the input differs.
BELL-Specific Invocation Snippet
The following snippet shows the key invocation sequence for a 1-based, I32 pattern. In the example, rows = cols = 4,
b = 2, and ellCols = 4, so the pattern has 4 items and values have 16 FP32 scalars.
-1 is padding.
constexpr int64_t rows = 4;
constexpr int64_t cols = 4;
constexpr int64_t b = 2;
constexpr int64_t ellCols = 4;
const int32_t hostPattern[] = {1, -1, 2, -1};
void *devicePattern = nullptr;
void *deviceBellValues = nullptr;
aclrtMalloc(&devicePattern, sizeof(hostPattern), ACL_MEM_MALLOC_HUGE_FIRST);
aclrtMemcpy(devicePattern, sizeof(hostPattern),
hostPattern, sizeof(hostPattern), ACL_MEMCPY_HOST_TO_DEVICE);
aclrtMalloc(&deviceBellValues, rows * ellCols * sizeof(float),
ACL_MEM_MALLOC_HUGE_FIRST);
// The handle, matA, and the FP32 Dense device data referenced by matA have been created beforehand;
// the stream has been bound to the handle through aclsparseSetStream(handle, stream).
aclsparseSpMatDescr_t matB = nullptr;
aclsparseCreateBlockedEll(
&matB, rows, cols, b, ellCols, devicePattern, deviceBellValues,
ACL_SPARSE_INDEX_32I, ACL_SPARSE_INDEX_BASE_ONE, ACL_FLOAT);
size_t bufferSize = 0;
aclsparseDenseToSparseGetBufferSize(
handle, matA, matB, ACL_SPARSE_DENSETOSPARSE_ALG_DEFAULT, &bufferSize);
// BELL always returns 0; the recommended three-phase sequence is still used here.
if (bufferSize == 0) {
aclsparseDenseToSparseAnalysis(
handle, matA, matB, ACL_SPARSE_DENSETOSPARSE_ALG_DEFAULT, nullptr);
aclsparseDenseToSparseConvert(
handle, matA, matB, ACL_SPARSE_DENSETOSPARSE_ALG_DEFAULT, nullptr);
}
aclrtSynchronizeStream(stream);
aclsparseDestroySpMat(matB);
aclrtFree(deviceBellValues);
aclrtFree(devicePattern);
The BELL index types support ACL_SPARSE_INDEX_32I and
ACL_SPARSE_INDEX_64I, and the value types support ACL_INT8, ACL_FLOAT16,
ACL_BF16, ACL_FLOAT, and ACL_COMPLEX64, which must be the same as the value type of Dense.
Supported Data Types
The value types of matA and matB must be the same. The support scope of each architecture is as follows.
| Data Type | Enum | arch22 (Atlas A2 products and Atlas A3 products) | arch35 |
|---|---|---|---|
| int8 | ACL_INT8 |
Supported | Supported |
| float16 | ACL_FLOAT16 |
Supported | Supported |
| bfloat16 | ACL_BF16 |
Supported | Supported |
| float32 | ACL_FLOAT |
Supported | Supported |
| complex64 | ACL_COMPLEX64 |
Supported | Supported |
complex64 consists of two interleaved FP32 values (real part, imaginary part) and is copied as a whole 8 bytes. The element is considered non-zero if the magnitude bits of either
component are non-zero. Therefore, elements whose both components are zero, such as (+0, -0), do not enter the structure, while
elements where any component is NaN or Inf, such as (NaN, 0) and (0, Inf), are all preserved, with the real and imaginary parts
bit-wise consistent respectively.
float64 and complex128 are not supported; passing in these types returns
ACL_SPARSE_STATUS_NOT_SUPPORTED.
Device indexes are fixed to I32 (ACL_SPARSE_INDEX_32I): I64 descriptors return ACL_SPARSE_STATUS_NOT_SUPPORTED on the three-phase APIs
(descriptor creation itself may succeed; this is the difference between the public creation
capability and the operator execution capability). The matrix row count, column count, and the actual nnz range of CSR/CSC/COO are
[0, INT32_MAX], and all output offset/index values must be representable by I32.
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. - For floating-point types, both
+0and-0are considered zero and are not written to CSR/CSC/COO. - NaN (including its payload),
+Inf,-Inf, and ordinary finite non-zero values are all considered non-zero. Values are 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. Zero-dimension CSR/CSC still generates offsets whose length is the major dimension plus one, and all elements are the index base. Zero-dimension COO has no output elements.
- For all-zero CSR/CSC, all offsets equal the index base; for all-zero COO,
nnzis 0. - The actual
nnzof CSR/CSC/COO does not exceedm * n. If dimensions,ld, workspace, or address computation overflows, a parameter error is returned.
Interface description
Common Parameters
The common parameters of the three 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 | aclsparseConstDnMatDescr_t |
Dense matrix A, containing the row count, column count, ld, layout, data type, and data pointer |
matB |
Host descriptor; arrays on device | Input/Output | aclsparseSpMatDescr_t |
Mutable sparse matrix B; Analysis can update the nnz of CSR/CSC/COO, and Convert writes the arrays |
alg |
Host | Input | aclsparseDenseToSparseAlg_t |
Only ACL_SPARSE_DENSETOSPARSE_ALG_DEFAULT is supported |
The specific parameters of each phase are as follows.
| API | Parameter | Memory Location | Direction | Description |
|---|---|---|---|---|
GetBufferSize |
bufferSize |
Host | Output | Device workspace bytes required by Analysis/Convert; cannot be empty. This API is a pure query and does not record phase state |
Analysis |
buffer |
Device | Input/Output | Workspace of at least bufferSize bytes; can be empty when bufferSize == 0 |
Convert |
buffer |
Device | Input/Output | Workspace of at least bufferSize bytes; must use the same workspace as Analysis (Convert trusts the structure prefix written by Analysis into this workspace, and calls that use a different buffer or skip Analysis return a parameter error); can be empty when bufferSize == 0 |
Invocation Process
- Create the handle, the dense matrix descriptor, and the mutable sparse matrix descriptor of the target format.
- Call
aclsparseDenseToSparseGetBufferSize, and allocate the device workspace by the returned size. - Call
aclsparseDenseToSparseAnalysis. - For CSR, CSC, and COO, query the actual
nnzby usingaclsparseSpMatGetSize, allocate the output indices/values, and call the correspondingaclsparseCsrSetPointers,aclsparseCscSetPointers, oraclsparseCooSetPointersto bind the pointers. BELL does not perform this step, and its fixed arrays should be allocated before the descriptor is created. - Call
aclsparseDenseToSparseConvert, then synchronize the stream bound to the handle, and then read the result.
This sequence is used to automatically obtain nnz and CSR/CSC offsets from Dense, and to allocate the payload
arrays accordingly. GetBufferSize does not modify descriptors and is not a state precondition of Analysis. Convert
trusts the status/level0 structure prefix written by Analysis into the workspace (the same workspace is
registered on the descriptor, and Convert calls that use a different buffer or skip Analysis return a parameter error), writes only
the payload without re-scanning the structure; the caller guarantees the pointers, capacity, and lifecycle.
arch22 uses independent DenseToSparse Analysis states. CSR/CSC can re-bind the output indices/values while keeping the original offsets
pointers, and COO can re-bind the row/column indexes and values. These
bindings preserve the Analysis results of the same workspace. After replacing the CSR/CSC offsets pointers or calling
aclsparseCsrSetStrides, you need to execute Analysis again. The preprocessing caches of
other operators still become invalid by pointer binding according to the original rules. Non-BELL Convert returns ACL_SPARSE_STATUS_INVALID_VALUE when
Analysis has not been successfully executed or a different workspace is used.
- The workspace is allocated only by the value queried by
GetBufferSize, and Analysis and Convert reuse the same workspace (arch22 protocol: Analysis registers the workspace it uses on the descriptor, and Convert returnsACL_SPARSE_STATUS_INVALID_VALUEwhen it uses a different address or Analysis has not been executed first, aligning with the analysis precondition contract of cuSPARSE DenseToSparse). The APIs have no workspace length parameter and cannot verify the actual allocation size on behalf of the caller. - When
bufferSize > 0, the workspace passed to the current API must be non-empty and must remain valid at least until that stream work completes. BELL and empty inputs that do not need scratch return 0, in which casebuffercan be empty. - The Analysis of CSR/CSC/COO obtains the actual
nnzbefore returning and updates the host descriptor; Convert executes asynchronously on the stream of the handle, and the caller must synchronize that stream before reading or releasing the output, workspace, descriptors, and handle. - The arch22 Convert trusts the status/level0 structure prefix written by Analysis into the same workspace, and consumes only the current canonical descriptor fields to write the payload (without re-scanning the structure). The caller must guarantee that the current descriptor data is consistent with the current Dense, and must provide valid storage for the declared capacity.
- For CSR/CSC, the output positions take the current offsets as the authoritative source; for COO, the current
matB.nnzserves as the capacity threshold (arch22 does not perform device-side re-counting verification, and the structure is subject to the Analysis prefix). - Convert remains stream-asynchronous: the preceding device mismatch is not converted through a host synchronous readback into a synchronous error return of the current API launch. The caller must still synchronize the stream before reading the result or reusing and releasing resources.
- The
ellColIndandellValueof BELL and their capacity must be bound before Convert and remain valid; BELL Convert reads the dense values at call time by the fixed pattern. - 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. The workspace and data pointers are allocated and released by the caller.
| Return Value | Meaning |
|---|---|
ACL_SPARSE_STATUS_SUCCESS |
Success |
ACL_SPARSE_STATUS_INVALID_VALUE |
Empty parameters, invalid enums/formats, incorrect shape/ld/index base/index types, overflow, missing required pointers, or an empty workspace |
ACL_SPARSE_STATUS_NOT_SUPPORTED |
The value data type is not supported; or the offset type of CSR/CSC is inconsistent with the element index type |
ACL_SPARSE_STATUS_EXECUTION_FAILED |
Device/runtime execution, copy, or stream synchronization fails |
ACL_SPARSE_STATUS_INTERNAL_ERROR |
Internal resource or device core information is abnormal |
Descriptor creation and device memory allocation may also return
ACL_SPARSE_STATUS_ALLOC_FAILED or ACL runtime errors respectively. These errors should be handled before entering the three-phase APIs.
Invocation example
The following example converts a row-major FP32 dense matrix to a 0-based, I32 CSR. The example deliberately uses
aclsparseCreateDnMat to create a non-const descriptor and passes it to the read-only matA parameter.
#include <cstdint>
#include <cstdio>
#include <vector>
#include "acl/acl.h"
#include "cann_ops_sparse.h"
#define CHECK_ACL(expr) \
do { \
const aclError acl_status = (expr); \
if (acl_status != ACL_SUCCESS) { \
std::fprintf(stderr, "%s failed: %d\n", #expr, acl_status); \
return 1; \
} \
} while (0)
#define CHECK_SPARSE(expr) \
do { \
const aclsparseStatus_t sparse_status = (expr); \
if (sparse_status != ACL_SPARSE_STATUS_SUCCESS) { \
std::fprintf(stderr, "%s failed: %d\n", #expr, sparse_status); \
return 1; \
} \
} while (0)
int main()
{
constexpr int32_t deviceId = 0;
constexpr int64_t m = 2;
constexpr int64_t n = 3;
const std::vector<float> hostA = {
1.0f, 0.0f, 2.0f,
0.0f, 3.0f, -0.0f
};
CHECK_ACL(aclInit(nullptr));
CHECK_ACL(aclrtSetDevice(deviceId));
aclrtStream stream = nullptr;
CHECK_ACL(aclrtCreateStream(&stream));
aclsparseHandle_t handle = nullptr;
CHECK_SPARSE(aclsparseCreate(&handle));
CHECK_SPARSE(aclsparseSetStream(handle, stream));
void *deviceA = nullptr;
void *rowOffsets = nullptr;
CHECK_ACL(aclrtMalloc(&deviceA, hostA.size() * sizeof(float),
ACL_MEM_MALLOC_HUGE_FIRST));
CHECK_ACL(aclrtMemcpy(deviceA, hostA.size() * sizeof(float),
hostA.data(), hostA.size() * sizeof(float),
ACL_MEMCPY_HOST_TO_DEVICE));
CHECK_ACL(aclrtMalloc(&rowOffsets, (m + 1) * sizeof(int32_t),
ACL_MEM_MALLOC_HUGE_FIRST));
aclsparseDnMatDescr_t matA = nullptr;
aclsparseSpMatDescr_t matB = nullptr;
CHECK_SPARSE(aclsparseCreateDnMat(
&matA, m, n, n, deviceA, ACL_FLOAT, ACL_SPARSE_ORDER_ROW));
CHECK_SPARSE(aclsparseCreateCsr(
&matB, m, n, 0, rowOffsets, nullptr, nullptr,
ACL_SPARSE_INDEX_32I, ACL_SPARSE_INDEX_32I,
ACL_SPARSE_INDEX_BASE_ZERO, ACL_FLOAT));
size_t bufferSize = 0;
CHECK_SPARSE(aclsparseDenseToSparseGetBufferSize(
handle, matA, matB, ACL_SPARSE_DENSETOSPARSE_ALG_DEFAULT,
&bufferSize));
void *workspace = nullptr;
if (bufferSize != 0) {
CHECK_ACL(aclrtMalloc(
&workspace, bufferSize, ACL_MEM_MALLOC_HUGE_FIRST));
}
CHECK_SPARSE(aclsparseDenseToSparseAnalysis(
handle, matA, matB, ACL_SPARSE_DENSETOSPARSE_ALG_DEFAULT,
workspace));
int64_t nnz = 0;
CHECK_SPARSE(aclsparseSpMatGetSize(matB, nullptr, nullptr, &nnz));
void *colIndices = nullptr;
void *values = nullptr;
if (nnz != 0) {
CHECK_ACL(aclrtMalloc(
&colIndices, nnz * sizeof(int32_t), ACL_MEM_MALLOC_HUGE_FIRST));
CHECK_ACL(aclrtMalloc(
&values, nnz * sizeof(float), ACL_MEM_MALLOC_HUGE_FIRST));
}
CHECK_SPARSE(
aclsparseCsrSetPointers(matB, rowOffsets, colIndices, values));
CHECK_SPARSE(aclsparseDenseToSparseConvert(
handle, matA, matB, ACL_SPARSE_DENSETOSPARSE_ALG_DEFAULT,
workspace));
CHECK_ACL(aclrtSynchronizeStream(stream));
std::vector<int32_t> hostOffsets(m + 1);
std::vector<int32_t> hostColumns(static_cast<size_t>(nnz));
std::vector<float> hostValues(static_cast<size_t>(nnz));
CHECK_ACL(aclrtMemcpy(
hostOffsets.data(), hostOffsets.size() * sizeof(int32_t),
rowOffsets, hostOffsets.size() * sizeof(int32_t),
ACL_MEMCPY_DEVICE_TO_HOST));
if (nnz != 0) {
CHECK_ACL(aclrtMemcpy(
hostColumns.data(), hostColumns.size() * sizeof(int32_t),
colIndices, hostColumns.size() * sizeof(int32_t),
ACL_MEMCPY_DEVICE_TO_HOST));
CHECK_ACL(aclrtMemcpy(
hostValues.data(), hostValues.size() * sizeof(float),
values, hostValues.size() * sizeof(float),
ACL_MEMCPY_DEVICE_TO_HOST));
}
std::printf("nnz = %lld\n", static_cast<long long>(nnz));
for (int64_t i = 0; i < nnz; ++i) {
std::printf("col[%lld] = %d, value = %.1f\n",
static_cast<long long>(i),
hostColumns[static_cast<size_t>(i)],
hostValues[static_cast<size_t>(i)]);
}
CHECK_SPARSE(aclsparseDestroySpMat(matB));
CHECK_SPARSE(aclsparseDestroyDnMat(matA));
if (values != nullptr) {
CHECK_ACL(aclrtFree(values));
}
if (colIndices != nullptr) {
CHECK_ACL(aclrtFree(colIndices));
}
if (workspace != nullptr) {
CHECK_ACL(aclrtFree(workspace));
}
CHECK_ACL(aclrtFree(rowOffsets));
CHECK_ACL(aclrtFree(deviceA));
CHECK_SPARSE(aclsparseDestroy(handle));
CHECK_ACL(aclrtDestroyStream(stream));
CHECK_ACL(aclrtResetDevice(deviceId));
CHECK_ACL(aclFinalize());
return 0;
}
The expected result is nnz = 3, CSR offsets
[0, 2, 3], column indices
[0, 2, 1], and values [1.0, 2.0, 3.0].
For details about compilation and linking, see Compiling and Running a Sample.
Compilation and Testing
cmake -S . -B build \
-DSOC_VERSION=ascend910b3 \
-DCMAKE_BUILD_TYPE=Release \
-DBUILD_TEST=ON \
-DOP_LIST=densetosparse
cmake --build build --target densetosparse_test densetosparse_perf --parallel
./build/test/densetosparse/densetosparse_test --gtest_color=no
The PyTorch interfaces (NPU adaptation of Tensor.to_sparse*) are provided through the torch_extension
framework. For building and loading, see
../../torch_extension/README.md.
Directory structure
sparse/densetosparse/
├── README.md
├── arch22/ # Atlas A2 products and Atlas A3 products (AIV vector programming model)
│ ├── densetosparse_host.cpp # Three-phase host orchestration and verification
│ ├── densetosparse_count_kernel.cpp # Counting/scan chain/offsets finalization + launch orchestration
│ ├── densetosparse_convert_kernel.cpp # CSR/CSC/COO payload extraction (panel fast path)
│ ├── densetosparse_bell_kernel.cpp # Blocked-ELL dedicated conversion (task-ring pipeline)
│ ├── densetosparse_judge.h # Shared decision chain/bitmap/geometry selection
│ ├── densetosparse_kernel.h / densetosparse_kernel_shared.h
│ └── densetosparse_tiling_data.h
├── arch35/ # arch35 implementation
│ ├── densetosparse_host.cpp
│ └── densetosparse_kernel.cpp / densetosparse_kernel.h
└── torch_extension/ # PyTorch interface registration (JIT compiled separately)
├── __init__.py / dense_to_sparse.py
└── csrc/densetosparse.cpp
The test code is located in test/densetosparse/ (arch22/ contains C++ UT and perf benchmarks,
and python/ contains ATen/end-to-end tests).