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
  • Atlas inference products : Not supported
  • 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 rt=σ(Wirxt+bir+Whrht−1+bhr)r_t= \sigma(W_{ir}x_t + b_{ir} + W_{hr}h_{t-1} + b_{hr})
    • Update gate zt=σ(Wizxt+biz+Whzht−1+bhz)z_t = \sigma(W_{iz}x_t + b_{iz} + W_{hz}h_{t-1} + b_{hz})
    • Candidate hidden state nt=tanh⁡(Winxt+bin+rt⊙(Whnht−1+bhn))n_t = \tanh(W_{in}x_t + b_{in} + r_t \odot (W_{hn}h_{t-1} + b_{hn}))
    • Hidden state ht=(1−z)⊙nt+zt⊙ht−1h_t = (1-z) \odot n_t + z_t \odot h_{t-1}
  • Backward computation formula:
    •  Total upstream gradient:dht=dyt+dhnext\text{ Total upstream gradient:} \quad dh_t = dy_t + dh_{next} \quad(dytdy_t is the gradient from the upper layer, and dhnextdh_{next} is the gradient passed back at time step t+1)
    •  Update gate gradient:dzt=dht∗(ht−1−h~t)∗zt∗(1−zt)\text{ Update gate gradient:} \quad dz_t = dh_t * (h_{t-1} - \tilde{h}_t) * z_t * (1 - z_t)
    •  Candidate state gradient:dhh~t=dht∗(1−zt)∗(1−h~t2)\text{ Candidate state gradient:} \quad dh_{\tilde{h}t} = dh_t * (1 - z_t) * (1 - \tilde{h}_t^2)
    •  Reset gate gradient:drt=dhh~t∗linhh[2∗hidden_size:3∗hidden_size]∗rt∗(1−rt)\text{ Reset gate gradient:} \quad dr_t = dh_{\tilde{h}t} * lin_{hh}[2*hidden\_size:3*hidden\_size] * r_t * (1 - r_t)
    •  Linear transformation gradient decomposition:\text{ Linear transformation gradient decomposition:} dlinih=[dzt;drt;dhh~t],dlinhh=[dzt;drt;dhh~t∗rt]\quad dlin_{ih} = [dz_t; dr_t; dh_{\tilde{h}t}], \quad dlin_{hh} = [dz_t; dr_t; dh_{\tilde{h}t} * r_t]
    •  Input gradient (passed to the lower layer):dxt=WihT@dlinih\text{ Input gradient (passed to the lower layer):} \quad dx_t = W_{ih}^T @ dlin_{ih}
    •  Previous hidden state gradient (passed to t-1):dhprev=WhhT@dlinhh+dht∗zt\text{ Previous hidden state gradient (passed to t-1):} \quad dh_{prev} = W_{hh}^T @ dlin_{hh} + dh_t * z_t
    •  Weight/bias gradient accumulation:\text{ Weight/bias gradient accumulation:} dWih+=dlinih@xtT,dWhh+=dlinhh@ht−1T\quad dW_{ih} += dlin_{ih} @ x_t^T, \quad dW_{hh} += dlin_{hh} @ h_{t-1}^T dbih+=dlinih.sum(dim=1),dbhh+=dlinhh.sum(dim=1)\quad db_{ih} += dlin_{ih}.sum(dim=1), \quad db_{hh} += dlin_{hh}.sum(dim=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.
  • batch_size indicates the number of sequences; time_step indicates the time dimension; input_size indicates the number of input features.
FLOAT32, FLOAT16 ND
  • If batchSizesOptional is valid: [time_step * batch_size, input_size];
  • If batchSizesOptional is a null pointer: [time_step, batch_size, input_size] or [batch_size, time_step, input_size].
  • Empty tensors are not supported.
√
params Input List of weight and bias tensors for each GRU layer, corresponding to w and b in the formula.
  • If bidirection is True, `D = 2`; otherwise, `D = 1`. If hasBiases is True, `B = 2`; otherwise, `B = 1`. The list length is D * B * num_layers * 2.
  • When both bidirection and hasBias are True, the layout is: [weight_ih_0, weight_hh_0, bias_ih_0, bias_hh_0, weight_ih_reverse_0, weight_hh_reverse_0, bias_ih_reverse_0, bias_hh_reverse_0].
  • If hasBias is False, no bias terms; if bidirection is False, no reverse terms.
  • For multiple layers, tensors are arranged layer by layer.
  • The data type is consistent with that of input.
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.
  • In multi-layer bidirectional mode, the data of each tensor is arranged along dimension 0 by direction first and then by layer.
  • The data type is consistent with that of input.
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).
  • In bidirectional mode, data is laid out in forward-to-backward order along the last dimension.
  • The data type is consistent with input.
FLOAT32, FLOAT16 ND
  • If a valid batchSizesOptional is passed in: [time_step * batch_size, hidden_size * D];
  • If a null-pointer batchSizesOptional is passed in: [time_step, batch_size, hidden_size * D] or [batch_size, time_step, hidden_size * D]
  • Empty tensors are not supported.
√
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.
  • In multi-layer bidirectional mode, data is laid out along dimension 0 with bidirectional directions first and then layer by layer.
  • The data type is consistent with that of input.
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.
  • List length is D * num_layers.
  • For multi-layer bidirectional, tensors are laid out in the order of bidirectional first, followed by multi-layer.
  • The data type is consistent with input.
FLOAT32, FLOAT16 ND
  • [time_step * batch_size, hidden_size] if a valid batchSizesOptional is passed;
  • [time_step, batch_size, hidden_size] if a null pointer batchSizesOptional is passed
  • Empty tensors are not supported.
√
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.
  • The list length is D * num_layers.
  • For multi-layer bidirectional, tensors are arranged bidirectional first and then by layer.
  • The data type is consistent with input.
FLOAT32, FLOAT16 ND
  • If a valid batchSizesOptional is passed in, the shape is [time_step * batch_size, hidden_size];
  • If an empty pointer is passed in for batchSizesOptional, the shape is [time_step, batch_size, hidden_size]
  • Empty tensors are not supported
√
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.
  • The list length is D * num_layers.
  • For multi-layer bidirectional, tensors are arranged bidirectional first and then by layer.
  • The data type is consistent with input.
FLOAT32, FLOAT16 ND
  • If a valid batchSizesOptional is passed in, the shape is [time_step * batch_size, hidden_size];
  • If a null-pointer batchSizesOptional is passed in, the shape is [time_step, batch_size, hidden_size].
  • Empty tensors are not supported.
√
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.
  • The list length is D * num_layers.
  • For multi-layer bidirectional settings, tensors are laid out in the order of bidirectional first, then multi-layer.
  • The data type is consistent with input.
FLOAT32, FLOAT16 ND
  • If a valid batchSizesOptional is passed in, the shape is [time_step * batch_size, hidden_size];
  • If a null-pointer batchSizesOptional is passed in, the shape is [time_step, batch_size, hidden_size].
  • Empty tensors are not supported.
√
h Input Hidden status of each layer at each time step in GRU forward propagation, corresponding to h in the formula.
  • The list length is D * num_layers.
  • In the multi-layer bidirectional case, tensors are laid out bidirectional first, then multi-layer.
  • The data type is consistent with that of input.
FLOAT32, FLOAT16 ND
  • If a valid batchSizesOptional is passed in: [time_step * batch_size, hidden_size];
  • If a null pointer batchSizesOptional is passed in: [time_step, batch_size, hidden_size]
  • Empty tensors are not supported
√
batchSizesOptional Input Number of valid sequence batches at each time step of the variable-length GRU input sequence.
  • Supported for variable-length sequences.
INT64 ND [time_step] √
hasBias Input Indicates whether the bias b exists. - BOOL - - -
numLayers Input Number of GRU layers.
  • Greater than 0.
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.
  • Shape consistent with input.
  • Data type consistent with input.
FLOAT32, FLOAT16 ND
  • If valid batchSizesOptional is passed in, [time_step * batch_size, input_size];
  • If a null-pointer batchSizesOptional is passed in, [time_step, batch_size, input_size] or [batch_size, time_step, input_size].
  • Empty tensors are not supported.
√
dhPrevOut(grad_h_prev) Output Gradient of the initial hidden state of each GRU layer, corresponding to δh_prev at t=0.
  • For multi-layer bidirectional, data is laid out along dim 0 in the order of bidirectional first and then layer by layer.
  • The data type is consistent with that of input.
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.
  • The list length is D * B * num_layers * 2.
  • The layout is consistent with that of input params.
  • The data type is consistent with that of input.
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;
}