aclnnClaGateBackward
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: Fusion operator. Computes backward gradients of the CLA (Cross-Layer Attention) gate merge. It takes the upstream gradient G = ∂L/∂O, two original Attention outputs O_g/O_l, and two gate logits z_g/z_l as inputs, and computes and returns four gradients at one time: two Attention output gradients (dO_g, dO_l) and two gate logits gradients (dz_g, dz_l). This API does not quantize gradients: the output keeps the input precision (BF16/FP16), and no FP8 gradient is generated. The backward operator does not receive the forward sigmoid intermediate result. s_g/s_l are recomputed inside the operator.
Formula:
Let T be the number of tokens on this rank, N the number of attention heads, and D the value head dim.
Phase 1: Sigmoid recomputation (recomputed within the operator, FP32 domain)
- Head-wise Sigmoid gating for the two paths and their derivative terms (z_g and z_l are the two gate logits):
Phase 2: Attention output gradients (element-wise chain rule, s_g/s_l broadcast along dimension D)
Phase 3: Gate logits gradients (chain rule + Sigmoid derivative, sum_d reduces only along head_dim D, not across tokens or heads)
- The products G⊙O_g/G⊙O_l and the reduction along D are both performed in the FP32 domain (completed in a single pass, with no extra memory round trips) to reduce accumulated reduction error.
- No division/exponential overflow paths. NaN/Inf inputs propagate according to IEEE semantics (no special protection required).
Function Prototype
Each operator uses a two-phase API. First call the "aclnnClaGateBackwardGetWorkspaceSize" API to obtain the workspace size required for the computation and the executor containing the operator computation flow, and then call the "aclnnClaGateBackward" API to execute the computation.
aclnnStatus aclnnClaGateBackwardGetWorkspaceSize(
const aclTensor *gradMerged,
const aclTensor *globalAttn,
const aclTensor *localAttn,
const aclTensor *globalGateLogits,
const aclTensor *localGateLogits,
const char *inputAttnLayout,
const aclTensor *gradGlobalAttnOut,
const aclTensor *gradLocalAttnOut,
const aclTensor *gradGlobalGateLogitsOut,
const aclTensor *gradLocalGateLogitsOut,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnClaGateBackward(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnClaGateBackwardGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Shape Non-contiguous Tensor gradMerged (aclTensor*) Input Gradient of the output projection back-propagated to gate merge, G in the formula. - shape=[T, N, D], D supports only 128 or 256.
- Does not support empty Tensor.
BFLOAT16, FLOAT16 ND 3 √ globalAttn(aclTensor*) Input Forward Global/CLA branch Attention output, O_g in the formula. - The shape is the same as that of gradMerged, which is [T, N, D].
- The data type is the same as that of gradMerged.
- Does not support empty tensor.
BFLOAT16, FLOAT16 ND 3 √ localAttn (aclTensor*) Input Attention output of the forward Local/SWA branch, which is O_l in the formula. - The shape is the same as that of gradMerged, which is [T, N, D].
- The data type is the same as that of gradMerged.
- Does not support empty tensor.
BFLOAT16, FLOAT16 ND 3 √ globalGateLogits (aclTensor*) Input Forward Global gate logits, z_g in the formula. - shape=[T, N]. T and N are the same as those of gradMerged.
- The data type is the same as that of gradMerged.
- Does not support empty Tensor.
BFLOAT16, FLOAT16 ND 2 √ localGateLogits (aclTensor*) Input Forward Local gate logits, which is z_l in the formula. - Same shape as globalGateLogits, which is [T, N].
- Same data type as gradMerged.
- Does not support empty tensors.
BFLOAT16, FLOAT16 ND 2 √ inputAttnLayout (const char*) Input Layout format string of the input tensor. - Currently, only "TND" is supported.
- The default value is "TND". If a null pointer is passed, the default value is used.
- - - - gradGlobalAttnOut (aclTensor*) Output Global Attention branch gradient, which is dO_g in the formula. - shape=[T, N, D], consistent with globalAttn.
- The data type is the same as that of globalAttn.
BFLOAT16, FLOAT16 ND 3 - gradLocalAttnOut (aclTensor*) Output Gradient of the Local Attention branch, dO_l in the formula. - shape=[T, N, D], consistent with localAttn.
- The data type is the same as that of localAttn.
BFLOAT16, FLOAT16 ND 3 - gradGlobalGateLogitsOut (aclTensor*) Output Gradient of global gate logits, which is dz_g in the formula. - shape=[T, N], the same as globalGateLogits.
- Data type is the same as globalGateLogits.
BFLOAT16, FLOAT16 ND 2 - gradLocalGateLogitsOut (aclTensor*) Output Local gate logits gradient, dz_l in the formula. - shape=[T, N], same as localGateLogits.
- Data type is the same as localGateLogits.
BFLOAT16, FLOAT16 ND 2 - workspaceSize (uint64_t*) Output Returns the workspace size that needs to be applied on the Device side. - - - - - executor (aclOpExecutor**) Output Returns the op executor, which contains the computation process of the operator. - - - - - Return Value
aclnnStatus: return status code. For details, see aclnn Return Codes.
The first-phase API validates the following input parameters and reports an error in the following use cases:
Return Value Error Code Description ACLNN_ERR_PARAM_NULLPTR 161001 gradMerged, globalAttn, localAttn, globalGateLogits, localGateLogits, gradGlobalAttnOut, gradLocalAttnOut, gradGlobalGateLogitsOut, or gradLocalGateLogitsOut is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type of the 5 inputs is not within the supported range. The data types of the 5 inputs are inconsistent, or the data type of one of the 4 outputs is inconsistent with that of the corresponding input. The number of dimensions of gradMerged, globalAttn, localAttn, globalGateLogits, or localGateLogits does not meet requirements, or the shapes of inputs of the same type are inconsistent, or the shape of one of the 4 outputs is inconsistent with that of the corresponding input.
aclnnClaGateBackward
Parameters
Parameter Input/Output Description workspace Input Workspace memory address applied on the side of the Device. workspaceSize Input Workspace size applied on the side of the Device, obtained by the first-phase API aclnnClaGateBackwardGetWorkspaceSize. executor Input Op executor that contains the operator computation flow. stream Input Stream that executes the task. Return Value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
- Deterministic computation: aclnnClaGateBackward defaults to a deterministic implementation.
Example
The following sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.
Ascend 950PR&950DT products :#include <cstdint> #include <cstring> #include <iostream> #include <vector> #include "acl/acl.h" #include "aclnnop/aclnn_cla_gate_backward.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 dim : shape) { shapeSize *= dim; } 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 ACL_SUCCESS; } void Finalize(int32_t deviceId, aclrtStream stream) { (void)aclrtDestroyStream(stream); (void)aclrtResetDevice(deviceId); (void)aclFinalize(); } bool CheckHardwareSupport() { const char* socName = aclrtGetSocName(); if (socName == nullptr) { LOG_PRINT("Warning: Cannot get SOC name, skip hardware check\n"); return true; } LOG_PRINT("Current SOC: %s\n", socName); if (strstr(socName, "Ascend950") != nullptr || strstr(socName, "ascend950") != nullptr) { return true; } LOG_PRINT("Warning: ClaGateBackward only supports Ascend950, current SOC '%s' is not supported. Skip test.\n", socName); return false; } // Convert float to the uint16_t representation of bfloat16. uint16_t FloatToBf16(float f) { uint32_t bits; std::memcpy(&bits, &f, sizeof(uint32_t)); return static_cast<uint16_t>(bits >> 16); } // Convert the uint16_t bit pattern of bfloat16 back to float. float Bf16ToFloat(uint16_t bf16) { uint32_t bits = static_cast<uint32_t>(bf16) << 16; float f; std::memcpy(&f, &bits, sizeof(float)); return f; } 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); 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, aclFormat::ACL_FORMAT_ND, shape.data(), shape.size(), *deviceAddr); return ACL_SUCCESS; } 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); if (!CheckHardwareSupport()) { LOG_PRINT("\n=== Test SKIPPED (hardware not supported) ===\n"); Finalize(deviceId, stream); return ACL_SUCCESS; } // token=8, head=64, dim=256: three TND inputs [T, N, D], two gate logits [T, N]. int64_t tokenCount = 8; int64_t headNum = 64; int64_t headDim = 256; std::vector<int64_t> tndShape = {tokenCount, headNum, headDim}; std::vector<int64_t> logitsShape = {tokenCount, headNum}; void* gradMergedDeviceAddr = nullptr; void* globalAttnDeviceAddr = nullptr; void* localAttnDeviceAddr = nullptr; void* globalGateLogitsDeviceAddr = nullptr; void* localGateLogitsDeviceAddr = nullptr; void* gradGlobalAttnOutDeviceAddr = nullptr; void* gradLocalAttnOutDeviceAddr = nullptr; void* gradGlobalGateLogitsOutDeviceAddr = nullptr; void* gradLocalGateLogitsOutDeviceAddr = nullptr; aclTensor* gradMerged = nullptr; aclTensor* globalAttn = nullptr; aclTensor* localAttn = nullptr; aclTensor* globalGateLogits = nullptr; aclTensor* localGateLogits = nullptr; aclTensor* gradGlobalAttnOut = nullptr; aclTensor* gradLocalAttnOut = nullptr; aclTensor* gradGlobalGateLogitsOut = nullptr; aclTensor* gradLocalGateLogitsOut = nullptr; // Inputs are stored in BF16 (carried by uint16_t); the output host buffer is only used for readback. std::vector<uint16_t> gradMergedHostData(GetShapeSize(tndShape), FloatToBf16(0.5f)); std::vector<uint16_t> globalAttnHostData(GetShapeSize(tndShape), FloatToBf16(1.0f)); std::vector<uint16_t> localAttnHostData(GetShapeSize(tndShape), FloatToBf16(0.5f)); std::vector<uint16_t> globalGateLogitsHostData(GetShapeSize(logitsShape), FloatToBf16(0.0f)); std::vector<uint16_t> localGateLogitsHostData(GetShapeSize(logitsShape), FloatToBf16(0.0f)); std::vector<uint16_t> gradGlobalAttnOutHostData(GetShapeSize(tndShape), FloatToBf16(0.0f)); std::vector<uint16_t> gradLocalAttnOutHostData(GetShapeSize(tndShape), FloatToBf16(0.0f)); std::vector<uint16_t> gradGlobalGateLogitsOutHostData(GetShapeSize(logitsShape), FloatToBf16(0.0f)); std::vector<uint16_t> gradLocalGateLogitsOutHostData(GetShapeSize(logitsShape), FloatToBf16(0.0f)); ret = CreateAclTensor(gradMergedHostData, tndShape, &gradMergedDeviceAddr, ACL_BF16, &gradMerged); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(globalAttnHostData, tndShape, &globalAttnDeviceAddr, ACL_BF16, &globalAttn); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(localAttnHostData, tndShape, &localAttnDeviceAddr, ACL_BF16, &localAttn); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(globalGateLogitsHostData, logitsShape, &globalGateLogitsDeviceAddr, ACL_BF16, &globalGateLogits); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(localGateLogitsHostData, logitsShape, &localGateLogitsDeviceAddr, ACL_BF16, &localGateLogits); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(gradGlobalAttnOutHostData, tndShape, &gradGlobalAttnOutDeviceAddr, ACL_BF16, &gradGlobalAttnOut); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(gradLocalAttnOutHostData, tndShape, &gradLocalAttnOutDeviceAddr, ACL_BF16, &gradLocalAttnOut); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(gradGlobalGateLogitsOutHostData, logitsShape, &gradGlobalGateLogitsOutDeviceAddr, ACL_BF16, &gradGlobalGateLogitsOut); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(gradLocalGateLogitsOutHostData, logitsShape, &gradLocalGateLogitsOutDeviceAddr, ACL_BF16, &gradLocalGateLogitsOut); CHECK_RET(ret == ACL_SUCCESS, return ret); // input_attn_layout: currently only "TND" is supported. const char* inputAttnLayout = "TND"; uint64_t workspaceSize = 0; aclOpExecutor* executor = nullptr; ret = aclnnClaGateBackwardGetWorkspaceSize( gradMerged, globalAttn, localAttn, globalGateLogits, localGateLogits, inputAttnLayout, gradGlobalAttnOut, gradLocalAttnOut, gradGlobalGateLogitsOut, gradLocalGateLogitsOut, &workspaceSize, &executor); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnClaGateBackwardGetWorkspaceSize 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 = aclnnClaGateBackward(workspaceAddr, workspaceSize, executor, stream); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnClaGateBackward 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 tndSize = GetShapeSize(tndShape); auto logitsSize = GetShapeSize(logitsShape); std::vector<uint16_t> gradGlobalAttnOutData(tndSize, 0); std::vector<uint16_t> gradLocalAttnOutData(tndSize, 0); std::vector<uint16_t> gradGlobalGateLogitsOutData(logitsSize, 0); std::vector<uint16_t> gradLocalGateLogitsOutData(logitsSize, 0); ret = aclrtMemcpy(gradGlobalAttnOutData.data(), tndSize * sizeof(uint16_t), gradGlobalAttnOutDeviceAddr, tndSize * sizeof(uint16_t), ACL_MEMCPY_DEVICE_TO_HOST); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy gradGlobalAttnOut failed. ERROR: %d\n", ret); return ret); ret = aclrtMemcpy(gradLocalAttnOutData.data(), tndSize * sizeof(uint16_t), gradLocalAttnOutDeviceAddr, tndSize * sizeof(uint16_t), ACL_MEMCPY_DEVICE_TO_HOST); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy gradLocalAttnOut failed. ERROR: %d\n", ret); return ret); ret = aclrtMemcpy(gradGlobalGateLogitsOutData.data(), logitsSize * sizeof(uint16_t), gradGlobalGateLogitsOutDeviceAddr, logitsSize * sizeof(uint16_t), ACL_MEMCPY_DEVICE_TO_HOST); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy gradGlobalGateLogitsOut failed. ERROR: %d\n", ret); return ret); ret = aclrtMemcpy(gradLocalGateLogitsOutData.data(), logitsSize * sizeof(uint16_t), gradLocalGateLogitsOutDeviceAddr, logitsSize * sizeof(uint16_t), ACL_MEMCPY_DEVICE_TO_HOST); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy gradLocalGateLogitsOut failed. ERROR: %d\n", ret); return ret); for (int64_t i = 0; i < 8 && i < tndSize; i++) { LOG_PRINT("gradGlobalAttnOut[%ld] is: %f\n", i, static_cast<double>(Bf16ToFloat(gradGlobalAttnOutData[i]))); } for (int64_t i = 0; i < 8 && i < logitsSize; i++) { LOG_PRINT("gradGlobalGateLogitsOut[%ld] is: %f\n", i, static_cast<double>(Bf16ToFloat(gradGlobalGateLogitsOutData[i]))); } aclDestroyTensor(gradMerged); aclDestroyTensor(globalAttn); aclDestroyTensor(localAttn); aclDestroyTensor(globalGateLogits); aclDestroyTensor(localGateLogits); aclDestroyTensor(gradGlobalAttnOut); aclDestroyTensor(gradLocalAttnOut); aclDestroyTensor(gradGlobalGateLogitsOut); aclDestroyTensor(gradLocalGateLogitsOut); aclrtFree(gradMergedDeviceAddr); aclrtFree(globalAttnDeviceAddr); aclrtFree(localAttnDeviceAddr); aclrtFree(globalGateLogitsDeviceAddr); aclrtFree(localGateLogitsDeviceAddr); aclrtFree(gradGlobalAttnOutDeviceAddr); aclrtFree(gradLocalAttnOutDeviceAddr); aclrtFree(gradGlobalGateLogitsOutDeviceAddr); aclrtFree(gradLocalGateLogitsOutDeviceAddr); if (workspaceSize > 0) { aclrtFree(workspaceAddr); } Finalize(deviceId, stream); return ACL_SUCCESS; }