aclnnSparseFlashMlaGrad
Applicable Products
Ascend 950PR&950DT products : Supported
Atlas A3 products : Supported
Atlas A2 products : Supported
Atlas 200I/500 A2 inference products : Not supported
Atlas inference products : Not supported
Atlas training products : Not supported
Function
Description: Computes the backward output of attention in the
SparseFlashMlatraining use case. Supports Sliding Window Attention, Compressed Attention, and Sparse Compressed Attention.Formula:
Stage 1: Select between input ori_kv and cmp_kv based on different cmp_ratio use cases
- When cmp_ratio = 1 (SWA):
$$ selectedKv\text{ }=\text{ }orikv $$- When cmp_ratio = 4 (SCFA):
$$ selectedKv\text{ }=concat(oriKv, \text{ }Gather \left( cmpkv,topkIndices \left[ i \left] \left)) ,\text{ }0\text{ } < =i < \text{ }selectBlockCount\right. \right. \right. \right. $$- else (CFA):
$$ selectedKv\text{ }=concat(oriKv, \text{ }cmpkv) $$Stage 2: Compute P, dP, dS
$$ P = SimpleSoftmax(Mask(Q \text{ }@\text{ } selectedKv^{{T}} \cdot \text{ } scale), lse) $$$$ dP = dO \text{ }@\text{ } selectedKv^{{T}} $$$$ dS = P \times (dP\text{ } -\text{ } SoftmaxGrad(dO, O)) $$Stage 3: Compute dQ, dKV, dSinks
$$ dQ = dS \text{ } @ \text{ } selectedKv \text{ } \cdot \text{ } scale $$$$ dKV = dS^{{T}} \text{ } @ \text{ } Q \text{ } \cdot \text{ } scale + P^{{T}} @ \text{ } dO $$$$ dSinks = ReduceSum(-P \text{ }\times\text{ } dP \text{ }\times\text{ } SimpleSoftmax(sinks, lse), dim=-1) $$
Function Prototype
Each operator uses a two-phase API. Call the "aclnnSparseFlashMlaGradGetWorkspaceSize" API first to obtain the workspace size required for computation and the executor containing the computation process of the operator. Then call the "aclnnSparseFlashMlaGrad" API to perform the computation.
aclnnStatus aclnnSparseFlashMlaGradGetWorkspaceSize(
const aclTensor *query,
const aclTensor *dOut,
const aclTensor *out,
const aclTensor *lse,
const aclTensor *oriKvOptional,
const aclTensor *cmpKvOptional,
const aclTensor *oriSparseIndicesOptional,
const aclTensor *cmpSparseIndicesOptional,
const aclTensor *cuSeqlensQOptional,
const aclTensor *cuSeqlensOriKvOptional,
const aclTensor *cuSeqlensCmpKvOptional,
const aclTensor *sequsedQOptional,
const aclTensor *sequsedOriKvOptional,
const aclTensor *sequsedCmpKvOptional,
const aclTensor *cmpResidualKvOptional,
const aclTensor *oriTopkLengthOptional,
const aclTensor *cmpTopkLengthOptional,
const aclTensor *sinksOptional,
const aclTensor *metadataOptional,
double scaleValue,
int64_t cmpRatio,
int64_t oriMaskMode,
int64_t cmpMaskMode,
int64_t oriWinLeft,
int64_t oriWinRight,
char *layoutQOptional,
char *layoutKvOptional,
const aclTensor *dQueryOut,
const aclTensor *dOriKvOutOptional,
const aclTensor *dCmpKvOutOptional,
const aclTensor *dSinksOutOptional,
const aclTensor *oriSoftmaxL1NormOptional,
const aclTensor *cmpSoftmaxL1NormOptional,
uint64_t *workspaceSize,
aclOpExecutor **executor);aclnnStatus aclnnSparseFlashMlaGrad(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream);aclnnSparseFlashMlaGradGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor query (aclTensor*) Input Input Q of the attention structure. The shapes of query, oriKvOptional, cmpKvOptional, dOut, outOptional, lse, oriSparseIndicesOptional, and cmpSparseIndicesOptional must be consistent. BFLOAT16, FLOAT16 ND (B,S1,N1,D), (T1,N1,D)
B: generalized; S1: generalized; N1: 1-128; D: 512; T1: B × S1√ dOut (aclTensor*) Input Gradient of the attention output matrix. - BFLOAT16, FLOAT16 ND (B,S1,N1,D), (T1,N1,D)
B: same as B of query; S1: same as S1 of query; N1: same as N1 of query; D: 512; T1: B × S1√ out (aclTensor*) Input Attention output matrix. - BFLOAT16, FLOAT16 ND (B,S1,N1,D), (T1,N1,D)
Shape consistent with dOut√ lse (aclTensor*) Input Output lse of the forward attention computation. For the calculation formula, see the sparse_flash_mla documentation. - FLOAT32 ND (B,N2,S1,G), (N2,T1,G)
B: same as B of query; N2: 1; S1: same as S1 of query; G: N1/N2; T1: B × S1√ oriKvOptional (aclTensor*) Input Original input K(V) of the attention structure. Empty tensors are currently not supported. BFLOAT16, FLOAT16 ND (B,S2,N2,D), (T2,N2,D)
B: same as the B of query; S2: generalization supported; N2: 1; D: 512; T2: B × S2√ cmpKvOptional (aclTensor*) Input K(V) compressed by the Compressor. Supports empty tensors. In this case, computation follows the SWA use case in Formula. BFLOAT16, FLOAT16 ND (B,S3,N2,D), (T3,N2,D)
B: consistent with B of query; S3 = S2 // cmpRatio; N2: 1; D: 512; T3: B × S3√ oriSparseIndicesOptional (aclTensor*) Input Attention indices with higher weights selected from oriKvOptional in the sparse use case. Sparse computation on ori_kv is not currently supported. Therefore, setting this parameter has no effect. INT32 ND (B,S1,N2,K1), (T1,N2,K1)
B: same as B of query; S1: same as S1 of query; N2: 1; K1: supports generalization; T1: B × S1√ cmpSparseIndicesOptional (aclTensor*) Input Attention indices with higher weights selected from cmpKvOptional in the sparse use case. Empty tensors are supported: - If cmpKvOptional is not empty, the calculation is performed in the CFA use case.
- If cmpKvOptional is empty, the calculation is performed in the SWA use case.
INT32 ND (B,S1,N2,K2),(T1,N2,K2)
B: same as B of query; S1: same as S1 of query; N2: 1; K2: generalization supported; T1: B × S1√ cuSeqlensQOptional (aclTensor*) Input Number of valid query tokens in each batch. - Optional: this variable exists when layout is TND.
- Length is same as B+1.
- Cumulative sum is same as T1.
INT32 ND (B+1,) √ cuSeqlensOriKvOptional (aclTensor*) Input Number of valid tokens of oriKvOptional in each batch. - Optional: available when layout is TND.
- The length must be consistent with B+1.
- The cumulative sum must be consistent with T2.
INT32 ND (B+1,) √ cuSeqlensCmpKvOptional (aclTensor*) Input Number of valid tokens of cmpKvOptional in each batch. - Optional: available when layout is TND.
- The length is consistent with B+1.
- The cumulative sum is consistent with T3.
INT32 ND (B+1,) √ sequsedQOptional (aclTensor*) Input Number of tokens of query that actually participate in the computation in different batches. Length: B. INT32 ND (B,)
√ sequsedOriKvOptional (aclTensor*) Input Indicates the number of tokens of oriKvOptional that actually participate in the computation in each batch. Length: B. INT32 ND (B,)
√ sequsedCmpKvOptional (aclTensor*) Input Specifies the number of tokens in cmpKvOptional that actually participate in the computation in different batches. Length: B. INT32 ND (B,)
√ cmpResidualKvOptional (aclTensor*) Input Represents the remainder of S2 // cmpRatio for each batch. Must be passed in when cmpKvOptional is not empty and cmpMaskMode=3. INT32 ND (B,)
√ oriTopkLengthOptional (aclTensor*) Input Represents the actual optional topk length of oriKvOptional corresponding to each row of query. Required when oriMaskMode=0 and oriSparseIndicesOptional is not empty, and must be an accurate value. INT32 ND (B,S1,N2), (T1,N2)
√ cmpTopkLengthOptional (aclTensor*) Input Represents the actual optional topk length of cmpKvOptional corresponding to each row of query. Required when cmpMaskMode=0 and cmpSparseIndicesOptional is not empty. Must be an exact value. INT32 ND (B,S1,N2), (T1,N2)
√ sinksOptional (aclTensor*) Input Attention sink tensor. - FLOAT32 ND (N1)
N1: same as the N1 of query.√ metadataOptional(aclTensor*) Input Represents the output of the AICPU operator with tiling sinking. - INT32 ND (x)
√ scaleValue (double) Input Scaling factor. Recommended value: reciprocal of the square root of d in the formula. FLOAT32 N/A - - cmpRatio (int64_t) Input Indicates the compression ratio of oriKvOptional. Value range: 1-128. INT64 N/A - - oriMaskMode (int64_t) Input Indicates the mask mode for computing query and oriKvOptional. - Specifies the sparse mode. For details about different sparse modes, see Constraints.
INT64 N/A - - cmpMaskMode (int64_t) Input Specifies the mask mode for computing query and cmpKvOptional. - Specifies the sparse mode. For details about different sparse modes, see Constraints.
INT64 N/A - - oriWinLeft (int64_t) Input Indicates the number of past tokens that query attends to in the computation of query and oriKvOptional. - Only 127 is supported.
INT64 - - - oriWinRight (int64_t) Input Indicates the number of future tokens computed by query in the computation of query and oriKvOptional. - Only 0 is supported
INT64 - - - layoutQOptional (char*) Input Specifies the data layout format of the input query. Supports "BSND" and "TND". STRING N/A - - layoutKvOptional (char*) Input Specifies the data layout format of the input ori_kv and cmp_kv. Supports "BSND" and "TND". STRING N/A - - dQueryOut (aclTensor*) Output Represents the gradient of query. Same shape as the input query. BFLOAT16, FLOAT16 ND (B,S1,N1,D)/(T1,N1,D)
√ dOriKvOutOptional (aclTensor*) Output Gradient of oriKvOptional. Same shape dimensions as the input oriKvOptional. BFLOAT16/FLOAT16 ND (B,S2,N2,D)/(T2,N2,D)
√ dCmpKvOptional (aclTensor*) Output Represents the gradient of cmpKvOptional. Same shape dimensions as input cmpKvOptional. BFLOAT16, FLOAT16 ND (B,S3,N2,D), (T3,N2,D)
√ dSinksOutOptional (aclTensor*) Output Gradient of sinksOptional. Consistent with the Shape dimensions of input sinksOptional. FLOAT32 ND (N1)
√ oriSoftmaxL1NormOptional (aclTensor*) Output Softmax L1Norm result computed from query and oriKvOptional. The formula is reduceG(softmax)/G. This output is not empty if oriSparseIndicesOptional exists; otherwise, it is empty in other use cases. FLOAT32 ND (B,S1,N2,K1), (T1,N2,K1)
√ cmpSoftmaxL1NormOptional (aclTensor*) Output Softmax L1Norm result computed by query and cmpKvOptional. The formula is reduceG(softmax)/G. This output is not empty if cmpSparseIndicesOptional exists; otherwise, it is empty in other use cases. FLOAT32 ND (B,S1,N2,K2), (T1,N2,K2)
√ Atlas A2 products andAtlas A3 products : The sequsedQOptional, sequsedOriKvOptional, sequsedCmpKvOptional, oriTopkLengthOptional, cmpTopkLengthOptional, and metadataOptional fields are not supported yet.
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 A required parameter or output is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data types and data formats of input variables such as query, oriKvOptional, and cmpKvOptional are not within the supported range. ACLNN_ERR_RUNTIME_ERROR 361001 An exception occurs when the API calls the NPU runtime interface for memory operations. ACLNN_ERR_INNER_TILING_ERROR 561002 The value of an input parameter (such as layout or maskMode) is out of the supported range, or the shape dimensions of the input Tensor do not meet the constraint requirements.
aclnnSparseFlashMlaGrad
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address allocated on the device. workspaceSize Input Workspace size allocated on the device, obtained by the first-phase API aclnnSparseFlashMlaGradGetWorkspaceSize. executor Input Op executor that contains the operator computation process. stream Input Stream for task execution. Return value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
Deterministic computation:
Atlas A2 products andAtlas A3 products : aclnnSparseFlashMlaGrad defaults to a non-deterministic implementation. Deterministic computation cannot be enabled through aclrtCtxSetSysParamOpt.
Ascend 950PR&950DT products : aclnnSparseFlashMlaGrad defaults to a non-deterministic implementation. Deterministic computation can be enabled through aclrtCtxSetSysParamOpt.
General Constraints
- This API does not support non-contiguous output.
- Handling of empty input parameters:
- query is an empty tensor: return directly.
Mask
maskMode Meaning Remarks 0 No mask operation. Supported 3 Mask in rightDownCausal mode, corresponding to the lower-triangle use case where the right vertex is the dividing point. Supported 4 Mask in band mode. The sliding window range is controlled by oriWinLeft and oriWinRight. The parameter origin is the bottom right corner. Ori supported Specification constraints
Specification Item Specification Specification Description B Generalization supported - S1, S2 Supports generalization. Supports unequal lengths of S1 and S2. N1 1-128 - N2 1 - D 512 - layout BSND/TND - Supported values of cmpMaskMode:
Atlas A2 products andAtlas A3 products : cmpMaskMode supports 3.
Ascend 950PR&950DT products : cmpMaskMode supports 0 and 3.
Supported values of oriMaskMode:
Atlas A2 products andAtlas A3 products : oriMaskMode supports 4.
Ascend 950PR&950DT products : oriMaskMode supports 0, 3, and 4.
Example
The sample code below is for reference only. For details about compilation and execution, see Compile and Run Samples.
#include <iostream>
#include <vector>
#include <numeric>
#include "acl/acl.h"
#include "aclnnop/aclnn_sparse_flash_mla_grad.h"
#include "aclnnop/aclnn_sparse_flash_mla_grad_metadata.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(std::vector<int64_t> &shape, void** deviceAddr) {
auto size = GetShapeSize(shape);
std::vector<short> 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);
for (int64_t i = 0; i < size; i++) {
LOG_PRINT("mean result[%ld] is: %e\n", i, resultData[i]);
}
}
int Init(int32_t deviceId, aclrtContext* context, aclrtStream* stream) {
// Boilerplate code, AscendCL initialization
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);
// Call aclrtMalloc to allocate memory on the device.
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);
// Call aclrtMemcpy to copy host-side data to the device memory.
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);
// Calculate strides of the contiguous tensor.
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];
}
// Call aclCreateTensor to create an aclTensor.
*tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
shape.data(), shape.size(), *deviceAddr);
return 0;
}
int main() {
// 1. (Boilerplate) Initialize device/context/stream. For details, see the acl API documentation.
// Set deviceId based on the actual device.
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);
// 2. Construct inputs and outputs, customized based on the API.
std::vector<int64_t> qShape = {1, 16, 512}; // T1, N1, D
std::vector<int64_t> oriKvShape = {2048, 1, 512}; // T2, N2, D
std::vector<int64_t> cmpKvShape = {16, 1, 512}; // T3, N2, D
std::vector<int64_t> dOutShape = {1, 16, 512}; // T1, N1, D
std::vector<int64_t> outShape = {1, 16, 512}; // T1, N1, D
std::vector<int64_t> lseShape = {1, 1, 16}; // N2, T1, G
std::vector<int64_t> cuSeqQLenshape = {2}; // B + 1
std::vector<int64_t> cuSeqOriKvLenshape = {2}; // B + 1
std::vector<int64_t> cuSeqCmpKvLenshape = {2}; // B + 1
std::vector<int64_t> cmpResidualKvShape = {1}; // B
std::vector<int64_t> sinksShape = {16}; // N1
std::vector<int64_t> metadataShape = {1024}; // Fixed size
void* qDeviceAddr = nullptr;
void* oriKvDeviceAddr = nullptr;
void* cmpKvDeviceAddr = nullptr;
void* outDeviceAddr = nullptr;
void* dOutDeviceAddr = nullptr;
void* lseDeviceAddr = nullptr;
void* cuSeqQLenDeviceAddr = nullptr;
void* cuSeqOriKvLenDeviceAddr = nullptr;
void* cuSeqCmpKvLenDeviceAddr = nullptr;
void* cmpResidualKvDeviceAddr = nullptr;
void* sinksDeviceAddr = nullptr;
void* dqDeviceAddr = nullptr;
void* dOriKvDeviceAddr = nullptr;
void* dCmpKvDeviceAddr = nullptr;
void* dSinksDeviceAddr = nullptr;
void* metadataDeviceAddr = nullptr;
void* oriSoftmaxL1NormDeviceAddr = nullptr;
void* cmpSoftmaxL1NormDeviceAddr = nullptr;
aclTensor* q = nullptr;
aclTensor* oriKv = nullptr;
aclTensor* cmpKv = nullptr;
aclTensor* out = nullptr;
aclTensor* dOut = nullptr;
aclTensor* lse = nullptr;
aclTensor* cuSeqQLen = nullptr;
aclTensor* cuSeqOriKvLen = nullptr;
aclTensor* cuSeqCmpKvLen = nullptr;
aclTensor* cmpResidualKv = nullptr;
aclTensor* sinks = nullptr;
aclTensor* dq = nullptr;
aclTensor* dOriKv = nullptr;
aclTensor* dCmpKv = nullptr;
aclTensor* dSinks = nullptr;
aclTensor* metadata = nullptr;
aclTensor* oriSoftmaxL1Norm = nullptr;
aclTensor* cmpSoftmaxL1Norm = nullptr;
std::vector<short> qHostData(1 * 16 * 512, 1.0);
std::vector<short> oriKvHostData(2048 * 1 * 512, 1.0);
std::vector<short> cmpKvHostData(16 * 1 * 512, 1.0);
std::vector<short> outHostData(1 * 16 * 512, 1.0);
std::vector<short> dOutHostData(1 * 16 * 512, 1.0);
std::vector<float> lseHostData(16, 3.0);
std::vector<int32_t> cuSeqQLenHostData = {0, 1};
std::vector<int32_t> cuSeqOriKvLenHostData = {0, 2048};
std::vector<int32_t> cuSeqCmpKvLenHostData = {0, 16};
std::vector<int32_t> cmpResidualKvHostData = {0};
std::vector<float> sinksHostData(16, 128.0);
std::vector<short> dqHostData(1 * 16 * 512, 0);
std::vector<short> dOriKvHostData(2048 * 1 * 512, 0);
std::vector<short> dCmpKvHostData(16 * 1 * 512, 0);
std::vector<float> dSinksHostData(16, 0);
std::vector<int32_t> metadataHostData(1024, 0);
ret = CreateAclTensor(qHostData, qShape, &qDeviceAddr, aclDataType::ACL_FLOAT16, &q);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(oriKvHostData, oriKvShape, &oriKvDeviceAddr, aclDataType::ACL_FLOAT16, &oriKv);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(cmpKvHostData, cmpKvShape, &cmpKvDeviceAddr, aclDataType::ACL_FLOAT16, &cmpKv);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT16, &out);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(dOutHostData, dOutShape, &dOutDeviceAddr, aclDataType::ACL_FLOAT16, &dOut);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(lseHostData, lseShape, &lseDeviceAddr, aclDataType::ACL_FLOAT, &lse);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(cuSeqQLenHostData, cuSeqQLenshape, &cuSeqQLenDeviceAddr, aclDataType::ACL_INT32, &cuSeqQLen);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(cuSeqOriKvLenHostData, cuSeqOriKvLenshape, &cuSeqOriKvLenDeviceAddr, aclDataType::ACL_INT32, &cuSeqOriKvLen);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(cuSeqCmpKvLenHostData, cuSeqCmpKvLenshape, &cuSeqCmpKvLenDeviceAddr, aclDataType::ACL_INT32, &cuSeqCmpKvLen);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(cmpResidualKvHostData, cmpResidualKvShape, &cmpResidualKvDeviceAddr, aclDataType::ACL_INT32, &cmpResidualKv);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(sinksHostData, sinksShape, &sinksDeviceAddr, aclDataType::ACL_FLOAT, &sinks);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(dqHostData, qShape, &dqDeviceAddr, aclDataType::ACL_FLOAT16, &dq);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(dOriKvHostData, oriKvShape, &dOriKvDeviceAddr, aclDataType::ACL_FLOAT16, &dOriKv);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(dCmpKvHostData, cmpKvShape, &dCmpKvDeviceAddr, aclDataType::ACL_FLOAT16, &dCmpKv);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(dSinksHostData, sinksShape, &dSinksDeviceAddr, aclDataType::ACL_FLOAT, &dSinks);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(metadataHostData, metadataShape, &metadataDeviceAddr, aclDataType::ACL_INT32, &metadata);
CHECK_RET(ret == ACL_SUCCESS, return ret);
double scaleValue = 0.088388;
int64_t cmpRatio = 128;
int64_t oriMaskMode = 4;
int64_t cmpMaskMode = 3;
int64_t oriWinLeft = 127;
int64_t oriWinRight = 0;
char layoutQ[5] = {'T', 'N', 'D', 0};
char layoutKv[5] = {'T', 'N', 'D', 0};
// 3. Call the CANN operator library API. Replace it with the specific API name.
// 3.1 Call SparseFlashMlaGradMetadata to obtain metadata.
uint64_t metaWorkspaceSize = 0;
aclOpExecutor* metaExecutor;
ret = aclnnSparseFlashMlaGradMetadataGetWorkspaceSize(
cuSeqQLen, cuSeqOriKvLen, cuSeqCmpKvLen,
nullptr, nullptr, nullptr,
cmpResidualKv,
nullptr, nullptr,
16, 1, 512,
0, 0, 0, 0,
0, 0,
cmpRatio, oriMaskMode, cmpMaskMode, oriWinLeft, oriWinRight,
layoutQ, layoutKv,
true, true,
metadata, &metaWorkspaceSize, &metaExecutor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("SparseFlashMlaGradMetadataGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
void* metaWorkspaceAddr = nullptr;
if (metaWorkspaceSize > 0) {
ret = aclrtMalloc(&metaWorkspaceAddr, metaWorkspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate metadata workspace failed. ERROR: %d\n", ret); return ret);
}
ret = aclnnSparseFlashMlaGradMetadata(metaWorkspaceAddr, metaWorkspaceSize, metaExecutor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("SparseFlashMlaGradMetadata 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);
// 3.2 Call SparseFlashMlaGrad to compute gradients.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
ret = aclnnSparseFlashMlaGradGetWorkspaceSize(q, dOut, out, lse, oriKv, cmpKv, nullptr, nullptr, cuSeqQLen, cuSeqOriKvLen, cuSeqCmpKvLen,
nullptr, nullptr, nullptr, cmpResidualKv, nullptr, nullptr, sinks, metadata, scaleValue, cmpRatio, oriMaskMode, cmpMaskMode, oriWinLeft, oriWinRight,
layoutQ, layoutKv, dq, dOriKv, dCmpKv, dSinks, oriSoftmaxL1Norm, cmpSoftmaxL1Norm,
&workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("SparseFlashMlaGradGetWorkspaceSize 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 = aclnnSparseFlashMlaGrad(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("SparseFlashMlaGrad failed. ERROR: %d\n", ret); return ret);
// 4. (boilerplate) Synchronize and wait for the task execution to complete.
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
// 5. Obtain the output values and copy the results from device memory to host memory. Modify the code based on the definition of the specific API.
PrintOutResult(qShape, &dqDeviceAddr);
PrintOutResult(cmpKvShape, &dCmpKvDeviceAddr);
PrintOutResult(sinksShape, &dSinksDeviceAddr);
// 6. Release aclTensor and aclScalar. Modify the code based on the definition of the specific API.
aclDestroyTensor(q);
aclDestroyTensor(oriKv);
aclDestroyTensor(cmpKv);
aclDestroyTensor(out);
aclDestroyTensor(dOut);
aclDestroyTensor(lse);
aclDestroyTensor(cuSeqQLen);
aclDestroyTensor(cuSeqOriKvLen);
aclDestroyTensor(cuSeqCmpKvLen);
aclDestroyTensor(cmpResidualKv);
aclDestroyTensor(sinks);
aclDestroyTensor(dq);
aclDestroyTensor(dOriKv);
aclDestroyTensor(dCmpKv);
aclDestroyTensor(dSinks);
aclDestroyTensor(metadata);
aclDestroyTensor(oriSoftmaxL1Norm);
aclDestroyTensor(cmpSoftmaxL1Norm);
// 7. Release device resources.
aclrtFree(qDeviceAddr);
aclrtFree(oriKvDeviceAddr);
aclrtFree(cmpKvDeviceAddr);
aclrtFree(outDeviceAddr);
aclrtFree(dOutDeviceAddr);
aclrtFree(lseDeviceAddr);
aclrtFree(cuSeqQLenDeviceAddr);
aclrtFree(cuSeqOriKvLenDeviceAddr);
aclrtFree(cuSeqCmpKvLenDeviceAddr);
aclrtFree(cmpResidualKvDeviceAddr);
aclrtFree(sinksDeviceAddr);
aclrtFree(dqDeviceAddr);
aclrtFree(dOriKvDeviceAddr);
aclrtFree(dCmpKvDeviceAddr);
aclrtFree(dSinksDeviceAddr);
aclrtFree(metadataDeviceAddr);
aclrtFree(oriSoftmaxL1NormDeviceAddr);
aclrtFree(cmpSoftmaxL1NormDeviceAddr);
if (metaWorkspaceSize > 0) {
aclrtFree(metaWorkspaceAddr);
}
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtDestroyContext(context);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}