aclnnStridedSliceGrad

📄 View Source Code

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: The backward operator of StridedSlice, which maps the slice gradient tensor dy back to the corresponding positions of the original tensor shape and fills the positions not covered by the slice with zeros.

Function Prototype

Each operator uses a two-phase API. First call the aclnnStridedSliceGradGetWorkspaceSize API to obtain the workspace size required for computation and the executor that includes computation flows of the operator, and then call the aclnnStridedSliceGrad API to execute the computation.

aclnnStatus aclnnStridedSliceGradGetWorkspaceSize(
    const aclIntArray  *shape,
    const aclIntArray  *begin,
    const aclIntArray  *end,
    const aclIntArray  *strides,
    const aclTensor    *dy,
    int64_t             beginMask,
    int64_t             endMask,
    int64_t             ellipsisMask,
    int64_t             newAxisMask,
    int64_t             shrinkAxisMask,
    const aclTensor    *out,
    uint64_t           *workspaceSize,
    aclOpExecutor     **executor)
aclnnStatus aclnnStridedSliceGrad(
    void           *workspace,
    uint64_t        workspaceSize,
    aclOpExecutor  *executor,
    aclrtStream     stream)

aclnnStridedSliceGradGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    shape (aclIntArray*) Input Shape of the original input tensor, that is, the shape of output out.
    • The length and begin/end/strides are the same.
    • Each element value ≥ 0 (0 indicates an empty tensor).
    • Rank no greater than 8 after removing dimensions of length 1.
    INT64 - - -
    begin (aclIntArray*) Input Slice start index, the begin parameter of the corresponding forward StridedSlice.
    • The length is the same as that of shape.
    • Negative indexing is supported (counting from the end).
    INT64 - - -
    end (aclIntArray*) Input Slice end index (exclusive), corresponding to the end parameter of forward StridedSlice.
    • The length is the same as that of shape.
    • Negative indexing is supported.
    INT64 - - -
    strides (aclIntArray*) Input Slice stride, corresponding to the strides parameter of forward StridedSlice.
    • The length is the same as shape.
    • Element values cannot be 0; negative values (reverse slicing) are supported.
    • For dimensions whose bit is set in shrinkAxisMask, the stride must be 1.
    INT64 - - -
    dy (aclTensor*) Input Output gradient tensor of the slice operation.
    • dy.shape must be equal to the output shape of the corresponding forward StridedSlice operation on the original shape.
    FLOAT16, BFLOAT16, FLOAT, DOUBLE, INT8, INT16, INT32, INT64, UINT8, UINT16, UINT32, UINT64, COMPLEX32, COMPLEX64 ND 0-8 √
    beginMask (int64_t) Input Bitmask. When the i-th bit is 1, begin of the dimension is ignored, and slicing starts from the first element of the dimension. - INT64 - - -
    endMask (int64_t) Input Bitmask. When the i-th bit is 1, end of the dimension is ignored, and the slice extends to the end of the dimension. - INT64 - - -
    ellipsisMask(int64_t) Input Bitmask that marks the ellipsis dimension. Dimensions marked by the bitmask are fully retained (equivalent to ":").
    • At most 1 bit is set to 1.
    INT64 - - -
    newAxisMask (int64_t) Input Bitmask. When the i-th bit is 1, a new dimension (length 1) is inserted at the corresponding position. - INT64 - - -
    shrinkAxisMask (int64_t) Input Bitmask. If bit i is 1, the corresponding dimension is shrunk in the output (a single element is taken for that dimension). The strides of the set dimensions must be 1. - INT64 - - -
    out (aclTensor*) Output Backward propagation result tensor, with the same shape as the input of the original forward operator (that is, the shape specified by the shape parameter).
    • The data type is the same as that of dy.
    • Positions not covered by the slice are filled with 0.
    Same as dy ND - -
    workspaceSize (uint64_t*) Output Returns the size of the workspace to be allocated on the Device side. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which includes computation flow of the operator. - - - - -
  • Return value:

    aclnnStatus: return status code, see aclnn return code.

    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 dy or out is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of dy or out is not within the supported range.

aclnnStridedSliceGrad

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the Device side.
    workspaceSize Input Workspace size allocated on the Device side, obtained by calling the first-phase API aclnnStridedSliceGradGetWorkspaceSize.
    executor Input op executor, includes computation flow of the operator.
    stream Input Stream for executing tasks.
  • Return value:

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

Constraints

  • Deterministic computation:
    • aclnnStridedSliceGrad defaults to a deterministic implementation.

Example

The sample code is as follows and for reference only. For the specific compilation and execution process, see Compile and Run Samples.

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_strided_slice_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 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 = 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);
    // Allocate memory on the device side.
    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);
    // Copy host data to the device.
    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];
    }
    // Create 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, see the AscendCL external API list.
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = Init(deviceId, &stream);
    CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

    // 2. Construct the input and output.
    //
    // Use case description:
    //   The forward StridedSlice slices [0:2, 1:3, 2:4] (stride is 1 for all dimensions) from a tensor with shape=[3,4,5],
    //   the forward output shape = [2, 2, 2].
    //   This backward operator scatters the gradients in dy (shape=[2,2,2]) back to output (shape=[3,4,5]),
    //   Positions not covered by the slice are filled with 0.
    //
    // Parameters:
    //   shape   = [3, 4, 5]   - shape of the original forward input, i.e. the shape of output
    //   begin   = [0, 1, 2]
    //   end     = [2, 3, 4]
    //   strides = [1, 1, 1]
    // mask all 0s

    std::vector<int64_t> shapeData = {3, 4, 5};
    std::vector<int64_t> beginData = {0, 1, 2};
    std::vector<int64_t> endData = {2, 3, 4};
    std::vector<int64_t> stridesData = {1, 1, 1};

    std::vector<int64_t> dyShape = {2, 2, 2};
    std::vector<int64_t> outputShape = {3, 4, 5};

    // dy gradient data (float, all 1.0)
    std::vector<float> dyHostData(GetShapeSize(dyShape), 1.0f);
    // output is initialized to 0
    std::vector<float> outputHostData(GetShapeSize(outputShape), 0.0f);

    void* dyDeviceAddr = nullptr;
    void* outputDeviceAddr = nullptr;
    aclTensor* dy = nullptr;
    aclTensor* output = nullptr;

    // Create the dy aclTensor.
    ret = CreateAclTensor(dyHostData, dyShape, &dyDeviceAddr, aclDataType::ACL_FLOAT, &dy);
    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);

    // Create value-dependent inputs (aclIntArray).
    aclIntArray* shape = aclCreateIntArray(shapeData.data(), shapeData.size());
    aclIntArray* begin = aclCreateIntArray(beginData.data(), beginData.size());
    aclIntArray* end = aclCreateIntArray(endData.data(), endData.size());
    aclIntArray* strides = aclCreateIntArray(stridesData.data(), stridesData.size());
    CHECK_RET(shape != nullptr && begin != nullptr && end != nullptr && strides != nullptr,
              LOG_PRINT("aclCreateIntArray failed.\n");
              return -1);

    // mask parameter (all 0s indicates that no special slicing semantics is enabled)
    int64_t beginMask = 0;
    int64_t endMask = 0;
    int64_t ellipsisMask = 0;
    int64_t newAxisMask = 0;
    int64_t shrinkAxisMask = 0;

    // 3. Call the CANN operator library API (two-phase API).
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor = nullptr;

    // Call the first-phase API of aclnnStridedSliceGrad.
    ret = aclnnStridedSliceGradGetWorkspaceSize(shape, begin, end, strides, dy, beginMask, endMask, ellipsisMask,
                                                newAxisMask, shrinkAxisMask, output, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnStridedSliceGradGetWorkspaceSize 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 aclnnStridedSliceGrad.
    ret = aclnnStridedSliceGrad(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnStridedSliceGrad failed. ERROR: %d\n", ret); return ret);

    // 4. (Boilerplate) Wait for task execution to complete synchronously.
    ret = aclrtSynchronizeStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);

    // 5. Copy the result from the device side back to the host side and print it.
    auto size = GetShapeSize(outputShape);
    std::vector<float> resultData(size, 0);
    ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(float), 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. Destroy aclIntArray and aclTensor.
    aclDestroyIntArray(shape);
    aclDestroyIntArray(begin);
    aclDestroyIntArray(end);
    aclDestroyIntArray(strides);
    aclDestroyTensor(dy);
    aclDestroyTensor(output);

    // 7. Release Device resources.
    aclrtFree(dyDeviceAddr);
    aclrtFree(outputDeviceAddr);
    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();

    return 0;
}