FilesLast commitLast update
README

aclsparseLtSpMMAPrune

Product support

Product Supported
Ascend 950PR&950DT products √
Atlas A3 products ×
Atlas A2 products ×
Atlas 200I/500 A2 inference products ×
Atlas inference products ×
Atlas training products ×

Function Description

  • Operator function: aclsparseLtSpMMAPrune performs 2:4 structured sparse pruning on a dense matrix and outputs a dense-storage matrix of the same shape as the input (pruned elements are represented by 0). This operator corresponds to cusparseLtSpMMAPrune in cuSPARSELt and is the prerequisite step of structured sparse matrix multiplication. The pruning object is determined by the sparsity field of matA/matB in the Matmul descriptor: when matA is ACL_SPARSE_LT_SPARSITY_50_PERCENT, matrix A is pruned (A-sparse, and the pruning result is used as the sparse-side input matA of Matmul); when matB is ACL_SPARSE_LT_SPARSITY_50_PERCENT, matrix B is pruned (B-sparse, and the pruning result is used as the sparse-side input matB of Matmul). Two pruning algorithms are supported: STRIP (group-wise pruning) and TILE (tile-wise pruning); for details, see "Pruning algorithm (pruneAlg)".
  • Target platform: Ascend 950PR&950DT products (arch35 / DAV_3510).
  • Programming model: ascendc vector API, with multi-core parallel splitting by row (row-wise pruning) or by row block (column-wise pruning); it does not use the matrix multiplication hardware (Cube). Pruning is a deterministic operation (comparison by absolute value) and involves no randomness. The operator starts asynchronously, does not perform stream synchronization internally, and the caller must synchronize itself if it needs to read the result.

Mathematical principle

Problem definition

For the m×k dense matrix A, prune it according to the structured sparse pattern:

A_pruned = Prune_2:4(A)
Symbol Meaning Dimension/Type
A Dense input matrix (to be pruned) m×k, FP32/FP16/BF16/INT8
A_pruned Matrix after pruning (dense storage, with pruned elements represented by 0) m×k, same type as A
Prune_2:4(·) 2:4 structured pruning operator —

Pruning rules

Pruning is performed in groups of a fixed size; each group keeps the elements with the largest absolute values, and the rest are zeroed:

Data type Group size Elements kept per group Sparsity
FP16 (ACL_FLOAT16) 4 2 (keeps the 2 with the largest absolute values) 50% (2:4)
BF16 (ACL_BF16) 4 2 (keeps the 2 with the largest absolute values) 50% (2:4)
INT8 (ACL_INT8) 4 2 (keeps the 2 with the largest absolute values) 50% (2:4)
FP32 (ACL_FLOAT) 2 1 (keeps the 1 with the largest absolute value) 50% (1:2, equivalent to 2:4 density)

Note: FP32 uniformly uses the 1:2 mode (group of 2, keep 1) to simplify the implementation, consistent with the 1:2 of the NVIDIA cuSPARSELt specification; FP16/BF16/INT8 use the standard 2:4 mode (group of 4, keep 2). The sparsity of all data types is 50%.

Pruning direction and physical layout (aligned with cuSPARSELt)

2:4 grouping is always along the K (contraction) dimension of op(the sparse side) = the row direction of the op view. order is the physical memory layout (not a direction switch): in ROW order, element (i,j) is at i*ld+j (ld ≥ cols), and in COL order it is at j*ld+i (ld ≥ rows), consistent with the Dense/Structured DescriptorInit ld constraints of cuSPARSELt. The physical forms of the four combinations:

opA order Descriptor (rows,cols) ld constraint Physical buffer form (op view basis) View
N ROW (m,k) ld ≥ k (m,k) row-major, row stride ld RowView
T COL (k,m) ld ≥ k (m,k) row-major, row stride ld RowView
N COL (m,k) ld ≥ m (k,m) row-major, row stride ld (transpose of the op view) ColView
T ROW (k,m) ld ≥ m (k,m) row-major, row stride ld (transpose of the op view) ColView
  • RowView ((N,ROW)/(T,COL)): grouping is along the op view rows (K dimension), contiguous in memory.
  • ColView ((N,COL)/(T,ROW)): grouping is along the op view rows = along the columns of the (k,m) physical view (across physical rows, with stride ld).
  • View discriminator: pruneAlongRow = (opA==T) != (order==ROW) (=1 → RowView, =0 → ColView)—consistent with the existing formula, with the semantics reinterpreted by the physical layout.
  • B-sparse is symmetric: the op view is (k,n), and the descriptor/ld constraints hold correspondingly by the rows/cols of B.

order semantics note ((b) basis): order is the physical memory layout—COL is column-major storage, and the kernel accesses memory in the physical form described by (order, ld) (the ColView combination reads in (k,m) row-major). The matrix must be stored in the (order, ld) physical layout of the sparse-side descriptor, not always in row-major.

Pruning algorithm (pruneAlg)

The pruneAlg parameter selects the pruning algorithm. Both algorithms guarantee 50% sparsity, but they differ in pruning granularity and optimality:

Algorithm Description
ACLSPARSELT_PRUNE_SPMMA_STRIP Group-wise pruning. FP16/BF16/INT8 group 4 elements and keep the 2 with the largest absolute values, and FP32 groups 2 elements and keeps the 1 with the largest absolute value. Each group is selected independently, with no cross-group optimization.
ACLSPARSELT_PRUNE_SPMMA_TILE Tile-wise pruning, aligned with the TILE specification of cuSPARSELt cusparseLtSpMMAPrune. It enumerates all valid configurations that satisfy the 2:4 constraints in units of tiles, selects the configuration with the largest L1-norm (the sum of the absolute values of the kept elements), and zeroes the remaining positions. Compared with STRIP, it can retain a larger total absolute value within a tile.

TILE algorithm details:

  • FP16/BF16/INT8 (4×4 tile): The matrix is divided into 4×4 tiles, and in each tile all 90 valid configurations are enumerated (exactly 2 non-zeros per row and exactly 2 non-zeros per column). The configuration with the largest L1-norm is selected, and the remaining positions are zeroed. Ties take the configuration with the smaller sequence number (deterministic). The 90 configurations are generated by enumerating C(4,2)^4 = 1296 row choices and filtering the configurations whose column sums are 2.
  • FP32 (2×2 tile): The matrix is divided into 2×2 tiles, and 2 valid configurations are enumerated (the diagonal and the anti-diagonal, exactly 1 non-zero per row and per column). The configuration with the largest L1-norm is selected.
  • Edge tile fallback: When the row and column tails of the matrix do not form complete tiles, the tail elements fall back to group-wise pruning by the STRIP algorithm.

TILE and STRIP have the same grouping direction logic: both along the op view rows (K dimension). The tile enumeration of TILE is performed on the physical view (RowView on (m,k) and ColView on (k,m)); the configuration set is closed under transposition, the L1 norm is transposition invariant, and the result is valid for the op view.

Interface description

aclsparseLtSpMMAPrune directly receives the Matmul descriptor and derives the pruning parameters from the dimensions, data type, order, and opA of matrix A read from it. Before the call, library handle initialization, matrix descriptor initialization, and Matmul descriptor initialization must be completed.

aclsparseLtSpMMAPrune

Function prototype

aclsparseStatus_t aclsparseLtSpMMAPrune(
    aclsparseLtConstHandle_t handle,
    aclsparseLtConstMatmulDescriptor_t* matmulDescr,
    const void* d_in,
    void* d_out,
    aclsparseLtPruneAlg_t pruneAlg,
    aclrtStream stream);

Parameter description

Parameter Input/Output Parameter type Description
handle Input aclsparseLtConstHandle_t const pointer to the aclsparseLt library handle; host memory
matmulDescr Input aclsparseLtConstMatmulDescriptor_t* Matmul operation descriptor; the operator reads the dimensions (m, k), data type, order, and opA of matrix A from it; host memory
d_in Input const void* Device memory pointer of the dense matrix A to be pruned; must be 16-byte aligned, must not be nullptr. Device memory
d_out Output void* Device memory pointer of the pruning result A_pruned; must be 16-byte aligned, must not be nullptr. in-place is supported (d_in == d_out). Device memory
pruneAlg Input aclsparseLtPruneAlg_t Pruning algorithm; supports ACLSPARSELT_PRUNE_SPMMA_STRIP and ACLSPARSELT_PRUNE_SPMMA_TILE; for details, see "Pruning algorithm (pruneAlg)"; host memory
stream Input aclrtStream ACL stream on which the operator executes asynchronously; can be nullptr (meaning the default stream is used); host memory

Constraints

  • handle must not be nullptr; otherwise, ACL_SPARSE_STATUS_HANDLE_IS_NULLPTR is returned.
  • matmulDescr must not be nullptr, and the matrix A descriptor (matA) bound to it must not be nullptr; otherwise, ACL_SPARSE_STATUS_INVALID_VALUE is returned.
  • stream can be nullptr (meaning the default stream is used).
  • pruneAlg supports ACLSPARSELT_PRUNE_SPMMA_STRIP and ACLSPARSELT_PRUNE_SPMMA_TILE, and other values return ACL_SPARSE_STATUS_NOT_SUPPORTED.
  • The data type of matrix A supports ACL_FLOAT (FP32) / ACL_FLOAT16 (FP16) / ACL_BF16 (BF16) / ACL_INT8 (INT8), and other types return ACL_SPARSE_STATUS_NOT_SUPPORTED.
  • d_in and d_out must be 16-byte aligned; otherwise, ACL_SPARSE_STATUS_INVALID_VALUE is returned.
  • d_in must not be nullptr; otherwise, ACL_SPARSE_STATUS_INVALID_VALUE is returned.
  • d_out must not be nullptr (no workspace fallback path); otherwise, ACL_SPARSE_STATUS_INVALID_VALUE is returned.
  • in-place support for all combinations (aligned with cuSPARSELt): d_in and d_out can point to the same Device memory—the output keeps the input layout (see below), RowView row-block-wise / ColView physical-block-wise reads before writing with overlapping read/write areas, cores are partitioned by the block grid without intersection, and the padding area is symmetrically skipped by the stride of load/store (in the in-place case, the input padding is preserved as is).
  • Batch pruning (batch): When the numBatches of the sparse side is > 1 (set through aclsparseLtMatDescSetAttribute with ACLSPARSELT_MAT_NUM_BATCHES; the four sides A/B/C/D must be consistent), a single aclsparseLtSpMMAPrune call completes the pruning of all batches—launched batch by batch, batchStride (ACLSPARSELT_MAT_BATCH_STRIDE, in elements) is the shared between-batch stride of d_in/d_out, and the matrices of all batches are arranged in the same contiguous Device memory at that stride offset. batchStride = 0 means cross-batch broadcast (aligned with the cuSPARSELt batch_stride=0 semantics): all batches read and write batch 0, equivalent to single-matrix pruning (prune is idempotent: in the out-of-place case, the same value is written repeatedly batch by batch, and in-place is the same; the buffer needs only single-batch capacity); batchStride < 0 returns ACL_SPARSE_STATUS_INVALID_VALUE. A positive value must also be ≥ the physical span of that side (order-aware) and batchStride × element byte size must be a multiple of 16 bytes, and batch stride overflow is likewise rejected (for the alignment/overflow check rules, see the batch constraints in prune_check/README_en.md; execution-time validation). When numBatches = 1, batchStride does not participate in the check.
  • K dimension alignment constraint: K must satisfy the alignment requirements of structured descriptor initialization (aclsparseLtStructuredDescriptorInit)—a multiple of 8 for FP32, a multiple of 16 for FP16/BF16, and a multiple of 32 for INT8. Descriptor initialization checks only whether rows, cols, and ld satisfy the corresponding multiples and does not align up automatically; the caller must complete the padding itself before initialization. After successful initialization through the API, K is necessarily a multiple of the corresponding group size.
  • UB capacity constraint: In RowView, STRIP requires the single-row data (k × elemSize) to not exceed the single-core UB capacity, and TILE requires the TS-row data (TS × k × elemSize, TS=4 for FP16 / 2 for FP32, each row aligned to 32 bytes) to not exceed the single-core UB capacity; ColView ((N,COL)/ (T,ROW)) loads by chunkM column blocks, and only a single block (TRANS_TILE × chunkM) needs to not exceed the UB capacity (the (N,COL) case of large k therefore changes from the NOT_SUPPORTED domain of whole-row full validation to supported, symmetric with (T,ROW)). Exceeding the limit returns ACL_SPARSE_STATUS_NOT_SUPPORTED.
  • Asynchronous execution: The operator starts asynchronously and does not call aclrtSynchronizeStream internally; if the caller needs to read the d_out result, it must synchronize the stream itself.
  • Memory layout: d_in is accessed according to the (order, ld) physical layout of the sparse-side descriptor (for details, see "Pruning direction and physical layout"). Output layout contract (aligned with cuSPARSELt): d_out and d_in have the same shape and ld—a matrix that must hold the physical span of the descriptor (rows×ld elements in ROW order / cols×ld elements in COL order); the pruned elements fall at the same physical positions as those read, and the padding area is not written (in the non-in-place case, the original values of d_out are kept; in the in-place case, the input padding is preserved).

Return codes

Return code Description
ACL_SPARSE_STATUS_SUCCESS The operation succeeds
ACL_SPARSE_STATUS_HANDLE_IS_NULLPTR handle is nullptr
ACL_SPARSE_STATUS_INVALID_VALUE matmulDescr/matA/d_in/d_out is nullptr, a data pointer is not 16-byte aligned, or the ld of the sparse-side descriptor is less than the physical row length (k for RowView / m for ColView; a defensive rejection of pseudo descriptors—valid descriptors never trigger this)
ACL_SPARSE_STATUS_NOT_SUPPORTED pruneAlg is not STRIP/TILE, the data type is not FP32/FP16/BF16/INT8, or the K dimension exceeds the UB capacity

Invocation example

The following is the sample code for reference only. For details about the compilation and execution procedure, refer to Compilation and Running Sample.

The following example demonstrates 2:4 pruning of the FP32 matrix A of m×k. Pruning requires creating the Matmul descriptor first (binding A/B/C/D). Even if you execute only pruning without Matmul, the B/C/D descriptors still need to be created (the dimensions must be consistent with A to keep the tiling metadata reasonable).

#include <cstdio>
#include <vector>

#include "acl/acl.h"
#include "cann_ops_sparseLt.h"

#define CHECK_RET(cond, action) \
    do {                        \
        if (!(cond)) {          \
            action;             \
            goto cleanup;       \
        }                       \
    } while (0)

#define LOG_PRINT(message, ...)         \
    do {                                \
        printf(message, ##__VA_ARGS__); \
    } while (0)

// Helper: allocate Device memory and copy Host data
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 aclsparseLtPruneTest()
{
    int32_t deviceId = 0;
    aclrtStream stream = nullptr;
    aclsparseLtHandle_t handle = nullptr;
    aclsparseLtMatDescriptor_t matA = nullptr, matB = nullptr, matC = nullptr, matD = nullptr;
    aclsparseLtMatmulDescriptor_t matmulDesc = nullptr;
    void *dA = nullptr;
    void *dAPruned = nullptr;
    int ret = 0;

    // Declarations are placed before the checks that may jump to cleanup, to avoid crossing C++ object initialization.
    int64_t m = 16, k = 32;
    std::vector<float> hA(static_cast<size_t>(m) * k);
    int64_t n = 128;
    std::vector<float> hAPruned(static_cast<size_t>(m) * k, 0.0f);
    int zeroCnt = 0;

    CHECK_RET(aclInit(nullptr) == ACL_SUCCESS, LOG_PRINT("aclInit failed\n"); return -1);
    CHECK_RET(aclrtSetDevice(deviceId) == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed\n"); aclFinalize(); return -1);
    CHECK_RET(aclrtCreateStream(&stream) == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed\n"); aclrtResetDevice(deviceId); aclFinalize(); return -1);

    // 1. Initialize the aclsparseLt library handle
    {
        auto s = aclsparseLtInit(&handle);
        CHECK_RET(s == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("aclsparseLtInit failed: %d\n", s); ret = -1);
    }

    // 2. Prepare the Host-side matrix A (m x k, FP32, row-major)
    //    k must be a multiple of 8 (FP32 structured descriptor alignment requirement, pruning groups in 2)
    for (size_t i = 0; i < hA.size(); i++) { hA[i] = static_cast<float>(i % 7) - 3.0f; }

    // 3. Copy data to the Device
    dA = AllocAndCopyDevice(hA.data(), static_cast<size_t>(m) * k * sizeof(float));
    aclrtMalloc(&dAPruned, static_cast<size_t>(m) * k * sizeof(float), ACL_MEM_MALLOC_HUGE_FIRST);

    // 4. Create matrix descriptors
    //    Matrix A: structured sparse descriptor (2:4); data is passed in explicitly through d_in at SpMMAPrune
    {
        auto s = aclsparseLtStructuredDescriptorInit(
            &handle, &matA, m, k, k, 16, ACL_FLOAT,
            ACL_SPARSE_ORDER_ROW, ACL_SPARSE_LT_SPARSITY_50_PERCENT);
        CHECK_RET(s == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("StructuredDescriptorInit A failed: %d\n", s); ret = -1);
    }

    //    B/C/D: placeholder dense descriptors (pruning does not consume their data, but Matmul descriptor initialization requires binding them)
    //    Dimensions must be consistent with A: B(k x n), C/D(m x n)
    aclsparseLtDenseDescriptorInit(&handle, &matB, k, n, n, 16, ACL_FLOAT, ACL_SPARSE_ORDER_ROW);
    aclsparseLtDenseDescriptorInit(&handle, &matC, m, n, n, 16, ACL_FLOAT, ACL_SPARSE_ORDER_ROW);
    aclsparseLtDenseDescriptorInit(&handle, &matD, m, n, n, 16, ACL_FLOAT, ACL_SPARSE_ORDER_ROW);

    // 5. Create the Matmul descriptor (opA=N, which determines pruning along rows)
    {
        auto s = aclsparseLtMatmulDescriptorInit(
            &handle, &matmulDesc,
            ACL_SPARSE_OP_NON_TRANSPOSE, ACL_SPARSE_OP_NON_TRANSPOSE,
            &matA, &matB, &matC, &matD, ACL_SPARSE_COMPUTE_32F);
        CHECK_RET(s == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("MatmulDescriptorInit failed: %d\n", s); ret = -1);
    }

    // 6. Execute pruning: dA -> dAPruned
    //    The second parameter must be aclsparseLtConstMatmulDescriptor_t* (a pointer to a const pointer),
    //    and &matmulDesc is aclsparseLtMatmulDescriptor_t*; C++ does not allow implicit conversion from T** -> const T**, so const_cast is required.
    {
        auto s = aclsparseLtSpMMAPrune(
            &handle, const_cast<aclsparseLtConstMatmulDescriptor_t*>(&matmulDesc),
            dA, dAPruned, ACLSPARSELT_PRUNE_SPMMA_STRIP, stream);
        CHECK_RET(s == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("SpMMAPrune failed: %d\n", s); ret = -1);
    }

    // 7. Synchronize and wait for pruning to complete (the caller is responsible for synchronization; the operator does not synchronize internally)
    aclrtSynchronizeStream(stream);

    // 8. Copy the result back to the Host
    aclrtMemcpy(hAPruned.data(), static_cast<size_t>(m) * k * sizeof(float),
                dAPruned, static_cast<size_t>(m) * k * sizeof(float),
                ACL_MEMCPY_DEVICE_TO_HOST);

    // Verify: for FP32, every 2 elements keep 1 (the one with the larger absolute value), and the other is zeroed
    for (size_t i = 0; i < hAPruned.size(); i++) {
        if (hAPruned[i] == 0.0f) { zeroCnt++; }
    }
    LOG_PRINT("prune done: %d / %zu elements zeroed (~50%% expected)\n", zeroCnt, hAPruned.size());

cleanup:
    // 9. Clean up resources (destroy in reverse dependency order; both the exception path and the normal path release from here)
    if (matmulDesc != nullptr) { aclsparseLtMatmulDescriptorDestroy(&matmulDesc); }
    if (matA != nullptr) { aclsparseLtMatDescriptorDestroy(&matA); }
    if (matB != nullptr) { aclsparseLtMatDescriptorDestroy(&matB); }
    if (matC != nullptr) { aclsparseLtMatDescriptorDestroy(&matC); }
    if (matD != nullptr) { aclsparseLtMatDescriptorDestroy(&matD); }
    if (handle != nullptr) { aclsparseLtDestroy(&handle); }
    if (dA != nullptr) { aclrtFree(dA); }
    if (dAPruned != nullptr) { aclrtFree(dAPruned); }
    if (stream != nullptr) { aclrtDestroyStream(stream); }
    aclrtResetDevice(deviceId);
    aclFinalize();
    return ret;
}

int main()
{
    return aclsparseLtPruneTest();
}

The expected output is as follows (the exact number of zero elements depends on the input data and is about 50% of the total number of elements):

prune done: 256 / 512 elements zeroed (~50% expected)

in-place usage: change dAPruned in the preceding example to reuse dA (that is, aclsparseLtSpMMAPrune(&handle, const_cast<aclsparseLtConstMatmulDescriptor_t*>(&matmulDesc), dA, dA, ...)), and the pruning result directly overwrites the Device memory of the input matrix A.

References