aclnnFusedCausalConv1d

📄 View Source Code

Applicable Products

  • Ascend 950PR&950DT products: Supported
  • Atlas A3 products: Not supported
  • Atlas A2 products: Not supported
  • Atlas 200I/500 A2 inference products: Not supported
  • Atlas inference products: Not supported
  • Atlas training products: Not supported

Function

  • Description: Performs causal 1D convolution on sequences, uses cached data (length: kernel width minus 1) along the sequence dimension to pad the head of each sequence, ensuring that the output depends on the current and historical inputs; after the convolution, updates the data of the current sequence portion to the cache; adds the original input to the causal 1D convolution output to implement the residual connection. Supports features such as APC (Automatic Prefix Caching), MTP (Multi-Token Prediction, which can be used for speculative decoding), and residual connection. Compared with the standard causal_conv1d operator, this operator adds optional functions such as APC cache reuse, PD colocation, and residual connection.

  • The following use cases are supported:

    • Scenario 1 (prefill scenario):

      x: [cuSeqLen, dim]
      weight: [K, dim], where K=3
      convStates: [-1, K-1, dim]
      queryStartLoc: [batch+1]
      cacheIndices: APC disabled: [batch] or None, APC enabled: [block, maxNumBlocks]
      initialStateMode: [batch]
      bias: [dim] (not supported yet)
      numAcceptedTokens: [batch] (not supported yet)
      numComputedTokens: [batch]
      blockIdxFirstScheduledToken: APC disabled: None, APC enabled: [batch]
      blockIdxLastScheduledToken: APC disabled: None, APC enabled: [batch]
      initialStateIdx: APC disabled: None, APC enabled: [batch]
      activationMode: (not supported yet)
      padSlotId: default value -1
      runMode: (not supported yet)
      residualConnection: without residual: 0, with residual: 1
      blockSize: typical value 128/256
      convMode: Qwen3-Next mode: 0, Pangu V2: 1
      y: [cuSeqLen, dim]

      where cuSeqLen is the total length of all variable-length sequences concatenated in a batch.

    • Scenario 2 (mixed prefill and decode scenario):

      x: [cuSeqLen, dim]
      weight: [K, dim], where K=3
      convStates: [-1, K-1+m, dim]
      queryStartLoc: [batch+1]
      cacheIndices: APC disabled: [batch] or None, APC enabled: [block, maxNumBlocks]
      initialStateMode: [batch]
      bias: [dim] (not supported yet)
      numAcceptedTokens: [batch]
      numComputedTokens: [batch]
      blockIdxFirstScheduledToken: APC disabled: None, APC enabled: [batch]
      blockIdxLastScheduledToken: APC disabled: None, APC enabled: [batch]
      initialStateIdx: APC disabled: None, APC enabled: [batch]
      activationMode: (not supported yet)
      padSlotId: default value -1
      runMode: (not supported yet)
      residualConnection: no residual connection: 0, with residual connection: 1
      blockSize: typical value 128/256
      convMode: Qwen3-Next mode: 0, Pangu V2: 1
      y: [cuSeqLen, dim]

      where cuSeqLen is the total length of all variable-length sequences concatenated in a batch.

    • Scenario 3 (decode scenario - variable-length sequences):

      x: [cuSeqLen, dim]
      weight: [K, dim], where K=3
      convStates: [-1, K-1+m, dim]
      queryStartLoc: [batch+1]
      cacheIndices: APC disabled: [batch] or None, APC enabled: [block, maxNumBlocks]
      initialStateMode: [batch]
      bias: [dim] (not supported yet)
      numAcceptedTokens: [batch]
      numComputedTokens: [batch]
      blockIdxFirstScheduledToken: APC disabled: None, APC enabled: [batch]
      blockIdxLastScheduledToken: APC disabled: None, APC enabled: [batch]
      initialStateIdx: APC disabled: None, APC enabled: [batch]
      activationMode: (not supported yet)
      padSlotId: default value -1
      runMode: (not supported yet)
      residualConnection: no residual connection: 0, residual connection: 1
      blockSize: typical values 128/256
      convMode: Qwen3-Next mode: 0, Pangu V2: 1
      y: [cuSeqLen, dim]

      where stateLen must be greater than the maximum token count in all batches plus 1.

    • Scenario 4 (decode scenario - fixed batch):

      x: [batch, m+1, dim]
      weight: [K, dim], where K=3
      convStates: [-1, K-1+m, dim]
      queryStartLoc: [batch+1]
      cacheIndices: APC disabled: [batch] or None, APC enabled: [block, maxNumBlocks]
      initialStateMode: [batch]
      bias: [dim] (not supported yet)
      numAcceptedTokens: [batch]
      numComputedTokens: [batch]
      blockIdxFirstScheduledToken: APC disabled: None, APC enabled: [batch]
      blockIdxLastScheduledToken: APC disabled: None, APC enabled: [batch]
      initialStateIdx: APC not enabled: None, APC enabled: [batch]
      activationMode: (not supported yet)
      padSlotId: default value -1
      runMode: (not supported yet)
      residualConnection: without residual connection: 0, with residual connection: 1
      blockSize: typical value 128/256
      convMode: Qwen3-Next mode: 0, Pangu V2: 1
      y: [batch, m+1, dim]
  • Formula:

    Formula: K is the convolution kernel width, L is the sequence length of the current batch, dim is the feature dimension, batchId is the index of the current variable-length sequence being processed, C is the length of the convStates cache space (convStates.size(1)), and B is the APC block size (bSize). For each batch in input x, perform the following operations:

    1. Cache Read

      Cache line index:

      $ readCacheLine = \begin{cases} cacheIndices[batchId, \; initialStateIdx[batchId]], & \text{APC mode} \\ cacheIndices[batchId], & \text{ non-APC and cacheIndices exist} \\ batchId, & \text{ otherwise} \end{cases} $

      Case 1: First computation (numComputedTokens[batchId] == 0)

      $$ cachedState[i, dim] = 0, \quad 0 \leq i < K-1 $$
      $$ offset = 0 $$

      Case 2: Speculative decoding mode (numAcceptedTokens exists)

      $$ offset = numAcceptedTokens[batchId] - 1 $$
      $$ cachedState[i, dim] = convStates[readCacheLine][i, dim], \quad 0 \leq i < offset + K - 1 $$

      Case 3: Default mode

      $$ offset = C - (K - 1) $$
      $$ cachedState[i, dim] = convStates[readCacheLine][i, dim], \quad 0 \leq i < offset + K - 1 $$
    2. Cache Concatenation

      $$ paddedInput[i, dim] = \begin{cases} cachedState[i, dim], & 0 \leq i < offset + K - 1 \\ x[i - (offset + K - 1), dim], & offset + K - 1 \leq i < offset + K - 1 + L \end{cases} $$
    3. Cache Update

      $$ Len = offset + K - 1 + L $$
      $$ M = \min(C, \; Len) $$
      $ writeCacheLine = \begin{cases} cacheIndices[batchId, \; idxLast], & \text{APC mode} \\ cacheIndices[batchId], & \text{ not APC and cacheIndices exist} \\ batchId, & \text{ otherwise} \end{cases} $
      $$ convStates[writeCacheLine][C - M + i, dim] = paddedInput[Len - M + i, dim], \quad i = 0, 1, \dots, M-1 $$
    4. Offset Cropping

      $$ x'[i, dim] = paddedInput[i + offset, dim], \quad 0 \leq i < K - 1 + L $$
    5. APC cache fill (optional, in APC mode)

      $$ seqCompletedOffsetToken = numComputedTokens[batchId] \mod B $$
      $$ seqCompletedOffset = B - seqCompletedOffsetToken $$
      $$ seqEndOffset = (L - seqCompletedOffset) \mod B $$
      $$ lastFullBlockTokenIndex = \begin{cases} L - seqEndOffset - B, & seqEndOffset = 0 \\ L - seqEndOffset, & \text{otherwise} \end{cases} $$
      $$ nBlockToFill = idxLast - idxFirst $$

      For each chunk = 0, 1, ..., nBlockToFill - 1:

      $$ boundaryIdx = lastFullBlockTokenIndex - (nBlockToFill - chunk - 1) \times B $$
      $$ convStates[cacheIndices[batchId, \; idxFirst + chunk]][C-(K-1)+j, \; dim] = x'[boundaryIdx + j, \; dim], \quad j = 0, \dots, K-2 $$
    6. Causal 1D convolution

      $$ y[i, dim] = \sum_{k=0}^{K-1} w[k, dim] \cdot x'[i + k, dim], \quad i = 0, 1, \dots, L-1 $$
    7. Zero padding reset (optional, when convMode == 1 and numComputedTokens is not empty)

      $$ resetIdx = \min\!\Big(\max\!\big(K - 1 - numComputedTokens[batchId], \; 0\big), \; L\Big) $$
      $$ y[i, dim] = 0, \quad 0 \leq i < resetIdx $$
    8. Residual connection (optional)

      $$ y[i, dim] = x[i, dim] + y[i, dim] $$

Function Prototype

Each operator uses a two-phase API. First call the aclnnFusedCausalConv1dGetWorkspaceSize API to obtain the input parameters, calculate the required workspace size, and obtain the executor that includes the operator calculation process. Then call the aclnnFusedCausalConv1d API to execute the calculation.

aclnnStatus aclnnFusedCausalConv1dGetWorkspaceSize(
  const aclTensor *x,
  const aclTensor *weight,
  aclTensor       *convStates,
  const aclTensor *queryStartLoc,
  const aclTensor *cacheIndices,
  const aclTensor *initialStateMode,
  const aclTensor *bias,
  const aclTensor *numAcceptedTokens,
  const aclTensor *numComputedTokens,
  const aclTensor *blockIdxFirstScheduledToken,
  const aclTensor *blockIdxLastScheduledToken,
  const aclTensor *initialStateIdx,
  int64_t          activationMode,
  int64_t          padSlotId,
  int64_t          runMode,
  int64_t          maxQueryLen,
  int64_t          residualConnection,
  int64_t          blockSize,
  int64_t          convMode,
  aclTensor       *y,
  uint64_t        *workspaceSize,
  aclOpExecutor  **executor)
aclnnStatus aclnnFusedCausalConv1d(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnFusedCausalConv1dGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    x (aclTensor*) Input x in the formula, representing the input sequence.
    • Empty tensors are not supported.
    • prefill scenario: shape is [cuSeqLen, dim].
    • decode scenario: shape is [cuSeqLen, dim] or [batch, seqLen, dim].
    • Only the token dimension (dim0 for 2D, dim1 for 3D) can be non-contiguous, and its stride must be greater than or equal to 1
    FLOAT16, BFLOAT16 ND 2-3 √
    weight (aclTensor*) Input w in the formula, representing the causal 1D convolution kernel.
    • Does not support empty tensor.
    • The shape is [K, dim].
    Data type consistent with x ND 2 ×
    convStates (aclTensor*) Input/Output cacheState in the formula. Represents the cache state tensor, which stores the historical token data of each sequence and is updated in place after each sequence is calculated.
    • Does not support empty tensor.
    • The shape is [..., stateLen, dim]. The size of dimension 0 is not fixed.
    • stateLen == K-1+m. m=0 in the prefill scenario, and m=[0,7] in the decode and PD mixed-deployment scenarios.
    • m indicates the speculative decoding count and maps to the value of the numAcceptedTokens parameter.
    • Supports non-contiguous dim0 and dim1 with a stride greater than or equal to 1.
    Data type consistent with x ND 3 √
    queryStartLoc (aclTensor*) Optional input Start position index of sequences, recording the start position of each sequence in the concatenated tensor x.
    • Empty tensors are not supported.
    • The shape is [batch+1,].
    • queryStartLoc[i] indicates the start offset of the i-th sequence.
    • queryStartLoc[0] must be 0, queryStartLoc[-1] must be cuSeqLen, and adjacent values are not equal.
    INT32 ND 1 ×
    cacheIndices (aclTensor*) Optional input Cache index. Specifies the index in convStates of the cache state corresponding to each sequence.
    • Empty tensors are not supported. When APC is enabled, it cannot be None and must be 2D.
    • 1D shape [batch,] or 2D shape [batch, maxNumBlocks], where maxNumBlocks is in range [1, 1024].
    • Values must be distinct from each other (unless equal to padSlotId).
    INT32 ND 1-2 ×
    initialStateMode (aclTensor*) Optional input Initial state flag, indicating whether each sequence uses cached data. Not supported yet in the current version. When passing parameters, please set it to nullptr or ignore it. INT32 ND 1 ×
    bias (aclTensor*) Optional input Bias of the convolution. Not supported yet in the current version. When passing parameters, please set it to nullptr or ignore it. Data type consistent with x ND 1 ×
    numAcceptedTokens (aclTensor*) Optional input numAcceptedTokens in the formula, which indicates the number of random speculative tokens for each batch.
    • For prefill, the corresponding element value is 0; during decode, 1<=the value in numAcceptedTokens<=seqlen - 1, where seqlen indicates the sequence length of the batch.
    • The shape is [batch,].
    INT32 ND 1 ×
    numComputedTokens (aclTensor*) Optional input numComputedTokens in the formula. Total number of tokens processed in the current batch, used to determine the initial state.
    • For the first token, a zero-initialized cache is used; cannot be empty in Pangu V2 mode.
    • Shape is [batch,].
    INT32 ND 1 ×
    blockIdxFirstScheduledToken (aclTensor*) Optional input Block index corresponding to the start position of the current batch.
    • Cannot be empty when APC is enabled.
    • Shape is [batch,].
    INT32 ND 1 ×
    blockIdxLastScheduledToken (aclTensor*) Optional input Block index corresponding to seqLen-1 of the current batch.
    • Cannot be empty when APC is enabled.
    • The shape is [batch,].
    INT32 ND 1 ×
    initialStateIdx (aclTensor*) Optional input Index of the initial index block.
    • Cannot be empty when APC is enabled.
    • Shape is [batch,].
    INT32 ND 1 ×
    activationMode (int64_t) attribute Activation function type. Not supported yet in the current version. When passing parameters, please set it to nullptr or ignore it. INT64 - - -
    padSlotId (int64_t) attribute Used to skip batches that do not need to participate in the calculation.
    • Only variable-length sequences that do not participate in the calculation are supported at the beginning or end of x.
    • Skips the batch when cacheIndices[i]==padSlotId.
    INT64 - - -
    runMode (int64_t) attribute Used to determine whether the scenario is prefill or decode. Not supported yet in the current version. When passing parameters, please set it to nullptr or ignore it. INT64 - - -
    maxQueryLen (int64_t) attribute Maximum seqLen in all batches. Only the decode scenario (fixed batch) supports -1. - INT64 - - -
    residualConnection (int64_t) attribute Whether to perform the residual connection.
    • Value: 0 or 1:
      0: no residual connection;
      1: output y and input x are added and then output.
    INT64 - - -
    blockSize (int64_t) attribute Block size.
    • Value range: greater than or equal to 2, or 0 (0 can be passed in non-APC scenarios). Typical values: 128/256.
    INT64 - - -
    convMode (int64_t) attribute convMode in the formula. Two implementations are supported: Qwen3-Next and Pangu V2.
    • Value: 0 or 1.
      0: Qwen3-Next community version implementation.
      1: Pangu V2 implementation.
    INT64 - - -
    y (aclTensor*) Output y in the formula, representing the output sequence. Shape consistent with x. Data type consistent with x. ND 2-3 -
    workspaceSize (int64_t*) Output Returns the workspace size that the user needs to apply on the Device side. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor that includes the calculation flow of the operator. - - - - -
  • Return Value

    aclnnStatus: return status code. For details, see aclnn Return Codes.

    The first-phase API performs input parameter validation and returns an error in the following scenarios:

    Return Values Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 The passed-in x, weight, convStates, and y are null pointers.
    ACLNN_ERR_INNER_TILING_ERROR 561002 The data types of inputs and outputs are not in the supported range.
    The data types of x, weight, convStates, bias, and y are inconsistent.
    The data types of queryStartLoc, cacheIndices, initialStateMode, numAcceptedTokens, numComputedTokens, blockIdxFirstScheduledToken, blockIdxLastScheduledToken, and initialStateIdx are inconsistent.
    The shapes of the input and output tensors are not in the supported range.
    The input attributes are not in the supported range.
    dim is not in the specified value range.

aclnnFusedCausalConv1d

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address applied on the Device side.
    workspaceSize Input Workspace size applied on the Device side, obtained by calling the first-phase API aclnnFusedCausalConv1dGetWorkspaceSize.
    executor Input Op executor, includes the calculation process of the operator.
    stream Input Stream that executes the task.
  • Return value

    aclnnStatus: return status code. For details, see aclnn Return Codes.

Constraints

  • Deterministic computation:

    • aclnnFusedCausalConv1d defaults to a deterministic implementation.
  • Input shape constraints:

    • prefill use case:
      • x supports 2D [cuSeqLen, dim].
      • weight must be 2D [K, dim], where K is fixed to 3.
      • convStates must be 3D [..., K-1, dim]. The size of dimension 0 is not fixed and must be greater than or equal to the number of batches involved in the calculation (that is, the number of batches whose cacheIndices is not equal to padSlotId).
      • queryStartLoc must exist.
      • cacheIndices is 1D [batch, ] or 2D [batch, maxNumBlocks], where 1D indicates that APC is not enabled and 2D indicates that APC is enabled.
      • cuSeqLen range [batch, 1024 1024], dim range [64, 16384] and must be a multiple of 16, and the product of the two must satisfy [64 batch, 4G], batch range [1, 256].
      • maxNumBlocks >= ceiv(maxQueryLen, blockSize).
      • maxQueryLen > 8.
    • Mixed prefill and decode scenario:
      • x supports 2D [cuSeqLen, dim].
      • weight must be 2D [K, dim], where K is fixed to 3.
      • convStates must be 3D [..., K-1+m, dim]. The size of dimension 0 is not fixed and must be greater than or equal to the number of batches involved in the calculation (that is, the number of batches whose cacheIndices is not equal to padSlotId).
      • queryStartLoc must exist.
      • cacheIndices is 1D [batch, ] or 2D [batch, maxNumBlocks], where 1D indicates that APC is not enabled and 2D indicates that APC is enabled.
      • The cuSeqLen range is [batch, 1024 1024], the dim range is [64, 16384] and dim must be a multiple of 16, the product of the two must be within [64 batch, 4G], and the batch range is [1, 256].
      • maxNumBlocks >= ceiv(maxQueryLen, blockSize).
      • maxQueryLen > 8.
    • decode scenario (variable-length sequences):
      • x supports 2D [cuSeqLen, dim].
      • weight must be 2D [K, dim], where K is fixed to 3.
      • convStates must be 3D [..., K-1+m, dim]. The size of dimension 0 is not fixed and must be greater than or equal to the number of batches involved in the calculation (that is, the number of batches whose cacheIndices is not equal to padSlotId).
      • queryStartLoc must exist.
      • cacheIndices is 1D [batch, ] or 2D [batch, maxNumBlocks], where 1D indicates that APC is not enabled and 2D indicates that APC is enabled.
      • The range of cuSeqLen is [batch, batch * 8], and the seqLen range of each batch is [1, 8]. dim is in the range [64, 16384] and must be a multiple of 16, and batch is in the range [1, 256].
      • maxNumBlocks >= ceiv(maxQueryLen, blockSize).
      • The range of maxQueryLen is [1, 8].
    • decode scenario (fixed batch):
      • For x, only the 3D shape [batch, m+1, dim] is supported.
      • weight must be 2D [K, dim], where K is fixed to 3.
      • convStates must be 3D [..., K-1+m, dim]. The size of dimension 0 is not fixed and must be greater than or equal to the number of batches involved in the calculation (that is, the number of batches whose cacheIndices is not equal to padSlotId).
      • cacheIndices is 1D [batch, ] or 2D [batch, maxNumBlocks], where 1D indicates that APC is not enabled and 2D indicates that APC is enabled.
      • m is in the range [0, 7], dim is in the range [64, 16384] and is a multiple of 16, and batch is in the range [1, 256].
      • maxNumBlocks >= ceiv(maxQueryLen, blockSize).
      • maxQueryLen is in the range [1, 8] and can be -1.
  • Input value range restrictions:

    • queryStartLoc is the cumulative offset. Its value range is [0, cuSeqLen] and its length is batch+1. queryStartLoc[i] indicates the start offset of the i-th sequence, and queryStartLoc[batch+1] indicates the end position of the last sequence.
    • blockSize is 0 or greater than or equal to 2, and must not be 0 when APC is enabled.
    • When blockIdxFirstScheduledToken, blockIdxLastScheduledToken, initialStateIdx, numComputedTokens, and cacheIndices all exist, APC is enabled and the following conditions must be met (i is the batch index):
      • cacheIndices is 2D
      • initialStateIdx[i] <= blockIdxFirstScheduledToken[i]+1
      • initialStateIdx[i] <= blockIdxLastScheduledToken[i]
      • blockIdxFirstScheduledToken[i] <= blockIdxLastScheduledToken[i]
      • blockIdxLastScheduledToken[i] < maxNumBlocks
    • numAcceptedTokens is divided into None and non-None. If not None, its length is batch. For prefill, the element value is 0; for decode, the element value is greater than 0 and less than or equal to seqLen-1 of the current batch.
    • Each element in numComputedTokens is greater than or equal to 0.
    • The value range of cacheIndices is [0, convStates.dim[0]-1], and the values cannot be the same (except when equal to padSlotId).
    • maxQueryLen = the maximum seqLen in the batch.
    • In Pangu V2 mode (convMode = 1), numComputedTokens cannot be None.
    • Operator inputs and intermediate computation results do not exceed the value range of the corresponding data type (float16/bfloat16).
    • The operator input does not support ±inf or Nan.

Example

The following sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.

#include <iostream>
#include <vector>
#include <cmath>
#include "acl/acl.h"
#include "aclnnop/aclnn_fused_causal_conv1d.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)

int64_t GetShapeSize(const std::vector<int64_t> &shape)
{
    int64_t shapeSize = 1;
    for (auto i : shape) {
        shapeSize *= i;
    }
    return shapeSize;
}

int Init(int32_t deviceId, aclrtStream *stream)
{
    auto ret = aclInit(nullptr);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret);
    ret = aclrtSetDevice(deviceId);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret);
    ret = aclrtCreateStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret);
    return 0;
}

// IEEE 754 fp16 decode (uint16_t → float)
float Fp16ToFloat(uint16_t raw)
{
    uint32_t sign = (raw >> 15) & 0x1;
    uint32_t exp = (raw >> 10) & 0x1F;
    uint32_t mant = raw & 0x3FF;
    float val;
    if (exp == 0) {
        // subnormal or zero
        val = (sign ? -1.0f : 1.0f) * (static_cast<float>(mant) / 1024.0f) * (1.0f / 16384.0f);
    } else if (exp == 31) {
        // infinity or NaN
        val = (mant == 0) ? (sign ? -HUGE_VALF : HUGE_VALF) : NAN;
    } else {
        val = (sign ? -1.0f : 1.0f) * (1.0f + static_cast<float>(mant) / 1024.0f) *
              ldexpf(1.0f, static_cast<int>(exp) - 15);
    }
    return val;
}

template <typename T>
int CreateAclTensor(const std::vector<T> &hostData, const std::vector<int64_t> &shape, void **deviceAddr,
                    aclDataType dataType, aclTensor **tensor, aclFormat format)
{
    auto size = GetShapeSize(shape) * sizeof(T);
    auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);
    ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);

    std::vector<int64_t> strides(shape.size(), 1);
    for (int64_t i = static_cast<int64_t>(shape.size()) - 2; i >= 0; i--) {
        strides[i] = shape[i + 1] * strides[i + 1];
    }

    *tensor = aclCreateTensor(shape.data(), static_cast<int64_t>(shape.size()), dataType, strides.data(), 0, format,
                              shape.data(), static_cast<int64_t>(shape.size()), *deviceAddr);
    return 0;
}

void FreeTensorAndBuffer(aclTensor *tensor, void *deviceAddr)
{
    if (tensor != nullptr) {
        aclDestroyTensor(tensor);
    }
    if (deviceAddr != nullptr) {
        aclrtFree(deviceAddr);
    }
}

int main()
{
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = Init(deviceId, &stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

    int64_t K = 3;            // kernel width
    int64_t dim = 128;        // feature dimension
    int64_t batch = 4;        // number of sequences
    int64_t numSlots = 8;     // total cache slots (>= batch for non-APC)
    int64_t stateLen = K - 1; // cache state length per slot (= 2)
    // prefill: seqLens = [5, 3, 7, 4], cuSeqLen = 19
    int64_t cuSeqLen = 19;

    // ---- Tensor shapes ----
    std::vector<int64_t> xShape = {cuSeqLen, dim};
    std::vector<int64_t> weightShape = {K, dim};
    std::vector<int64_t> convStatesShape = {numSlots, stateLen, dim};
    std::vector<int64_t> queryStartLocShape = {batch + 1};
    std::vector<int64_t> cacheIndicesShape = {batch}; // 1D: non-APC
    std::vector<int64_t> initialStateModeShape = {batch};
    std::vector<int64_t> biasShape = {dim};
    std::vector<int64_t> numAcceptedTokensShape = {batch};
    std::vector<int64_t> yShape = {cuSeqLen, dim};

    // ---- Host data ----
    std::vector<uint16_t> hostX(cuSeqLen * dim, 0x3C00); // fp16 1.0

    // weight: pass-through at k=0, zero elsewhere — used to simplify golden verification
    std::vector<uint16_t> hostWeight(K * dim, 0);
    for (int64_t d = 0; d < dim; d++) {
        hostWeight[0 * dim + d] = 0x3C00; // k=0: 1.0
    }

    // convStates: zero-initialized, shape [8, 2, 128]
    std::vector<uint16_t> hostConvStates(numSlots * stateLen * dim, 0);

    // queryStartLoc: [0, 5, 8, 15, 19]
    std::vector<int32_t> hostQueryStartLoc = {0, 5, 8, 15, 19};

    // cacheIndices: each batch uses a distinct cache slot
    std::vector<int32_t> hostCacheIndices = {0, 3, 1, 5};

    // initialStateMode: 1=from cache, 0=zero-init, 2=from cache (MTP variant)
    std::vector<int32_t> hostInitialStateMode = {1, 0, 2, 1};

    // bias: zero (unused)
    std::vector<uint16_t> hostBias(dim, 0);

    // numAcceptedTokens: 0 for prefill (no speculative decoding)
    std::vector<int32_t> hostNumAcceptedTokens(batch, 0);

    // y output buffer
    std::vector<uint16_t> hostY(cuSeqLen * dim, 0);

    // ---- Device pointers and aclTensors ----
    void *xDev = nullptr, *weightDev = nullptr, *convStatesDev = nullptr;
    void *queryStartLocDev = nullptr, *cacheIndicesDev = nullptr;
    void *initialStateModeDev = nullptr, *biasDev = nullptr;
    void *numAcceptedTokensDev = nullptr, *yDev = nullptr;

    aclTensor *xTensor = nullptr, *weightTensor = nullptr, *convStatesTensor = nullptr;
    aclTensor *queryStartLocTensor = nullptr, *cacheIndicesTensor = nullptr;
    aclTensor *initialStateModeTensor = nullptr, *biasTensor = nullptr;
    aclTensor *numAcceptedTokensTensor = nullptr, *yTensor = nullptr;

    // ---- Create required tensors ----
    ret = CreateAclTensor(hostX, xShape, &xDev, ACL_FLOAT16, &xTensor, ACL_FORMAT_ND);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    ret = CreateAclTensor(hostWeight, weightShape, &weightDev, ACL_FLOAT16, &weightTensor, ACL_FORMAT_ND);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    ret =
        CreateAclTensor(hostConvStates, convStatesShape, &convStatesDev, ACL_FLOAT16, &convStatesTensor, ACL_FORMAT_ND);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    ret = CreateAclTensor(hostQueryStartLoc, queryStartLocShape, &queryStartLocDev, ACL_INT32, &queryStartLocTensor,
                          ACL_FORMAT_ND);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    ret = CreateAclTensor(hostCacheIndices, cacheIndicesShape, &cacheIndicesDev, ACL_INT32, &cacheIndicesTensor,
                          ACL_FORMAT_ND);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    ret = CreateAclTensor(hostInitialStateMode, initialStateModeShape, &initialStateModeDev, ACL_INT32,
                          &initialStateModeTensor, ACL_FORMAT_ND);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    ret = CreateAclTensor(hostBias, biasShape, &biasDev, ACL_FLOAT16, &biasTensor, ACL_FORMAT_ND);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    ret = CreateAclTensor(hostNumAcceptedTokens, numAcceptedTokensShape, &numAcceptedTokensDev, ACL_INT32,
                          &numAcceptedTokensTensor, ACL_FORMAT_ND);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    ret = CreateAclTensor(hostY, yShape, &yDev, ACL_FLOAT16, &yTensor, ACL_FORMAT_ND);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    int64_t activationMode = 0; // 0: None
    int64_t padSlotId = -1;     // -1: no pad-slot skipping
    int64_t runMode = 0;
    int64_t maxQueryLen = 7;
    int64_t residualConnection = 0; // 0: no residual
    int64_t blockSize = 0;          // 0: non-APC
    int64_t convMode = 0;           // 0: Qwen3-Next

    uint64_t workspaceSize = 0;
    aclOpExecutor *executor = nullptr;

    ret = aclnnFusedCausalConv1dGetWorkspaceSize(xTensor, weightTensor, convStatesTensor, queryStartLocTensor,
                                                 cacheIndicesTensor, initialStateModeTensor, biasTensor,
                                                 numAcceptedTokensTensor,
                                                 nullptr, // numComputedTokens (non-APC: nullptr)
                                                 nullptr, // blockIdxFirstScheduledToken
                                                 nullptr, // blockIdxLastScheduledToken
                                                 nullptr, // initialStateIdx
                                                 activationMode, padSlotId, runMode, maxQueryLen, residualConnection,
                                                 blockSize, convMode, yTensor, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFusedCausalConv1dGetWorkspaceSize failed. ERROR: %d\n", ret);
              return ret);

    void *workspaceAddr = nullptr;
    if (workspaceSize > 0) {
        ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
    }

    ret = aclnnFusedCausalConv1d(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFusedCausalConv1d failed. ERROR: %d\n", ret); return ret);

    ret = aclrtSynchronizeStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);

    auto ySize = GetShapeSize(yShape);
    std::vector<uint16_t> yResult(ySize, 0);
    ret = aclrtMemcpy(yResult.data(), ySize * sizeof(uint16_t), yDev, ySize * sizeof(uint16_t),
                      ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy y from device to host failed. ERROR: %d\n", ret); return ret);

    auto csSize = GetShapeSize(convStatesShape);
    std::vector<uint16_t> csResult(csSize, 0);
    ret = aclrtMemcpy(csResult.data(), csSize * sizeof(uint16_t), convStatesDev, csSize * sizeof(uint16_t),
                      ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy convStates from device to host failed. ERROR: %d\n", ret);
              return ret);

    LOG_PRINT("=== y output (first 10 elements) ===\n");
    for (int64_t i = 0; i < 10 && i < ySize; i++) {
        LOG_PRINT("  y[%lld] = %f\n", (long long)i, (double)Fp16ToFloat(yResult[i]));
    }
    LOG_PRINT("  ...\n");

    LOG_PRINT("=== convStates output (first 10 elements) ===\n");
    for (int64_t i = 0; i < 10 && i < csSize; i++) {
        LOG_PRINT("  convStates[%lld] = %f\n", (long long)i, (double)Fp16ToFloat(csResult[i]));
    }
    LOG_PRINT("  ...\n");

    FreeTensorAndBuffer(xTensor, xDev);
    FreeTensorAndBuffer(weightTensor, weightDev);
    FreeTensorAndBuffer(convStatesTensor, convStatesDev);
    FreeTensorAndBuffer(queryStartLocTensor, queryStartLocDev);
    FreeTensorAndBuffer(cacheIndicesTensor, cacheIndicesDev);
    FreeTensorAndBuffer(initialStateModeTensor, initialStateModeDev);
    FreeTensorAndBuffer(biasTensor, biasDev);
    FreeTensorAndBuffer(numAcceptedTokensTensor, numAcceptedTokensDev);
    FreeTensorAndBuffer(yTensor, yDev);

    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }

    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();

    LOG_PRINT("Test completed successfully!\n");
    return 0;
}