aclnnInplaceFusedCausalConv1d
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 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, part of the current sequence data is updated to the cache. The original input is added to the causal 1D convolution output to implement the residual connection. It supports features such as APC (Automatic Prefix Caching), MTP (Multi-Token Prediction, which can be used for speculative decoding), residual connection, and in-place update. Compared with the standard causal_conv1d operator, this operator adds APC cache reuse, PD mixed deployment, optional residual connection, and other functions.
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: without APC: [batch] or None, with APC: [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 connection: 0, with residual connection: 1 blockSize: typical value 128/256 convMode: Qwen3-Next mode: 0, Pangu V2: 1where 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: 1where 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: 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: without residual: 0, with residual: 1 blockSize: typical values 128/256 convMode: Qwen3-Next mode: 0, Pangu V2: 1where 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: 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 values 128/256 convMode: Qwen3-Next mode: 0, Pangu V2: 1
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] $$In-place update
$$ x[i, dim] = y[i, dim] $$
Function Prototype
Each operator uses a two-phase API. Call the aclnnInplaceFusedCausalConv1dGetWorkspaceSize API first to obtain the input parameters, calculate the required workspace size, and obtain the executor that contains the operator computing process. Then, call the aclnnInplaceFusedCausalConv1d API to perform the computation.
aclnnStatus aclnnInplaceFusedCausalConv1dGetWorkspaceSize(
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,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnInplaceFusedCausalConv1d(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnInplaceFusedCausalConv1dGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor x (aclTensor*) Input/Output x in the Formula denotes the input sequence. The convolution result updates x in place. - Empty tensors are not supported.
- prefill scenario: shape [cuSeqLen, dim].
- decode scenario: shape [cuSeqLen, dim] or [batch, seqLen, dim].
- Only non-contiguity in the token dimension (dim0 for 2D, dim1 for 3D) is supported, 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.
- shape: [K, dim].
Same data type as 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 an in-place update is performed after each sequence is computed. - Empty tensors are not supported.
- shape: [..., stateLen, dim]. The size of dimension 0 is not fixed.
- stateLen == K-1+m. In prefill scenarios, m=0. In decode and PD mixed deployment scenarios, m=[0,7].
- m indicates the count of speculated tokens and maps to the value of the numAcceptedTokens parameter.
- Non-contiguous dim0 and dim1 with stride greater than or equal to 1 are supported.
Same data type as x ND 3 √ queryStartLoc(aclTensor*) Optional input Index of sequence start positions, 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 must be different.
INT32 ND 1 × cacheIndices (aclTensor*) Optional input Cache indices. Specifies the index of the cache state corresponding to each sequence in convStates. - Empty tensors are not supported. When APC is enabled, the tensor cannot be None and must be two-dimensional.
- 1D shape [batch,] or 2D shape [batch, maxNumBlocks], where maxNumBlocks ranges from 1 to 1024.
- The values must be unique (except 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. Set it to nullptr or ignore it when passing parameters. INT32 ND 1 × bias (aclTensor*) Optional input Bias of the convolution. Not supported yet in the current version. Set it to nullptr or ignore it when passing the parameter. Same data type as x ND 1 × numAcceptedTokens (aclTensor*) Optional input numAcceptedTokens in the formula, indicating the number of random speculative tokens for each batch. - The element value is 0 for prefill. For decode, 1 <= value of 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 count of tokens processed in the current batch, used to determine the initial state. - A zero-initialized cache is used for the first token. It cannot be empty in Pangu V2 mode.
- The shape is [batch,].
INT32 ND 1 × blockIdxFirstScheduledToken (aclTensor*) Optional 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 × blockIdxLastScheduledToken (aclTensor*) Optional input Block index corresponding to seqLen-1 of the current batch. - Must not be empty when APC is enabled.
- Shape is [batch,].
INT32 ND 1 × initialStateIdx (aclTensor*) Optional input Index of the initial index block. - Cannot be empty when APC is enabled.
- The shape is [batch,].
INT32 ND 1 × activationMode (int64_t) attribute Activation function type. Not supported yet in the current version. Set it to nullptr or ignore it when passing the parameter. INT64 - - - padSlotId (int64_t) attribute Used to skip batches that do not need to 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) attribute Used to determine whether it is the prefill scenario or the decode scenario. Not supported yet in the current version. Set it to nullptr or ignore it when passing the parameter. INT64 - - - maxQueryLen (int64_t) attribute Maximum seqLen across all batches. -1 is supported only in the decode scenario (fixed batch). - INT64 - - - residualConnection (int64_t) attribute Whether to perform a residual connection. - Value: 0 or 1:
0: no residual connection;
1: y and x are added and then output.
INT64 - - - blockSize (int64_t) attribute Size of a block. - >Value range: greater than or equal to 2, or equal to 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 - - - workspaceSize (int64_t*) Output Returns the workspace size to be applied for on the Device side. - - - - - 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 Value Error Code Description ACLNN_ERR_PARAM_NULLPTR 161001 The input x, weight, or convStates is a null pointer. ACLNN_ERR_INNER_TILING_ERROR 561002 The data type of the input or output is out of the supported range.
The data types of x, weight, convStates, and bias are inconsistent.
The data types of queryStartLoc, cacheIndices, initialStateMode, numAcceptedTokens, numComputedTokens, blockIdxFirstScheduledToken, blockIdxLastScheduledToken, and initialStateIdx are inconsistent.
The shape of the input or output tensor is out of the supported range.
The input attributes are out of the supported range.
dim is out of the specified value range.
aclnnInplaceFusedCausalConv1d
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address requested on the Device. workspaceSize Input Size of the workspace requested on the Device, obtained by calling the first-phase API aclnnInplaceFusedCausalConv1dGetWorkspaceSize. executor Input Op executor, which contains the operator computation flow. stream Input Specifies the stream for executing tasks. Return value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
Deterministic computation:
- aclnnInplaceFusedCausalConv1d 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. The product of the two must be in the range [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.
- cuSeqLen: range [batch, 1024 1024]; dim: range [64, 16384] and a multiple of 16; their product must be within [64 batch, 4G]; batch: range [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.
- prefill use case:
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 the compilation and execution process, see Compile and Run Samples.
#include <iostream>
#include <vector>
#include <cmath>
#include "acl/acl.h"
#include "aclnnop/aclnn_inplace_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) {
val = (sign ? -1.0f : 1.0f) * (static_cast<float>(mant) / 1024.0f) * (1.0f / 16384.0f);
} else if (exp == 31) {
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};
// ---- Host data ----
// x: fp16 1.0, shape [19, 128]
std::vector<uint16_t> hostX(cuSeqLen * dim, 0x3C00); // fp16 1.0
// weight: pass-through at k=0, zero elsewhere
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);
// ---- Device pointers and aclTensors ----
void *xDev = nullptr, *weightDev = nullptr, *convStatesDev = nullptr;
void *queryStartLocDev = nullptr, *cacheIndicesDev = nullptr;
void *initialStateModeDev = nullptr, *biasDev = nullptr;
void *numAcceptedTokensDev = nullptr;
aclTensor *xTensor = nullptr, *weightTensor = nullptr, *convStatesTensor = nullptr;
aclTensor *queryStartLocTensor = nullptr, *cacheIndicesTensor = nullptr;
aclTensor *initialStateModeTensor = nullptr, *biasTensor = nullptr;
aclTensor *numAcceptedTokensTensor = nullptr;
// ---- Create required tensors (x is non-const for inplace) ----
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);
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 = aclnnInplaceFusedCausalConv1dGetWorkspaceSize(
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, &workspaceSize,
&executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnInplaceFusedCausalConv1dGetWorkspaceSize 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 = aclnnInplaceFusedCausalConv1d(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnInplaceFusedCausalConv1d 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 xSize = GetShapeSize(xShape);
std::vector<uint16_t> xResult(xSize, 0);
ret = aclrtMemcpy(xResult.data(), xSize * sizeof(uint16_t), xDev, xSize * sizeof(uint16_t),
ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy x 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("=== x output (inplace, first 10 elements) ===\n");
for (int64_t i = 0; i < 10 && i < xSize; i++) {
LOG_PRINT(" x[%lld] = %f\n", (long long)i, (double)Fp16ToFloat(xResult[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]));
}
FreeTensorAndBuffer(xTensor, xDev);
FreeTensorAndBuffer(weightTensor, weightDev);
FreeTensorAndBuffer(convStatesTensor, convStatesDev);
FreeTensorAndBuffer(queryStartLocTensor, queryStartLocDev);
FreeTensorAndBuffer(cacheIndicesTensor, cacheIndicesDev);
FreeTensorAndBuffer(initialStateModeTensor, initialStateModeDev);
FreeTensorAndBuffer(biasTensor, biasDev);
FreeTensorAndBuffer(numAcceptedTokensTensor, numAcceptedTokensDev);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
LOG_PRINT("Test completed successfully!\n");
return 0;
}