aclnnGRUBackward
Applicable Products
Ascend 950PR&950DT products : Not supported
Atlas A3 products : Supported
Atlas A2 products : Supported
Atlas 200I/500 A2 inference products : Not supported
: Not supportedAtlas inference products
Atlas training products : Not supported
Function
- Description: backward propagation of GRU. Computes the gradients of the forward input input, weight params, and initial state hx.
- Forward formula:
- Reset gate
- Update gate
- Candidate hidden state
- Hidden state
- Backward computation formula:
- ( is the gradient from the upper layer, and is the gradient passed back at time step t+1)
Function Prototype
Each operator is divided into a two-phase API. Call the "aclnnGRUBackwardGetWorkspaceSize" API first to obtain the workspace size required for the computation and the executor that contains the operator computation process, and then call the "aclnnGRUBackward" API to perform the computation.
aclnnStatus aclnnGRUBackwardGetWorkspaceSize(
const aclTensor *input,
const aclTensorList *params,
const aclTensor *hx,
const aclTensor *dy,
const aclTensor *dh,
const aclTensorList *r,
const aclTensorList *z,
const aclTensorList *n,
const aclTensorList *h_n,
const aclTensorList *h,
const aclTensor *batchSizesOptional,
bool hasBias,
int64_t numLayers,
bool bidirection,
bool batchFirst,
aclTensor *dxOut,
aclTensor *dhPrevOut,
aclTensorList *dparamsOut,
uint64_t *workspaceSize,
aclOpExecutor **executor) aclnnStatus aclnnGRUBackward(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnGRUBackwardGetWorkspaceSize
- Parameters:
| Parameter | Input/Output | Description | Instruction | Data Type | Data Format | Dimension (shape) | Non-contiguous Tensor |
|---|---|---|---|---|---|---|---|
| Input | Input | Input sequence of the GRU, corresponding to x in the formula. |
|
FLOAT32, FLOAT16 | ND |
|
√ |
| params | Input | List of weight and bias tensors for each GRU layer, corresponding to w and b in the formula. |
|
FLOAT32, FLOAT16 | ND | weight_ih: [3*hidden_size, cur_input_size] weight_hh: [3*hidden_size, hidden_size] bias_ih: [3*hidden_size] bias_hh: [3*hidden_size] Empty tensors are not supported |
√ |
| hx | Input | Initial hidden state of each GRU layer. Corresponds to h(t-1) at time step 0. |
|
FLOAT32, FLOAT16 | ND | Each tensor is of shape [numLayers * D, batch_size, hidden_size] Empty tensors are not supported. |
√ |
| dy | Input | Gradient of hidden, the last-layer output of GRU forward propagation. Corresponding formula: ∂L/∂h^(l). |
|
FLOAT32, FLOAT16 | ND |
|
√ |
| dh | Input | Gradient of the hidden output of each layer in the forward GRU at time step T, passed from the next time step. Corresponding to δh_next. |
|
FLOAT32, FLOAT16 | ND | [numLayers * D, batch_size, hidden_size] Empty tensors are not supported. |
√ |
| r | Input | Activation value of the reset gate of each layer at each time step during GRU forward propagation. Corresponds to r in the corresponding formula. |
|
FLOAT32, FLOAT16 | ND |
|
√ |
| z | Input | Activation value of the update gate of each layer at each time step during GRU forward propagation. Corresponds to z in the corresponding formula. |
|
FLOAT32, FLOAT16 | ND |
|
√ |
| n | Input | Activation value of the candidate hidden state of each layer at each time step in forward GRU. It corresponds to n in the corresponding formula. |
|
FLOAT32, FLOAT16 | ND |
|
√ |
| h_n | Input | Intermediate value of the candidate hidden state of each layer at each time step in the forward GRU. Corresponds to $W_{hn}h_{t-1} + b_{hn}$ in the corresponding formula. |
|
FLOAT32, FLOAT16 | ND |
|
√ |
| h | Input | Hidden status of each layer at each time step in GRU forward propagation, corresponding to h in the formula. |
|
FLOAT32, FLOAT16 | ND |
|
√ |
| batchSizesOptional | Input | Number of valid sequence batches at each time step of the variable-length GRU input sequence. |
|
INT64 | ND | [time_step] | √ |
| hasBias | Input | Indicates whether the bias b exists. | - | BOOL | - | - | - |
| numLayers | Input | Number of GRU layers. |
|
INT64 | - | - | - |
| bidirection | Input | Indicates whether it is bidirectional. | - | BOOL | - | - | - |
| batchFirst | Input | Indicates whether the format of the input data (input, y, dy) has batch as the first dimension. | - | BOOL | - | - | - |
| dxOut(grad_x_t) | Output | Gradient of input input, corresponding to δx in the corresponding formula. |
|
FLOAT32, FLOAT16 | ND |
|
√ |
| dhPrevOut(grad_h_prev) | Output | Gradient of the initial hidden state of each GRU layer, corresponding to δh_prev at t=0. |
|
FLOAT32, FLOAT16 | ND | [D * num_layers, batch_size, hidden_size] Empty tensors are not supported. |
√ |
| dparamsOut(total_grad_w_ih, total_grad_w_hh) | Output | List of gradient tensors of weights and biases. δw and δb in the corresponding formula. |
|
FLOAT32, FLOAT16 | ND | dweight_ih: [3*hidden_size, cur_input_size] dweight_hh: [3*hidden_size, hidden_size] dbias: [3*hidden_size] Empty tensors are not supported. |
√ |
| workspaceSize | Output | Returns the workspace size to be allocated on the device. | Output parameter on the host. | UINT64 | - | - | - |
| executor | Output | Returns the op executor, which contains the operator computation flow. | Output parameter on the host. | - | - | - | - |
- Return value
aclnnStatus: return status code. For details, see [aclnn_return_code].
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 | If the input parameter is aclTensor or aclTensorList (other than batchSizesOptional) and is a null pointer. |
| ACLNN_ERR_PARAM_INVALID | 161002 | If the input parameter is aclTensor or aclTensorList, the data type is not within the supported range. |
| If the input parameter is of type aclTensor or aclTensorList, the data types are different. | ||
| If the input parameter is of type aclTensor or aclTensorList, the shape does not meet the corresponding shape requirements. | ||
| numLayers is not greater than 0. |
aclnnGRUBackward
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address allocated on the device. workspaceSize Input Workspace size allocated on the device, obtained by calling the first-phase API aclnnGRUBackwardGetWorkspaceSize. executor Input Operator executor that contains the computation flow of the operator. stream Input Stream for task execution. Return value
aclnnStatus: return status code. For details, see [aclnn_return_code].
Constraints
- aclnnGRUBackward defaults to a deterministic implementation.
- FP16/FP32 is supported. The data types of all inputs must be consistent.
- When W = numLayers・D・T・B・H・(I+H) ≥ 9,622,080, a timeout may occur.
Example
The following sample code is for reference only. For details about how to compile and run the sample, see Compile and Run Samples.
#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_gru_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;
}
void PrintOutResult(const std::string& name, const std::vector<int64_t>& shape, void** deviceAddr)
{
auto size = GetShapeSize(shape);
std::vector<float> resultData(size, 0);
auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), *deviceAddr,
size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy %s from device to host failed. ERROR: %d\n", name.c_str(), ret);
return );
LOG_PRINT("=== %s shape=[", name.c_str());
for (size_t i = 0; i < shape.size(); i++) {
LOG_PRINT("%ld%s", shape[i], (i + 1 < shape.size()) ? "," : "");
}
LOG_PRINT("] ===\n");
for (int64_t i = 0; i < size; i++) {
LOG_PRINT(" [%ld] = %f\n", i, resultData[i]);
}
LOG_PRINT("\n");
}
int Init(int32_t deviceId, aclrtStream* stream)
{
// Boilerplate code for 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);
// 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);
// 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 aclTensor.
*tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
shape.data(), shape.size(), *deviceAddr);
return 0;
}
template <typename T>
int CreateAclTensorList(const std::vector<std::vector<int64_t>>& shapes, void** deviceAddr, aclDataType dataType,
aclTensorList** tensor, T initVal = 1)
{
int size = shapes.size();
aclTensor* tensors[size];
for (int i = 0; i < size; i++) {
std::vector<T> hostData(GetShapeSize(shapes[i]), initVal);
int ret = CreateAclTensor<float>(hostData, shapes[i], deviceAddr + i, dataType, tensors + i);
CHECK_RET(ret == ACL_SUCCESS, return ret);
}
*tensor = aclCreateTensorList(tensors, size);
return ACL_SUCCESS;
}
int main()
{
// 1. (Boilerplate) Device/stream initialization. For details, see the list of AscendCL external APIs.
// 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 inputs and outputs as required by the API.
int64_t timeStep = 2;
int64_t batchSize = 3;
int64_t inputSize = 4;
int64_t hiddenSize = 5;
int64_t gateNum = 3;
int64_t numLayers = 1;
bool hasBias = false;
bool batchFirst = false;
bool bidirection = false;
int64_t dScale = bidirection ? 2 : 1;
int64_t ldScale = numLayers * dScale;
std::vector<int64_t> inputShape = {timeStep, batchSize, inputSize};
std::vector<int64_t> dyShape = {timeStep, batchSize, dScale * hiddenSize};
std::vector<int64_t> dhShape = {ldScale, batchSize, hiddenSize};
std::vector<int64_t> hxShape = {ldScale, batchSize, hiddenSize};
std::vector<std::vector<int64_t>> paramsListShape = {};
auto curLayerInputSize = inputSize;
for (int i = 0; i < numLayers; i++) {
for (int64_t j = 0; j < dScale; j++) {
paramsListShape.push_back({hiddenSize * gateNum, curLayerInputSize});
paramsListShape.push_back({hiddenSize * gateNum, hiddenSize});
if (hasBias) {
paramsListShape.push_back({hiddenSize * gateNum});
paramsListShape.push_back({hiddenSize * gateNum});
}
}
curLayerInputSize = dScale * hiddenSize;
}
// gate lists: r, z, n, hn, h each has ldScale tensors of [T, B, H]
std::vector<std::vector<int64_t>> gateListShape;
for (int64_t i = 0; i < ldScale; i++) {
gateListShape.push_back({timeStep, batchSize, hiddenSize});
}
void* inputDeviceAddr = nullptr;
std::vector<void*> paramsListDeviceAddr(paramsListShape.size(), nullptr);
void* dyDeviceAddr = nullptr;
void* dhDeviceAddr = nullptr;
void* hxDeviceAddr = nullptr;
std::vector<void*> rDeviceAddr;
std::vector<void*> zDeviceAddr;
std::vector<void*> nDeviceAddr;
std::vector<void*> hnDeviceAddr;
std::vector<void*> hDeviceAddr;
// output
void* dxDeviceAddr = nullptr;
std::vector<void*> dparamsListDeviceAddr(paramsListShape.size(), nullptr);
void* dhPrevDeviceAddr = nullptr;
aclTensor* input = nullptr;
aclTensorList* params = nullptr;
aclTensor* dy = nullptr;
aclTensor* dh = nullptr;
aclTensor* hx = nullptr;
aclTensorList* r = nullptr;
aclTensorList* z = nullptr;
aclTensorList* n = nullptr;
aclTensorList* hn = nullptr;
aclTensorList* h = nullptr;
aclTensor* dxOut = nullptr;
aclTensor* dhPrevOut = nullptr;
aclTensorList* dparamsOut = nullptr;
// Construct the inputs.
std::vector<float> inputHostData(GetShapeSize(inputShape), 1.0);
ret = CreateAclTensor<float>(inputHostData, inputShape, &inputDeviceAddr, aclDataType::ACL_FLOAT, &input);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensorList<float>(paramsListShape, paramsListDeviceAddr.data(), aclDataType::ACL_FLOAT, ¶ms,
1.0);
CHECK_RET(ret == ACL_SUCCESS, return ret);
std::vector<float> dyHostData(GetShapeSize(dyShape), 0.5);
ret = CreateAclTensor<float>(dyHostData, dyShape, &dyDeviceAddr, aclDataType::ACL_FLOAT, &dy);
CHECK_RET(ret == ACL_SUCCESS, return ret);
std::vector<float> dhHostData(GetShapeSize(dhShape), 0.1);
ret = CreateAclTensor<float>(dhHostData, dhShape, &dhDeviceAddr, aclDataType::ACL_FLOAT, &dh);
CHECK_RET(ret == ACL_SUCCESS, return ret);
std::vector<float> hxHostData(GetShapeSize(hxShape), 0.0);
ret = CreateAclTensor<float>(hxHostData, hxShape, &hxDeviceAddr, aclDataType::ACL_FLOAT, &hx);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Construct the gate lists (r, z, n, hn, h) - intermediate values of the forward computation.
rDeviceAddr.resize(ldScale, nullptr);
zDeviceAddr.resize(ldScale, nullptr);
nDeviceAddr.resize(ldScale, nullptr);
hnDeviceAddr.resize(ldScale, nullptr);
hDeviceAddr.resize(ldScale, nullptr);
ret = CreateAclTensorList<float>(gateListShape, rDeviceAddr.data(), aclDataType::ACL_FLOAT, &r, 0.5);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensorList<float>(gateListShape, zDeviceAddr.data(), aclDataType::ACL_FLOAT, &z, 0.5);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensorList<float>(gateListShape, nDeviceAddr.data(), aclDataType::ACL_FLOAT, &n, 0.5);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensorList<float>(gateListShape, hnDeviceAddr.data(), aclDataType::ACL_FLOAT, &hn, 0.5);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensorList<float>(gateListShape, hDeviceAddr.data(), aclDataType::ACL_FLOAT, &h, 0.5);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Construct the outputs.
std::vector<float> dxHostData(GetShapeSize(inputShape), 0.0);
ret = CreateAclTensor<float>(dxHostData, inputShape, &dxDeviceAddr, aclDataType::ACL_FLOAT, &dxOut);
CHECK_RET(ret == ACL_SUCCESS, return ret);
std::vector<float> dhPrevHostData(GetShapeSize(hxShape), 0.0);
ret = CreateAclTensor<float>(dhPrevHostData, hxShape, &dhPrevDeviceAddr, aclDataType::ACL_FLOAT, &dhPrevOut);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensorList<float>(paramsListShape, dparamsListDeviceAddr.data(), aclDataType::ACL_FLOAT, &dparamsOut,
0.0);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API.
uint64_t workspaceSize = 0;
aclOpExecutor* executor = nullptr;
// Call the first-phase API of aclnnGRUBackward.
ret = aclnnGRUBackwardGetWorkspaceSize(
input, params, hx, dy, dh, r, z, n, hn, h, nullptr, hasBias, numLayers, bidirection, batchFirst,
dxOut, dhPrevOut, dparamsOut, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGRUBackwardGetWorkspaceSize 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 aclnnGRUBackward.
ret = aclnnGRUBackward(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGRUBackward failed. ERROR: %d\n", ret); return ret);
// 4. (boilerplate) 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 to the host.
PrintOutResult("dxOut", inputShape, &dxDeviceAddr);
PrintOutResult("dhPrevOut", hxShape, &dhPrevDeviceAddr);
for (size_t i = 0; i < paramsListShape.size(); i++) {
PrintOutResult("dparamsOut[" + std::to_string(i) + "]", paramsListShape[i], &dparamsListDeviceAddr[i]);
}
// 6. Release aclTensor and aclTensorList.
aclDestroyTensor(input);
aclDestroyTensorList(params);
aclDestroyTensor(dy);
aclDestroyTensor(dh);
aclDestroyTensor(hx);
aclDestroyTensorList(r);
aclDestroyTensorList(z);
aclDestroyTensorList(n);
aclDestroyTensorList(hn);
aclDestroyTensorList(h);
aclDestroyTensor(dxOut);
aclDestroyTensor(dhPrevOut);
aclDestroyTensorList(dparamsOut);
// 7. Release device resources.
aclrtFree(inputDeviceAddr);
for (size_t i = 0; i < paramsListShape.size(); i++) {
aclrtFree(paramsListDeviceAddr[i]);
}
aclrtFree(dyDeviceAddr);
aclrtFree(dhDeviceAddr);
aclrtFree(hxDeviceAddr);
for (size_t i = 0; i < rDeviceAddr.size(); i++) {
aclrtFree(rDeviceAddr[i]);
aclrtFree(zDeviceAddr[i]);
aclrtFree(nDeviceAddr[i]);
aclrtFree(hnDeviceAddr[i]);
aclrtFree(hDeviceAddr[i]);
}
aclrtFree(dxDeviceAddr);
aclrtFree(dhPrevDeviceAddr);
for (size_t i = 0; i < dparamsListDeviceAddr.size(); i++) {
aclrtFree(dparamsListDeviceAddr[i]);
}
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}