| Files | Last commit | Last update |
|---|---|---|
CSRSORT Operator
Operator Overview
The csrsort operator performs a stable sort on each row of a sparse matrix in CSR (Compressed Sparse Row) format. The operator reorders the column index array csrColInd in place and reorders the array P with the same permutation; the row offset array csrRowPtr remains unchanged.
For row row, the sorting range and output relationship are as follows:
begin = csrRowPtr[row] - indexBase
end = csrRowPtr[row + 1] - indexBase
csrColInd_out[begin:end] = stable_sort(csrColInd_in[begin:end])
P_out[begin:end] = P_in[stable_permutation(begin:end)]
When the caller initializes P to 0, 1, ..., nnz - 1, the sorted P[i] denotes the original non-zero element index corresponding to output position i, and you can reorder the value array of the sparse matrix synchronously based on it.
The operator uses a two-step invocation process: first call aclsparseXcsrsort_bufferSizeExt to query the workspace size and allocate Device memory, then call aclsparseXcsrsort to perform the sort. The sort interface is asynchronously dispatched to the stream bound to the handle, and you need to synchronize that stream before reading the result.
This operator provides the following interfaces:
| Interface name | Function brief |
|---|---|
| aclsparseXcsrsort_bufferSizeExt | Queries the Device workspace size required for the sort |
| aclsparseXcsrsort | Performs an in-place stable ascending sort on the column indices of each row of a CSR matrix and reorders P synchronously |
Operator Execution Interfaces
aclsparseXcsrsort_bufferSizeExt
Product support
- Ascend 950PR&950DT products: Supported
- Atlas A3 products: Not supported
- Atlas A2 products: Not supported
Function prototype
aclsparseStatus_t aclsparseXcsrsort_bufferSizeExt(
aclsparseHandle_t handle,
int m,
int n,
int nnz,
const int *csrRowPtr,
const int *csrColInd,
size_t *pBufferSizeInBytes)
Parameter description
| Parameter | Input/Output | Parameter type | Description | Memory location |
|---|---|---|---|---|
| handle | Input | aclsparseHandle_t | ops-sparse library context handle | Host |
| m | Input | int | Number of rows of the sparse matrix | Host |
| n | Input | int | Number of columns of the sparse matrix; used only for Host parameter validation and does not participate in the sorting computation | Host |
| nnz | Input | int | Number of non-zero elements of the sparse matrix | Host |
| csrRowPtr | Input | const int* (INT32) | CSR row offset array with length m + 1 |
Device |
| csrColInd | Input | const int* (INT32) | CSR column index array with length nnz |
Device |
| pBufferSizeInBytes | Output | size_t* | Returns the workspace size in bytes | Host |
Constraints
handlecannot be nullptr; otherwiseACL_SPARSE_STATUS_HANDLE_IS_NULLPTRis returned.m >= 0,n >= 0, andnnz >= 0.- When
m == 0orn == 0,nnzmust be 0. - When
m > 0,csrRowPtrcannot be nullptr. - When
nnz > 0,csrColIndcannot be nullptr. pBufferSizeInBytescannot be nullptr.- When
nnz == 0, the interface returns success and sets*pBufferSizeInBytesto 0; otherwise it returns2 * nnz * sizeof(int32_t). - This interface introduces no Device synchronization.
Supported sparse formats
| Format | Supported | Description |
|---|---|---|
| CSR | ✅ | The input uses the CSR row offset and column index arrays |
| COO | ❌ | The COO format is not supported |
| CSC | ❌ | The CSC format is not supported |
aclsparseXcsrsort
Product support
- Ascend 950PR&950DT products: Supported
- Atlas A3 products: Not supported
- Atlas A2 products: Not supported
Function prototype
aclsparseStatus_t aclsparseXcsrsort(
aclsparseHandle_t handle,
int m,
int n,
int nnz,
const aclsparseMatDescr_t descrA,
const int *csrRowPtr,
int *csrColInd,
int *P,
void *pBuffer)
Parameter description
| Parameter | Input/Output | Parameter type | Description | Memory location |
|---|---|---|---|---|
| handle | Input | aclsparseHandle_t | ops-sparse library context handle that provides the execution stream | Host |
| m | Input | int | Number of rows of the sparse matrix | Host |
| n | Input | int | Number of columns of the sparse matrix; used only for Host parameter validation and does not participate in the sorting computation | Host |
| nnz | Input | int | Number of non-zero elements of the sparse matrix | Host |
| descrA | Input | const aclsparseMatDescr_t | Legacy matrix descriptor; its index base is used, and other attributes do not participate in the sort | Host |
| csrRowPtr | Input | const int* (INT32) | CSR row offset array with length m + 1, unchanged during the sort |
Device |
| csrColInd | Input/Output | int* (INT32) | CSR column index array with length nnz; on output, stably ascending within each row |
Device |
| P | Input/Output | int* (INT32) | Permutation array with length nnz; reordered with the same stable permutation as csrColInd |
Device |
| pBuffer | Input | void* | Workspace whose size is queried by aclsparseXcsrsort_bufferSizeExt and allocated by the caller |
Device |
Constraints
handlecannot be nullptr; otherwiseACL_SPARSE_STATUS_HANDLE_IS_NULLPTRis returned.m >= 0,n >= 0, andnnz >= 0.- When
m == 0orn == 0,nnzmust be 0. descrAcannot be nullptr, and the index base supports onlyACL_SPARSE_INDEX_BASE_ZEROandACL_SPARSE_INDEX_BASE_ONE.- When
m > 0,csrRowPtrcannot be nullptr. - When
nnz > 0,csrColInd,P, andpBuffercannot be nullptr. - The caller must ensure that the CSR structure is legal, including
csrRowPtrbeing monotonically non-decreasing,csrRowPtr[m] - indexBase == nnz, and column indices being within the column range of the matrix. pBufferdoes not require 128-byte alignment, but it must not overlap the storage areas ofcsrRowPtr,csrColInd, orP.- When
nnz == 0, the interface returns success directly and dispatches no kernel. - This interface executes asynchronously; before reading
csrColIndandP, the caller must synchronize the stream bound to the handle. - Illegal parameters such as dimensions or pointers return
ACL_SPARSE_STATUS_INVALID_VALUE; a failure to obtain the AIV core count or UB capacity returnsACL_SPARSE_STATUS_INTERNAL_ERROR; when the UB capacity is insufficient to hold the minimum sorting segment,ACL_SPARSE_STATUS_INSUFFICIENT_RESOURCESis returned; a kernel dispatch failure returnsACL_SPARSE_STATUS_EXECUTION_FAILED.
Supported sparse formats
| Format | Supported | Description |
|---|---|---|
| CSR | ✅ | Sorts the column indices of each CSR row independently |
| COO | ❌ | The COO format is not supported |
| CSC | ❌ | The CSC format is not supported |
Invocation example
The example code is as follows, for reference only. For the detailed build and execution process, see Build and Run Example.
#include <cstdint>
#include <cstdio>
#include <memory>
#include <numeric>
#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;
};
using DevicePtr = std::unique_ptr<void, aclError (*)(void *)>;
static int AllocAndCopyDevice(DevicePtr &devicePtr, const void *hostPtr, size_t sizeBytes)
{
void *rawPtr = nullptr;
auto ret = aclrtMalloc(&rawPtr, sizeBytes, ACL_MEM_MALLOC_HUGE_FIRST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);
devicePtr.reset(rawPtr);
if (hostPtr != nullptr && sizeBytes > 0) {
ret = aclrtMemcpy(devicePtr.get(), sizeBytes, hostPtr, sizeBytes, ACL_MEMCPY_HOST_TO_DEVICE);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy data to Device failed. ERROR: %d\n", ret); return ret);
}
return ACL_SUCCESS;
}
static void PrintVector(const char *name, const std::vector<int> &values)
{
LOG_PRINT("%s:", name);
for (int value : values) {
LOG_PRINT(" %d", value);
}
LOG_PRINT("\n");
}
int aclsparseCsrsortTest(AclContext &ctx)
{
aclrtStream stream = ctx.Stream();
// 1. Create the ops-sparse handle and bind the stream
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(handlePtr.get(), stream);
CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS,
LOG_PRINT("aclsparseSetStream failed. ERROR: %d\n", sparseRet); return sparseRet);
// 2. Prepare Host-side CSR data
const int m = 3;
const int n = 5;
const int nnz = 7;
std::vector<int> hCsrRowPtr = {0, 3, 5, 7};
std::vector<int> hCsrColInd = {4, 1, 3, 2, 0, 4, 1};
std::vector<int> hP(nnz);
std::iota(hP.begin(), hP.end(), 0);
// 3. Allocate Device memory and copy the CSR data and P
DevicePtr dCsrRowPtr(nullptr, aclrtFree);
DevicePtr dCsrColInd(nullptr, aclrtFree);
DevicePtr dP(nullptr, aclrtFree);
auto aclRet = AllocAndCopyDevice(
dCsrRowPtr, hCsrRowPtr.data(), hCsrRowPtr.size() * sizeof(int));
CHECK_RET(aclRet == ACL_SUCCESS, return aclRet);
aclRet = AllocAndCopyDevice(
dCsrColInd, hCsrColInd.data(), hCsrColInd.size() * sizeof(int));
CHECK_RET(aclRet == ACL_SUCCESS, return aclRet);
aclRet = AllocAndCopyDevice(dP, hP.data(), hP.size() * sizeof(int));
CHECK_RET(aclRet == ACL_SUCCESS, return aclRet);
// 4. Query the workspace size
size_t bufferSize = 0;
sparseRet = aclsparseXcsrsort_bufferSizeExt(
handlePtr.get(), m, n, nnz,
static_cast<const int *>(dCsrRowPtr.get()),
static_cast<const int *>(dCsrColInd.get()), &bufferSize);
CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS,
LOG_PRINT("bufferSizeExt failed. ERROR: %d\n", sparseRet); return sparseRet);
LOG_PRINT("bufferSize = %zu bytes\n", bufferSize);
DevicePtr dBuffer(nullptr, aclrtFree);
aclRet = AllocAndCopyDevice(dBuffer, nullptr, bufferSize);
CHECK_RET(aclRet == ACL_SUCCESS, return aclRet);
// 5. Create and configure the Legacy MatDescr; it is destroyed automatically by unique_ptr
aclsparseMatDescr_t rawDescr = nullptr;
sparseRet = aclsparseCreateMatDescr(&rawDescr);
CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS,
LOG_PRINT("aclsparseCreateMatDescr failed. ERROR: %d\n", sparseRet); return sparseRet);
std::unique_ptr<aclsparseMatDescr, aclsparseStatus_t (*)(aclsparseMatDescr_t)> descrPtr(
rawDescr, aclsparseDestroyMatDescr);
aclsparseSetMatType(descrPtr.get(), ACL_SPARSE_MATRIX_TYPE_GENERAL);
aclsparseSetMatIndexBase(descrPtr.get(), ACL_SPARSE_INDEX_BASE_ZERO);
// 6. Perform the stable sort within each CSR row
sparseRet = aclsparseXcsrsort(
handlePtr.get(), m, n, nnz, descrPtr.get(),
static_cast<const int *>(dCsrRowPtr.get()),
static_cast<int *>(dCsrColInd.get()),
static_cast<int *>(dP.get()), dBuffer.get());
CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS,
LOG_PRINT("aclsparseXcsrsort failed. ERROR: %d\n", sparseRet); return sparseRet);
// 7. Synchronize and wait for the task execution to finish
aclRet = aclrtSynchronizeStream(stream);
CHECK_RET(aclRet == ACL_SUCCESS,
LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", aclRet); return aclRet);
// 8. Copy the result back to Host and print it
std::vector<int> hSortedColInd(nnz, 0);
std::vector<int> hSortedP(nnz, 0);
aclRet = aclrtMemcpy(hSortedColInd.data(), hSortedColInd.size() * sizeof(int),
dCsrColInd.get(), hSortedColInd.size() * sizeof(int),
ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(aclRet == ACL_SUCCESS,
LOG_PRINT("copy csrColInd to Host failed. ERROR: %d\n", aclRet); return aclRet);
aclRet = aclrtMemcpy(hSortedP.data(), hSortedP.size() * sizeof(int),
dP.get(), hSortedP.size() * sizeof(int), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(aclRet == ACL_SUCCESS,
LOG_PRINT("copy P to Host failed. ERROR: %d\n", aclRet); return aclRet);
PrintVector("csrRowPtr", hCsrRowPtr);
PrintVector("csrColInd", hSortedColInd);
PrintVector("P", hSortedP);
return ACL_SPARSE_STATUS_SUCCESS;
}
int main()
{
AclContext ctx(0);
auto ret = ctx.Init();
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = aclsparseCsrsortTest(ctx);
CHECK_RET(ret == ACL_SPARSE_STATUS_SUCCESS,
LOG_PRINT("aclsparseCsrsortTest failed. ERROR: %d\n", ret); return ret);
return 0;
}
The expected output is as follows:
bufferSize = 56 bytes
csrRowPtr: 0 3 5 7
csrColInd: 1 3 4 0 2 1 4
P: 1 2 0 4 3 6 5