aclnnMultiScaleDeformableAttentionGrad
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:
The forward operator of MultiScaleDeformableAttention mainly traverses different sampling points of feature maps of different sizes through parameters such as sample locations, attention weights, mapped value features, the starting index positions of multi-scale features, and the spatial sizes of multi-scale feature maps (to convert sample locations from normalized values to absolute positions). The backward operator computes the gradients of the inputs based on the contribution of the forward inputs to the outputs and the initial gradients.
Formula:
Let , , , , , and be the indices of batch, query, head, feature map, sampling point, and channel, respectively. The height and width of the -th level feature map are and , i.e., ; the flattened index of the pixel in the -th level feature map along the dimension of is . The sampling point (the 0th and 1st elements in the last dimension correspond to the and directions, respectively) is mapped to the pixel coordinates and ; let , , , , , and ; the bilinear interpolation weights are , , , and ; and the feature vectors of the four neighboring points are (, with out-of-bounds neighboring points treated as 0).
The forward output is:
Based on the gradient (shape , with the last dimension laid out as ), the backward operator computes the gradients of the three inputs , , and . Denote the slice of head in as .
Expand by attention weights:
Compute , the gradient of (shape consistent with value): For each sampling point , accumulate its expanded gradient to the four neighboring positions according to the bilinear weights (accumulate over all and ; out-of-bounds neighbors are not accumulated):
Compute , the gradient of (shape consistent with attnWeight), which is the inner product of the output gradient and the sampled feature vectors:
Compute , the gradient of (shape consistent with location). The gradient of the pixel coordinates of the sampling point is obtained from the first-order partial derivatives of bilinear interpolation:
Based on and , scale the gradient of the normalized regression coordinates by the chain rule and write the result to (in the last dimension, the 0th and 1st elements correspond to the and directions respectively, consistent with location):
Function Prototype
Each operator uses a two-phase API. Call the "aclnnMultiScaleDeformableAttentionGradGetWorkspaceSize" API first to obtain the workspace size required for computation and the executor that contains the operator computation process, and then call the "aclnnMultiScaleDeformableAttentionGrad" API to perform computation.
aclnnStatus aclnnMultiScaleDeformableAttentionGradGetWorkspaceSize(
const aclTensor* value,
const aclTensor* spatialShape,
const aclTensor* levelStartIndex,
const aclTensor* location,
const aclTensor* attnWeight,
const aclTensor* gradOutput,
aclTensor* gradValue,
aclTensor* gradLocation,
aclTensor* gradAttnWeight,
uint64_t* workspaceSize,
aclOpExecutor** executor)aclnnStatus aclnnMultiScaleDeformableAttentionGrad(
void* workspace,
uint64_t workspaceSize,
aclOpExecutor* executor,
aclrtStream stream)aclnnMultiScaleDeformableAttentionGradGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor value Input Feature values of the feature map. Corresponds to `value` in the corresponding formula. The shape is (bs, num_keys, num_heads, channels), where: - bs is the batch size.
- num_keys is the size of the feature map.
- num_heads is the quantity of heads.
- channels is the dimension of the feature map.
FLOAT, FLOAT16, BFLOAT16 ND 4 √ spatialShape Input Stores the height and width of the feature map at each scale. Corresponds to `spatialShape` in the corresponding formula. Shape is (num_levels, 2), where: - num_levels is the quantity of feature maps.
- 2 indicates H and W respectively.
INT32, INT64 ND 2 √ levelStartIndex Input Start index of each feature map. Corresponds to `levelStartIndex` in the formula. Shape is (num_levels). INT32, INT64 ND 1 √ location Input Tensor of the sampling point positions, storing the coordinate position of each sampling point. Corresponds to `location` in the formula. The shape is (bs, num_queries, num_heads, num_levels, num_points, 2), where: - num_queries is the quantity of queries.
- num_points is the quantity of sampling points.
- 2 represents y and x respectively.
FLOAT, FLOAT16, BFLOAT16 ND 6 √ attnWeight Input Sampling point weight tensor. Corresponds to `attnWeight` in the formula. Shape is (bs, num_queries, num_heads, num_levels, num_points). FLOAT, FLOAT16, BFLOAT16 ND 5 √ gradOutput Input Gradient of the forward output, and also the initial gradient of the backward operator. It is `gradOutput` in the corresponding formula. The shape is (bs, num_queries, num_heads*channels). FLOAT, FLOAT16, BFLOAT16 ND 3 √ gradValue Output Gradient of the input value. It is `gradValue` in the corresponding formula. Shape consistent with value FLOAT, FLOAT16, BFLOAT16 ND 4 √ gradLocation Output Gradient of input location. `gradLocation` in the corresponding formula. Shape consistent with location FLOAT, FLOAT16, BFLOAT16 ND 6 √ gradAttnWeight Output Gradient of the input attnWeight. Corresponds to `gradAttnWeight` in the formula. Shape consistent with attnWeight FLOAT, FLOAT16, BFLOAT16 ND 5 √ workspaceSize Output Returns the size of the workspace to be allocated on the Device side. - - - - - executor 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 input or output passed in is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type of the input or output is not within the supported range. The constraints described in the Constraints section are not met.
aclnnMultiScaleDeformableAttentionGrad
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 aclnnMultiScaleDeformableAttentionGradGetWorkspaceSize. executor Input Op executor, which contains the operator compute flow. stream Input Stream for task execution. Return value:
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
Deterministic Computation
- aclnnMultiScaleDeformableAttentionGrad defaults to a non-deterministic implementation. You can call aclrtCtxSetSysParamOpt to enable deterministic computation.
The number of channels satisfies channels % 8 = 0 and channels <= 256.
The number of queries satisfies num_queries < 500000.
The number of feature maps: num_levels <= 16.
The number of heads: num_heads <= 16.
The number of sampling points: num_points <= 16.
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_multi_scale_deformable_attention_grad.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) {
// Boilerplate: resource 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 = 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 data from the host 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);
// Compute the 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/stream. For details, see the ACL API list.
// Set deviceId based on the actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = Init(deviceId, &stream);
// Process the check as required.
CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct the input and output. Customize the construction based on the API.
std::vector<int64_t> valueShape = {1, 1, 1, 8};
std::vector<int64_t> spatialShapeShape = {1, 2};
std::vector<int64_t> levelStartIndexShape = {1};
std::vector<int64_t> locationShape = {1, 32, 1, 1, 1, 2};
std::vector<int64_t> attnWeightShape = {1, 32, 1, 1, 1};
std::vector<int64_t> gradOutputShape = {1, 32, 8};
std::vector<int64_t> gradValueShape = {1, 1, 1, 8};
std::vector<int64_t> gradLocationShape = {1, 32, 1, 1, 1, 2};
std::vector<int64_t> gradAttnWeightShape = {1, 32, 1, 1, 1};
void* valueDeviceAddr = nullptr;
void* spatialShapeDeviceAddr = nullptr;
void* levelStartIndexDeviceAddr = nullptr;
void* locationDeviceAddr = nullptr;
void* attnWeightDeviceAddr = nullptr;
void* gradOutputDeviceAddr = nullptr;
void* gradValueDeviceAddr = nullptr;
void* gradLocationDeviceAddr = nullptr;
void* gradAttnWeightDeviceAddr = nullptr;
aclTensor* value = nullptr;
aclTensor* spatialShape = nullptr;
aclTensor* levelStartIndex = nullptr;
aclTensor* location = nullptr;
aclTensor* attnWeight = nullptr;
aclTensor* gradOutput = nullptr;
aclTensor* gradValue = nullptr;
aclTensor* gradLocation = nullptr;
aclTensor* gradAttnWeight = nullptr;
std::vector<float> valueHostData = {1, 1, 1, 1, 1, 1, 1, 1};
std::vector<int32_t> spatialShapeHostData = {1, 1};
std::vector<float> levelStartIndexHostData = {0};
std::vector<float> gradValueHostData = {0, 0, 0, 0, 0, 0, 0, 0};
std::vector<float> gradLocationHostData(GetShapeSize(gradLocationShape), 0);
std::vector<float> gradAttnWeightHostData(GetShapeSize(gradAttnWeightShape), 0);
std::vector<float> locationHostData(GetShapeSize(locationShape), 0);
std::vector<float> attnWeightHostData(GetShapeSize(attnWeightShape), 1);
std::vector<float> gradOutputHostData(GetShapeSize(gradOutputShape), 1);
// value aclTensor
ret = CreateAclTensor(valueHostData, valueShape, &valueDeviceAddr, aclDataType::ACL_FLOAT, &value);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the spatialShape aclTensor.
ret = CreateAclTensor(spatialShapeHostData, spatialShapeShape, &spatialShapeDeviceAddr, aclDataType::ACL_INT32, &spatialShape);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the levelStartIndex aclTensor.
ret = CreateAclTensor(levelStartIndexHostData, levelStartIndexShape, &levelStartIndexDeviceAddr, aclDataType::ACL_INT32, &levelStartIndex);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the location aclTensor.
ret = CreateAclTensor(locationHostData, locationShape, &locationDeviceAddr, aclDataType::ACL_FLOAT, &location);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the attnWeight aclTensor.
ret = CreateAclTensor(attnWeightHostData, attnWeightShape, &attnWeightDeviceAddr, aclDataType::ACL_FLOAT, &attnWeight);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// gradOutput aclTensor
ret = CreateAclTensor(gradOutputHostData, gradOutputShape, &gradOutputDeviceAddr, aclDataType::ACL_FLOAT, &gradOutput);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the gradValue aclTensor.
ret = CreateAclTensor(gradValueHostData, gradValueShape, &gradValueDeviceAddr, aclDataType::ACL_FLOAT, &gradValue);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the gradLocation aclTensor.
ret = CreateAclTensor(gradLocationHostData, gradLocationShape, &gradLocationDeviceAddr, aclDataType::ACL_FLOAT, &gradLocation);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the gradAttnWeight aclTensor.
ret = CreateAclTensor(gradAttnWeightHostData, gradAttnWeightShape, &gradAttnWeightDeviceAddr, aclDataType::ACL_FLOAT, &gradAttnWeight);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API and replace it with the specific API.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API of aclnnMultiScaleDeformableAttentionGrad.
ret = aclnnMultiScaleDeformableAttentionGradGetWorkspaceSize(value, spatialShape, levelStartIndex, location, attnWeight, gradOutput, gradValue, gradLocation, gradAttnWeight, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMultiScaleDeformableAttentionGradGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
// Allocate device memory based on the workspaceSize computed by the first-phase API.
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;);
}
// Call the second-phase API of aclnnMultiScaleDeformableAttentionGrad.
ret = aclnnMultiScaleDeformableAttentionGrad(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMultiScaleDeformableAttentionGrad failed. ERROR: %d\n", ret); return ret);
// 4. (Boilerplate) Synchronously 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, copy the results from the device memory to the host, and modify them based on the specific API definition.
auto size = GetShapeSize(gradValueShape);
std::vector<float> resultData(size, 0);
ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), gradValueDeviceAddr, size * sizeof(float),
ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return ret);
for (int64_t i = 0; i < size; i++) {
LOG_PRINT("result[%ld] is: %f\n", i, resultData[i]);
}
// 6. Release aclTensor and aclScalar, and modify them based on the specific API definition.
aclDestroyTensor(value);
aclDestroyTensor(spatialShape);
aclDestroyTensor(levelStartIndex);
aclDestroyTensor(location);
aclDestroyTensor(attnWeight);
aclDestroyTensor(gradOutput);
aclDestroyTensor(gradValue);
aclDestroyTensor(gradLocation);
aclDestroyTensor(gradAttnWeight);
// 7. Release device resources, and modify them based on the specific API definition.
aclrtFree(valueDeviceAddr);
aclrtFree(spatialShapeDeviceAddr);
aclrtFree(levelStartIndexDeviceAddr);
aclrtFree(locationDeviceAddr);
aclrtFree(attnWeightDeviceAddr);
aclrtFree(gradOutputDeviceAddr);
aclrtFree(gradValueDeviceAddr);
aclrtFree(gradLocationDeviceAddr);
aclrtFree(gradAttnWeightDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}