FilesLast commitLast update
README

aclsparseLtMatmul

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: aclsparseLtMatmul executes 2:4 structured sparse matrix multiplication with fused epilogue post-processing:

    D = Activation(alpha * op(A_pruned) * op(B) + beta * C + bias)
    

    where A_pruned is the dense-storage matrix after pruning by aclsparseLtSpMMAPrune (pruned elements are represented by 0). The epilogue chain executes in sequence: alpha scaling → beta·C accumulation → per-row broadcast addition of bias → activation (ReLU/GeLU, optional) → type conversion and writeout. alpha/beta support scalars (Host float) or per-row vector scaling (Device float[M], with ALPHA_VECTOR_SCALING/BETA_VECTOR_SCALING enabled). bias is a per-row broadcast vector with length = m (same dtype as C; the only exception: for INT8 A/B × C/D ∈ {INT8,INT32} (32I compute domain), the dtype is FP32—for INT8 × C/D=FP16/BF16, the bias is still FP16/BF16 = C dtype). activation supports ReLU (min(upperBound, max(threshold, D))) and GeLU (gelu_scaling * x * sigmoid(sqrt(8/π) * (x + 0.044715 * x³))), which are mutually exclusive. Batch computation is supported (NUM_BATCHES + BATCH_STRIDE). This operator corresponds to cusparseLtMatmul in cuSPARSELt and adopts the segmented invocation model of descriptor (Descriptor) + algorithm selection (AlgSelection) + execution plan (Plan). Epilogue functions are implemented through descriptor attribute extension, and no new computation interface is added.

  • Target platform: Ascend 950PR&950DT products (arch35 / DAV_3510).

  • Programming model: The ascendc Cube (Mmad/Fixpipe) matrix multiplication hardware unit executes the core GEMM, and the Vector unit executes the epilogue (alpha·acc + beta·C + bias + activation + type conversion). When splitK=1, the AIC+AIV fused single-kernel path is used (L0C→UB→GM); when splitK>1, the two-stage path is used (Cube writes temp → epilogue reduces and writes D). bias and activation are executed in the FP32 domain after beta·C and before type conversion. The operator starts asynchronously and does not perform stream synchronization internally.

  • Supported dtypes: FP32 / FP16 / BF16 / INT8 (v2 extends BF16/INT8). The INT8 path uses computeType = ACL_SPARSE_COMPUTE_32I (int32 accumulation), and C/D supports INT8/INT32/FP16/BF16 combinations (for details, see the data type consistency in "Constraints" and the "INT8 dual output" section).

  • Supported paths: sparse×dense (2:4 structured sparse × dense) + dense×dense (dense × dense, newly added in v2). The dense×dense path skips the pruning prerequisite, and matA must be passed in explicitly.

Mathematical principle

Problem definition

A_pruned = Prune_2:4(A)
D = Activation(alpha * op(A_pruned) * op(B) + beta * C + bias)
Symbol Meaning Dimension/Type
A_pruned Structured sparse matrix after pruning (dense storage, produced by SpMMAPrune) m×k, FP32/FP16/BF16/INT8
B Dense input matrix k×n (or n×k when transB=1), FP32/FP16/BF16/INT8
C Dense input matrix (accumulation term) m×n, same type as A/B (in the INT8 path, C must be INT8)
D Dense output matrix m×n, same type as C (in the INT8 path, D can be INT8 or INT32)
alpha Scaling factor: in scalar mode, a Host-side float; in vector scaling mode, a Device-side float[M] (per-row) float / float[M]
beta Scaling factor: in scalar mode, a Host-side float; in vector scaling mode, a Device-side float[M] (per-row) float / float[M]
bias Per-row broadcast bias vector with length = m, broadcast per row to n elements in each row Same dtype as C; the exception for INT8 A/B × C/D ∈ {INT8,INT32} (32I compute domain) is FP32, and for INT8 × C/D=FP16/BF16 it is FP16/BF16 (= C dtype)

alpha/beta in scalar mode are always parsed as Host-side floats (aligned with cuSPARSELt). When ALPHA_VECTOR_SCALING is enabled, alpha is a Device-side float[M] for per-row scaling; when BETA_VECTOR_SCALING is enabled, beta is a Device-side float[M] for per-row scaling (which implies enabling ALPHA_VECTOR_SCALING, cuSPARSELt semantics). Currently FP32/FP16/BF16/INT8 inputs are supported.

bias

bias is a vector with length = m (same dtype as C: in the FP32 path, bias is FP32; in the FP16 path, bias is FP16; in the BF16 path, bias is BF16; the exception for INT8 A/B × C/D ∈ {INT8,INT32} (32I compute domain) is FP32—as specified by cuSPARSELt, for INT8 × C/D=FP16/BF16, the bias is FP16/BF16 = C dtype), with per-row broadcast: all n elements in row r add bias[r]. bias is accumulated in the FP32 domain into the intermediate result dFp32UB after beta·C and before activation (in the FP16/BF16 path, bias is first cast to FP32 and then accumulated).

activation

activation is executed in the FP32 domain after bias and before type conversion. ReLU and GeLU are mutually exclusive (enabling both returns ACL_SPARSE_STATUS_INVALID_VALUE). By default, no activation is used (activationRelu=0 and activationGelu=0).

Activation type Formula Parameters Default values
ReLU D = min(upperBound, max(threshold, D)) threshold, upperBound threshold=0.0f, upperBound=FLT_MAX (degrades to standard ReLU max(0, x))
GeLU D = gelu_scaling * x * sigmoid(sqrt(8/π) * (x + 0.044715 * x³)) gelu_scaling 1.0f

GeLU constants: sqrt(8/π) ≈ 1.5957691f, 0.044715f. In the implementation, the internal variable z = sqrt(8/π) * (x + 0.044715 * x³) is truncated by min(z, 20.0f) before Exp, to prevent the FP32 Exp from returning inf (which causes NaN) when the input exceeds 88.7; exp(20)≈4.85e8 and sigmoid(20)≈1.0, so within the truncation range the result is consistent with the golden value and does not change the numerical semantics.

GeLU dtype support: cuSPARSELt restricts GeLU to the INT8/FP8 paths; this implementation extends it to all dtypes (FP32/FP16/BF16/INT8), all computed in the FP32 domain. The INT8 path behaves the same as cuSPARSELt, and the extension targets only dtypes not covered by cuSPARSELt.

batch

Batch matrix multiplication is supported: numBatches matrix pairs are computed iteratively at their own batchStride offsets:

D[b] = Activation(alpha * op(A[b]) * op(B[b]) + beta * C[b] + bias[b])
b = 0 .. numBatches-1
  • The numBatches values of the four matrices A/B/C/D must be consistent (aclsparseLtMatmulDescriptorInit validates this; an inconsistency returns INVALID_VALUE).
  • batchStride is measured in elements and set independently for each matrix (through aclsparseLtMatDescSetAttribute). batchStride = 0 means cross-batch broadcast on that side (aligned with the cuSPARSELt batch_stride=0 semantics): all batches on that side read and write batch 0—on the read side (A/B/C), each batch reuses the batch 0 matrix; on the write side (D), this is alias writing across batches, and the final value is the computation result of the last batch (deterministic under single-stream sequential execution). Each side is set and determined independently; a negative value returns INVALID_VALUE.
  • When biasStride == 0, all batches share the same bias vector; when biasStride != 0, each batch uses its own bias at the biasStride offset.
  • Multi-core splitting: totalTiles = numBatches × mTiles × nTiles (fused path) or numBatches × splitK × mTiles × nTiles (two-stage path), with blockId allocated by stride.

Dimension derivation

The logical dimensions m/n/k are derived from the descriptor dimensions of matrices A and B and from opA/opB (consistent with cuSPARSELt):

opA m k
NON_TRANSPOSE A.rows A.cols
TRANSPOSE A.cols A.rows
opB k n
NON_TRANSPOSE B.rows B.cols
TRANSPOSE B.cols B.rows

Currently the Matmul execution stage supports opA/opB = NON_TRANSPOSE and TRANSPOSE. transA is implemented by switching the pruning direction in the pruning stage (pruneAlongRow = (transA != isRowOrder), for details see prune/README_en.md); transB is implemented by having the matmul kernel declare the GM B as a DNExt(k,n) column-major view, where CopyGM2L1 automatically selects the DN2ZN transposition. CONJUGATE_TRANSPOSE is not supported.

splitK splitting

When the K dimension is large or the number of m×n tiles is not enough to fill all cores, you can set splitK > 1 through aclsparseLtMatmulAlgSetAttribute to split the K dimension into splitK segments computed in parallel; the results of all segments are written to the temp buffer and then reduced and summed by the epilogue. When splitK=1, the fused path is used and no temp buffer is needed. The value range of splitK is [1, K].

Interface description

The complete invocation chain of aclsparseLtMatmul includes: library handle management, matrix descriptor initialization, Matmul descriptor initialization, algorithm selection and attribute setting, plan initialization, workspace query, execution, and destruction. The following describes each interface in invocation order.

Library handle management

aclsparseLtInit

Initializes the aclsparseLt library handle. You must call it before calling any other aclsparseLt function.

aclsparseStatus_t aclsparseLtInit(aclsparseLtHandle_t* handle);
Parameter Input/Output Parameter type Description
handle Output aclsparseLtHandle_t* Output parameter of the library handle; *handle must be nullptr before the call; host memory

aclsparseLtDestroy

Releases all resources occupied by the library handle. After the call, the handle can no longer be used.

aclsparseStatus_t aclsparseLtDestroy(const aclsparseLtHandle_t* handle);
Parameter Input/Output Parameter type Description
handle Input const aclsparseLtHandle_t* const pointer to the library handle to destroy. If the pointer itself is nullptr, HANDLE_IS_NULLPTR is returned; if the handle value pointed to is nullptr, the call is treated as a no-op; host memory

The handle parameter of all public APIs is aclsparseLtConstHandle_t (that is, const aclsparseLtHandle_t*); pass &handle at invocation.

Matrix descriptor initialization

aclsparseLtStructuredDescriptorInit

Initializes the structured (2:4 sparse) matrix descriptor for matrix A.

aclsparseStatus_t aclsparseLtStructuredDescriptorInit(
    aclsparseLtConstHandle_t handle,
    aclsparseLtMatDescriptor_t* matDescr,
    int64_t rows, int64_t cols, int64_t ld,
    uint32_t alignment, aclDataType valueType, aclsparseOrder_t order,
    aclsparseLtSparsity_t sparsity);
Parameter Input/Output Parameter type Description
handle Input aclsparseLtConstHandle_t const pointer to the library handle; host memory
matDescr Output aclsparseLtMatDescriptor_t* Output of the structured matrix descriptor; host memory
rows Input int64_t Number of matrix rows; must be > 0 and ≤ INT32_MAX; host memory
cols Input int64_t Number of matrix columns; must be > 0 and ≤ INT32_MAX; host memory
ld Input int64_t Leading dimension (row-to-row span); must be > 0; for ROW order, ld ≥ cols; for COL order, ld ≥ rows; host memory
alignment Input uint32_t Memory alignment in bytes; must be a multiple of 16; host memory
valueType Input aclDataType Matrix data type; supports ACL_FLOAT / ACL_FLOAT16 / ACL_BF16 / ACL_INT8; host memory
order Input aclsparseOrder_t Matrix storage order (ROW / COL); affects only the pruning direction; host memory
sparsity Input aclsparseLtSparsity_t Sparsity mode; supports only ACL_SPARSE_LT_SPARSITY_50_PERCENT; host memory

Aligned with cuSPARSELt: no data pointer is bound at descriptor initialization; data is passed in explicitly through parameters such as matA/d_in at Matmul/Prune execution.

aclsparseLtDenseDescriptorInit

Initializes the dense matrix descriptor for matrices B/C/D.

aclsparseStatus_t aclsparseLtDenseDescriptorInit(
    aclsparseLtConstHandle_t handle,
    aclsparseLtMatDescriptor_t* matDescr,
    int64_t rows, int64_t cols, int64_t ld,
    uint32_t alignment, aclDataType valueType, aclsparseOrder_t order);

The parameter semantics are the same as those of aclsparseLtStructuredDescriptorInit; the difference is that there is no sparsity parameter. valueType supports ACL_FLOAT / ACL_FLOAT16 / ACL_BF16 / ACL_INT8 / ACL_INT32 (INT32 is used only for the matC/matD output descriptors in the INT8 path). The data pointer is passed in explicitly at Matmul execution.

Matmul descriptor initialization

aclsparseLtMatmulDescriptorInit

Initializes the Matmul operation descriptor and binds A/B/C/D and the operation types.

aclsparseStatus_t aclsparseLtMatmulDescriptorInit(
    aclsparseLtConstHandle_t handle,
    aclsparseLtMatmulDescriptor_t* matmulDescr,
    aclsparseOperation_t opA, aclsparseOperation_t opB,
    const aclsparseLtMatDescriptor_t* matA,
    const aclsparseLtMatDescriptor_t* matB,
    const aclsparseLtMatDescriptor_t* matC,
    const aclsparseLtMatDescriptor_t* matD,
    aclsparseComputeType_t computeType);
Parameter Input/Output Parameter type Description
handle Input aclsparseLtConstHandle_t const pointer to the library handle; host memory
matmulDescr Output aclsparseLtMatmulDescriptor_t* Output of the Matmul descriptor; host memory
opA Input aclsparseOperation_t Operation type of matrix A; supports NON_TRANSPOSE / TRANSPOSE; CONJUGATE_TRANSPOSE is not supported; host memory
opB Input aclsparseOperation_t Operation type of matrix B; supports NON_TRANSPOSE / TRANSPOSE; CONJUGATE_TRANSPOSE is not supported; host memory
matA Input const aclsparseLtMatDescriptor_t* Structured sparse matrix A descriptor; host memory
matB Input const aclsparseLtMatDescriptor_t* Dense matrix B descriptor; host memory
matC Input const aclsparseLtMatDescriptor_t* Dense matrix C descriptor (accumulation term); host memory
matD Input const aclsparseLtMatDescriptor_t* Dense matrix D descriptor (output); host memory
computeType Input aclsparseComputeType_t Computation precision, bound to the A/B input dtype (aligned with the cuSPARSELt data type table): ACL_SPARSE_COMPUTE_32F corresponds to FP32/FP16/BF16 inputs (FP32 accumulation); ACL_SPARSE_COMPUTE_16F corresponds only to FP16 inputs (this implementation executes with FP32 accumulation, see the note below); ACL_SPARSE_COMPUTE_32I corresponds to INT8 inputs (int32 accumulation). A mismatch returns ACL_SPARSE_STATUS_NOT_SUPPORTED. valueTypes outside the main four types, such as FP8/FP4, do not participate in binding validation (superset at the descriptor layer; still rejected at the execution layer); host memory

computeType binding rules (validated at the MatmulDescriptorInit layer): COMPUTE_32F requires A/B to be FP32/FP16/BF16 (L0C accumulates as float); COMPUTE_16F requires A/B to be FP16—the hardware does not support FP16 accumulation, so this implementation executes through the FP32 accumulation path, with precision identical to the 32F path and better than the half-precision accumulation of cuSPARSELt 16F (superset behavior: it accepts the officially valid combinations without degrading result precision); COMPUTE_32I requires A/B to be INT8 (L0C accumulates as int32_t). A binding mismatch returns ACL_SPARSE_STATUS_NOT_SUPPORTED. In the INT8 path, the supported combinations of C/D can be INT8/INT32/FP16/BF16 (for details, see "Constraints" and the "INT8 dual output" section below).

Matmul descriptor attribute setting / query

The Matmul descriptor attributes configure vector scaling, bias, and activation of the epilogue chain. These attributes are read from the descriptor at execution time (each execution of aclsparseLtMatmul / aclsparseLtMatmulSearch), and modifications after aclsparseLtMatmulPlanInit take effect for subsequent executions (lenient timing, no plan reinitialization needed). Exception: ACLSPARSELT_MATMUL_SPARSE_MAT_POINTER (value 9) is a store-only attribute—provided to be compatible with the invocation sequence of the official cuSPARSELt samples that Set the sparse matrix pointer after DescriptorInit. Matmul/Search execution always follows the function parameters matA/matB (parameters take precedence); this attribute does not participate in algorithm selection or execution, and is not a fallback source for matA=null (for the fallback semantics of matA=null, see the matA fallback path entry in "Constraints").

aclsparseLtMatmulDescSetAttribute

Sets matmul descriptor attributes (aligned with cuSPARSELt cusparseLtMatmulDescSetAttribute).

aclsparseStatus_t aclsparseLtMatmulDescSetAttribute(
    aclsparseLtConstHandle_t handle,
    aclsparseLtMatmulDescriptor_t* matmulDescr,
    aclsparseLtMatmulDescAttribute_t matmulAttribute,
    const void* data,
    size_t dataSize);
Parameter Input/Output Parameter type Description
handle Input aclsparseLtConstHandle_t const pointer to the library handle; host memory
matmulDescr Input/Output aclsparseLtMatmulDescriptor_t* matmul descriptor; must be initialized; host memory
matmulAttribute Input aclsparseLtMatmulDescAttribute_t Attribute enumeration to set; host memory
data Input const void* Data pointer of the attribute value; host memory
dataSize Input size_t Size of the data buffer (bytes); must equal the sizeof of the corresponding enumeration; host memory

The settable attributes are as follows:

Attribute enumeration Value Value type Default value Description
ACLSPARSELT_MATMUL_ALPHA_VECTOR_SCALING 0 int 0 alpha per-row vector scaling switch; 0=disabled (scalar mode), non-0=enabled (alpha is Device float[M]). dataSize must = sizeof(int)
ACLSPARSELT_MATMUL_BETA_VECTOR_SCALING 1 int 0 beta per-row vector scaling switch; 0=disabled, non-0=enabled. Enabling it implies enabling ALPHA_VECTOR_SCALING (cuSPARSELt semantics). dataSize must = sizeof(int)
ACLSPARSELT_MATMUL_BIAS_POINTER 2 void* NULL Device pointer of the bias vector, length = m. Same dtype as the C matrix (in the FP32 path, bias is FP32; in the FP16 path, bias is FP16; in the BF16 path, bias is BF16); the exception for INT8 A/B × C/D ∈ {INT8,INT32} (32I compute domain) is FP32, and for INT8 × C/D=FP16/BF16 it is FP16/BF16 (= C dtype). NULL=bias not enabled. dataSize must = sizeof(void*)
ACLSPARSELT_MATMUL_BIAS_STRIDE 3 int64_t 0 bias stride between batches (in elements); 0=all batches share the same bias. dataSize must = sizeof(int64_t)
ACLSPARSELT_MATMUL_ACTIVATION_RELU 4 int 0 ReLU switch; 0=disabled, non-0=enabled. Mutually exclusive with GeLU. dataSize must = sizeof(int)
ACLSPARSELT_MATMUL_ACTIVATION_RELU_UPPERBOUND 5 float FLT_MAX ReLU upper bound (min(upperBound, D)). dataSize must = sizeof(float)
ACLSPARSELT_MATMUL_ACTIVATION_RELU_THRESHOLD 6 float 0.0f ReLU threshold (max(threshold, D)). dataSize must = sizeof(float)
ACLSPARSELT_MATMUL_ACTIVATION_GELU 7 int 0 GeLU switch; 0=disabled, non-0=enabled. Mutually exclusive with ReLU. dataSize must = sizeof(int)
ACLSPARSELT_MATMUL_ACTIVATION_GELU_SCALING 8 float 1.0f GeLU scaling coefficient. Setting this attribute implies enabling GeLU (cuSPARSELt semantics: It implies ACTIVATION_GELU). If ReLU is already enabled, GeLU is not enabled automatically (mutual exclusion semantics are preserved). dataSize must = sizeof(float)
ACLSPARSELT_MATMUL_SPARSE_MAT_POINTER 9 void* NULL Device pointer of the sparse matrix (A_pruned/B_pruned). Store-only: Matmul/Search execution follows the function parameters matA/matB (parameters take precedence), and this attribute does not participate in algorithm selection or execution—provided to be compatible with the invocation sequence of the official cuSPARSELt samples that Set this attribute after DescriptorInit (the official cuSPARSELt note says "it provides algorithm selection flexibility for Search"; in this implementation, the Search candidate space is unrelated to this pointer). Keep the lifetime of the referenced memory until the descriptor is no longer used, as suggested by the official note. dataSize must = sizeof(void*)

ReLU/GeLU mutual exclusion check: When SetAttribute enables one activation and the other is already enabled, ACL_SPARSE_STATUS_INVALID_VALUE is returned; when set to 0 (off), no check is performed. For example, if GeLU is enabled (ACTIVATION_GELU=1) and you then set ACTIVATION_RELU=1, an error is returned; if you first set ACTIVATION_GELU=0 to disable GeLU and then enable ReLU, the operation succeeds.

aclsparseLtMatmulDescGetAttribute

Queries the current values of matmul descriptor attributes (aligned with cuSPARSELt cusparseLtMatmulDescGetAttribute).

aclsparseStatus_t aclsparseLtMatmulDescGetAttribute(
    aclsparseLtConstHandle_t handle,
    aclsparseLtConstMatmulDescriptor_t* matmulDescr,
    aclsparseLtMatmulDescAttribute_t matmulAttribute,
    void* data,
    size_t dataSize);

The parameter semantics are the same as those of SetAttribute, and data is the output. Querying the current values of all 10 attribute enumerations above is supported (including SPARSE_MAT_POINTER, default NULL), and dataSize must equal the sizeof of the corresponding enumeration.

Matrix descriptor attribute setting / query (batch)

The matrix descriptor attributes configure batch-related parameters. They must be set before aclsparseLtMatmulDescriptorInit (the Init validates the numBatches consistency of the four matrices A/B/C/D).

aclsparseLtMatDescSetAttribute

Sets matrix descriptor attributes (aligned with cuSPARSELt cusparseLtMatDescSetAttribute).

aclsparseStatus_t aclsparseLtMatDescSetAttribute(
    aclsparseLtConstHandle_t handle,
    aclsparseLtMatDescriptor_t* matDescr,
    aclsparseLtMatDescAttribute_t matAttribute,
    const void* data,
    size_t dataSize);
Parameter Input/Output Parameter type Description
handle Input aclsparseLtConstHandle_t const pointer to the library handle; host memory
matDescr Input/Output aclsparseLtMatDescriptor_t* Matrix descriptor; host memory
matAttribute Input aclsparseLtMatDescAttribute_t Attribute enumeration to set; host memory
data Input const void* Data pointer of the attribute value; host memory
dataSize Input size_t Size of the data buffer (bytes); must equal the sizeof of the corresponding enumeration; host memory

The settable attributes are as follows:

Attribute enumeration Value Value type Default value Description
ACLSPARSELT_MAT_NUM_BATCHES 0 int32_t 1 Number of batches; must be >= 1. dataSize must = sizeof(int32_t)
ACLSPARSELT_MAT_BATCH_STRIDE 1 int64_t 0 Stride between batches (in elements); set independently for each matrix. dataSize must = sizeof(int64_t)

numBatches consistency check: At aclsparseLtMatmulDescriptorInit, the numBatches values of the four matrices A/B/C/D must be consistent; an inconsistency returns ACL_SPARSE_STATUS_INVALID_VALUE. aclsparseLtMatDescSetAttribute checks only that the numBatches of a single descriptor is >= 1, without cross-matrix validation.

aclsparseLtMatDescGetAttribute

Queries the current values of matrix descriptor attributes (aligned with cuSPARSELt cusparseLtMatDescGetAttribute).

aclsparseStatus_t aclsparseLtMatDescGetAttribute(
    aclsparseLtConstHandle_t handle,
    aclsparseLtConstMatDescriptor_t* matDescr,
    aclsparseLtMatDescAttribute_t matAttribute,
    void* data,
    size_t dataSize);

The parameter semantics are the same as those of SetAttribute, and data is the output. Querying the current values of ACLSPARSELT_MAT_NUM_BATCHES and ACLSPARSELT_MAT_BATCH_STRIDE is supported.

Algorithm selection and attribute setting

aclsparseLtMatmulAlgSelectionInit

Initializes the algorithm selection descriptor, with default algConfigId=0, splitK=1, and searchIterations=5.

aclsparseStatus_t aclsparseLtMatmulAlgSelectionInit(
    aclsparseLtConstHandle_t handle,
    aclsparseLtMatmulAlgSelection_t* algSelection,
    const aclsparseLtMatmulDescriptor_t* matmulDescr,
    aclsparseLtMatmulAlg_t alg);
Parameter Input/Output Parameter type Description
handle Input aclsparseLtConstHandle_t const pointer to the library handle; host memory
algSelection Output aclsparseLtMatmulAlgSelection_t* Output of the algorithm selection descriptor; host memory
matmulDescr Input aclsparseLtConstMatmulDescriptor_t* Matmul descriptor; host memory
alg Input aclsparseLtMatmulAlg_t Algorithm type; supports only ACL_SPARSE_LT_MATMUL_ALG_DEFAULT; host memory

aclsparseLtMatmulAlgSetAttribute

Sets algorithm selection attributes. This is the core interface for configuring Matmul execution behavior, used to switch the algorithm configuration, splitK splitting, and so on.

aclsparseStatus_t aclsparseLtMatmulAlgSetAttribute(
    aclsparseLtConstHandle_t handle,
    aclsparseLtMatmulAlgSelection_t* algSelection,
    aclsparseLtMatmulAlgAttribute_t attr,
    const void* attrValue,
    size_t attrValueSize);
Parameter Input/Output Parameter type Description
handle Input aclsparseLtConstHandle_t const pointer to the library handle; host memory
algSelection Input aclsparseLtMatmulAlgSelection_t* Algorithm selection descriptor; host memory
attr Input aclsparseLtMatmulAlgAttribute_t Attribute enumeration to set; host memory
attrValue Input const void* Pointer to the attribute value; host memory
attrValueSize Input size_t Size of the attrValue buffer (bytes); host memory

The settable attributes are as follows:

Attribute enumeration Value type Value range Description
ACLSPARSELT_MATMUL_ALG_CONFIG_ID int32_t 0 / 1 Algorithm configuration ID, which affects cube tiling (baseM/baseN/baseK). Set it before PlanInit
ACLSPARSELT_MATMUL_SPLIT_K int32_t [1, K] splitK split factor. Set it before PlanInit
ACLSPARSELT_MATMUL_SEARCH_ITERATIONS int32_t > 0 Number of search iterations (5 by default), consumed live by the aclsparseLtMatmulSearch search entry
ACLSPARSELT_MATMUL_SPLIT_K_MODE int32_t 0 / 1 splitK mode (ONE_KERNEL / TWO_KERNELS), which participates in the effectiveSplitK computation: in ONE_KERNEL mode, effectiveSplitK=1 (fused path); in TWO_KERNELS mode, effectiveSplitK=splitK (two-stage path)
ACLSPARSELT_MATMUL_SPLIT_K_BUFFERS int32_t [0, splitK-1] Number of splitK buffers; currently the value is stored only and does not participate in execution
ACLSPARSELT_MATMUL_ALG_CONFIG_MAX_ID — Read-only Cannot be set; returns ACL_SPARSE_STATUS_NOT_SUPPORTED

Attributes must be set before aclsparseLtMatmulPlanInit; PlanInit reads algConfigId and splitK to compute tiling.

aclsparseLtMatmulAlgGetAttribute

Queries the current values of algorithm selection attributes.

aclsparseStatus_t aclsparseLtMatmulAlgGetAttribute(
    aclsparseLtConstHandle_t handle,
    aclsparseLtConstMatmulAlgSelection_t* algSelection,
    aclsparseLtMatmulAlgAttribute_t attr,
    void* attrValue,
    size_t attrValueSize);

The parameter semantics are the same as those of AlgSetAttribute, and attrValue is the output. The ACLSPARSELT_MATMUL_ALG_CONFIG_MAX_ID query returns 2 (algConfigId 0 and 1 give 2 configurations in total). For detailed documentation, see alg_get_attribute/README_en.md.

Plan initialization and workspace query

aclsparseLtMatmulPlanInit

Initializes the execution plan, computes the cube tiling parameters and workspace size, and freezes them into the plan. PlanInit validates descriptor dimension consistency, dtype consistency, the validity of algConfigId/splitK values, and so on.

aclsparseStatus_t aclsparseLtMatmulPlanInit(
    aclsparseLtConstHandle_t handle,
    aclsparseLtMatmulPlan_t* plan,
    const aclsparseLtMatmulDescriptor_t* matmulDescr,
    const aclsparseLtMatmulAlgSelection_t* algSelection);
Parameter Input/Output Parameter type Description
handle Input aclsparseLtConstHandle_t const pointer to the library handle; host memory
plan Output aclsparseLtMatmulPlan_t* Output of the execution plan; host memory
matmulDescr Input aclsparseLtConstMatmulDescriptor_t* Matmul descriptor; host memory
algSelection Input aclsparseLtConstMatmulAlgSelection_t* Algorithm selection descriptor; host memory

aclsparseLtMatmulGetWorkspace

Queries the workspace size (bytes) required by Matmul.

aclsparseStatus_t aclsparseLtMatmulGetWorkspace(
    aclsparseLtConstHandle_t handle,
    aclsparseLtConstMatmulPlan_t* plan, size_t* workspaceSize);
Parameter Input/Output Parameter type Description
handle Input aclsparseLtConstHandle_t const pointer to the library handle; host memory
plan Input aclsparseLtConstMatmulPlan_t* Execution plan; host memory
workspaceSize Output size_t* Required workspace size (bytes); host memory

workspace layout (each area 64-byte aligned): [ *tiling area* .. *aPruned area* .. *temp area* ]. When splitK=1, no temp area is allocated (the fused path directly uses L0C→UB→GM); when splitK>1, the temp area size is numBatches×splitK×m×n×4 bytes (multiplied by numBatches in batch mode).

Execution

aclsparseLtMatmul

Executes structured sparse matrix multiplication with fused epilogue post-processing: D = Activation(alpha * op(A_pruned) * op(B) + beta * C + bias). bias and activation are pre-configured into the matmul descriptor through aclsparseLtMatmulDescSetAttribute; no extra parameters are passed at execution.

aclsparseStatus_t aclsparseLtMatmul(
    aclsparseLtConstHandle_t handle,
    aclsparseLtConstMatmulPlan_t* plan,
    const void* alpha,
    const void* matA, const void* matB,
    const void* beta,
    const void* matC, void* matD,
    void* workspace,
    aclrtStream* streams, int32_t numStreams);
Parameter Input/Output Parameter type Description
handle Input aclsparseLtConstHandle_t const pointer to the library handle; host memory
plan Input aclsparseLtConstMatmulPlan_t* Execution plan; host memory
alpha Input const void* Scaling factor. In scalar mode, a Host-side float pointer (nullptr is treated as 1.0); in vector scaling mode (with ALPHA_VECTOR_SCALING enabled), a Device-side float[M] pointer (per-row, must not be nullptr). Host/Device memory
matA Input const void* Device memory pointer of the sparse-side matrix A_pruned; must be 16-byte aligned. In the A-sparse case, it is A_pruned (produced by SpMMAPrune); in the B-sparse case, it is the dense matrix A. Only in the sparse×dense and A-sparse case, matA can be nullptr to fall back to the aPruned area of the workspace (the caller must have filled that area through SpMMAPrune); in the B-sparse and dense×dense paths, matA must be passed in explicitly. Device memory
matB Input const void* Device memory pointer of the dense matrix B; must be 16-byte aligned and must not be nullptr. In the A-sparse case, it is the dense matrix B; in the B-sparse case, it is B_pruned (produced by SpMMAPrune). Device memory
beta Input const void* Scaling factor. In scalar mode, a Host-side float pointer (nullptr is treated as 0.0); in vector scaling mode (with BETA_VECTOR_SCALING enabled), a Device-side float[M] pointer (per-row, must not be nullptr). Host/Device memory
matC Input const void* Device memory pointer of the dense matrix C; must be 16-byte aligned, must not be nullptr; Device memory. In batch mode, C arranges numBatches matrices at batchStrideC offsets; batchStrideC = 0 means C broadcasts across batches (each batch reuses batch 0)
matD Output void* Device memory pointer of the dense matrix D; must be 16-byte aligned, must not be nullptr; Device memory. In batch mode, D arranges numBatches matrices at batchStrideD offsets; batchStrideD = 0 means D broadcasts across batches (alias writing of the same buffer across batches; the final value is the computation result of the last batch, deterministic—it is not recommended to rely on intermediate states when combined with in-place (matC==matD))
workspace Input void* Device memory pointer of the workspace; must be 16-byte aligned, must not be nullptr; Device memory. In the two-stage path, the temp area size = numBatches × splitK × m × n × 4 bytes
streams Input aclrtStream* Array of ACL stream pointers; the operator executes asynchronously on these streams. It can be nullptr (meaning the default stream is used, aligned with the direct-pass usage streams=nullptr, numStreams=0 of the official cuSPARSELt samples; in this case, numStreams does not participate in the check). streams[0] can be nullptr (meaning the default stream is used); host memory. Currently only streams[0] is used (multiple streams are not yet supported)
numStreams Input int32_t Number of streams. When streams is nullptr, it does not participate in the check; when streams is not nullptr, it must be > 0; host memory

How bias and activation are passed in: The bias pointer is set into the matmul descriptor through aclsparseLtMatmulDescSetAttribute(ACLSPARSELT_MATMUL_BIAS_POINTER, &biasDevPtr), and the execution interface aclsparseLtMatmul does not include bias in its parameters. activation parameters (ReLU/GeLU and their threshold/scaling) are likewise set through descriptor attributes. All attribute settings must be completed before aclsparseLtMatmulPlanInit.

For the fallback path where matA is nullptr, the caller must ensure that the aPruned area of the workspace has been filled with valid data through SpMMAPrune; otherwise, uninitialized Device memory is read. The recommended path is to pass the d_out of SpMMAPrune explicitly as matA. matB/matC/matD must be passed in explicitly (aligned with cuSPARSELt; descriptor fallback is not supported).

Destruction

Call the destroy interfaces in reverse dependency order; destruction does not cascade invalidation:

aclsparseStatus_t aclsparseLtMatmulPlanDestroy(aclsparseLtMatmulPlan_t* plan);
aclsparseStatus_t aclsparseLtMatmulAlgSelectionDestroy(aclsparseLtMatmulAlgSelection_t* algSelection);
aclsparseStatus_t aclsparseLtMatmulDescriptorDestroy(aclsparseLtMatmulDescriptor_t* matmulDescr);
aclsparseStatus_t aclsparseLtMatDescriptorDestroy(aclsparseLtMatDescriptor_t* matDescr);

Each destroy interface takes a second-level pointer and sets it to nullptr after destruction. Passing nullptr or a *ptr that is nullptr returns SUCCESS (no-op).

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 Invalid parameter values (descriptor/matmulDescr/plan/stream is nullptr, dimensions do not match, ld does not satisfy layout constraints, data pointer is not 16-byte aligned, attrValueSize/dataSize does not match, algConfigId/splitK/searchIterations/splitKBuffers has an invalid value, alg is not the default, ReLU/GeLU mutual exclusion conflict, numBatches < 1 or the numBatches values of A/B/C/D are inconsistent, or matmulDesc is not fully initialized)
ACL_SPARSE_STATUS_NOT_SUPPORTED Unsupported parameter combinations (data type is not FP32/FP16/BF16/INT8, computeType does not match the dtype, CONJUGATE_TRANSPOSE, sparsity is not 50%, dimensions exceed 2097120, or matmulAttribute/matAttribute is out of the supported range)
ACL_SPARSE_STATUS_INSUFFICIENT_RESOURCES workspace is nullptr or the size is insufficient
ACL_SPARSE_STATUS_ALLOC_FAILED Descriptor memory allocation fails
ACL_SPARSE_STATUS_EXECUTION_FAILED An ACL runtime call fails (for example, aclrtMemcpy/aclrtMemsetAsync fails)

Supported specifications

Specification item Supported value Description
Data type (storage) ACL_FLOAT (FP32), ACL_FLOAT16 (FP16), ACL_BF16 (BF16), ACL_INT8 (INT8) The value types of matA/matB must be consistent; FP8 is not supported. In the INT8 path, matC must be INT8, and matD can be INT8 or INT32
Computation precision (computeType) ACL_SPARSE_COMPUTE_32F (FP32 accumulation), ACL_SPARSE_COMPUTE_16F (FP16 inputs, executed with FP32 accumulation), ACL_SPARSE_COMPUTE_32I (INT8 int32 accumulation) Binding rules (validated at the MatmulDescriptorInit layer; a mismatch returns NOT_SUPPORTED): COMPUTE_32F ↔ FP32/FP16/BF16 inputs; COMPUTE_16F ↔ FP16 inputs only (this implementation executes with FP32 accumulation, precision identical to the 32F path and better than the half-precision accumulation of cuSPARSELt 16F, superset behavior); COMPUTE_32I ↔ INT8 inputs
Computation path sparse×dense, dense×dense sparse×dense: matA or matB is structured sparse (2:4) and must be pruned first; dense×dense: matA/matB are both dense, skipping the pruning prerequisite
opA / opB (execution stage) NON_TRANSPOSE / TRANSPOSE transA is implemented by switching the pruning direction in the pruning stage; transB is implemented through a DNExt column-major view + automatic transposition in CopyGM2L1. CONJUGATE_TRANSPOSE is not supported
order ROW / COL Affects only the pruning direction; the kernel always accesses memory in row-major order
Sparsity mode ACL_SPARSE_LT_SPARSITY_50_PERCENT Supports only 2:4 (sparse×dense path)
alg ACL_SPARSE_LT_MATMUL_ALG_DEFAULT Default algorithm only
algConfigId 0 / 1 Affects cube tiling
splitK [1, K] splitK=1 fused path; splitK>1 two-stage path
Dimension upper limit m/n/k ≤ 2097120 Exceeding the limit returns INVALID_VALUE
K dimension alignment No alignment constraint The kernel handles non-aligned K through DataCopyPad and tail-clearing
Memory alignment Multiple of 16 bytes All data pointers and the alignment parameter (aligned with cuSPARSELt "All pointers must be aligned to 16 bytes"; bias/vector scaling pointers are loaded through DataCopyPad with GM source addresses; in actual tests, 16B-aligned sources work)
alpha / beta Host-side float (scalar mode) / Device-side float[M] (vector scaling mode) Scalar mode: alpha/beta are Host float pointers, and nullptr is treated as 1.0/0.0; vector scaling mode: after ALPHA_VECTOR_SCALING/BETA_VECTOR_SCALING is enabled, they are Device float[M] per-row scaling pointers, must not be nullptr, and the Device pointers must be 16-byte aligned. Enabling BETA_VECTOR_SCALING implies enabling ALPHA_VECTOR_SCALING
bias Device-side pointer, length = m, same dtype as C (the exception in the INT8 × 32I domain is FP32) Per-row broadcast. Set through ACLSPARSELT_MATMUL_BIAS_POINTER, default NULL (not enabled)
activation ReLU / GeLU / none (default) ReLU and GeLU are mutually exclusive. ReLU: min(upperBound, max(threshold, D)), default threshold=0.0f and upperBound=FLT_MAX; GeLU: gelu_scaling * x * sigmoid(sqrt(8/π) * (x + 0.044715 * x³)), default gelu_scaling=1.0f. Full dtype support (computed in the FP32 domain)
batch (numBatches) int32_t, >= 1, default 1 The numBatches values of the four matrices A/B/C/D must be consistent. batchStride is measured in elements and set independently for each matrix; 0=cross-batch broadcast on that side (all batches read and write batch 0, aligned with cuSPARSELt), and a negative value returns INVALID_VALUE. When biasStride=0, all batches share the bias
in-place Supported matC and matD can point to the same Device memory

Constraints

  • Data type consistency (validated at the execution layer; a violation returns ACL_SPARSE_STATUS_NOT_SUPPORTED):
    • FP32/FP16/BF16 paths: the value types of matC/matD must be consistent with those of matA/matB.
    • INT8 path (computeType = ACL_SPARSE_COMPUTE_32I): matA/matB must be INT8; the supported combinations of (matC, matD) are (INT8,INT8) / (INT8,INT32) / (INT32,INT32) / (FP16,FP16) / (BF16,BF16) (C/D have the same dtype, or C=INT8→D=INT32).
    • Unsupported types return ACL_SPARSE_STATUS_NOT_SUPPORTED. FP8 is not supported.
  • computeType and dtype matching (validated at the MatmulDescriptorInit layer, aligned with the cuSPARSELt data type table): ACL_SPARSE_COMPUTE_32F requires A/B to be FP32/FP16/BF16; ACL_SPARSE_COMPUTE_16F requires A/B to be FP16—this implementation executes with FP32 accumulation (the hardware does not support FP16 accumulation), with precision identical to the 32F path and better than the half-precision accumulation of cuSPARSELt 16F (superset behavior); ACL_SPARSE_COMPUTE_32I requires A/B to be INT8. A binding mismatch on either side of A/B returns ACL_SPARSE_STATUS_NOT_SUPPORTED. valueTypes outside the main four types, such as FP8/FP4, do not participate in binding validation (superset at the descriptor layer; the execution-layer dtype whitelist still rejects them).
  • Computation paths (sparse×dense / dense×dense):
    • sparse×dense: the sparsity of matA or matB is ACL_SPARSE_LT_SPARSITY_50_PERCENT (both cannot be sparse at the same time). You must first call aclsparseLtSpMMAPrune to prune, and pass the pruning result as matA.
    • dense×dense: matA and matB are both dense (sparsity=NONE). The pruning prerequisite is skipped (no prune group check), and matA must be passed in explicitly (no workspace fallback, because no prune front end fills the aPruned area).
  • Dimension consistency: the physical dimensions of A/B/C/D must match the logical (m, k, n) derived from opA/opB. C and D must have the same ld and order. Dimensions exceeding the limit (m/n/k > 2097120) return ACL_SPARSE_STATUS_INVALID_VALUE.
  • No K dimension alignment constraint: the kernel handles non-aligned K through DataCopyPad and tail-clearing, and K does not need to be a multiple of the group size. Both the sparse×dense and dense×dense paths have no such constraint.
  • Leading dimension constraints: for ROW order, ld ≥ the number of physical columns; for COL order, ld ≥ the number of physical rows. An ld of 0 returns ACL_SPARSE_STATUS_INVALID_VALUE.
  • Memory alignment: all Device data pointers (matA/matB/matC/matD/workspace/bias/vector scaling alpha/beta) must be 16-byte aligned; the alignment parameter must be a multiple of 16 (aligned with cuSPARSELt "All pointers must be aligned to 16 bytes"—bias pointers and vector scaling pointers are loaded through DataCopyPad with GM source addresses; in actual tests, 16B-aligned GM sources work; see ltmatmul_test_align16.cpp for the regression anchor; the d_in of prune_check is likewise 16 bytes, see prune_check/README_en.md). The per-batch bias stride biasStride must keep the sources of all batches 16-byte aligned (a multiple of 4 for FP32 and a multiple of 8 for FP16/BF16).
  • transpose support: the Matmul execution stage supports opA/opB = NON_TRANSPOSE and TRANSPOSE. transA is implemented by switching the pruning direction in the pruning stage (pruneAlongRow = (transA != isRowOrder); for the physical forms of the four RowView/ColView combinations, see prune/README_en.md); the transposed read of the sparse A_pruned on the matmul side is carried by the cube transpose flag (final view isColView = ((op==T) != (order==COL)); at execution time, the op component base value is flipped by order==COL); transB is isomorphic—dense B is carried by the DNExt/NDExt view + ld direct-read row stride, with no entry copy or preprocessing. CONJUGATE_TRANSPOSE is rejected at the descriptor initialization stage.
  • order semantics: order is the physical memory layout (not a direction switch), aligned with cuSPARSELt—in ROW order, element (i,j) is at i*ld+j (ld ≥ cols); in COL order, it is at j*ld+i (ld ≥ rows). The sparse side (A_pruned/B_pruned) is the (order, ld) layout output of the prune descriptor (the output keeps the input layout), and the matmul kernel accesses it through NDExt/DNExt views according to the descriptor layout (ld direct-read row stride; non-compact inputs with padding pass through); the dense side (A/B) and C/D are likewise accessed according to their own descriptor (order, ld) layouts. For details, see the pruning direction and physical layout in prune/README_en.md.
  • algConfigId semantics: algConfigId affects cube tiling (baseM/baseN/baseK), and different configurations deliver different performance for different shapes. Only 0 or 1 is accepted, and the ACLSPARSELT_MATMUL_ALG_CONFIG_MAX_ID query returns 2.
  • splitK semantics: splitK must be in the range [1, K]. splitK=1 uses the fused path (no temp buffer); splitK>1 uses the two-stage path (each Cube segment writes temp → epilogue reduces and writes D), and the temp area size is numBatches×splitK×m×n×4 bytes.
  • workspace lifecycle: the workspace can be released only after Matmul execution completes (stream synchronization). The workspace must not be nullptr, and the size must be ≥ the value computed by PlanInit.
  • matA fallback path: when matA is nullptr, the aPruned area of the workspace is used as the fallback (only in the sparse×dense and A-sparse path), and the caller must ensure that the area has been filled with valid data through SpMMAPrune. In the dense×dense path and the B-sparse path, matA must not be nullptr. It is recommended to pass the d_out of SpMMAPrune explicitly as matA.
  • Destruction order: raw pointer dependencies exist among descriptors (no reference counting), and destruction does not cascade invalidation. You must destroy in the reverse order plan → algSelection → matmulDesc → mat; otherwise, dangling pointers occur. Destroy the handle after all descriptors are destroyed.
  • Asynchronous execution: Matmul starts asynchronously and does not call aclrtSynchronizeStream internally; if the caller needs to read the matD result, it must synchronize the stream itself.
  • Attribute setting timing: the three attributes of aclsparseLtMatmulAlgSetAttribute (algConfigId / splitK / splitKMode) must be called before aclsparseLtMatmulPlanInit; PlanInit reads them to compute tiling, and modifications afterwards do not take effect (the plan needs to be reinitialized). Descriptor attributes—vector scaling / bias / activation (aclsparseLtMatmulDescSetAttribute) and batch (aclsparseLtMatDescSetAttribute)—are read from the descriptor at execution time, and modifications after PlanInit take effect for subsequent executions.
  • bias constraints:
    • bias sets the Device pointer through ACLSPARSELT_MATMUL_BIAS_POINTER; the dtype is the same as the C matrix (in the FP32 path, bias is FP32; in the FP16 path, bias is FP16; in the BF16 path, bias is BF16); the exception for INT8 A/B × C/D ∈ {INT8,INT32} (32I compute domain) is FP32, and for INT8 × C/D=FP16/BF16 the bias is FP16/BF16 (= C dtype)—length = m, must be 16-byte aligned (aligned with cuSPARSELt; bias is loaded through DataCopyPad with GM source addresses; in actual tests, 16B-aligned sources work). After loading, bias is cast to the FP32 domain for accumulation.
    • bias dtype migration note (porting from pre-SM9.0 cuSPARSELt): pre-SM9.0 (A100 and earlier generations) cuSPARSELt requires the bias in the "INT8 input × FP16/BF16 output" scenario to be FP32; this implementation follows the SM9.0+ generation rule, with bias = C dtype = FP16/BF16. Applications ported from pre-SM9.0 cuSPARSELt for this scenario must also change the bias buffer type from FP32 to FP16/BF16; otherwise, silent wrong values occur.
    • ACLSPARSELT_MATMUL_BIAS_STRIDE is the bias stride between batches (in elements); 0=all batches share the same bias (default). When non-0, each batch uses its own bias vector at the biasStride offset.
    • bias performs per-row broadcast in the FP32 domain after beta·C and before activation (the n elements in each row add bias[r]).
    • UB capacity degradation: when the full simultaneous loading of the three vectors—alpha/beta vector scaling and bias—exceeds the UB capacity (the extreme scenario of the FP16/BF16/INT8 fused path is m=15737), it automatically degrades to per-tile on-demand bias loading, ensuring that the extreme scenario can run.
  • activation constraints:
    • ReLU and GeLU are mutually exclusive: when SetAttribute enables one and the other is already enabled, ACL_SPARSE_STATUS_INVALID_VALUE is returned; when set to 0 (off), no check is performed.
    • activation is executed in the FP32 domain after bias and before type conversion. By default, no activation is used.
    • ReLU default parameters (threshold=0.0f and upperBound=FLT_MAX) degrade to standard ReLU (max(0, x)).
    • The GeLU implementation truncates the internal variable z by min(z, 20.0f) before Exp to prevent FP32 overflow; within the truncation range, the result is consistent with the golden value and does not change the numerical semantics.
    • GeLU dtype support: cuSPARSELt restricts GeLU to the INT8/FP8 paths; this implementation extends it to all dtypes (FP32/FP16/BF16/INT8), computed in the FP32 domain. The INT8 path behaves the same as cuSPARSELt.
  • batch constraints:
    • ACLSPARSELT_MAT_NUM_BATCHES must be >= 1, default 1 (non-batch). The numBatches values of the four matrices A/B/C/D must be consistent; aclsparseLtMatmulDescriptorInit validates this, and an inconsistency returns ACL_SPARSE_STATUS_INVALID_VALUE.
    • ACLSPARSELT_MAT_BATCH_STRIDE is measured in elements and set independently for each matrix (A/B/C/D). The matrices of each batch are arranged in the same contiguous Device memory at batchStride offsets. batchStride = 0 means cross-batch broadcast on that side (aligned with the cuSPARSELt batch_stride=0 semantics): all batches on that side read and write batch 0—on the read side (A/B/C), each batch reuses the batch 0 matrix (scenarios of shared weights/shared bias matrices), and the buffer needs only single-batch capacity; on the write side (D), this is alias writing across batches, and under single-stream sequential execution the final value is the computation result of the last batch (deterministic); it is not recommended to rely on intermediate states when used in combination with in-place (matC==matD). Each side is determined independently (for example, A broadcasts while B/C/D are per-batch, which is valid). batchStride < 0 returns ACL_SPARSE_STATUS_INVALID_VALUE (the backward walk goes out of bounds).
    • In the two-stage path (splitK>1), the temp area size = numBatches × splitK × m × n × 4 bytes, and the workspace must increase accordingly (the temp area stride is an independent internal library value, and broadcasting on one side does not change the temp requirement—when splitK>1, the partial sums of each batch still need independent areas).
    • Multi-core splitting: totalTiles = numBatches × mTiles × nTiles (fused path) or numBatches × splitK × mTiles × nTiles (two-stage path).
    • matA fallback path × batch: the workspace aPruned fallback with matA as nullptr is limited to numBatches=1 (the fallback area has single-batch capacity); when numBatches>1, matA must be passed in explicitly even if batchStrideA == 0 (broadcast fallback belongs to the scope of later A6 work and is not relaxed in this version).
  • FastPath condition: the FastPath of the fused path (splitK=1) (alpha==1 + beta==0 pass-through, skipping the intermediate buffer) takes effect only when there is no bias and no activation. When bias/activation exists, the GeneralPath is used automatically (complete epilogue chain processing in the FP32 domain), and functional correctness is guaranteed by the GeneralPath.

INT8 dual output (INT8/INT32)

The INT8 input path (computeType = ACL_SPARSE_COMPUTE_32I, with A/B as INT8) supports two output dtypes, determined by the valueType of the matD descriptor:

  • INT8 output (matD.valueType = ACL_INT8): the epilogue saturates and truncates the int32 accumulation result to [-128, 127] and then writes it as int8. It uses Mins/Maxs clamping + SpltCastFp32ToInt8 (a two-step Vector Cast float→half→int8; DAV-3510 does not support direct float→int8_t Cast, nor CAST_SATURATE).
  • INT32 output (matD.valueType = ACL_INT32): the epilogue writes the int32 accumulation result directly (no Cast, no saturation truncation), preserving the full accumulation precision. The alpha=1+beta=0 fast path uses Vector Add<int32_t> accumulation (splitK>1 reduction) + direct int32 UB→GM output, fully bypassing float intermediate conversion.

INT32 output precision boundary (int32 domain vs FP32 domain):

  • int32-domain exact region: when INT8 A/B × C/D=INT32, alpha is an integer value (within the int32 domain), and beta=0, with no bias and no activation, scaling completes in the int32 domain (Muls<int32_t>, both fused and two-stage paths)—exact for any |sum| (including |sum| > 2^24). The alpha=1 sub-region is covered by the fast path (also exact).
  • FP32-domain chain: in other scenarios (alpha is a non-integer value / beta≠0 / with bias / with activation / vector scaling), the int32 accumulation result is cast to FP32 once with Cast, then scaled/accumulated/activated and rounded back to INT32. FP32 has a 24-bit mantissa: when |sum| > 2^24 (roughly k > 1032 at full-scale ±127), a rounding deviation of up to 1 ulp(2^⌈log2|sum|⌉-24) exists (typically ±1~±4 at |sum| ∈ [2^24, 2^26)).
  • Clamp edge of D=INT8: clamp to [-128,127] before output; for edge combinations with |sum| > 2^24 and alpha≠1, a deviation of 1 quantization step may occur (within tolerance).
  • int32 L0C accumulation upper limit: 127×127×k < 2^31 → k < ~131k (beyond this is the int32 overflow domain, outside the repair scope of this path).

In the INT8 path, the dtype of the C matrix (accumulation term) is linked with matD: five combinations are supported—C=D=INT8, C=INT8/D=INT32, C=D=INT32, C=D=FP16, C=D=BF16 (aligned with the cuSPARSELt COMPUTE_32I dtype table). When C=INT8, the kernel reads C through GlobalTensor<int8_t>; when C=INT32/FP16/BF16, it reads through the corresponding CType pass-through branches (int8_ci32/int8_cf16/int8_cbf16). The INT8 path supports beta≠0 (C is read and then cast to float to participate in the beta*C accumulation).

Known limitations

Limitation Description Follow-up plan
GeLU dtype extension (beyond the cuSPARSELt scope) cuSPARSELt restricts GeLU to the INT8/FP8 paths; this implementation extends it to all dtypes (FP32/FP16/BF16/INT8), computed in the FP32 domain. The INT8 path behaves the same as cuSPARSELt, and the extension targets dtypes not covered by cuSPARSELt —
bias UB overflow degradation In the extreme scenario of the FP16/BF16/INT8 fused path (m=15737, with alpha/beta vector scaling + bias, all three vectors enabled), when UB overflows, it automatically degrades to per-tile on-demand bias loading to ensure runnability —
Two-step INT8 output Cast path DAV-3510 does not support direct float→int8_t Cast; SpltCastFp32ToInt8 (a two-step Vector Cast float→half→int8) + Mins/Maxs saturation truncation are used Explore hardware saturation Cast instructions in later versions
INT8 C→float scalar Cast When beta≠0 in the INT8 path, the Cast of C (int8_t) → float uses the scalar SpltScalarCastLoop (DAV-3510 Vector Cast does not support int8_t→float); performance is not vectorized Explore L0C→UB direct output or hardware Cast support in later versions
BF16 Cast is vectorized The BF16 epilogue uses SpltCastFp32ToBf16Vec/SpltCastBf16ToFp32Vec (Vector Cast<bfloat16_t,float>), already vectorized and optimized —
INT8 splitK accumulation is vectorized The INT8 splitK>1 epilogue reduction uses Vector Add<int32_t> (replacing the scalar GetValue/SetValue loop), already vectorized and optimized —

Invocation description

The invocation flow is segmented (descriptor + execution plan mode):

  1. Library handle: aclsparseLtInit.
  2. Matrix descriptors: aclsparseLtStructuredDescriptorInit (A) and aclsparseLtDenseDescriptorInit (B/C/D). If you need batch, set NUM_BATCHES/BATCH_STRIDE through aclsparseLtMatDescSetAttribute (before step 3).
  3. Matmul descriptor: aclsparseLtMatmulDescriptorInit (validates the numBatches consistency of A/B/C/D).
  4. Matmul descriptor attributes (optional): set vector scaling (ALPHA_VECTOR_SCALING/BETA_VECTOR_SCALING), bias (BIAS_POINTER/BIAS_STRIDE), and activation (ACTIVATION_RELU/RELU_UPPERBOUND/RELU_THRESHOLD/ACTIVATION_GELU/GELU_SCALING) through aclsparseLtMatmulDescSetAttribute.
  5. Algorithm selection: aclsparseLtMatmulAlgSelectionInit + aclsparseLtMatmulAlgSetAttribute (optional, sets algConfigId/splitK).
  6. Plan: aclsparseLtMatmulPlanInit (reads all the attributes above to compute tiling).
  7. workspace: aclsparseLtMatmulGetWorkspace queries the size and allocates Device memory.
  8. Pruning: aclsparseLtSpMMAPrune prunes A into A_pruned (for details, see prune/README_en.md).
  9. Execution: aclsparseLtMatmul executes D = Activation(alpha * op(A_pruned) * op(B) + beta * C + bias).
  10. Destruction: destroy all descriptors and the plan in reverse order.

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 the complete prune + structured sparse matrix multiplication flow. It computes D = 1.0 * A_pruned * B + 0.0 * C, where A is m×k (FP32, row-major), B is k×n, and C/D are m×n.

#include <cstdio>
#include <vector>

#include "acl/acl.h"
#include "cann_ops_sparseLt.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)

// 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 aclsparseLtMatmulTest()
{
    int32_t deviceId = 0;
    CHECK_RET(aclInit(nullptr) == ACL_SUCCESS, return -1);
    CHECK_RET(aclrtSetDevice(deviceId) == ACL_SUCCESS, aclFinalize(); return -1);
    aclrtStream stream = nullptr;
    CHECK_RET(aclrtCreateStream(&stream) == ACL_SUCCESS, aclrtResetDevice(deviceId); aclFinalize(); return -1);

    // 1. Initialize the aclsparseLt library handle
    aclsparseLtHandle_t handle = nullptr;
    auto ret = aclsparseLtInit(&handle);
    CHECK_RET(ret == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("aclsparseLtInit failed: %d\n", ret); return ret);

    // 2. Prepare matrix dimensions and Host data (FP32, row-major)
    //    k must be a multiple of 2 (FP32 pruning groups in 2)
    int64_t m = 64, k = 64, n = 128;
    float alpha = 1.0f, beta = 0.0f;
    std::vector<float> hA(static_cast<size_t>(m) * k);
    std::vector<float> hB(static_cast<size_t>(k) * n);
    std::vector<float> hC(static_cast<size_t>(m) * n, 0.0f);
    for (size_t i = 0; i < hA.size(); i++) { hA[i] = static_cast<float>(i % 11) - 5.0f; }
    for (size_t i = 0; i < hB.size(); i++) { hB[i] = static_cast<float>(i % 7) - 3.0f; }

    // 3. Copy data to the Device
    void *dA = AllocAndCopyDevice(hA.data(), static_cast<size_t>(m) * k * sizeof(float));
    void *dB = AllocAndCopyDevice(hB.data(), static_cast<size_t>(k) * n * sizeof(float));
    void *dC = AllocAndCopyDevice(hC.data(), static_cast<size_t>(m) * n * sizeof(float));
    void *dD = nullptr;
    aclrtMalloc(&dD, static_cast<size_t>(m) * n * sizeof(float), ACL_MEM_MALLOC_HUGE_FIRST);
    // A_pruned buffer: written by SpMMAPrune and read by Matmul
    void *dAPruned = nullptr;
    aclrtMalloc(&dAPruned, static_cast<size_t>(m) * k * sizeof(float), ACL_MEM_MALLOC_HUGE_FIRST);

    // 4. Create matrix descriptors
    aclsparseLtMatDescriptor_t matA = nullptr;
    aclsparseLtMatDescriptor_t matB = nullptr, matC = nullptr, matD = nullptr;
    aclsparseLtStructuredDescriptorInit(
        &handle, &matA, m, k, k, 16, ACL_FLOAT,
        ACL_SPARSE_ORDER_ROW, ACL_SPARSE_LT_SPARSITY_50_PERCENT);
    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, opB=N, FP32 accumulation)
    aclsparseLtMatmulDescriptor_t matmulDesc = nullptr;
    ret = aclsparseLtMatmulDescriptorInit(
        &handle, &matmulDesc,
        ACL_SPARSE_OP_NON_TRANSPOSE, ACL_SPARSE_OP_NON_TRANSPOSE,
        &matA, &matB, &matC, &matD, ACL_SPARSE_COMPUTE_32F);
    CHECK_RET(ret == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("MatmulDescriptorInit failed: %d\n", ret); return ret);

    // 6. Create the algorithm selection descriptor and set attributes
    aclsparseLtMatmulAlgSelection_t algSel = nullptr;
    ret = aclsparseLtMatmulAlgSelectionInit(&handle, &algSel, &matmulDesc, ACL_SPARSE_LT_MATMUL_ALG_DEFAULT);
    CHECK_RET(ret == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("AlgSelectionInit failed: %d\n", ret); return ret);

    //    Set algConfigId=0 and splitK=1 (default values, set explicitly to demonstrate usage)
    int32_t algConfigId = 0;
    int32_t splitK = 1;
    ret = aclsparseLtMatmulAlgSetAttribute(&handle, &algSel, ACLSPARSELT_MATMUL_ALG_CONFIG_ID,
                                           &algConfigId, sizeof(int32_t));
    CHECK_RET(ret == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("AlgSetAttribute(ALG_CONFIG_ID) failed: %d\n", ret); return ret);
    ret = aclsparseLtMatmulAlgSetAttribute(&handle, &algSel, ACLSPARSELT_MATMUL_SPLIT_K,
                                           &splitK, sizeof(int32_t));
    CHECK_RET(ret == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("AlgSetAttribute(SPLIT_K) failed: %d\n", ret); return ret);

    // 7. Create the execution plan
    aclsparseLtMatmulPlan_t plan = nullptr;
    ret = aclsparseLtMatmulPlanInit(&handle, &plan, &matmulDesc, &algSel);
    CHECK_RET(ret == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("PlanInit failed: %d\n", ret); return ret);

    // 8. Query and allocate the workspace size
    //    Note: the descriptor/plan parameter types of aclsparseLtMatmulGetWorkspace / aclsparseLtSpMMAPrune / aclsparseLtMatmul
    //    are aclsparseLtConstXxx_t* (that is, const struct Xxx**),
    //    while the local variables are declared as aclsparseLtXxx_t (that is, struct Xxx*), and taking their address gives struct Xxx**.
    //    C++ does not allow implicit conversion from T** to const T**; use const_cast for explicit conversion.
    size_t workspaceSize = 0;
    ret = aclsparseLtMatmulGetWorkspace(&handle, const_cast<aclsparseLtConstMatmulPlan_t*>(&plan), &workspaceSize);
    CHECK_RET(ret == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("GetWorkspaceSize failed: %d\n", ret); return ret);
    LOG_PRINT("workspaceSize = %zu bytes\n", workspaceSize);
    void *dWorkspace = nullptr;
    if (workspaceSize > 0) {
        aclrtMalloc(&dWorkspace, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
    }

    // 9. Prune: dA -> dAPruned
    ret = aclsparseLtSpMMAPrune(
        &handle, const_cast<aclsparseLtConstMatmulDescriptor_t*>(&matmulDesc),
        dA, dAPruned, ACLSPARSELT_PRUNE_SPMMA_STRIP, stream);
    CHECK_RET(ret == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("SpMMAPrune failed: %d\n", ret); return ret);

    // 10. Execute Matmul: D = Activation(alpha * A_pruned * B + beta * C + bias)
    //     Pass dAPruned (the pruning result) as matA, and dWorkspace as workspace
    ret = aclsparseLtMatmul(
        &handle, const_cast<aclsparseLtConstMatmulPlan_t*>(&plan),
        &alpha,
        dAPruned, dB,
        &beta, dC, dD,
        dWorkspace, &stream, 1);
    CHECK_RET(ret == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("Matmul failed: %d\n", ret); return ret);

    // 11. Synchronize and wait for completion (the caller is responsible for synchronization; the operator does not synchronize internally)
    aclrtSynchronizeStream(stream);

    // 12. Copy the result back to the Host
    std::vector<float> hD(static_cast<size_t>(m) * n, 0.0f);
    aclrtMemcpy(hD.data(), static_cast<size_t>(m) * n * sizeof(float),
                dD, static_cast<size_t>(m) * n * sizeof(float),
                ACL_MEMCPY_DEVICE_TO_HOST);
    LOG_PRINT("matmul done: D[0]=%.4f, D[%zu]=%.4f\n", hD[0], hD.size() - 1, hD.back());

    // 13. Clean up resources (destroy in reverse dependency order: plan -> algSel -> matmulDesc -> mat -> handle)
    aclsparseLtMatmulPlanDestroy(&plan);
    aclsparseLtMatmulAlgSelectionDestroy(&algSel);
    aclsparseLtMatmulDescriptorDestroy(&matmulDesc);
    aclsparseLtMatDescriptorDestroy(&matA);
    aclsparseLtMatDescriptorDestroy(&matB);
    aclsparseLtMatDescriptorDestroy(&matC);
    aclsparseLtMatDescriptorDestroy(&matD);
    aclsparseLtDestroy(&handle);

    aclrtFree(dA);
    aclrtFree(dB);
    aclrtFree(dC);
    aclrtFree(dD);
    aclrtFree(dAPruned);
    if (dWorkspace) { aclrtFree(dWorkspace); }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return 0;
}

int main()
{
    return aclsparseLtMatmulTest();
}

splitK > 1 usage: change splitK in the preceding example to a value greater than 1 (must be ≤ k). PlanInit automatically allocates the temp buffer (splitK×m×n×4 bytes) for reducing the results of all segments. The workspace size increases accordingly.

in-place usage: bind the matC and matD descriptors to the same Device pointer (dD reuses dC), that is, D = alpha * A_pruned * B + beta * C writes in place into the memory of C.

Example: bias + ReLU activation + batch

The following example demonstrates the complete flow of bias + ReLU activation + batch. It computes D[b] = ReLU(1.0 * A_pruned[b] * B[b] + 1.0 * C[b] + bias), with batch=3, A as m×k (FP16, row-major), B as k×n, C/D as m×n, and bias as __fp16[M] (same dtype as C). ReLU threshold=0.0f and upperBound=FLT_MAX (default parameters, degrading to standard ReLU).

#include <cstdio>
#include <vector>
#include <cfloat>

#include "acl/acl.h"
#include "cann_ops_sparseLt.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)

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 aclsparseLtMatmulBiasActBatchTest()
{
    int32_t deviceId = 0;
    CHECK_RET(aclInit(nullptr) == ACL_SUCCESS, return -1);
    CHECK_RET(aclrtSetDevice(deviceId) == ACL_SUCCESS, aclFinalize(); return -1);
    aclrtStream stream = nullptr;
    CHECK_RET(aclrtCreateStream(&stream) == ACL_SUCCESS, aclrtResetDevice(deviceId); aclFinalize(); return -1);

    // 1. Initialize the aclsparseLt library handle
    aclsparseLtHandle_t handle = nullptr;
    auto ret = aclsparseLtInit(&handle);
    CHECK_RET(ret == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("aclsparseLtInit failed: %d\n", ret); return ret);

    // 2. Prepare matrix dimensions and Host data (FP16, row-major, batch=3)
    //    k must be a multiple of 2 (FP16 pruning groups in 2)
    int64_t m = 128, k = 64, n = 256;
    int32_t numBatches = 3;
    int64_t batchStrideA = m * k;
    int64_t batchStrideB = k * n;
    int64_t batchStrideC = m * n;
    int64_t batchStrideD = m * n;
    int64_t biasStride = m;  // per-batch independent bias (biasStride != 0)

    float alpha = 1.0f, beta = 1.0f;  // beta != 0 enables C accumulation

    std::vector<__fp16> hA(static_cast<size_t>(numBatches) * m * k);
    std::vector<__fp16> hB(static_cast<size_t>(numBatches) * k * n);
    std::vector<__fp16> hC(static_cast<size_t>(numBatches) * m * n, 0.0f);
    std::vector<__fp16> hBias(static_cast<size_t>(numBatches) * m, static_cast<__fp16>(0.5f));  // bias is FP16 (= C dtype, as specified by cuSPARSELt)
    for (size_t i = 0; i < hA.size(); i++) { hA[i] = static_cast<__fp16>(static_cast<float>(i % 11) - 5.0f); }
    for (size_t i = 0; i < hB.size(); i++) { hB[i] = static_cast<__fp16>(static_cast<float>(i % 7) - 3.0f); }

    // 3. Copy data to the Device
    void *dA = AllocAndCopyDevice(hA.data(), static_cast<size_t>(numBatches) * m * k * sizeof(__fp16));
    void *dB = AllocAndCopyDevice(hB.data(), static_cast<size_t>(numBatches) * k * n * sizeof(__fp16));
    void *dC = AllocAndCopyDevice(hC.data(), static_cast<size_t>(numBatches) * m * n * sizeof(__fp16));
    void *dD = nullptr;
    aclrtMalloc(&dD, static_cast<size_t>(numBatches) * m * n * sizeof(__fp16), ACL_MEM_MALLOC_HUGE_FIRST);
    void *dBias = AllocAndCopyDevice(hBias.data(), static_cast<size_t>(numBatches) * m * sizeof(__fp16));
    void *dAPruned = nullptr;
    aclrtMalloc(&dAPruned, static_cast<size_t>(numBatches) * m * k * sizeof(__fp16), ACL_MEM_MALLOC_HUGE_FIRST);

    // 4. Create matrix descriptors and set batch attributes
    aclsparseLtMatDescriptor_t matA = nullptr, matB = nullptr, matC = nullptr, matD = nullptr;
    aclsparseLtStructuredDescriptorInit(
        &handle, &matA, m, k, k, 16, ACL_FLOAT16,
        ACL_SPARSE_ORDER_ROW, ACL_SPARSE_LT_SPARSITY_50_PERCENT);
    aclsparseLtDenseDescriptorInit(&handle, &matB, k, n, n, 16, ACL_FLOAT16, ACL_SPARSE_ORDER_ROW);
    aclsparseLtDenseDescriptorInit(&handle, &matC, m, n, n, 16, ACL_FLOAT16, ACL_SPARSE_ORDER_ROW);
    aclsparseLtDenseDescriptorInit(&handle, &matD, m, n, n, 16, ACL_FLOAT16, ACL_SPARSE_ORDER_ROW);

    //    Set batch attributes (must be set before MatmulDescriptorInit)
    ret = aclsparseLtMatDescSetAttribute(&handle, &matA, ACLSPARSELT_MAT_NUM_BATCHES,
                                         &numBatches, sizeof(int32_t));
    CHECK_RET(ret == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("SetAttribute NUM_BATCHES A failed: %d\n", ret); return ret);
    ret = aclsparseLtMatDescSetAttribute(&handle, &matA, ACLSPARSELT_MAT_BATCH_STRIDE,
                                         &batchStrideA, sizeof(int64_t));
    CHECK_RET(ret == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("SetAttribute BATCH_STRIDE A failed: %d\n", ret); return ret);
    // B/C/D set numBatches and batchStride in the same way (omitted; the code structure is identical)
    aclsparseLtMatDescSetAttribute(&handle, &matB, ACLSPARSELT_MAT_NUM_BATCHES, &numBatches, sizeof(int32_t));
    aclsparseLtMatDescSetAttribute(&handle, &matB, ACLSPARSELT_MAT_BATCH_STRIDE, &batchStrideB, sizeof(int64_t));
    aclsparseLtMatDescSetAttribute(&handle, &matC, ACLSPARSELT_MAT_NUM_BATCHES, &numBatches, sizeof(int32_t));
    aclsparseLtMatDescSetAttribute(&handle, &matC, ACLSPARSELT_MAT_BATCH_STRIDE, &batchStrideC, sizeof(int64_t));
    aclsparseLtMatDescSetAttribute(&handle, &matD, ACLSPARSELT_MAT_NUM_BATCHES, &numBatches, sizeof(int32_t));
    aclsparseLtMatDescSetAttribute(&handle, &matD, ACLSPARSELT_MAT_BATCH_STRIDE, &batchStrideD, sizeof(int64_t));

    // 5. Create the Matmul descriptor (opA=N, opB=N, FP32 accumulation)
    aclsparseLtMatmulDescriptor_t matmulDesc = nullptr;
    ret = aclsparseLtMatmulDescriptorInit(
        &handle, &matmulDesc,
        ACL_SPARSE_OP_NON_TRANSPOSE, ACL_SPARSE_OP_NON_TRANSPOSE,
        &matA, &matB, &matC, &matD, ACL_SPARSE_COMPUTE_32F);
    CHECK_RET(ret == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("MatmulDescriptorInit failed: %d\n", ret); return ret);

    // 6. Set bias + activation attributes (read at execution time; settings before or after PlanInit both take effect)
    //    bias: Device pointer + batch stride
    ret = aclsparseLtMatmulDescSetAttribute(&handle, &matmulDesc, ACLSPARSELT_MATMUL_BIAS_POINTER,
                                            &dBias, sizeof(void*));
    CHECK_RET(ret == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("SetAttribute BIAS_POINTER failed: %d\n", ret); return ret);
    ret = aclsparseLtMatmulDescSetAttribute(&handle, &matmulDesc, ACLSPARSELT_MATMUL_BIAS_STRIDE,
                                            &biasStride, sizeof(int64_t));
    CHECK_RET(ret == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("SetAttribute BIAS_STRIDE failed: %d\n", ret); return ret);
    //    ReLU: enable (default threshold=0.0f, upperBound=FLT_MAX, degrades to standard ReLU)
    int reluEnable = 1;
    ret = aclsparseLtMatmulDescSetAttribute(&handle, &matmulDesc, ACLSPARSELT_MATMUL_ACTIVATION_RELU,
                                            &reluEnable, sizeof(int));
    CHECK_RET(ret == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("SetAttribute ACTIVATION_RELU failed: %d\n", ret); return ret);

    // 7. Create the algorithm selection descriptor and execution plan
    aclsparseLtMatmulAlgSelection_t algSel = nullptr;
    ret = aclsparseLtMatmulAlgSelectionInit(&handle, &algSel, &matmulDesc, ACL_SPARSE_LT_MATMUL_ALG_DEFAULT);
    CHECK_RET(ret == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("AlgSelectionInit failed: %d\n", ret); return ret);
    aclsparseLtMatmulPlan_t plan = nullptr;
    ret = aclsparseLtMatmulPlanInit(&handle, &plan, &matmulDesc, &algSel);
    CHECK_RET(ret == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("PlanInit failed: %d\n", ret); return ret);

    // 8. Query and allocate the workspace size
    size_t workspaceSize = 0;
    ret = aclsparseLtMatmulGetWorkspace(&handle, const_cast<aclsparseLtConstMatmulPlan_t*>(&plan), &workspaceSize);
    CHECK_RET(ret == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("GetWorkspaceSize failed: %d\n", ret); return ret);
    LOG_PRINT("workspaceSize = %zu bytes\n", workspaceSize);
    void *dWorkspace = nullptr;
    if (workspaceSize > 0) {
        aclrtMalloc(&dWorkspace, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
    }

    // 9. Prune: dA -> dAPruned (batch-dimension pruning is driven by the descriptor numBatches)
    ret = aclsparseLtSpMMAPrune(
        &handle, const_cast<aclsparseLtConstMatmulDescriptor_t*>(&matmulDesc),
        dA, dAPruned, ACLSPARSELT_PRUNE_SPMMA_STRIP, stream);
    CHECK_RET(ret == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("SpMMAPrune failed: %d\n", ret); return ret);

    // 10. Execute Matmul: D[b] = ReLU(1.0 * A_pruned[b] * B[b] + 1.0 * C[b] + bias[b])
    //     bias/activation are configured through descriptor attributes; the execution interface takes no extra parameters
    ret = aclsparseLtMatmul(
        &handle, const_cast<aclsparseLtConstMatmulPlan_t*>(&plan),
        &alpha,
        dAPruned, dB,
        &beta, dC, dD,
        dWorkspace, &stream, 1);
    CHECK_RET(ret == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("Matmul failed: %d\n", ret); return ret);

    // 11. Synchronize and wait for completion
    aclrtSynchronizeStream(stream);

    // 12. Copy the result back to the Host (omitted)

    // 13. Clean up resources
    aclsparseLtMatmulPlanDestroy(&plan);
    aclsparseLtMatmulAlgSelectionDestroy(&algSel);
    aclsparseLtMatmulDescriptorDestroy(&matmulDesc);
    aclsparseLtMatDescriptorDestroy(&matA);
    aclsparseLtMatDescriptorDestroy(&matB);
    aclsparseLtMatDescriptorDestroy(&matC);
    aclsparseLtMatDescriptorDestroy(&matD);
    aclsparseLtDestroy(&handle);

    aclrtFree(dA); aclrtFree(dB); aclrtFree(dC); aclrtFree(dD);
    aclrtFree(dBias); aclrtFree(dAPruned);
    if (dWorkspace) { aclrtFree(dWorkspace); }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return 0;
}

biasStride=0 (all batches share the bias): set biasStride to 0; the bias vector length is still m (not numBatches×m), and all batches use the same bias. Allocating m * sizeof(float) for dBias is sufficient.

GeLU usage: replace the ReLU attribute setting with ACLSPARSELT_MATMUL_ACTIVATION_GELU (set to 1 to enable), and optionally set ACLSPARSELT_MATMUL_ACTIVATION_GELU_SCALING (default 1.0f). You cannot enable ReLU and GeLU at the same time.

alpha/beta vector scaling usage: enable it through aclsparseLtMatmulDescSetAttribute(ACLSPARSELT_MATMUL_BETA_VECTOR_SCALING, &enable, sizeof(int)), and change the alpha/beta parameters to Device-side float[M] pointers (per-row scaling). Enabling BETA_VECTOR_SCALING implies enabling ALPHA_VECTOR_SCALING.

References