aclnnStemOamPrepVarlenQ
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 Q-side preprocessing computation for Stem OAM block-sparse attention. Converts a varlen Q tensor from the paged storage format into flattened qFlat output grouped by stem block (128 tokens) for subsequent OAM score computation.
Formula:
Stage 1 Scale Fusion: $q\_scale[b, h, pos] = qscale[b, h, pos]$
Stage 2 De-page Varlen: $Q\_dense[b] = Cast(q[cu\_seqlens\_q[b]:cu\_seqlens\_q[b]+q\_len[b], :, :], \text{FP32})$
Stage 3 Weighted Group Sum (natural order, NO flip): $Q\_group\_sum[b,h,qb,g,:] = \sum_{r=0}^{R-1} Q\_blocks[b,h,qb,r,g,:] \times q\_scale[b,h,position(qb,r,g)]$
Stage 4 Flatten: $qflat[b, h, qb, g \times D : (g+1) \times D] = Q\_group\_sum[b, h, qb, g, :]$
Stage 5 Cast output: $qflat\_out = qflat.to(\text{BF16})$
Key feature: The stride dimension on the Q side is in natural order (no flip), which differs from the flip processing on the K side.
Function Prototype
Each operator is split into a two-phase API. You must first call the "aclnnStemOamPrepVarlenQGetWorkspaceSize" API to obtain the workspace size required for computation and the executor that contains the operator computation flow, and then call the "aclnnStemOamPrepVarlenQ" API to perform computation.
aclnnStatus aclnnStemOamPrepVarlenQGetWorkspaceSize(
const aclTensor *q,
const aclIntArray *qSeqLens,
const aclIntArray *cuSeqLensQ,
const aclTensor *qScale,
int64_t stemBlockSize,
int64_t stemStride,
aclTensor *qFlat,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnStemOamPrepVarlenQ(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnStemOamPrepVarlenQGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor q (aclTensor*) Input Indicates the varlen Q tensor, with tokens of all batches concatenated and stored. Corresponds to q in the formula. - Empty tensors are supported. For an empty tensor, the API returns directly and workspaceSize is 0.
- The last dimension must be 128.
- Only the data type FLOAT8_E4M3FN is supported.
FLOAT8_E4M3FN ND 3 ([total_tokens, H_q, D]), D=128 - qSeqLens (aclIntArray*) Input Indicates the Q sequence length of each batch. Corresponds to q_seq_lens in the formula. - Length equals batch, with a value range of (0, 1024].
- Each value ≥0.
- If the length is 0, the tensor is treated as an empty tensor and returned directly.
INT64 - 1 ([batch]) - cuSeqLensQ (aclIntArray*) Input Indicates the cumulative sequence length offsets of Q, used for varlen indexing. Corresponds to cu_seqlens_q in the formula. - Length equals batch+1.
- cuSeqLensQ[0] must be 0.
- cuSeqLensQ[batch] must be equal to total_tokens.
- Monotonically increasing (equal values allowed).
INT64 - 1 ([batch+1]) - qScale (aclTensor*) Input Indicates the per-token scale factor of Q, corresponding to qscale in the corresponding formula. - Required. Must not be nullptr when q is FLOAT8_E4M3FN.
- Shape is [total_tokens, H_q].
- Data type must be FLOAT.
FLOAT ND 2 ([total_tokens, H_q]) - stemBlockSize (int64_t) Input Indicates the stem block size, corresponding to B in the formula. Controls the number of tokens in each stem block and determines the grouping granularity of Q Processing. - Only 128 is supported.
- - - - stemStride (int64_t) Input Indicates the stem stride size, corresponding to S in the formula. Controls the number of tokens in each stride group within a stem block, determining the dimension granularity of qFlat. - Only 16 is supported.
- - - - qFlat (aclTensor*) Output Indicates the flattened Q output used for OAM score computation. Corresponds to qflat_out in the formula. - The data type is fixed to BFLOAT16.
- The shape is [batch, H_q, max_Qb, kflat_dim], where max_Qb=ceil(max(qSeqLens)/stemBlockSize) and kflat_dim=stemStride×D=16×128=2048.
BFLOAT16 ND 4 ([batch, H_q, max_Qb, kflat_dim]) × workspaceSize (uint64_t*) Output Indicates the workspace size to be requested 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 Value Error Code Description ACLNN_ERR_PARAM_NULLPTR 161001 q, qSeqLens, cuSeqLensQ, qFlat, workspaceSize, or executor is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type of q is not FLOAT8_E4M3FN. qScale is nullptr when q is FP8. The data type of qScale is not FLOAT. The data type of qFlat is not BFLOAT16. The dimension of q is not 3 or the last dimension is not 128; the dimension of qScale is not 2; the dimension of qFlat is not 4. The length of qSeqLens is out of the range (0, 1024]; the length of cuSeqLensQ is not batch+1, cuSeqLensQ[0] is not 0, cuSeqLensQ is not monotonically increasing, or cuSeqLensQ[batch] is not total_tokens. stemBlockSize is not 128 or stemStride is not 16. ACLNN_ERR_INNER 361001 Internal error, such as a Tiling computation failure or kernel search failure.
aclnnStemOamPrepVarlenQ
Parameters
Parameter Input/Output Description workspace Input Workspace memory address requested on the Device side. workspaceSize Input Workspace size requested on the Device side, obtained by the first-phase API aclnnStemOamPrepVarlenQGetWorkspaceSize. executor Input Executor of the op, which contains the operator computation flow. stream Input Stream for task execution. Return Value
aclnnStatus: Return status code. For details, see ACLNN Return Codes.
Constraints
- Deterministic computation: aclnnStemOamPrepVarlenQ defaults to a deterministic implementation.
- The last dimension D of q must be equal to 128.
- Only 128 is supported for stemBlockSize, and only 16 for stemStride. Derived values: R = stemBlockSize / stemStride = 8, kflat_dim = stemStride × D = 2048.
- qFlat output dimension kflat_dim = stemStride × D = 16 × 128 = 2048.
- The stride dimension on the Q side is in natural order (g ∈ [0, S-1]) and is not flipped (unlike the K-side processing).
- When a batch value in qSeqLens is 0, the qFlat output corresponding to that batch is filled with zeros.
- q supports only the FLOAT8_E4M3FN data type. qScale is mandatory and its data type is FLOAT. The qFlat output is fixed to BFLOAT16.
- Empty tensor input is supported: when q is empty or the length of qSeqLens is 0, the API returns directly and workspaceSize is 0.
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_stem_oam_prep_varlen_q.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;
}
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 = shape.size() - 2; i >= 0; i--) {
strides[i] = shape[i + 1] * strides[i + 1];
}
*tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, format, shape.data(),
shape.size(), *deviceAddr);
return 0;
}
int main()
{
// 1. Initialize the Device and Stream.
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);
// 2. Create the input tensors.
int64_t totalTokens = 256;
int64_t numHeadQ = 32;
int64_t dimQk = 128;
int64_t batch = 2;
int64_t stemBlockSize = 128;
int64_t stemStride = 16;
int64_t kflatDim = stemStride * dimQk;
std::vector<int64_t> qShape = {totalTokens, numHeadQ, dimQk};
std::vector<int64_t> qScaleShape = {totalTokens, numHeadQ};
std::vector<int64_t> qFlatShape = {batch, numHeadQ, 1, kflatDim};
void *qDeviceAddr = nullptr;
void *qScaleDeviceAddr = nullptr;
void *qFlatDeviceAddr = nullptr;
aclTensor *q = nullptr;
aclTensor *qScale = nullptr;
aclTensor *qFlat = nullptr;
std::vector<uint8_t> hostQ(GetShapeSize(qShape), 1);
std::vector<float> hostQScale(GetShapeSize(qScaleShape), 1.0f);
std::vector<uint16_t> hostQFlat(GetShapeSize(qFlatShape), 0);
ret = CreateAclTensor(hostQ, qShape, &qDeviceAddr, aclDataType::ACL_FLOAT8_E4M3FN, &q,
aclFormat::ACL_FORMAT_ND);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(hostQScale, qScaleShape, &qScaleDeviceAddr, aclDataType::ACL_FLOAT, &qScale,
aclFormat::ACL_FORMAT_ND);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(hostQFlat, qFlatShape, &qFlatDeviceAddr, aclDataType::ACL_BF16, &qFlat,
aclFormat::ACL_FORMAT_ND);
CHECK_RET(ret == ACL_SUCCESS, return ret);
int64_t qSeqLensData[] = {128, 128};
int64_t cuSeqLensQData[] = {0, 128, 256};
aclIntArray *qSeqLens = aclCreateIntArray(qSeqLensData, 2);
aclIntArray *cuSeqLensQ = aclCreateIntArray(cuSeqLensQData, 3);
// 3. Obtain the workspace size.
uint64_t workspaceSize = 0;
aclOpExecutor *executor;
ret = aclnnStemOamPrepVarlenQGetWorkspaceSize(q, qSeqLens, cuSeqLensQ, qScale, stemBlockSize, stemStride,
qFlat, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnStemOamPrepVarlenQGetWorkspaceSize failed. ERROR: %d\n", ret);
return ret);
// 4. Allocate the workspace and execute the computation.
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 = aclnnStemOamPrepVarlenQ(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnStemOamPrepVarlenQ 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);
// 5. Release the resources.
aclDestroyTensor(q);
aclDestroyTensor(qScale);
aclDestroyTensor(qFlat);
aclDestroyIntArray(qSeqLens);
aclDestroyIntArray(cuSeqLensQ);
aclrtFree(qDeviceAddr);
aclrtFree(qScaleDeviceAddr);
aclrtFree(qFlatDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}