aclnnMultiScaleDeformableAttnFunction

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: Supported
  • Atlas training products: Not supported

Function

  • Description:

    Different sampling points in feature maps of different sizes are traversed based on parameters such as the sampling location, attention weights, mapped value features, start index positions of the multi-scale features, and the spatial sizes of the multi-scale feature maps (to convert the sampling locations from normalized values to absolute positions).

  • Formula:

    Let b∈[0,bs)b \in [0, bs), q∈[0,num_queries)q \in [0, num\_queries), h∈[0,num_heads)h \in [0, num\_heads), ℓ∈[0,num_levels)\ell \in [0, num\_levels), p∈[0,num_points)p \in [0, num\_points), and c∈[0,channels)c \in [0, channels) be the indices of the batch, query, head, feature map, sampling point, and channel, respectively. The height and width of the ℓ\ell-th layer feature map are HℓH_\ell and WℓW_\ell, that is, spatialShape[ℓ]=(Hℓ,Wℓ)\mathrm{spatialShape}[\ell] = (H_\ell, W_\ell); the num_keysnum\_keys dimension of value\mathrm{value} flattens and concatenates the pixels of all layer feature maps layer by layer (num_keys=∑ℓ=0num_levels−1HℓWℓnum\_keys = \sum_{\ell=0}^{num\_levels-1} H_\ell W_\ell), and the start index of the ℓ\ell-th layer is levelStartIndex[ℓ]\mathrm{levelStartIndex}[\ell].

    1. Map the normalized coordinates of the sampling point location[b,q,h,ℓ,p]=(u,v)∈[0,1]2\mathrm{location}[b, q, h, \ell, p] = (u, v) \in [0,1]^2 (where uu and vv are the 0th and 1st elements of the last dimension, corresponding to the xx and yy directions, respectively) to the pixel coordinate system of the ℓ\ell-th layer feature map:

      x=u⋅Wℓ−0.5,y=v⋅Hℓ−0.5x = u \cdot W_\ell - 0.5, \qquad y = v \cdot H_\ell - 0.5
    2. Determine which four integer grid points the sampling point falls between:

      x0=⌊x⌋,x1=x0+1,y0=⌊y⌋,y1=y0+1x_0 = \lfloor x \rfloor,\quad x_1 = x_0 + 1,\qquad y_0 = \lfloor y \rfloor,\quad y_1 = y_0 + 1
    3. Calculate the offset of the sampling point relative to the top-left grid point for interpolation weights:

      αx=x−x0,αy=y−y0\alpha_x = x - x_0, \qquad \alpha_y = y - y_0
    4. Calculate the bilinear interpolation weights. The sum of the four neighboring points is 1:

      w00=(1−αy)(1−αx),w10=(1−αy)αx,w01=αy(1−αx),w11=αyαx\begin{aligned} w_{00} &= (1-\alpha_y)(1-\alpha_x), \\ w_{10} &= (1-\alpha_y)\alpha_x, \\ w_{01} &= \alpha_y(1-\alpha_x), \\ w_{11} &= \alpha_y\alpha_x \end{aligned}
    5. After flattening, the index of the pixel (y,x)(y, x) on the ℓ\ell layer feature map in the num_keysnum\_keys dimension of value\mathrm{value} is:

      kℓ(y,x)=levelStartIndex[ℓ]+y⋅Wℓ+xk_\ell(y, x) = \mathrm{levelStartIndex}[\ell] + y \cdot W_\ell + x
    6. Perform bilinear sampling on value\mathrm{value} to obtain the feature vector corresponding to the sampling point (length: channelschannels):

      bilinear⁡(value; b,h,ℓ,x,y)=w00⋅value[b,  kℓ(y0,x0),  h,  :]+w10⋅value[b,  kℓ(y0,x1),  h,  :]+w01⋅value[b,  kℓ(y1,x0),  h,  :]+w11⋅value[b,  kℓ(y1,x1),  h,  :]\begin{aligned} \operatorname{bilinear}(\mathrm{value};\,b,h,\ell,x,y) ={}& w_{00} \cdot \mathrm{value}[b,\; k_\ell(y_0, x_0),\; h,\; :] \\ &+ w_{10} \cdot \mathrm{value}[b,\; k_\ell(y_0, x_1),\; h,\; :] \\ &+ w_{01} \cdot \mathrm{value}[b,\; k_\ell(y_1, x_0),\; h,\; :] \\ &+ w_{11} \cdot \mathrm{value}[b,\; k_\ell(y_1, x_1),\; h,\; :] \end{aligned}
    7. The bilinear sampling results of all layers and all sampling points are weighted and summed using attnWeight\mathrm{attnWeight} to obtain the final output output\mathrm{output} (shape: (bs,num_queries,num_heads×channels)(bs, num\_queries, num\_heads \times channels), with the last dimension arranged as h×channels+ch \times channels + c):

      output[b,  q,  h×channels+c]=∑ℓ=0num_levels−1∑p=0num_points−1attnWeight[b,q,h,ℓ,p]⋅bilinear⁡ ⁣(value; b,h,ℓ,  xb,q,h,ℓ,p, yb,q,h,ℓ,p)[c]\mathrm{output}[b,\; q,\; h \times channels + c] = \sum_{\ell=0}^{num\_levels-1} \sum_{p=0}^{num\_points-1} \mathrm{attnWeight}[b, q, h, \ell, p] \cdot \operatorname{bilinear}\!\left(\mathrm{value};\, b, h, \ell,\; x_{b,q,h,\ell,p},\, y_{b,q,h,\ell,p}\right)[c]

      Where xb,q,h,ℓ,px_{b,q,h,\ell,p} and yb,q,h,ℓ,py_{b,q,h,\ell,p} are the pixel coordinates obtained by mapping the sampling point location[b,q,h,ℓ,p]\mathrm{location}[b, q, h, \ell, p] through the preceding coordinate mapping.

Function Prototype

Each operator uses a two-phase API. Call the "aclnnMultiScaleDeformableAttnFunctionGetWorkspaceSize" API first to obtain the workspace size required for the computation and the executor containing the operator computation process. Then call the "aclnnMultiScaleDeformableAttnFunction" API to perform the computation.

aclnnStatus aclnnMultiScaleDeformableAttnFunctionGetWorkspaceSize(
    const aclTensor* value,
    const aclTensor* spatialShape,
    const aclTensor* levelStartIndex,
    const aclTensor* location,
    const aclTensor* attnWeight,
    aclTensor*       output,
    uint64_t*        workspaceSize,
    aclOpExecutor**  executor)
aclnnStatus aclnnMultiScaleDeformableAttnFunction(
    void*          workspace,
    uint64_t       workspaceSize,
    aclOpExecutor* executor,
    aclrtStream    stream)

aclnnMultiScaleDeformableAttnFunctionGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    value (aclTensor*) Input Feature values of the feature map. This corresponds to `value` in the 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, and channels is the dimension of the feature map. FLOAT, FLOAT16, BFLOAT16 ND 4 √
    spatialShape (aclTensor*) Input Stores the height and width of each scale's feature map. This corresponds to `spatialShape` in the formula. The shape is (num_levels, 2). num_levels is the quantity of feature maps, and 2 indicates H and W, respectively. INT32, INT64 ND 2 √
    levelStartIndex (aclTensor*) Input Start index of each feature map. Corresponds to `levelStartIndex` in the formula. The shape is (num_levels). INT32, INT64 ND 1 √
    location (aclTensor*) Input Sampling point location tensor, which stores the coordinates of each sampling point. It corresponds to `location` in the formula.
      The data type is the same as that of value.The shape is (bs, num_queries, num_heads, num_levels, num_points, 2). num_queries denotes the quantity of queries, num_points denotes the quantity of sampling points, and 2 denotes y and x respectively.
    FLOAT, FLOAT16, BFLOAT16 ND 6 √
    attnWeight (aclTensor*) Input Weight tensor of sampling points. Corresponds to `attnWeight` in the formula.
      Data type must be the same as that of value.Shape is (bs, num_queries, num_heads, num_levels, num_points).
    FLOAT, FLOAT16, BFLOAT16 ND 5 √
    output (aclTensor*) Output Computation output of the operator. Corresponds to `output` in the corresponding formula.
      data type is the same as that of value.shape is (bs, num_queries, num_heads * channels).
    FLOAT, FLOAT16, BFLOAT16 ND 3 √
    workspaceSize(uint64_t*) Output Returns the workspace size to be requested on the Device side. - - - - -
    executor(aclOpExecutor**) Output Returns an op executor containing the operator computation flow. - - - - -
    • Atlas inference products: BFLOAT16 data type is not supported.
  • Return value:

    aclnnStatus: Returns the status code. For details, see aclnnReturnCode.

    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 is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of the input or output is out of the supported range.
    The data types of the input and output are inconsistent.
    The shape of value is not 4-dimensional.
    The shape of spatialShape is not 2-dimensional.
    The shape of levelStartIndex is not 1-dimensional.
    The shape of location is not 6-dimensional.
    The shape of attnWeight is not 5-dimensional.
    The last axis of spatialShape is not 2.
    The last axis of location is not 2.
    The API constraints are not met.

aclnnMultiScaleDeformableAttnFunction

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the Device.
    workspaceSize Input Size of the workspace allocated on the Device, obtained by calling the first-phase API aclnnMultiScaleDeformableAttnFunctionGetWorkspaceSize.
    executor Input Op executor that contains the operator computation flow.
    stream Input Stream for executing tasks.
  • Return value:

    aclnnStatus: return status code. For details, see aclnn Return Codes.

Constraints

  • Deterministic computation:

    • Atlas A2 products, Atlas A3 products, Atlas inference products: aclnnMultiScaleDeformableAttnFunction defaults to a deterministic implementation.
    • Ascend 950PR&950DT products: aclnnMultiScaleDeformableAttnFunction defaults to a non-deterministic implementation. Deterministic computation can be enabled through aclrtCtxSetSysParamOpt.
  • Atlas inference products:
    • channels % 32 = 0, and channels <= 256.
    • Query count: 32 <= num_queries < 500000.
    • The number of feature maps: num_levels <= 16.
    • Head count: num_heads = [2, 4, 8].
    • Sampling point count: num_points = [4, 8].
  • Atlas A2 products, Atlas A3 products, Ascend 950PR&950DT products:
    • Channel count: channels%8 = 0, and channels <= 256.
    • The number of queries: 32 <= 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_attn_function.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 for 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 device memory.
    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 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 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 the aclCreateTensor API 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) Device/stream initialization. For details, see the ACL external API list.
    // Set deviceId based on the actual device.
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = Init(deviceId, &stream);
    // Handle the check as needed.
    CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
   // 2. Construct the inputs and outputs. Customize the construction based on the API interface.
    std::vector<int64_t> valueShape = {1, 1, 2, 32};
    std::vector<int64_t> spatialShapeShape = {1, 2};
    std::vector<int64_t> levelStartIndexShape = {1};
    std::vector<int64_t> locationShape = {1, 32, 2, 1, 4, 2};
    std::vector<int64_t> attnWeightShape = {1, 32, 2, 1, 4};
    std::vector<int64_t> outputShape = {1, 32, 64};
    void* valueDeviceAddr = nullptr;
    void* spatialShapeDeviceAddr = nullptr;
    void* levelStartIndexDeviceAddr = nullptr;
    void* locationDeviceAddr = nullptr;
    void* attnWeightDeviceAddr = nullptr;
    void* outputDeviceAddr = nullptr;
    aclTensor* value = nullptr;
    aclTensor* spatialShape = nullptr;
    aclTensor* levelStartIndex = nullptr;
    aclTensor* location = nullptr;
    aclTensor* attnWeight = nullptr;
    aclTensor* output = nullptr;
    std::vector<float> valueHostData(static_cast<float>(GetShapeSize(valueShape)), 0);
    std::vector<int32_t> spatialShapeHostData = {1, 1};
    std::vector<float> levelStartIndexHostData = {0};
    std::vector<float> locationHostData(static_cast<float>(GetShapeSize(locationShape)), 0);
    std::vector<float> attnWeightHostData(static_cast<float>(GetShapeSize(attnWeightShape)), 0);
    std::vector<float> outputHostData(static_cast<float>(GetShapeSize(outputShape)), 0);
    // 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);
    // Create the output aclTensor.
    ret = CreateAclTensor(outputHostData, outputShape, &outputDeviceAddr, aclDataType::ACL_FLOAT, &output);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // 3. Call the CANN operator library API. Replace it with the specific API.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API of aclnnMultiScaleDeformableAttnFunction.
    ret = aclnnMultiScaleDeformableAttnFunctionGetWorkspaceSize(value, spatialShape, levelStartIndex, location, attnWeight, output,
                                                                &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMultiScaleDeformableAttnFunctionGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
    // Allocate device memory based on the workspaceSize calculated 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 aclnnMultiScaleDeformableAttnFunction.
    ret = aclnnMultiScaleDeformableAttnFunction(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMultiScaleDeformableAttnFunction 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 value, and copy the result from the device memory to the host memory. Modify the code based on the specific API definition.
    auto size = GetShapeSize(outputShape);
    std::vector<float> resultData(size, 0);
    ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), outputDeviceAddr, 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 the aclTensor and aclScalar. Modify the code based on the specific API definition.
    aclDestroyTensor(value);
    aclDestroyTensor(spatialShape);
    aclDestroyTensor(levelStartIndex);
    aclDestroyTensor(location);
    aclDestroyTensor(attnWeight);
    aclDestroyTensor(output);

    // 7. Release the device resources. Modify the code based on the specific API definition.
    aclrtFree(valueDeviceAddr);
    aclrtFree(spatialShapeDeviceAddr);
    aclrtFree(levelStartIndexDeviceAddr);
    aclrtFree(locationDeviceAddr);
    aclrtFree(attnWeightDeviceAddr);
    aclrtFree(outputDeviceAddr);
    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return 0;
}