aclnnConvTbcBackward
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: Implements backward propagation for 1D convolution with input and output dimensions of T (time or spatial dimension), B (batch), and C (channel).
Formula: Assume the input of Conv_tbc forward propagation has the shape , and the output gradient has a shape of , the convolution kernel has a shape of , the bias has a shape of , and the padding for the input during backward propagation is . The relationship among these parameters is:
Convolution backward propagation requires computing the gradients with respect to the convolution forward input tensor (corresponding to the input parameter in the function prototype), the convolution kernel weight tensor (corresponding to the weight parameter in the function prototype), and the bias (corresponding to the bias parameter in the function prototype).
For the gradient of , (corresponding to the gradInput parameter in the function prototype):
Where denotes the batch size, denotes the number of channels, denotes the temporal or spatial dimension, denotes the loss function, and represents the gradient of the output tensor with respect to (corresponding to the self parameter in the function prototype).
For the gradient of , (corresponding to the gradWeight parameter in the function prototype):
For the gradient of , (corresponding to the gradBias parameter in the function prototype):
Function Prototype
Each operator uses a two-phase API. Call the "aclnnConvTbcBackwardGetWorkspaceSize" API first to obtain the workspace size required for the computation and the executor containing the operator computation flow, and then call the "aclnnConvTbcBackward" API to perform the computation.
aclnnStatus aclnnConvTbcBackwardGetWorkspaceSize(
const aclTensor *self,
const aclTensor *input,
const aclTensor *weight,
const aclTensor *bias,
int64_t pad,
int8_t cubeMathType,
aclTensor *gradInput,
aclTensor *gradWeight,
aclTensor *gradBias,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnConvTbcBackward(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
const aclrtStream stream)aclnnConvTbcBackwardGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor self Input Gradient of L with respect to output tensor y in the formula, representing the input of convolution backward. FLOAT, FLOAT16, BFLOAT16 ND, NCL 3 √ Input Input x in the formula, representing the input of forward convolution. FLOAT, FLOAT16, BFLOAT16 ND, NCL 3 √ weight Input w in the formula, which represents the convolution weight. FLOAT, FLOAT16, BFLOAT16 ND, NCL 3 √ bias Input b in the formula represents the convolution bias. - The shape is (Cout).
- One-dimensional and equal to the first dimension of weight. Null pointers are not allowed.
- The data type is consistent with self and weight.
FLOAT, FLOAT16, BFLOAT16 ND 1 √ pad Input Number of paddings added to the left and right of the input along the H dimension during backward propagation. - The size must be in the range [0,2147483647].
INT64 - - × cubeMathType Input Used to determine which computation logic the Cube unit uses. The supported enumeration values are as follows: - 0: KEEP_DTYPE, keeps the data type of the input for computation.
- 1: ALLOW_FP32_DOWN_PRECISION, allows down-precision computation of the input data.
- 2: USE_FP16, allows converting to the data type FLOAT16 for computation. When the input data type is FLOAT, it is converted to FLOAT16 for computation.
- 3: USE_HF32, allows converting to the data type HFLOAT32 for computation. When the input is FLOAT16, FLOAT16 is still used for computation.
- - - × gradInput Output Gradient of the input tensor x in the formula with respect to L. - Supports empty tensors.
- The data type must be consistent with that of input.
- The shape is (N,Cin,Hin).
FLOAT, FLOAT16, BFLOAT16 ND, NCL - × gradWeight Output Gradient of L with respect to the convolution kernel weight tensor w. - Supports empty tensors.
- The data type must be consistent with that of weight.
- The shape is (Cout,Cin,K).
FLOAT, FLOAT16, BFLOAT16, HIFLOAT8, FLOAT8_E4M3FN ND, NCL - × gradBias Output Gradient of L with respect to bias b. - Supports empty tensor.
- The data type must be consistent with that of bias.
- The shape is (Cout).
FLOAT, FLOAT16, BFLOAT16 ND - × workspaceSize Output Returns the workspace size to be applied on the Device side. - - - - × executor Output Op executor that contains the operator computation flow. - - - - × 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 pointer-type input parameter is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data types and data formats of self, input, weight, bias, gradInput, gradWeight, and gradBias are not within the supported range. The data types of self, input, weight, and bias are inconsistent. The shapes of gradInput, gradWeight, and gradBias do not match the infershape result. The shapes of gradInput, gradWeight, and gradBias contain values less than 0. The dim of self, input, or weight is not 3. The dim of bias is not 1. The third dimension of input is not equal to the second dimension of weight. The value of bias is not equal to the third dimension of weight. The pad value does not meet the requirement. ACLNN_ERR_INNER_NULLPTR 561103 An internal API verification error, usually caused by input data or attribute specifications that are not within the supported range.
aclnnConvTbcBackward
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address applied on the Device side. workspaceSize Input Workspace size applied on the Device side, obtained by the first-phase API aclnnConvTbcBackwardGetWorkspaceSize. executor Input Op executor that contains the operator computation flow. stream Input Specifies the stream for task execution. Return value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
deterministic computation
Atlas A3 products ,Atlas A2 products ,Atlas 200I/500 A2 inference products , andAtlas training products : aclnnConvTbcBackward defaults to a non-deterministic implementation. Deterministic computation can be enabled through aclrtCtxSetSysParamOpt.
Ascend 950PR&950DT products : aclnnConvTbcBackward defaults to a deterministic implementation.
| Constraint Type | |||
|---|---|---|---|
| self constraint |
|
Supports the N, C, and L dimensions greater than or equal to 0 (the scenario where the dimension equals 0 is supported only when the N, C, or L dimension of self equals 0). | |
| input constraint | input supports the N and C dimensions greater than or equal to 0, and the L dimension greater than or equal to 0 (the scenario where the dimension equals 0 is supported only when the L dimension of gradOutput is also equal to 0). | The data type of input does not support HIFLOAT8. Supports the N, C, and L dimensions greater than or equal to 0. | The input data type does not support BFLOAT16 or HIFLOAT8. Values greater than or equal to 0 are supported for the N, C, and L dimensions. |
| weight constraints |
|
The weight data type does not support HIFLOAT8. Values greater than or equal to 0 are supported for the N, C, and L dimensions. | The weight data type does not support BFLOAT16 or HIFLOAT8. Values greater than or equal to 0 are supported for the N, C, and L dimensions. |
| dtype constraints | HIFLOAT8 and FLOAT8_E4M3FN are supported only in the gradWeight parameter, and are not supported in other parameters. | HIFLOAT8 and FLOAT8_E4M3FN are not supported. | BFLOAT16, HIFLOAT8, and FLOAT8_E4M3FN are not supported. |
| cubeMathType description |
|
|
|
| Other constraints |
|
- | - |
Example
The following sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.
#include <iostream>
#include <memory>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_convolution_backward.h"
#define CHECK_RET(cond, return_expr) \
do { \
if (!(cond)) { \
return_expr; \
} \
} while (0)
#define CHECK_FREE_RET(cond, return_expr) \
do { \
if (!(cond)) { \
Finalize(deviceId, stream); \
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 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);
// 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 the aclCreateTensor API to create an aclTensor.
if (shape.size() == 4) {
*tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_NCHW,
shape.data(), shape.size(), *deviceAddr);
} else {
*tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
shape.data(), shape.size(), *deviceAddr);
}
return 0;
}
void Finalize(int32_t deviceId, aclrtStream stream)
{
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
}
int aclnnConvTbcBackwardTest(int32_t deviceId, aclrtStream &stream)
{
// 1. Initialization
auto ret = Init(deviceId, &stream);
CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct the input and output. Customize the construction according to the API.
std::vector<int64_t> selfShape = {5, 1, 2};
std::vector<int64_t> inputShape = {5, 1, 2};
std::vector<int64_t> weightShape = {1, 2, 2};
std::vector<int64_t> biasShape = {2};
const int64_t pad = 0;
int8_t cubeMathType = 1;
std::vector<int64_t> gradInputShape = {5, 1, 2};
std::vector<int64_t> gradWeightShape = {1, 2, 2};
std::vector<int64_t> gradBiasShape = {2};
// Create the self aclTensor.
std::vector<float> selfData(GetShapeSize(selfShape), 1);
aclTensor *self = nullptr;
void *selfdeviceAddr = nullptr;
ret = CreateAclTensor(selfData, selfShape, &selfdeviceAddr, aclDataType::ACL_FLOAT, &self);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> selfTensorPtr(self, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void *)> selfdeviceAddrPtr(selfdeviceAddr, aclrtFree);
CHECK_FREE_RET(ret == ACL_SUCCESS, return ret);
// Create the input aclTensor.
std::vector<float> inputData(GetShapeSize(inputShape), 1);
aclTensor *input = nullptr;
void *inputdeviceAddr = nullptr;
ret = CreateAclTensor(inputData, inputShape, &inputdeviceAddr, aclDataType::ACL_FLOAT, &input);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> inputTensorPtr(input, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void *)> inputDeviceAddrPtr(inputdeviceAddr, aclrtFree);
CHECK_FREE_RET(ret == ACL_SUCCESS, return ret);
// Create the weight aclTensor.
std::vector<float> weightData(GetShapeSize(weightShape), 1);
aclTensor *weight = nullptr;
void *weightDeviceAddr = nullptr;
ret = CreateAclTensor(weightData, weightShape, &weightDeviceAddr, aclDataType::ACL_FLOAT, &weight);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> weightTensorPtr(weight, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void *)> weightDeviceAddrPtr(weightDeviceAddr, aclrtFree);
CHECK_FREE_RET(ret == ACL_SUCCESS, return ret);
// Create the bias aclTensor.
std::vector<float> biasData(GetShapeSize(biasShape), 1);
aclTensor *bias = nullptr;
void *biasDeviceAddr = nullptr;
ret = CreateAclTensor(biasData, biasShape, &biasDeviceAddr, aclDataType::ACL_FLOAT, &bias);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> biasTensorPtr(bias, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void *)> biasDeviceAddrPtr(biasDeviceAddr, aclrtFree);
CHECK_FREE_RET(ret == ACL_SUCCESS, return ret);
// Create the gradInput aclTensor.
std::vector<float> gradInputData(GetShapeSize(inputShape), 1);
aclTensor *gradInput = nullptr;
void *gradInputDeviceAddr = nullptr;
ret = CreateAclTensor(gradInputData, inputShape, &gradInputDeviceAddr, aclDataType::ACL_FLOAT, &gradInput);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> gradInputTensorPtr(gradInput, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void *)> gradInputDeviceAddrPtr(gradInputDeviceAddr, aclrtFree);
CHECK_FREE_RET(ret == ACL_SUCCESS, return ret);
// Create the gradWeight aclTensor.
std::vector<float> gradWeightData(GetShapeSize(weightShape), 1);
aclTensor *gradWeight = nullptr;
void *gradWeightDeviceAddr = nullptr;
ret = CreateAclTensor(gradWeightData, weightShape, &gradWeightDeviceAddr, aclDataType::ACL_FLOAT, &gradWeight);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> gradWeightTensorPtr(gradWeight, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void *)> gradWeightDeviceAddrPtr(gradWeightDeviceAddr, aclrtFree);
CHECK_FREE_RET(ret == ACL_SUCCESS, return ret);
// Create the gradBias aclTensor.
std::vector<float> gradBiasData(GetShapeSize(gradBiasShape), 1);
aclTensor *gradBias = nullptr;
void *gradBiasDeviceAddr = nullptr;
ret = CreateAclTensor(gradBiasData, gradBiasShape, &gradBiasDeviceAddr, aclDataType::ACL_FLOAT, &gradBias);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> gradBiasTensorPtr(gradBias, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void *)> gradBiasDeviceAddrPtr(gradBiasDeviceAddr, aclrtFree);
CHECK_FREE_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API. Replace the API name with the actual one.
uint64_t workspaceSize = 0;
aclOpExecutor *executor;
// Call the first-phase API of aclnnConvTbcBackward
ret = aclnnConvTbcBackwardGetWorkspaceSize(self, input, weight, bias, pad, cubeMathType, gradInput, gradWeight,
gradBias, &workspaceSize, &executor);
CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnConvTbcBackwardGetWorkspaceSize failed. ERROR: %d\n", ret);
return ret);
// Allocate device memory based on the workspaceSize calculated by the first-phase API
void *workspaceAddr = nullptr;
std::unique_ptr<void, aclError (*)(void *)> workspaceAddrPtr(nullptr, aclrtFree);
if (workspaceSize > 0) {
ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
workspaceAddrPtr.reset(workspaceAddr);
}
// Call the second-phase API of aclnnConvTbcBackward
ret = aclnnConvTbcBackward(workspaceAddr, workspaceSize, executor, stream);
CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnConvTbcBackward failed. ERROR: %d\n", ret); return ret);
// 4. (boilerplate) Synchronize and wait for the task to complete.
ret = aclrtSynchronizeStream(stream);
CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
// 5. Obtain the output values and copy the results from the device side to the host side. Modify the code according to the specific API definition.
auto size = GetShapeSize(gradInputShape);
std::vector<float> gradInputResult(size, 0);
ret = aclrtMemcpy(gradInputResult.data(), gradInputResult.size() * sizeof(gradInputResult[0]), gradInputDeviceAddr,
size * sizeof(gradInputResult[0]), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_FREE_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("gradInputResult[%ld] is: %f\n", i, gradInputResult[i]);
}
size = GetShapeSize(gradWeightShape);
std::vector<float> gradWeightResult(size, 0);
ret = aclrtMemcpy(gradWeightResult.data(), gradWeightResult.size() * sizeof(gradWeightResult[0]), gradWeightDeviceAddr,
size * sizeof(gradWeightResult[0]), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_FREE_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("gradWeightResult[%ld] is: %f\n", i, gradWeightResult[i]);
}
size = GetShapeSize(gradBiasShape);
std::vector<float> gradBiasResult(size, 0);
ret = aclrtMemcpy(gradBiasResult.data(), gradBiasResult.size() * sizeof(gradBiasResult[0]), gradBiasDeviceAddr,
size * sizeof(gradBiasResult[0]), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_FREE_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("gradBiasResult[%ld] is: %f\n", i, gradBiasResult[i]);
}
return ACL_SUCCESS;
}
int main()
{
// 1. (boilerplate) Initialize the device/stream.
// Set deviceId based on the actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = aclnnConvTbcBackwardTest(deviceId, stream);
CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnConvTbcBackwardTest failed. ERROR: %d\n", ret); return ret);
Finalize(deviceId, stream);
return 0;
}