aclnnCausalConv1dFn
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 forward computation of causal 1D convolution (Causal Conv1d) (prefill / chunk-prefill). The operator internally supports features such as SiLU activation, cache index (cacheIndices), and initial state mode (initialStateMode).
The following use cases are supported:
Use case 1 (prefill scenario - fixed batch):
x: [batch, seqLen, 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 initialStateModeOptional: [batch] or nullptr blockIdxFirstScheduledTokenOptional: [batch] or nullptr blockIdxLastScheduledTokenOptional: [batch] or nullptr initialStateIdxOptional: [batch] or nullptr numComputedTokensOptional: [batch] or nullptr activation: "silu" or "none" nullBlockId: int64_t blockSizeToAlign: int64_t y: [batch, seqLen, dim]Use case 2 (prefill scenario — variable-length sequence):
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 initialStateModeOptional: [batch] or nullptr blockIdxFirstScheduledTokenOptional: [batch] or nullptr blockIdxLastScheduledTokenOptional: [batch] or nullptr initialStateIdxOptional: [batch] or nullptr numComputedTokensOptional: [batch] or nullptr activation: "silu" or "none" nullBlockId: int64_t blockSizeToAlign: int64_t y: [cuSeqLen, dim]where cuSeqLen is the total length of all variable-length sequences concatenated in a batch.
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) $$Here, $W$ is the kernel width (2, 3, and 4 are 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.For $t < W-1$ with no historical state, the output is zero (causal constraint).
Function Prototype
Each operator uses a two-phase API. First call the aclnnCausalConv1dFnGetWorkspaceSize API to obtain the workspace size required for computation and the executor that contains the operator computation process, and then call the aclnnCausalConv1dFn API to perform the computation.
aclnnStatus aclnnCausalConv1dFnGetWorkspaceSize(
const aclTensor *x,
const aclTensor *weight,
aclTensor *convStatesRef,
const aclTensor *biasOptional,
const aclTensor *queryStartLocOptional,
const aclTensor *cacheIndicesOptional,
const aclTensor *initialStateModeOptional,
const aclTensor *blockIdxFirstScheduledTokenOptional,
const aclTensor *blockIdxLastScheduledTokenOptional,
const aclTensor *initialStateIdxOptional,
const aclTensor *numComputedTokensOptional,
const char *activation,
int64_t nullBlockId,
int64_t blockSizeToAlign,
aclTensor *y,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnCausalConv1dFn(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnCausalConv1dFnGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor x (aclTensor*) Input x in the Formula represents the input sequence. - Empty tensors are not supported.
- prefill fixed batch scenario: shape [batch, seqLen, dim].
- prefill variable-length scenario: shape [cuSeqLen, dim].
FLOAT16, BFLOAT16 ND 2-3 √ weight (aclTensor*) Input w in the Formula represents the causal 1D convolution kernel. - Empty tensors are not supported.
- The shape is [K, dim], K∈{2,3,4}.
Data type: consistent with x ND 2 × convStatesRef (aclTensor*) Input/Output Cache state tensor that stores the historical token data of each sequence. After the computation of each sequence is complete, this tensor is updated in place with the latest state. - Empty tensors are not supported.
- The shape is [numCacheLines, stateLen, dim].
- stateLen ≥ K-1.
- numCacheLines ≥ batch (when cacheIndices is not provided).
- After each call, the operator writes the latest state back to this tensor.
Data type: consistent with x ND 3 √ biasOptional (aclTensor*) Optional input Bias of the convolution. The shape is [dim]. The data type is consistent with x. ND 1 × queryStartLocOptional (aclTensor*) Optional input Sequence start position index, recording the start position of each sequence in the concatenated tensor x. Must be provided for variable-length sequence scenarios. The shape is [batch+1]. queryStartLoc[0] must be 0, queryStartLoc[-1] must be equal to cuSeqLen, and the values must be non-decreasing. INT32 ND 1 × cacheIndicesOptional (aclTensor*) Optional input Cache index, specifying the index of the cached state of each sequence in convStates. If not provided, the identity mapping is used. The shape is [batch]. The value ∈ [0, numCacheLines), or equals nullBlockId, indicating that the sequence is skipped. nullBlockId can be reused by multiple sequences (padding scenario); values other than nullBlockId must not be repeated. Otherwise, multiple sequences read and write the same cache slot, causing incorrect historical states and write conflicts. INT32 ND 1 × initialStateModeOptional (aclTensor*) Optional input Initial state flag, indicating whether each sequence uses the cached initial state. If not provided, all sequences are initialized to zero. The shape is [batch]. Values: 0=zero initialization, 1=use cached state. When enabled, additional workspace is required for the snapshot. INT32 ND 1 × blockIdxFirstScheduledTokenOptional (aclTensor*) Optional input Index of the first scheduled token block, pointing to the position of the first cache block to be filled in cacheIndices. The shape is [batch]. INT32 ND 1 × blockIdxLastScheduledTokenOptional (aclTensor*) Optional input Index of the last scheduled token block, pointing to the last cache block to be filled in cacheIndices. The shape is [batch]. INT32 ND 1 × initialStateIdxOptional (aclTensor*) Optional input Initial state index, pointing to the position of the initial state in cacheIndices. The shape is [batch]. INT32 ND 1 × numComputedTokensOptional (aclTensor*) Optional input Number of completed tokens for each sequence. 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 need to participate in the computation. When cacheIndices[i]==nullBlockId, the batch is skipped and the corresponding output is filled with zeros. Users should set it to a value that does not appear in cacheIndices (such as -1) to avoid skipping valid batches by mistake. INT64 - - - blockSizeToAlign (int64_t) Input Block size for cache state alignment. - INT64 - - - y (aclTensor*) Output y in the Formula, representing the convolution output sequence. - prefill with fixed batch: shape is [batch, seqLen, dim].
- variable-length sequence: shape is [cuSeqLen, dim].
Data type consistent with x ND 2-3 √ workspaceSize (uint64_t*) Output Returns the workspace size that users need to allocate on the Device. - - - - - executor (aclOpExecutor**) Output Returns the op executor, which contains the computation 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 Value Error Code Description ACLNN_ERR_PARAM_NULLPTR 161001 The passed-in x, weight, convStatesRef, or y is a null pointer. 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 not consistent.
The data types of queryStartLocOptional, cacheIndicesOptional, initialStateModeOptional, 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 must be satisfied).
K is not in the range [2, 4].
queryStartLocOptional is not provided for the variable-length scenario.
aclnnCausalConv1dFn
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 aclnnCausalConv1dFnGetWorkspaceSize. executor Input Op executor that contains the operator computation flow. stream Input Specifies the Stream for task execution. Return value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
Deterministic computation:
- aclnnCausalConv1dFn defaults to a deterministic implementation.
Input shape constraints:
- prefill scenario (fixed batch):
- x is a 3D tensor of shape [batch, seqLen, dim], with seqLen > 0.
- weight is a 2D tensor of shape [K, dim], with K∈{2,3,4}.
- convStatesRef is a 3D tensor of shape [numCacheLines, stateLen, dim], with stateLen ≥ K-1 and numCacheLines ≥ batch.
- dim is in the range [64, 16384] and satisfies (dim * dtypeSize) % 32 == 0; batch is in the range [1, 1024].
- prefill scenario (variable-length sequence):
- x is a 2D tensor of shape [cuSeqLen, dim].
- queryStartLocOptional is a 1D tensor of shape [batch+1] and must be provided.
- convStatesRef is a 3D tensor of shape [numCacheLines, stateLen, dim], with numCacheLines ≥ batch.
- cuSeqLen is in the range [batch, 1024×1024].
- prefill scenario (fixed batch):
Input value range restrictions:
- queryStartLocOptional[0] must be 0, queryStartLocOptional[-1] must be equal to cuSeqLen, and the values must be non-decreasing.
- Values in cacheIndicesOptional must be in the range [0, numCacheLines), or equal to nullBlockId to indicate skipping. nullBlockId can be repeated. Values other than nullBlockId should not be repeated. Otherwise, multiple sequences read and write the same cache slot, causing incorrect historical states and write conflicts.
- Values of initialStateModeOptional must be in {0,1}.
The convolution kernel width K supports only 2, 3, and 4.
K is a compile-time constant and supports the FnRolling fast-path optimization.
When the initialStateModeOptional input is present, the operator requires additional workspace for initial state snapshots.
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_fn.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 *queryStartLocDeviceAddr = nullptr;
void *yDeviceAddr = nullptr;
aclTensor *x = nullptr;
aclTensor *weight = nullptr;
aclTensor *bias = nullptr;
aclTensor *convStates = nullptr;
aclTensor *queryStartLoc = nullptr;
aclTensor *y = nullptr;
int32_t batchSize = 2;
int32_t seqLen = 4;
int32_t dim = 64;
int32_t width = 3;
int32_t stateLen = width;
std::vector<int64_t> xShape = {batchSize * seqLen, 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> queryStartLocShape = {batchSize + 1};
std::vector<int64_t> yShape = {batchSize * seqLen, 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<int32_t> queryStartLocHostData = {0, seqLen, batchSize * seqLen};
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(queryStartLocHostData, queryStartLocShape, &queryStartLocDeviceAddr, aclDataType::ACL_INT32, &queryStartLoc);
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 blockSizeToAlign = 0;
ret = aclnnCausalConv1dFnGetWorkspaceSize(x, weight, convStates, bias, queryStartLoc, nullptr, nullptr,
nullptr, nullptr, nullptr, nullptr,
activation, nullBlockId, blockSizeToAlign,
y, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCausalConv1dFnGetWorkspaceSize 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 = aclnnCausalConv1dFn(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCausalConv1dFn 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(queryStartLoc);
aclDestroyTensor(y);
aclrtFree(xDeviceAddr);
aclrtFree(weightDeviceAddr);
aclrtFree(biasDeviceAddr);
aclrtFree(convStatesDeviceAddr);
aclrtFree(queryStartLocDeviceAddr);
aclrtFree(yDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtDestroyContext(context);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}