| Files | Last commit | Last update |
|---|---|---|
Non-zero Element Counting Operator
Operator Overview
The nnz operator counts the number of non-zero elements in each row or column of a dense matrix, as well as the total number of non-zero elements. This function is the first step of the dense-to-sparse format conversion process. The typical usage is: first call nnz to obtain the number of non-zero elements in each row/column and the total number of non-zero elements, then build the offset array of the CSR or CSC format based on the statistics (by prefix sum), and finally perform the dense-to-sparse conversion.
The core computation is:
dirA = ROW: nnzPerRow[i] = sum_{j=0}^{n-1} [A[i][j] != 0], i in [0, m)
dirA = COLUMN: nnzPerCol[j] = sum_{i=0}^{m-1} [A[i][j] != 0], j in [0, n)
nnzTotal = sum(nnzPerRow) = sum(nnzPerCol)
where [A[i][j] != 0] is the indicator function, which takes 1 when A[i][j] != 0 and 0 otherwise.
This operator includes the following APIs:
| API | Brief Description |
|---|---|
| aclsparseSnnz | Counts the number of non-zero elements in each row or column of an FP32 dense matrix and the total number of non-zero elements |
Operator Execution APIs
aclsparseSnnz
Product support
- Ascend 950PR&950DT products: Supported
- Atlas A3 products: Not supported
- Atlas A2 products: Not supported
Function prototype
aclsparseStatus_t aclsparseSnnz(aclsparseHandle_t handle, aclsparseDirection_t dirA, int m, int n, const aclsparseMatDescr_t descrA, const float *A, int lda, int *nnzPerRowColumn, int *nnzTotalDevHostPtr)
Parameter description
| Parameter | Input/Output | Type | Description |
|---|---|---|---|
| handle | Input | aclsparseHandle_t | Context handle of the ops-sparse library, carrying the stream, host memory |
| dirA | Input | aclsparseDirection_t | Counting direction: ACL_SPARSE_DIRECTION_ROW (by row) or ACL_SPARSE_DIRECTION_COLUMN (by column), host memory |
| m | Input | int | Number of rows of matrix A, host memory |
| n | Input | int | Number of columns of matrix A, host memory |
| descrA | Input | const aclsparseMatDescr_t | Matrix descriptor, supporting only the ACL_SPARSE_MATRIX_TYPE_GENERAL type, host memory |
| A | Input | const float* (FP32) | Dense matrix data stored in column-major order, with dimensions lda × n and elements A[i][j] = A[j * lda + i], device memory |
| lda | Input | int | Leading dimension of matrix A, host memory |
| nnzPerRowColumn | Output | int* | Array of the number of non-zero elements in each row (size m when dirA=ROW) or each column (size n when dirA=COLUMN), device memory |
| nnzTotalDevHostPtr | Output | int* | Total number of non-zero elements, whose memory location is controlled by aclsparseSetPointerMode: host memory in HOST mode and device memory in DEVICE mode |
Constraints
- m >= 0
- n >= 0
- lda >= max(1, m)
- descrA cannot be nullptr, and descrA.type supports only
ACL_SPARSE_MATRIX_TYPE_GENERAL - When m > 0 and n > 0, A cannot be nullptr
- When totalUnits > 0 (totalUnits = m or n, depending on dirA), nnzPerRowColumn cannot be nullptr
- nnzTotalDevHostPtr cannot be nullptr
- When m = 0 or n = 0, the counting kernel is not launched, nnzTotal is set to 0, and nnzPerRowColumn is not written. In DEVICE pointer mode, failure to enqueue the counting zeroing operation returns
ACL_SPARSE_STATUS_EXECUTION_FAILED
Returns / Error Codes
| Return Value | Scenario |
|---|---|
ACL_SPARSE_STATUS_SUCCESS |
Success |
ACL_SPARSE_STATUS_HANDLE_IS_NULLPTR |
handle is nullptr |
ACL_SPARSE_STATUS_INVALID_VALUE |
The parameters do not satisfy the preceding constraints |
ACL_SPARSE_STATUS_MATRIX_TYPE_NOT_SUPPORTED |
The matrix type of descrA is not GENERAL |
ACL_SPARSE_STATUS_INTERNAL_ERROR |
Obtaining the AIV core count fails or the result is 0 |
ACL_SPARSE_STATUS_EXECUTION_FAILED |
In HOST pointer mode, the valid workspace is less than sizeof(int32_t); the counting zeroing aclrtMemsetAsync fails; kernel enqueue fails; the D2H aclrtMemcpyAsync enqueue of the total number of non-zero elements fails |
The API returns asynchronously, and the caller checks the device asynchronous execution result through stream synchronization.
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;
};
int aclsparseSnnzTest(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);
// Use DEVICE mode: nnzTotalDevHostPtr points to device memory
sparseRet = aclsparseSetPointerMode(static_cast<aclsparseHandle_t>(handlePtr.get()), ACL_SPARSE_POINTER_MODE_DEVICE);
CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("aclsparseSetPointerMode failed. ERROR: %d\n", sparseRet);
return sparseRet);
// 2. Prepare host data (3x3 matrix in column-major order)
// Matrix content:
// [1.0 0.0 3.0]
// [0.0 0.0 4.0]
// [2.0 0.0 0.0]
int m = 3, n = 3, lda = 3;
std::vector<float> hA(static_cast<size_t>(lda) * n, 0.0f);
hA[0 * lda + 0] = 1.0f; // A[0][0]
hA[0 * lda + 2] = 2.0f; // A[2][0]
hA[2 * lda + 0] = 3.0f; // A[0][2]
hA[2 * lda + 1] = 4.0f; // A[1][2]
// 3. Allocate device memory and copy data
void* rawMemA = nullptr;
auto aclRet = aclrtMalloc(&rawMemA, static_cast<size_t>(lda) * n * sizeof(float), ACL_MEM_MALLOC_HUGE_FIRST);
CHECK_RET(aclRet == ACL_SUCCESS, LOG_PRINT("aclrtMalloc for A failed. ERROR: %d\n", aclRet); return aclRet);
std::unique_ptr<void, aclError (*)(void*)> dA(rawMemA, aclrtFree);
aclRet = aclrtMemcpy(dA.get(), static_cast<size_t>(lda) * n * sizeof(float),
hA.data(), static_cast<size_t>(lda) * n * sizeof(float),
ACL_MEMCPY_HOST_TO_DEVICE);
CHECK_RET(aclRet == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy for A failed. ERROR: %d\n", aclRet); return aclRet);
void* rawMemNnzPerRow = nullptr;
aclRet = aclrtMalloc(&rawMemNnzPerRow, m * sizeof(int), ACL_MEM_MALLOC_HUGE_FIRST);
CHECK_RET(aclRet == ACL_SUCCESS, LOG_PRINT("aclrtMalloc for nnzPerRow failed. ERROR: %d\n", aclRet); return aclRet);
std::unique_ptr<void, aclError (*)(void*)> dNnzPerRow(rawMemNnzPerRow, aclrtFree);
void* rawMemNnzTotal = nullptr;
aclRet = aclrtMalloc(&rawMemNnzTotal, sizeof(int), ACL_MEM_MALLOC_HUGE_FIRST);
CHECK_RET(aclRet == ACL_SUCCESS, LOG_PRINT("aclrtMalloc for nnzTotal failed. ERROR: %d\n", aclRet); return aclRet);
std::unique_ptr<void, aclError (*)(void*)> dNnzTotal(rawMemNnzTotal, aclrtFree);
// 4. Create MatDescr (Legacy API)
aclsparseMatDescr_t matDescr = nullptr;
sparseRet = aclsparseCreateMatDescr(&matDescr);
CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("aclsparseCreateMatDescr failed. ERROR: %d\n", sparseRet);
return sparseRet);
aclsparseSetMatType(matDescr, ACL_SPARSE_MATRIX_TYPE_GENERAL);
aclsparseSetMatIndexBase(matDescr, ACL_SPARSE_INDEX_BASE_ZERO);
// 5. Call aclsparseSnnz (counting by row)
aclsparseDirection_t dirA = ACL_SPARSE_DIRECTION_ROW;
sparseRet = aclsparseSnnz(
static_cast<aclsparseHandle_t>(handlePtr.get()), dirA, m, n, matDescr,
static_cast<const float*>(dA.get()), lda,
static_cast<int*>(dNnzPerRow.get()), static_cast<int*>(dNnzTotal.get()));
CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("aclsparseSnnz failed. ERROR: %d\n", sparseRet);
aclsparseDestroyMatDescr(matDescr); return sparseRet);
// 6. Synchronize and wait for task execution to finish
aclRet = aclrtSynchronizeStream(stream);
CHECK_RET(aclRet == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", aclRet); return aclRet);
// 7. Copy the result from the device back to the host and print it
std::vector<int> hNnzPerRow(m, 0);
aclRet = aclrtMemcpy(hNnzPerRow.data(), m * sizeof(int),
dNnzPerRow.get(), m * sizeof(int),
ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(aclRet == ACL_SUCCESS, LOG_PRINT("copy nnzPerRow from device to host failed. ERROR: %d\n", aclRet);
return aclRet);
int hNnzTotal = 0;
aclRet = aclrtMemcpy(&hNnzTotal, sizeof(int),
dNnzTotal.get(), sizeof(int),
ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(aclRet == ACL_SUCCESS, LOG_PRINT("copy nnzTotal from device to host failed. ERROR: %d\n", aclRet);
return aclRet);
for (int i = 0; i < m; i++) {
LOG_PRINT("nnzPerRow[%d] is: %d\n", i, hNnzPerRow[i]);
}
LOG_PRINT("nnzTotal is: %d\n", hNnzTotal);
// 8. Clean up MatDescr
aclsparseDestroyMatDescr(matDescr);
return ACL_SPARSE_STATUS_SUCCESS;
}
int main()
{
AclContext ctx(0);
auto ret = ctx.Init();
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = aclsparseSnnzTest(ctx);
CHECK_RET(ret == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("aclsparseSnnzTest failed. ERROR: %d\n", ret); return ret);
return 0;
}
The expected output is as follows:
nnzPerRow[0] is: 2
nnzPerRow[1] is: 1
nnzPerRow[2] is: 1
nnzTotal is: 4