aclnnFusedCausalConv1dV2
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. Along the sequence dimension, cached data (with a length of the convolution kernel width minus 1) is used to pad the head of each sequence, ensuring that the output depends on the current and historical inputs. After the convolution is complete, part of the data in the current sequence is updated to the cache. On the basis of the causal 1D convolution output, the original input is added to the output to implement the residual connection. Supports features such as APC (Automatic Prefix Caching), MTP (Multi-Token Prediction, usable for speculative decoding), and residual connection. Compared with aclnnFusedCausalConv1dV1, this API supports the new maxDraftTokens parameter, indicating the maximum number of speculative tokens supported. Compared with InplaceCausalConv1d, this operator does not support in-place update of input x.
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: no residual connection: 0, 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 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: without APC: [batch] or None, with APC: [block, maxNumBlocks] initialStateMode: [batch] bias: [dim] (not supported yet) numAcceptedTokens: [batch] numComputedTokens: [batch] blockIdxFirstScheduledToken: without APC: None, with APC: [batch] blockIdxLastScheduledToken: without APC: None, with APC: [batch] initialStateIdx: without APC: None, with APC: [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 maxDraftTokens: number of speculative tokens (multiTokenNum), value range [0, 16] 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 currently) 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: 0, residual: 1 blockSize: typical values 128/256 convMode: Qwen3-Next mode: 0, Pangu V2: 1 maxDraftTokens: number of speculative tokens (multiTokenNum), value range [0, 16] 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: without APC: [batch] or None, with APC: [block, maxNumBlocks] initialStateMode: [batch] bias: [dim] (not supported yet) numAcceptedTokens: [batch] numComputedTokens: [batch] blockIdxFirstScheduledToken: without APC: None, with APC: [batch] blockIdxLastScheduledToken: without APC: None, with APC: [batch] initialStateIdx: without APC: None, with APC: [batch] activationMode: (currently not supported) padSlotId: default value -1 runMode: (currently not supported) residualConnection: without residual: 0, with residual: 1 blockSize: typical value 128/256 convMode: Qwen3-Next mode: 0, Pangu V2: 1 maxDraftTokens: number of speculative tokens (multiTokenNum), value range [0, 16] 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:
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 $$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} $$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 $$Offset Cropping
$$ x'[i, dim] = paddedInput[i + offset, dim], \quad 0 \leq i < K - 1 + L $$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 $$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 $$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 $$Residual connection (optional)
$$ y[i, dim] = x[i, dim] + y[i, dim] $$
Function Prototype
Each operator uses a two-phase API. First call the aclnnFusedCausalConv1dV2GetWorkspaceSize API to obtain the input parameters, calculate the required workspace size, and obtain the executor that contains the operator computation process. Then call the aclnnFusedCausalConv1dV2 API to execute the computation.
aclnnStatus aclnnFusedCausalConv1dV2GetWorkspaceSize(
const aclTensor *x,
const aclTensor *weight,
aclTensor *convStates,
const aclTensor *queryStartLocOptional,
const aclTensor *cacheIndicesOptional,
const aclTensor *initialStateModeOptional,
const aclTensor *biasOptional,
const aclTensor *numAcceptedTokensOptional,
const aclTensor *numComputedTokensOptional,
const aclTensor *blockIdxFirstScheduledTokenOptional,
const aclTensor *blockIdxLastScheduledTokenOptional,
const aclTensor *initialStateIdxOptional,
int64_t activationMode,
int64_t padSlotId,
int64_t runMode,
int64_t maxQueryLen,
int64_t residualConnection,
int64_t blockSize,
int64_t convMode,
int64_t maxDraftTokens,
aclTensor *y,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnFusedCausalConv1dV2(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnFusedCausalConv1dV2GetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor x (aclTensor*) Input x in the formula denotes the input sequence. - Empty tensors are not supported.
- Prefill task: shape is [cuSeqLen, dim].
- Decode task: shape is [cuSeqLen, dim] or [batch, seqLen, dim].
- Only the token dimension (dim0 for 2D, dim1 for 3D) can be non-contiguous, and the stride must be greater than or equal to 1
FLOAT16, BFLOAT16 ND 2-3 √ weight (aclTensor*) Input w in the formula denotes the causal 1D convolution kernel. - Empty tensors are not supported.
- The shape is [K, dim].
Same as the data type of x ND 2 × convStates (aclTensor*) Input/Output cacheState in the formula, representing the cache state tensor. It stores the historical token data of each sequence and is updated in place after each sequence is computed. - Empty tensors are not supported.
- The shape is [..., stateLen, dim], and the size of dim0 is not fixed.
- stateLen == K-1+m. m is 0 for prefill use cases and [0, maxDraftTokens] for decode and PD mixed-deployment use cases.
- m indicates the number of speculative tokens, which maps to the value of numAcceptedTokensOptional.
- Non-contiguous dim0 and dim1 with strides greater than or equal to 1 are supported.
Same as the data type of x ND 3 √ queryStartLocOptional(aclTensor*) Input Start position index of sequences. It records the start position of each sequence in the concatenated tensor x. - Empty tensors are not supported.
- The shape is [batch+1,].
- queryStartLocOptional[i] indicates the start offset of the i-th sequence.
- queryStartLocOptional[0] must be 0, queryStartLocOptional[-1] must be cuSeqLen, and adjacent values must not be equal.
INT32 ND 1 × cacheIndicesOptional (aclTensor*) Input Cache indices. Specifies the index in convStates of the cache state corresponding to each sequence. - Empty tensors are not supported. When APC is enabled, this parameter cannot be None and must be two-dimensional.
- 1D shape[batch,] or 2D shape[batch, maxNumBlocks], with maxNumBlocks in the range [1,1024].
- Values must be unique (unless equal to padSlotId).
INT32 ND 1-2 × initialStateModeOptional (aclTensor*) Input Initial state flag, indicating whether each sequence uses cached data. Not supported in the current version. Set it to nullptr or ignore it when passing the parameter. INT32 ND 1 × biasOptional (aclTensor*) Input Convolution bias. Not supported in the current version. Set this parameter to nullptr or ignore it. Data type: same as x ND 1 × numAcceptedTokensOptional (aclTensor*) Input numAcceptedTokens in the formula, indicating the number of random speculative tokens for each batch. - For prefile, the element value is 0. For decode, 1<= the value in numAcceptedTokens <=seqlen -1, where seqlen indicates the sequence length of the batch.
- The shape is [batch,].
INT32 ND 1 × numComputedTokensOptional (aclTensor*) Input numComputedTokens in the formula. Total number of tokens processed in the current batch, used to determine the initial state. - The cache is initialized with zeros for the first token; must not be empty in Pangu V2 mode.
- Shape is [batch,].
INT32 ND 1 × blockIdxFirstScheduledTokenOptional (aclTensor*) Input Block index corresponding to the start position of the current batch. - Must not be empty when APC is enabled.
- Shape is [batch,].
INT32 ND 1 × blockIdxLastScheduledTokenOptional (aclTensor*) Input Index of the block corresponding to seqLen-1 of the current batch. - Cannot be empty when APC is enabled.
- shape is [batch,].
INT32 ND 1 × initialStateIdxOptional (aclTensor*) Input Index of the initial index block. - Cannot be empty when APC is enabled.
- shape is [batch,].
INT32 ND 1 × activationMode (int64_t) Input Activation function type. INT64 - - - padSlotId (int64_t) Input Used to skip batches that do not participate in the computation. - Only variable-length sequences that do not participate in the computation at the beginning or end of x are supported.
- The batch is skipped when cacheIndices[i]==padSlotId.
INT64 - - - runMode (int64_t) Input Used to determine the prefill use case or the decode use case. Legacy API. INT64 - - - maxQueryLen (int64_t) Input Maximum seqLen across all batches. Only the decode use case (fixed batch) supports -1. - INT64 - - - residualConnection (int64_t) Input Whether to perform a residual connection. - Values are 0 and 1:
0: no residual connection;
1: adds output y and input x and outputs the sum.
INT64 - - - blockSize (int64_t) Input Size of the block. - Value range: greater than or equal to 2, or 0 (0 is allowed for non-APC use cases). Typical values: 128/256.
INT64 - - - convMode (int64_t) Input 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 - - - maxDraftTokens(int64_t) Input Maximum number of speculative tokens. - Value range: [0, 16].
INT64 - - - y(aclTensor*) Output y in the formula, representing the output sequence. Same shape as x. Same data type as x ND 2-3 - workspaceSize (int64_t*) Output Returns the workspace size that the user needs to allocate on the device. - - - - - executor(aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - - 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 x, weight, convStates, or y is a null pointer. ACLNN_ERR_INNER_TILING_ERROR 561002 The data types of input and output are not in the supported range.
The data types of x, weight, convStates, bias, and y are inconsistent.
The data types of queryStartLocOptional, cacheIndicesOptional, initialStateModeOptional, numAcceptedTokensOptional, numComputedTokensOptional, blockIdxFirstScheduledTokenOptional, blockIdxLastScheduledTokenOptional, and initialStateIdxOptional are inconsistent.
The shapes of 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.
aclnnFusedCausalConv1dV2
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address allocated on the device. workspaceSize Input Workspace size allocated on the device, obtained by calling the first-phase API aclnnFusedCausalConv1dV2GetWorkspaceSize. executor Input Executor of the op, containing the computation process of the operator. stream Input Stream for executing tasks. Return value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
Deterministic computation:
- aclnnFusedCausalConv1dV2 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 count of batches involved in the calculation (that is, the count of batches where cacheIndicesOptional is not equal to padSlotId).
- queryStartLocOptional must exist.
- cacheIndicesOptional 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 a multiple of 16; the product of cuSeqLen and dim must be within [64 batch, 4G]; batch: range [1, 256].
- maxNumBlocks >= ceiv(maxQueryLen, blockSize).
- maxQueryLen > maxDraftTokens + 1.
- 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]. Its dimension 0 size is not fixed and must be greater than or equal to the count of batches participating in the calculation (that is, the count of batches whose cacheIndicesOptional is not equal to padSlotId).
- queryStartLocOptional must exist.
- cacheIndicesOptional is 1D [batch, ] or 2D [batch, maxNumBlocks], where 1D indicates that APC is not enabled and 2D indicates that APC is enabled.
- cuSeqLen must be in the range of [batch, 1024 * 1024], dim must be in the range of [64, 16384] and be a multiple of 16, the product of the two must be in the range of [64*batch, 4G], and batch must be in the range of [1, 256].
- maxNumBlocks >= ceiv(maxQueryLen, blockSize).
- maxQueryLen > maxDraftTokens + 1.
- 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]. Its dimension 0 size is not fixed and must be greater than or equal to the count of batches participating in the calculation (that is, the count of batches whose cacheIndicesOptional is not equal to padSlotId).
- queryStartLocOptional must exist.
- cacheIndicesOptional 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, batch * (maxDraftTokens + 1)], and the seqLen range of each batch is [1, maxDraftTokens + 1]. The dim range is [64, 16384] and dim is a multiple of 16. The batch range is [1, 256].
- maxNumBlocks >= ceiv(maxQueryLen, blockSize).
- The maxQueryLen range is [1, maxDraftTokens + 1].
- 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]. Its dimension 0 size is not fixed and must be greater than or equal to the count of batches participating in the calculation (that is, the count of batches whose cacheIndicesOptional is not equal to padSlotId).
- cacheIndicesOptional is 1D [batch, ] or 2D [batch, maxNumBlocks], where 1D indicates that APC is not enabled and 2D indicates that APC is enabled.
- m: range [0, maxDraftTokens]; dim: range [64, 16384] and a multiple of 16; batch: range [1, 256].
- maxNumBlocks >= ceiv(maxQueryLen, blockSize).
- maxQueryLen: range [1, maxDraftTokens + 1]; can be -1.
- prefill use case:
Input value range restrictions:
- queryStartLocOptional is the cumulative offset, with a value range of [0, cuSeqLen] and a length of batch+1. queryStartLocOptional[i] indicates the start offset of the i-th sequence, and queryStartLocOptional[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 blockIdxFirstScheduledTokenOptional, blockIdxLastScheduledTokenOptional, initialStateIdxOptional, numComputedTokensOptional, and cacheIndicesOptional all exist, APC is enabled and the following conditions must be met (i is the batch index):
- cacheIndices is 2D
- initialStateIdxOptional[i] <= blockIdxFirstScheduledTokenOptional[i]+1
- initialStateIdxOptional[i] <= blockIdxLastScheduledTokenOptional[i]
- blockIdxFirstScheduledTokenOptional[i] <= blockIdxLastScheduledTokenOptional[i]
- blockIdxLastScheduledTokenOptional[i] < maxNumBlocks
- numAcceptedTokensOptional can be None or non-None. When not None, its length is batch. Elements corresponding to prefill are 0, and elements corresponding to decode are greater than 0 and less than or equal to seqLen-1 of the current batch.
- Each element in numComputedTokensOptional is greater than or equal to 0.
- The value range of cacheIndicesOptional is [0, convStates.dim[0]-1], and the values must not be equal to each other (unless equal to padSlotId).
- maxQueryLen = the maximum seqLen in the batch.
- The value range of maxDraftTokens is [0, 16].
- In Pangu V2 mode (convMode = 1), numComputedTokensOptional 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_v2.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
int64_t maxDraftTokens = 7;
uint64_t workspaceSize = 0;
aclOpExecutor *executor = nullptr;
ret = aclnnFusedCausalConv1dV2GetWorkspaceSize(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, maxDraftTokens, yTensor, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFusedCausalConv1dV2GetWorkspaceSize 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 = aclnnFusedCausalConv1dV2(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFusedCausalConv1dV2 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;
}