aclnnCausalConv1dUpdate
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 the state update (decode / update) computation of causal 1D convolution (Causal Conv1d). The operator internally supports features such as SiLU activation, cache indices (cacheIndices), and speculative decoding (numAcceptedTokens).
The following use cases are supported:
Use case 1 (decode/update — fixed batch):
x: [batch, 1, dim] weight: [K, dim], where K∈{2,3,4} convStatesRef: [numCacheLines, stateLen, dim] biasOptional: [dim] or nullptr queryStartLocOptional: [batch+1] or nullptr cacheIndicesOptional: [batch] or nullptr (identity mapping is used by default) numAcceptedTokensOptional: [batch] or nullptr (speculative decoding use case, supported only when K=4) blockIdxLastScheduledTokenOptional: [batch] or nullptr initialStateIdxOptional: [batch] or nullptr activation: "silu" or "none" nullBlockId: int64_t maxQueryLen: int64_t y: [batch, 1, dim]Scenario 2 (decode/update use case — speculative decoding for variable-length sequences):
x: [cuSeqLen, dim] weight: [K, dim], where K∈{2,3,4} convStatesRef: [numCacheLines, stateLen, dim] biasOptional: [dim] or nullptr queryStartLocOptional: [batch+1] (must be provided) cacheIndicesOptional: [batch] or nullptr numAcceptedTokensOptional: [batch] (must be provided, supported only for K=4) blockIdxLastScheduledTokenOptional: [batch] or nullptr initialStateIdxOptional: [batch] or nullptr activation: "silu" or "none" nullBlockId: int64_t maxQueryLen: int64_t y: [cuSeqLen, dim]cuSeqLen is the total length of all variable-length sequences concatenated within the batch. 2D variable-length input is supported only when numAcceptedTokens (speculative decoding) is provided. For decode use cases with non-speculative decoding, use 3D input [batch, 1, dim].
Formula:
Causal Conv1d is a causal 1D convolution operator, commonly used in sequence modeling. At each time step $t$, it computes the convolution output $y_t$ based on the current input $x_t$, the convolution weight $w$, and the historical state.
$$ y_t = \text{Activation}\left(\sum_{j=0}^{W-1} w_j \cdot x_{t-j} + b\right) $$where $W$ is the convolution kernel width (2, 3, or 4 supported), $w_j$ is the convolution weight, $b$ is the bias (optional), and $\text{Activation}$ is the activation function (optional, SiLU). When
activation="none", no activation function is used. Whenactivation="silu", the SiLU activation function is used.
Function Prototype
Each operator uses a two-phase API. First call the aclnnCausalConv1dUpdateGetWorkspaceSize API to obtain the workspace size required for the computation and the executor that contains the operator computation process. Then call the aclnnCausalConv1dUpdate API to execute the computation.
aclnnStatus aclnnCausalConv1dUpdateGetWorkspaceSize(
const aclTensor *x,
const aclTensor *weight,
aclTensor *convStatesRef,
const aclTensor *biasOptional,
const aclTensor *queryStartLocOptional,
const aclTensor *cacheIndicesOptional,
const aclTensor *numAcceptedTokensOptional,
const aclTensor *blockIdxLastScheduledTokenOptional,
const aclTensor *initialStateIdxOptional,
const char *activation,
int64_t nullBlockId,
int64_t maxQueryLen,
aclTensor *y,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnCausalConv1dUpdate(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnCausalConv1dUpdateGetWorkspaceSize
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.
- Fixed-batch decode use case: shape is [batch, 1, dim] (3D).
- Speculative decoding variable-length use case: shape is [cuSeqLen, dim] (2D), and numAcceptedTokens must also be provided. For the decode use case of non-speculative decoding, use 3D input [batch, 1, dim].
FLOAT16, BFLOAT16 ND 2-3 √ weight (aclTensor*) Input w in the Formula, representing the CausalConv1d kernel. - Empty tensors are not supported.
- shape is [K, dim], where K∈{2,3,4}.
Same data type as x. ND 2 × convStatesRef (aclTensor*) Input/Output Cache state tensor. Stores the historical token data of each sequence. After the computation on each sequence is complete, the tensor is updated in place to the latest state. - Empty tensors are not supported.
- shape is [numCacheLines, stateLen, dim].
- stateLen ≥ K-1.
- numCacheLines ≥ batch (if cacheIndices is not provided).
- After each call, the operator writes the latest state back to this tensor.
Same data type as x. ND 3 √ biasOptional (aclTensor*) Optional input Bias of the convolution. The shape is [dim]. Data type: same as x ND 1 × queryStartLocOptional (aclTensor*) Optional input Sequence start position index. It records the start position of each sequence in the concatenated tensor x. Required for variable-length sequence use cases. If provided, the batch size is determined by queryStartLoc.size(0)-1 instead of being derived from the shape of x. shape is [batch+1]. queryStartLoc[0] must be 0, queryStartLoc[-1] must be equal to cuSeqLen, and values must be non-decreasing. INT32 ND 1 × cacheIndicesOptional (aclTensor*) Optional input Cache index. Specifies the index of the cache state of each sequence in convStates. If not specified, the identity mapping is used. Shape is [batch]. The value is in [0, numCacheLines), or equals nullBlockId to skip the sequence. Multiple sequences can reuse nullBlockId (padding use case); values other than nullBlockId must not be duplicated. Otherwise, multiple sequences read and write the same cache slot, causing incorrect historical states and write conflicts. INT32 ND 1 × numAcceptedTokensOptional (aclTensor*) Optional input Number of accepted tokens per batch in speculative decoding, used to determine the start position for reading historical states from convStates. Supported only for K=4. If not specified, historical states are read from the start of convStates. shape is [batch], dtype is INT32. Value range: [0, stateLen - (K - 1)], where stateLen is convStates.shape[1] and K is weight.shape[0]. The operator internally computes offset = max(numAcceptedTokens[i] - 1, 0) and reads historical states starting from the offset-th position of convStates to perform the convolution computation. Values beyond this range cause out-of-bounds access to convStates. INT32 ND 1 × blockIdxLastScheduledTokenOptional (aclTensor*) Optional input Index of the last scheduled token block, pointing to the position of the last cache block to be filled in cacheIndices. shape is [batch]. INT32 ND 1 × initialStateIdxOptional (aclTensor*) Optional input Initial state index, pointing to the location of the initial state in cacheIndices. The shape is [batch]. INT32 ND 1 × activation (const char*) Input Activation function type. "silu": SiLU; "none": no activation. STRING - - - nullBlockId (int64_t) Input Used to skip batches that do not participate in the computation. If cacheIndices[i]==nullBlockId, the batch is skipped and the corresponding output is filled with zeros. Set it to a value that does not appear in cacheIndices (such as -1) to avoid skipping valid batches by mistake. INT64 - - - maxQueryLen (int64_t) Input Maximum query length. -1 means no limit. INT64 - - - y (aclTensor*) Output y in the Formula, representing the convolution output sequence. - Fixed batch in decode mode: shape is [batch, 1, dim].
- Variable-length sequence in speculative decoding mode: shape is [cuSeqLen, dim].
Same data type as x. ND 2-3 √ workspaceSize (uint64_t*) Output Returns the workspace size that the user needs to allocate on the device. - - - - - executor (aclOpExecutor**) Output Returns the op executor containing the operator computation flow. - - - - - Return Value
aclnnStatus: Return status code. For details, see Error 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 x, weight, convStatesRef, and y are null pointers. ACLNN_ERR_INNER_TILING_ERROR 561002 The data types of inputs and outputs are out of the supported range.
The data types of x, weight, convStatesRef, biasOptional, and y are inconsistent.
The data types of cacheIndicesOptional, queryStartLocOptional, numAcceptedTokensOptional, etc., are not INT32.
The shapes of input and output tensors are out of the supported range.
The input attributes are out of the supported range.
dim does not meet the alignment requirement ((dim * dtypeSize) % 32 == 0 is required).
K is not in the range [2,4].
queryStartLocOptional is not provided in variable-length sequence use cases.
numAcceptedTokensOptional is provided when K≠4.
aclnnCausalConv1dUpdate
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address allocated on the Device. workspaceSize Input Size of the workspace allocated on the Device, obtained by calling the first-phase API aclnnCausalConv1dUpdateGetWorkspaceSize. executor Input Op executor, containing the operator computation flow. stream Input Specifies the Stream for task execution. Return value
aclnnStatus: return status code. For details, see aclnn Error Codes.
Constraints
Deterministic computation:
- aclnnCausalConv1dUpdate defaults to a deterministic implementation.
Input shape constraints:
- decode scenario (fixed batch):
- x is a 3D tensor of [batch, 1, dim].
- weight is 2D [K, dim], where K∈{2,3,4}.
- convStatesRef is 3D [numCacheLines, stateLen, dim], where stateLen ≥ K-1 and numCacheLines ≥ batch.
- dim range [64, 16384] and (dim * dtypeSize) % 32 == 0; batch range [1, 1024].
- Decode use case (speculative decoding with variable-length sequences):
- x is 2D [cuSeqLen, dim], and numAcceptedTokens must also be provided.
- queryStartLocOptional is 1D [batch+1] and must be provided.
- convStatesRef is 3D [numCacheLines, stateLen, dim], where numCacheLines ≥ batch.
- cuSeqLen range [batch, batch×8].
- The decode use case for non-speculative decoding does not support 2D variable-length input. Use the 3D input [batch, 1, dim].
- decode scenario (fixed batch):
Input value range restrictions:
- queryStartLocOptional[0] must be 0, queryStartLocOptional[-1] must equal cuSeqLen, and the values must be non-decreasing.
- Values in cacheIndicesOptional range [0, numCacheLines) or equal nullBlockId to indicate skipping. nullBlockId can be repeated; values other than nullBlockId must not be repeated. Otherwise, multiple sequences reading and writing the same cache slot cause incorrect historical states and write conflicts.
- numAcceptedTokensOptional is supported only when K=4. The value range is [0, stateLen - (K - 1)], where stateLen is convStates.shape[1].
The convolution kernel width K supports only 2, 3, and 4.
K is a runtime parameter.
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 "acl/acl.h"
#include "aclnnop/aclnn_causal_conv1d_update.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;
}
void PrintOutResult(const char *name, std::vector<int64_t> &shape, void **deviceAddr)
{
auto size = GetShapeSize(shape);
std::vector<aclFloat16> resultData(size, 0);
auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), *deviceAddr,
size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return);
LOG_PRINT("%s (first 5 elements):\n", name);
for (int64_t i = 0; i < 5 && i < size; i++) {
LOG_PRINT(" [%ld] = %f\n", i, (double)aclFloat16ToFloat(resultData[i]));
}
}
int Init(int32_t deviceId, aclrtContext *context, 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 = aclrtCreateContext(context, deviceId);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateContext failed. ERROR: %d\n", ret); return ret);
ret = aclrtSetCurrentContext(*context);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetCurrentContext 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;
}
template <typename T>
int CreateAclTensor(const std::vector<T> &hostData, const std::vector<int64_t> &shape, void **deviceAddr,
aclDataType dataType, aclTensor **tensor)
{
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);
*tensor = aclCreateTensor(shape.data(), shape.size(), dataType, nullptr, 0, aclFormat::ACL_FORMAT_ND, shape.data(),
shape.size(), *deviceAddr);
return ACL_SUCCESS;
}
int main()
{
int32_t deviceId = 0;
aclrtContext context;
aclrtStream stream;
auto ret = Init(deviceId, &context, &stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
void *xDeviceAddr = nullptr;
void *weightDeviceAddr = nullptr;
void *biasDeviceAddr = nullptr;
void *convStatesDeviceAddr = nullptr;
void *yDeviceAddr = nullptr;
aclTensor *x = nullptr;
aclTensor *weight = nullptr;
aclTensor *bias = nullptr;
aclTensor *convStates = nullptr;
aclTensor *y = nullptr;
int32_t batchSize = 4;
int32_t dim = 512;
int32_t width = 2;
int32_t stateLen = 4;
std::vector<int64_t> xShape = {batchSize, 1, dim};
std::vector<int64_t> weightShape = {width, dim};
std::vector<int64_t> biasShape = {dim};
std::vector<int64_t> convStatesShape = {batchSize, stateLen, dim};
std::vector<int64_t> yShape = {batchSize, 1, dim};
std::vector<int16_t> xHostData(GetShapeSize(xShape), 1);
std::vector<int16_t> weightHostData(GetShapeSize(weightShape), 1);
std::vector<int16_t> biasHostData(GetShapeSize(biasShape), 0);
std::vector<int16_t> convStatesHostData(GetShapeSize(convStatesShape), 0);
std::vector<int16_t> yHostData(GetShapeSize(yShape), 0);
ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_BF16, &x);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(weightHostData, weightShape, &weightDeviceAddr, aclDataType::ACL_BF16, &weight);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(biasHostData, biasShape, &biasDeviceAddr, aclDataType::ACL_BF16, &bias);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(convStatesHostData, convStatesShape, &convStatesDeviceAddr, aclDataType::ACL_BF16, &convStates);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(yHostData, yShape, &yDeviceAddr, aclDataType::ACL_BF16, &y);
CHECK_RET(ret == ACL_SUCCESS, return ret);
uint64_t workspaceSize = 0;
aclOpExecutor *executor;
const char *activation = "silu";
int64_t nullBlockId = 0;
int64_t maxQueryLen = -1;
ret = aclnnCausalConv1dUpdateGetWorkspaceSize(x, weight, convStates, bias, nullptr, nullptr, nullptr,
nullptr, nullptr,
activation, nullBlockId, maxQueryLen,
y, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCausalConv1dUpdateGetWorkspaceSize 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 = aclnnCausalConv1dUpdate(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCausalConv1dUpdate 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);
PrintOutResult("convStates (in-place updated)", convStatesShape, &convStatesDeviceAddr);
PrintOutResult("y", yShape, &yDeviceAddr);
aclDestroyTensor(x);
aclDestroyTensor(weight);
aclDestroyTensor(bias);
aclDestroyTensor(convStates);
aclDestroyTensor(y);
aclrtFree(xDeviceAddr);
aclrtFree(weightDeviceAddr);
aclrtFree(biasDeviceAddr);
aclrtFree(convStatesDeviceAddr);
aclrtFree(yDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtDestroyContext(context);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}