aclnnUpsampleLinear1dBackward
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 : Supported
Function
Description: Backward propagation of aclnnUpsampleLinear1d.
Formula:
- Core algorithm logic of the forward pass:
- Map each point of the target image back to the original image to obtain a coordinate with a fractional part.
- Based on this floating-point coordinate, compute the adjacent original image points before and after.
- Compute the weights of the adjacent points to the corresponding target point respectively, and multiply and accumulate them according to the weights to obtain the target point value.
- Specific computation logic:
The scaling method is divided into corner alignment and edge alignment. Corner alignment (alignCorners = true) means aligning according to the pixel center point at the top-left corner of the original image; edge alignment (alignCorners = false) means aligning according to the top-left vertex and two edges of the original image. There are differences in computing the scaling coefficient and coordinate position. Then the following formula applies:
Therefore, for a point p(x) in a certain direction of output, the point mapped back to the original image is denoted as q(x'), and the relationship is:
Notation:
Then the following formula applies:
Assumption: The output image out of forward interpolation is affected by the original image input . Then:
- Core algorithm logic of the forward pass:
Function Prototype
Each operator uses a two-phase API. Call the "aclnnUpsampleLinear1dBackwardGetWorkspaceSize" API first to obtain the workspace size required for computation and the executor that contains the operator computation process, and then call the "aclnnUpsampleLinear1dBackward" API to execute the computation.
aclnnStatus aclnnUpsampleLinear1dBackwardGetWorkspaceSize(
const aclTensor * gradOut,
const aclIntArray * outputSize,
const aclIntArray * inputSize,
bool alignCorners,
double scales,
aclTensor * out,
uint64_t * workspaceSize,
aclOpExecutor ** executor)aclnnStatus aclnnUpsampleLinear1dBackward(
void * workspace,
uint64_t workspaceSize,
aclOpExecutor * executor,
aclrtStream stream)aclnnUpsampleLinear1dBackward
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Shape Non-contiguous Tensor gradOut (aclTensor*) Input Gradient tensor for backward computation, corresponding to `gradOut` in the formula. - Empty tensors are not supported.
- When the data format is ND, the tensor is processed as NCL by default.
FLOAT32, FLOAT16, BFLOAT16 ND, NCL 3 √ outputSize (aclIntArray*) Input Spatial size of input `gradOut` on the L dimension, corresponding to `outputSize` in the formula. size is 1, and the value is greater than 0. INT64 - - - inputSize (aclIntArray*) Input Represents the spatial size of output out in the N, C, and L dimensions, corresponding to `inputSize` in the formula. size is 3, and each element is greater than 0. INT64 - - - alignCorners (bool) Input BOOL type parameter, corresponding to `alignCorners` in the formula. - If set to True, the input and output tensors are aligned by the center point of their corner pixels, preserving the values at the corner pixels;
- If set to False, the input and output tensors are aligned by the corner point of their corner pixels, and the interpolation uses edge value padding for out-of-boundary values.
- - - - scales(double) Input Multiplier of the L dimension of the output out, corresponding to `scales` in the formula. The value must not be greater than 500. - - - - out(aclTensor*) Output Output tensor of the backward computation, corresponding to `gradInput` in the formula. - Empty tensors are not supported.
- The output dimension must be 3. The data type and data format must be the same as those of input parameter `gradOut`.
FLOAT32, FLOAT16, BFLOAT16 NCL 3 √ workspaceSize(uint64_t*) Output Returns the size of the workspace to be requested on the Device side. - - - - - executor(aclOpExecutor**) Output Returns the op executor, which contains the operator computation process. - - - - - Atlas training products :The data types of input parameter
gradOutand output parameteroutonly support FLOAT32 and FLOAT16.
Atlas A2 products ,Atlas A3 products :Input parameter
gradOut: When the value of the corresponding axis of gradOut's shape is different from that of inputSize's corresponding axis, the data type only supports FLOAT32 and FLOAT16.
Return Value
aclnnStatus: return status code. For details, see aclnn Error Codes.
The first-phase API performs input parameter validation and returns an error in the following scenarios:
Error Code Error Code Description ACLNN_ERR_PARAM_NULLPTR 161001 A passed-in required input, output, or required attribute parameter is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type of gradOut is not within the supported range. The data types of gradOut and out are inconsistent. The number of dimensions of gradOut is not 3. The size of outputSize is not 1. The value of an element in outputSize is less than 1. The size of inputSize is not 3. The value of an element in inputSize is less than 1. The size of gradOut on the L dimension is different from outputSize[0]. The dimension sizes of gradOut and out on the N/C axis are not equal. The shape size of out on each dimension is different from the corresponding element value in inputSize. The value of scales does not satisfy the constraints.
aclnnUpsampleLinear1dBackward
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 aclnnUpsampleLinear1dBackwardGetWorkspaceSize. executor Input Executor of the op, which contains the operator computation flow. stream Input Stream for task execution. Return Value
aclnnStatus: return status code. For details, see aclnn Error Codes.
Constraints
- Shape constraints for parameters
gradOutandout:The value of each dimension is less than or equal to 2^20.
The N and C axes of parameter
outare the same as those ofgradOut.The memory usage must be less than 60 GB. The formula for memory usage is as follows:
Where:
- N represents the N axis of the input and output.
- C represents the C axis of the input and output.
- dtype represents the data type of the input tensor.
N * C < 2^31
- When the data format of input parameter
gradOutand output parameteroutis neither NCL nor ND, other input data formats are processed as NCL by default.
Atlas A2 products ,Atlas A3 products : The input data reduction factor of the backward API must be less than or equal to 500, that is:
Parameters inputSize, outputSize, and scales must satisfy the following constraints:
Deterministic computation:
Atlas A3 products ,Atlas A2 products ,Atlas training products : aclnnUpsampleLinear1dBackward defaults to a deterministic implementation.
Ascend 950PR&950DT products : aclnnUpsampleLinear1dBackward defaults to a non-deterministic implementation. Deterministic computation can be enabled through aclrtCtxSetSysParamOpt.
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_upsample_linear_1d_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 i : shape) {
shapeSize *= i;
}
return shapeSize;
}
int Init(int32_t deviceId, aclrtStream* stream)
{
// Boilerplate code 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 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);
// 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 manual.
// Set deviceId based on the actual device.
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);
// 2. Construct the input and output. Customize the construction based on the API.
std::vector<int64_t> selfShape = {1, 1, 3};
std::vector<int64_t> outShape = {1, 1, 6};
void* selfDeviceAddr = nullptr;
void* outDeviceAddr = nullptr;
aclTensor* self = nullptr;
aclTensor* out = nullptr;
std::vector<float> selfHostData = {1, 2, 3};
std::vector<float> outHostData = {0, 0, 0, 0, 0, 0};
// Create the self aclTensor.
ret = CreateAclTensor(selfHostData, selfShape, &selfDeviceAddr, aclDataType::ACL_FLOAT, &self);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the out aclTensor.
ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT, &out);
CHECK_RET(ret == ACL_SUCCESS, return ret);
std::vector<int64_t> outArraySize = {3};
const aclIntArray* outputSize = aclCreateIntArray(outArraySize.data(), outArraySize.size());
CHECK_RET(outputSize != nullptr, return ACL_ERROR_INTERNAL_ERROR);
std::vector<int64_t> inputArraySize = {1, 1, 6};
const aclIntArray* inputSize = aclCreateIntArray(inputArraySize.data(), inputArraySize.size());
CHECK_RET(inputSize != nullptr, return ACL_ERROR_INTERNAL_ERROR);
// 3. Call the CANN operator library API. Replace it with the actual API name.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API of aclnnUpsampleLinear1dBackward.
ret = aclnnUpsampleLinear1dBackwardGetWorkspaceSize(self, outputSize, inputSize, true, 0.5, out, &workspaceSize,
&executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnUpsampleLinear1dBackwardGetWorkspaceSize 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 aclnnUpsampleLinear1dBackward.
ret = aclnnUpsampleLinear1dBackward(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnUpsampleLinear1dBackward failed. ERROR: %d\n", ret); return ret);
// 4. (boilerplate) Wait for the task execution to complete synchronously.
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 on the device memory to the host. Modify the code based on the specific API definition.
auto size = GetShapeSize(outShape);
std::vector<float> resultData(size, 0);
ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), outDeviceAddr,
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 ret);
for (int64_t i = 0; i < size; i++) {
LOG_PRINT("result[%ld] is: %f\n", i, resultData[i]);
}
// 6. Release aclTensor and aclScalar. Modify the code based on the specific API definition.
aclDestroyTensor(self);
aclDestroyTensor(out);
aclDestroyIntArray(outputSize);
aclDestroyIntArray(inputSize);
// 7. Release device resources. Modify the code based on the specific API definition.
aclrtFree(selfDeviceAddr);
aclrtFree(outDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}