aclnnLstmBackward
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 : Not supported
Function
Description: Backward propagation of LSTM. Computes the gradients of the forward input input, the weights params, and the initial state hx.
Formula:
Single-layer LSTM backward propagation formula
Component Formula Input concatenation Forget gate Input gate Candidate state Output gate Cell state Hidden state Where:
- is the sigmoid function
- denotes element-wise multiplication (Hadamard product)
- is the learnable weight matrix
- is the learnable bias term
Backward Propagation Variable Definitions
- Total loss:
- Hidden state gradient:
- Cell state gradient:
Backward propagation algorithm (time step t -> t-1)
- Initialization
Loop from to
- Current hidden state gradient
- Current cell state gradient
- Gate gradient computation
- Parameter gradient accumulation
- Propagate to the previous time step
- Update propagation variables
Gradient Computation Principle
Cell State Gradient Derivation
Where:
Forget Gate Gradient Derivation
Parameter Gradient Derivation
LSTM Gradient Flow Characteristics
Long-Term Dependency Handling
Multi-layer LSTMBackward backward propagation
In a multi-layer LSTM network, gradient propagation between layers only concerns the transfer of hidden states (intra-layer details such as gating mechanisms or cell states are ignored). Let:- : the hidden state of layer (, where is the total number of layers)
- : Loss function
- : Gradient of the loss function with respect to the hidden state of layer
Core propagation formula
Gradients propagate from the top layer () to the bottom layer (). The inter-layer relationship is given by the chain rule:
Where:
- : Gradient of the current layer (already obtained by backward propagation from the previous layer)
- : Jacobian matrix of the hidden state of layer with respect to the hidden state of layer
- : Matrix multiplication (gradient propagation is essentially vector-matrix multiplication)
That is, the output gradient dx of each layer is the input gradient dy of the upper layer.
Function Prototype
Each operator uses a two-phase API. Call "aclnnLstmBackwardGetWorkspaceSize" first to obtain the workspace size required for the computation and the executor that contains the operator computation process, and then call "aclnnLstmBackward" to execute the computation.
aclnnStatus aclnnLstmBackwardGetWorkspaceSize(
const aclTensor *input,
const aclTensorList *hx,
const aclTensorList *params,
const aclTensor *dy,
const aclTensor *dh,
const aclTensor *dc,
const aclTensorList *i,
const aclTensorList *g,
const aclTensorList *f,
const aclTensorList *o,
const aclTensorList *h,
const aclTensorList *c,
const aclTensorList *tanhc,
const aclTensor *batchSizesOptional,
bool hasBias,
int64_t numLayers,
double dropout,
bool train,
bool bidirectional,
bool batchFirst,
const aclBoolArray *outputMask,
aclTensor *dxOut,
aclTensor *dhPrevOut,
aclTensor *dcPrevOut,
aclTensorList *dparamsOut,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnLstmBackward(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnLstmBackwardGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor Input Input Fixed-length input sequence of LSTM. It is x in the corresponding 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 a valid batchSizesOptional is passed in, the shape is [time_step * batch_size, input_size]
- If a null-pointer batchSizesOptional is passed in, the shape is [time_step, batch_size, input_size] or [batch_size, time_step, input_size]
√ hx Input Initial hidden state and cell state of each LSTM layer. They correspond to h(t-1) and c(t-1) at time 0. - The list length is 2, containing h_0 and c_0.
- For multi-layer bidirectional, the data of each tensor is arranged along dimension 0 by bidirectional first and then layer by layer.
- The data type is consistent with input.
FLOAT32, FLOAT16 ND Each tensor in the list has a shape of [D * num_layers, batch_size, hidden_size]. √ params Input List of weight and bias tensors for each LSTM layer, i.e., w and b in the corresponding formula. - If bidirectional is True, `D = 2`; otherwise, `D = 1`. If hasBias is True, `B = 2`; otherwise, `B = 1`. The list length is D * B * num_layers.
- When both bidirectional and hasBias are True, the arrangement 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, there is no bias term; if bidirectional is False, there is no reverse term.
- For multiple layers, the tensors are arranged layer by layer.
- The data type is consistent with input.
FLOAT32, FLOAT16 ND - weight_ih: [4*hidden_size, cur_input_size]
- weight_hh: [4*hidden_size, hidden_size]
- bias_ih: [4*hidden_size]
- bias_hh: [4*hidden_size]
√ dy Input Gradient of hidden, the output of the last layer in LSTM forward propagation. Corresponds to ∂L/∂h^(l) in the formula. - In bidirectional cases, data is arranged along the last dimension in forward and backward directions.
- Data type is consistent with input.
FLOAT32, FLOAT16 ND - If valid batchSizesOptional is passed in, the shape is [time_step * batch_size, hidden_size * D]
- If a null-pointer batchSizesOptional is passed in, the shape is [time_step, batch_size, hidden_size * D] or [batch_size, time_step, hidden_size * D]
√ dh Input Gradient passed from the next time step to hidden, which is the output of each layer in the forward direction of LSTM, at time T. Corresponds to δh_next. - For multi-layer bidirectional, data along dimension 0 is arranged by bidirectional first, then layer-by-layer.
- The data type is consistent with that of input.
FLOAT32, FLOAT16 ND [numLayers * D, batch_size, hidden_size] √ dc Input Gradient of the output cell of each LSTM layer at time T, passed from the next time step. Corresponding to δc_next. - In the multi-layer bidirectional case, time data along dimension 0 is arranged by bidirectional first and then layer by layer.
- The data type is consistent with that of input.
FLOAT32, FLOAT16 ND [numLayers * D, batch_size, hidden_size] √ i Input Activation value of the input gate output by each layer in the forward direction of the LSTM. Corresponding to i in the formula. - The list length is D * num_layers.
- For multi-layer bidirectional, tensors are arranged by bidirectional first, then multi-layer.
- The data type is consistent with input.
FLOAT32, FLOAT16 ND [time_step, batch_size, hidden_size] √ g Input Activation value of the candidate cell state output by each layer in the LSTM forward direction. It corresponds to g in the formula. - The list length is D * num_layers.
- For multi-layer bidirectional, tensors are arranged by bidirectional first, then multi-layer.
- The data type is consistent with input.
FLOAT32, FLOAT16 ND [time_step, batch_size, hidden_size] √ f Input Activation value of the forget gate in each layer in forward direction of LSTM. Corresponding to f in the formula. - The list length is D * num_layers.
- In multi-layer bidirectional mode, tensors are arranged bidirectional first and then multi-layer.
- The data type is consistent with that of input.
FLOAT32, FLOAT16 ND [time_step, batch_size, hidden_size] √ o Input Activation value of the output gate of each layer in the forward direction of LSTM. It is o in the corresponding formula. - The list length is D * num_layers.
- In the multi-layer bidirectional case, tensors are arranged by bidirectional first, then by multi-layer.
- The data type is consistent with that of input.
FLOAT32, FLOAT16 ND [time_step, batch_size, hidden_size] √ h Input The hidden state of each layer in LSTM forward direction. Corresponds to h in the formula. - The list length is D * num_layers.
- For multi-layer bidirectional, tensors are arranged by bidirectional first and then by layers.
- The data type is consistent with input.
FLOAT32, FLOAT16 ND [time_step, batch_size, hidden_size] √ c Input The final cell state of each layer in LSTM forward direction. Corresponds to c in the formula. - List length is D * num_layers.
- For multi-layer bidirectional, tensors are arranged by bidirectional first and then by layers.
- The data type is consistent with that of input.
FLOAT32, FLOAT16 ND [time_step, batch_size, hidden_size] √ tanhc Input Output of the final cell state of each layer in the LSTM forward direction after passing through the tanh activation function. Corresponds to tanh(c). - List length is D * num_layers.
- For multi-layer bidirectional, tensors are arranged by bidirectional first and then by layers.
- The data type is consistent with that of input.
FLOAT32, FLOAT16 ND [time_step, batch_size, hidden_size] √ batchSizesOptional Input Number of valid batches at each time step in the variable-length LSTM input sequence. Supported for variable-length sequences. INT64 ND [time_step] √ hasBias Input Indicates whether bias b exists. - BOOL - - - numLayers Input Indicates the number of LSTM layers. The value must be greater than 0. INT64 - - - dropout Input Indicates the probability of the random mask. - DOUBLE - - - train Input Indicates whether the use case is training. - BOOL - - - bidirectional Input Indicates whether it is bidirectional. - BOOL - - - batchFirst Input Indicates whether the format of input data input, y, dy, dxOut has batch as the first dimension. - BOOL - - - outputMask Input Indicates whether to compute the four gradients. Array length is 4, not supported yet. ACL_BOOL_ARRAY - - - dxOut Output Gradient of input, corresponding to δx in the formula. - Shape consistent with that of input.
- Data type consistent with that of input.
FLOAT32, FLOAT16 ND - √ dhPrevOut Output Gradient of the initial hidden state of each LSTM layer, corresponding to δh_prev at t=0. - In the multi-layer bidirectional case, data along dimension 0 is arranged by bidirectional first and then layer by layer.
- Data type consistent with that of input.
FLOAT32, FLOAT16 ND [D * num_layers, batch_size, hidden_size] √ dcPrevOut Output Gradient of the initial cell state in each LSTM layer, corresponding to δc_prev at t=0. - In multi-layer bidirectional mode, data along dimension 0 is arranged by bidirectional first and then layer by layer.
- The data type is consistent with input.
FLOAT32, FLOAT16 ND [D * num_layers, batch_size, hidden_size] √ dparamsOut Output Tensor list of gradients of weights and biases. δw and δb in the corresponding formula. - The list length is D * B * num_layers.
- The arrangement is consistent with input params.
- The data type is consistent with input.
FLOAT32, FLOAT16 ND - dweight_ih: [4*hidden_size, cur_input_size]
- dweight_hh: [4*hidden_size, hidden_size]
- dbias: [4*hidden_size]
√ workspaceSize Output Returns the workspace size that needs to be side-applied on the Device. - - - - - executor Output Returns the op executor containing the operator computation flow. - - - - - 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 If the passed-in parameter is aclTensor or aclTensorList and is not batchSizesOptional, it is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 If the passed-in parameter is aclTensor or aclTensorList, the data type is not within the supported range. If the passed-in parameters are of type aclTensor or aclTensorList, their data types are different. If the passed-in parameter is of type aclTensor or aclTensorList, the shape does not meet the corresponding shape requirement. numLayers does not meet the requirement of >0.
aclnnLstmBackward
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address side-applied on the Device. workspaceSize Input Size of the workspace side-applied on the Device, obtained by calling the first-phase API aclnnLstmBackwardGetWorkspaceSize. executor Input Op executor, which contains the operator computation flow. stream Input Specifies the stream for executing tasks. Return value
aclnnStatus: return status code. For details, see aclnn Error Codes.
Constraints
Deterministic computation:
- aclnnLstmBackward defaults to a deterministic implementation.
Boundary value scenario description:
- When the input is Inf, the output is NAN.
- When the input is NaN, the output is NaN.
Example
The following sample code is for reference only. For details about the compilation and execution process, see Compile and Run Samples.
#include <iostream>
#include <cmath>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_lstm_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, 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, aclFormat format=aclFormat::ACL_FORMAT_ND) {
auto size = GetShapeSize(shape) * sizeof(T);
// Call aclrtMalloc to allocate device-side 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-side data to device-side 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, format,
shape.data(), shape.size(), *deviceAddr);
return 0;
}
int main() {
// 1. (Boilerplate) Device/stream initialization. For details, see the AscendCL external API list.
// 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 input and output. Custom construction is required based on the API.
// Define variables.
int64_t t = 1;
int64_t n = 1;
int64_t inputSize = 8;
int64_t hiddenSize = 8;
// Define shapes.
std::vector<int64_t> xShape = {t, n, inputSize};
std::vector<int64_t> wiShape = {hiddenSize * 4, inputSize};
std::vector<int64_t> whShape = {hiddenSize * 4, hiddenSize};
std::vector<int64_t> bShape = {hiddenSize * 4};
std::vector<int64_t> yShape = {t, n, hiddenSize};
std::vector<int64_t> initHShape = {1, n, hiddenSize};
std::vector<int64_t> initCShape = initHShape; // Same as initHShape
std::vector<int64_t> hShape = yShape;
std::vector<int64_t> cShape = hShape;
std::vector<int64_t> dyShape = yShape;
std::vector<int64_t> dhShape = {1, n, hiddenSize};
std::vector<int64_t> dcShape = dhShape;
std::vector<int64_t> iShape = hShape;
std::vector<int64_t> jShape = hShape;
std::vector<int64_t> fShape = hShape;
std::vector<int64_t> oShape = hShape;
std::vector<int64_t> tanhCtShape = hShape;
// Backward propagation output tensor shape
std::vector<int64_t> dwiShape = wiShape; // Same as wi
std::vector<int64_t> dwhShape = wiShape; // Same as wh
std::vector<int64_t> dbShape = bShape; // Same as b
std::vector<int64_t> dxShape = xShape; // Same as x
std::vector<int64_t> dhPrevShape = initHShape; // Same as initH
std::vector<int64_t> dcPrevShape = initCShape; // Same as initC
// Device address pointer
void* xDeviceAddr = nullptr;
void* wiDeviceAddr = nullptr;
void* whDeviceAddr = nullptr;
void* biDeviceAddr = nullptr;
void* bhDeviceAddr = nullptr;
void* yDeviceAddr = nullptr;
void* initHDeviceAddr = nullptr;
void* initCDeviceAddr = nullptr;
void* hDeviceAddr = nullptr;
void* cDeviceAddr = nullptr;
void* dyDeviceAddr = nullptr;
void* dhDeviceAddr = nullptr;
void* dcDeviceAddr = nullptr;
void* iDeviceAddr = nullptr;
void* jDeviceAddr = nullptr;
void* fDeviceAddr = nullptr;
void* oDeviceAddr = nullptr;
void* tanhCtDeviceAddr = nullptr;
// Backward propagation output device address pointer
void* dwiDeviceAddr = nullptr;
void* dwhDeviceAddr = nullptr;
void* dbiDeviceAddr = nullptr;
void* dbhDeviceAddr = nullptr;
void* dxDeviceAddr = nullptr;
void* dhPrevDeviceAddr = nullptr;
void* dcPrevDeviceAddr = nullptr;
// ACL Tensor pointer
aclTensor* x = nullptr;
aclTensor* wi = nullptr;
aclTensor* wh = nullptr;
aclTensor* bi = nullptr;
aclTensor* bh = nullptr;
aclTensor* y = nullptr;
aclTensor* initH = nullptr;
aclTensor* initC = nullptr;
aclTensor* h = nullptr;
aclTensor* c = nullptr;
aclTensor* dy = nullptr;
aclTensor* dh = nullptr;
aclTensor* dc = nullptr;
aclTensor* i = nullptr;
aclTensor* j = nullptr;
aclTensor* f = nullptr;
aclTensor* o = nullptr;
aclTensor* tanhCt = nullptr;
// ACL Tensor pointers for backward propagation output.
aclTensor* dwi = nullptr;
aclTensor* dwh = nullptr;
aclTensor* dbi = nullptr;
aclTensor* dbh = nullptr;
aclTensor* dx = nullptr;
aclTensor* dhPrev = nullptr;
aclTensor* dcPrev = nullptr;
std::vector<float> xHostData(xShape[0] * xShape[1] * xShape[2], 1.0f); // 1 * 1 * 8 = 8 ones
std::vector<float> wiHostData(wiShape[0] * wiShape[1], 1.0f); // (8+8)*32 = 16 * 32 = 512 ones
std::vector<float> whHostData(whShape[0] * whShape[1], 1.0f); // (8+8)*32 = 16 * 32 = 512 ones
std::vector<float> biHostData(bShape[0], 1.0f); // 32 ones
std::vector<float> bhHostData(bShape[0], 1.0f); // 32 ones
std::vector<float> yHostData(yShape[0] * yShape[1] * yShape[2], 1.0f); // 1 * 1 * 8 = 8 ones
std::vector<float> initHHostData(initHShape[0] * initHShape[1] * initHShape[2], 1.0f); // 1 * 8 = 8 ones
std::vector<float> initCHostData(initCShape[0] * initCShape[1] * initCShape[2], 1.0f); // 1 * 8 = 8 ones
std::vector<float> hHostData(hShape[0] * hShape[1] * hShape[2], 1.0f); // 1 * 1 * 8 = 8 ones
std::vector<float> cHostData(cShape[0] * cShape[1] * cShape[2], 1.0f); // 1 * 1 * 8 = 8 ones
std::vector<float> dyHostData(dyShape[0] * dyShape[1] * dyShape[2], 1.0f); // 1 * 1 * 8 = 8 ones
std::vector<float> dhHostData(dhShape[0] * dhShape[1] * dhShape[2], 1.0f); // 1 * 8 = 8 ones
std::vector<float> dcHostData(dcShape[0] * dcShape[1] * dcShape[2], 1.0f); // 1 * 8 = 8 ones
std::vector<float> iHostData(iShape[0] * iShape[1] * iShape[2], 1.0f); // 1 * 1 * 8 = 8 ones
std::vector<float> jHostData(jShape[0] * jShape[1] * jShape[2], 1.0f); // 1 * 1 * 8 = 8 ones
std::vector<float> fHostData(fShape[0] * fShape[1] * fShape[2], 1.0f); // 1 * 1 * 8 = 8 ones
std::vector<float> oHostData(oShape[0] * oShape[1] * oShape[2], 1.0f); // 1 * 1 * 8 = 8 ones
std::vector<float> tanhCtHostData;
tanhCtHostData.reserve(cHostData.size());
for (const auto& cVal : cHostData) {
tanhCtHostData.push_back(std::tanh(cVal)); // Apply the tanh function to each c value.
}
// Backward propagation output host data (initialized to 0)
std::vector<float> dwiHostData(dwiShape[0] * dwiShape[1], 0.0f);
std::vector<float> dwhHostData(dwhShape[0] * dwhShape[1], 0.0f);
std::vector<float> dbiHostData(dbShape[0], 0.0f);
std::vector<float> dbhHostData(dbShape[0], 0.0f);
std::vector<float> dxHostData(dxShape[0] * dxShape[1] * dxShape[2], 0.0f);
std::vector<float> dhPrevHostData(dhPrevShape[0] * dhPrevShape[1] * dhPrevShape[2], 0.0f);
std::vector<float> dcPrevHostData(dcPrevShape[0] * dcPrevShape[1] * dcPrevShape[2], 0.0f);
// Create x aclTensor.
ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT, &x, aclFormat::ACL_FORMAT_NCL);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create params aclTensorList.
ret = CreateAclTensor(wiHostData, wiShape, &wiDeviceAddr, aclDataType::ACL_FLOAT, &wi);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(whHostData, whShape, &whDeviceAddr, aclDataType::ACL_FLOAT, &wh);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(biHostData, bShape, &biDeviceAddr, aclDataType::ACL_FLOAT, &bi);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(bhHostData, bShape, &bhDeviceAddr, aclDataType::ACL_FLOAT, &bh);
CHECK_RET(ret == ACL_SUCCESS, return ret);
aclTensor* paramsArray[] = {wi, wh, bi, bh};
auto paramsList = aclCreateTensorList(paramsArray, 4);
// Create y aclTensor.
ret = CreateAclTensor(yHostData, yShape, &yDeviceAddr, aclDataType::ACL_FLOAT, &y);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create initH aclTensor.
ret = CreateAclTensor(initHHostData, initHShape, &initHDeviceAddr, aclDataType::ACL_FLOAT, &initH, aclFormat::ACL_FORMAT_NCL);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create initC aclTensor.
ret = CreateAclTensor(initCHostData, initCShape, &initCDeviceAddr, aclDataType::ACL_FLOAT, &initC, aclFormat::ACL_FORMAT_NCL);
CHECK_RET(ret == ACL_SUCCESS, return ret);
aclTensor* initHcArray[] = {initH, initC};
auto initHcList = aclCreateTensorList(initHcArray, 2);
// Create h aclTensor.
ret = CreateAclTensor(hHostData, hShape, &hDeviceAddr, aclDataType::ACL_FLOAT, &h, aclFormat::ACL_FORMAT_NCL);
CHECK_RET(ret == ACL_SUCCESS, return ret);
aclTensor* hArray[] = {h};
auto hList = aclCreateTensorList(hArray, 1);
// Create c aclTensor.
ret = CreateAclTensor(cHostData, cShape, &cDeviceAddr, aclDataType::ACL_FLOAT, &c, aclFormat::ACL_FORMAT_NCL);
CHECK_RET(ret == ACL_SUCCESS, return ret);
aclTensor* cArray[] = {c};
auto cList = aclCreateTensorList(cArray, 1);
// Create dy aclTensor.
ret = CreateAclTensor(dyHostData, dyShape, &dyDeviceAddr, aclDataType::ACL_FLOAT, &dy, aclFormat::ACL_FORMAT_NCL);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create dh aclTensor.
ret = CreateAclTensor(dhHostData, dhShape, &dhDeviceAddr, aclDataType::ACL_FLOAT, &dh, aclFormat::ACL_FORMAT_NCL);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create dc aclTensor.
ret = CreateAclTensor(dcHostData, dcShape, &dcDeviceAddr, aclDataType::ACL_FLOAT, &dc, aclFormat::ACL_FORMAT_NCL);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the i aclTensor.
ret = CreateAclTensor(iHostData, iShape, &iDeviceAddr, aclDataType::ACL_FLOAT, &i, aclFormat::ACL_FORMAT_NCL);
CHECK_RET(ret == ACL_SUCCESS, return ret);
aclTensor* iArray[] = {i};
auto iList = aclCreateTensorList(iArray, 1);
// Create the j aclTensor.
ret = CreateAclTensor(jHostData, jShape, &jDeviceAddr, aclDataType::ACL_FLOAT, &j, aclFormat::ACL_FORMAT_NCL);
CHECK_RET(ret == ACL_SUCCESS, return ret);
aclTensor* jArray[] = {j};
auto jList = aclCreateTensorList(jArray, 1);
// Create the f aclTensor.
ret = CreateAclTensor(fHostData, fShape, &fDeviceAddr, aclDataType::ACL_FLOAT, &f, aclFormat::ACL_FORMAT_NCL);
CHECK_RET(ret == ACL_SUCCESS, return ret);
aclTensor* fArray[] = {f};
auto fList = aclCreateTensorList(fArray, 1);
// Create the o aclTensor.
ret = CreateAclTensor(oHostData, oShape, &oDeviceAddr, aclDataType::ACL_FLOAT, &o, aclFormat::ACL_FORMAT_NCL);
CHECK_RET(ret == ACL_SUCCESS, return ret);
aclTensor* oArray[] = {o};
auto oList = aclCreateTensorList(oArray, 1);
// Create the tanhCt aclTensor.
ret = CreateAclTensor(tanhCtHostData, tanhCtShape, &tanhCtDeviceAddr, aclDataType::ACL_FLOAT, &tanhCt, aclFormat::ACL_FORMAT_NCL);
CHECK_RET(ret == ACL_SUCCESS, return ret);
aclTensor* tanhCtArray[] = {tanhCt};
auto tanhCtList = aclCreateTensorList(tanhCtArray, 1);
// Create the backward propagation output tensor.
// Create the dx aclTensor.
ret = CreateAclTensor(dxHostData, dxShape, &dxDeviceAddr, aclDataType::ACL_FLOAT, &dx, aclFormat::ACL_FORMAT_NCL);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the dhPrev aclTensor.
ret = CreateAclTensor(dhPrevHostData, dhPrevShape, &dhPrevDeviceAddr, aclDataType::ACL_FLOAT, &dhPrev, aclFormat::ACL_FORMAT_NCL);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the dcPrev aclTensor.
ret = CreateAclTensor(dcPrevHostData, dcPrevShape, &dcPrevDeviceAddr, aclDataType::ACL_FLOAT, &dcPrev, aclFormat::ACL_FORMAT_NCL);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the dparams aclTensorList.
ret = CreateAclTensor(dwiHostData, dwiShape, &dwiDeviceAddr, aclDataType::ACL_FLOAT, &dwi);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(dwhHostData, dwhShape, &dwhDeviceAddr, aclDataType::ACL_FLOAT, &dwh);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(dbiHostData, bShape, &dbiDeviceAddr, aclDataType::ACL_FLOAT, &dbi);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(dbhHostData, bShape, &dbhDeviceAddr, aclDataType::ACL_FLOAT, &dbh);
CHECK_RET(ret == ACL_SUCCESS, return ret);
aclTensor* dparamsArray[] = {dwi, dwh, dbi, dbh};
auto dparamsList = aclCreateTensorList(dparamsArray, 4);
// 3. Call the CANN operator library API. Change it to the specific API name.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API of aclnnLstmBackward
ret = aclnnLstmBackwardGetWorkspaceSize(x, initHcList, paramsList, dy, dh, dc, iList, jList, fList,
oList, hList, cList ,tanhCtList, nullptr, true, 1, 0, true, false, false, nullptr, dx, dhPrev, dcPrev, dparamsList,
&workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnLstmBackwardGetWorkspaceSize 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 aclnnLstmBackward
ret = aclnnLstmBackward(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnLstmBackward failed. ERROR: %d\n", ret); return ret);
// 4. (Boilerplate) Synchronously 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 values, and copy the results in device-side memory to the host side. Modify them based on the interface definition of the specific API.
// Print the dparams result.
auto dwiSize = GetShapeSize(dwiShape);
std::vector<float> resultDwiData(dwiSize, 0);
ret = aclrtMemcpy(resultDwiData.data(), resultDwiData.size() * sizeof(resultDwiData[0]), dwiDeviceAddr,
dwiSize * sizeof(resultDwiData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy dwi result from device to host failed. ERROR: %d\n", ret); return ret);
for (int64_t i = 0; i < dwiSize; i++) {
LOG_PRINT("result dwi[%ld] is: %f\n", i, resultDwiData[i]);
}
auto dwhSize = GetShapeSize(dwhShape);
std::vector<float> resultDwhData(dwhSize, 0);
ret = aclrtMemcpy(resultDwhData.data(), resultDwhData.size() * sizeof(resultDwhData[0]), dwhDeviceAddr,
dwhSize * sizeof(resultDwhData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy dwh result from device to host failed. ERROR: %d\n", ret); return ret);
for (int64_t i = 0; i < dwhSize; i++) {
LOG_PRINT("result dwh[%ld] is: %f\n", i, resultDwhData[i]);
}
auto dbiSize = GetShapeSize(bShape);
std::vector<float> resultDbiData(dbiSize, 0);
ret = aclrtMemcpy(resultDbiData.data(), resultDbiData.size() * sizeof(resultDbiData[0]), dbiDeviceAddr,
dbiSize * sizeof(resultDbiData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy dbi result from device to host failed. ERROR: %d\n", ret); return ret);
for (int64_t i = 0; i < dbiSize; i++) {
LOG_PRINT("result dbi[%ld] is: %f\n", i, resultDbiData[i]);
}
auto dbhSize = GetShapeSize(bShape);
std::vector<float> resultDbhData(dbhSize, 0);
ret = aclrtMemcpy(resultDbhData.data(), resultDbhData.size() * sizeof(resultDbhData[0]), dbhDeviceAddr,
dbhSize * sizeof(resultDbhData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy dbh result from device to host failed. ERROR: %d\n", ret); return ret);
for (int64_t i = 0; i < dbhSize; i++) {
LOG_PRINT("result dbh[%ld] is: %f\n", i, resultDbhData[i]);
}
// Print the dx result.
auto dxSize = GetShapeSize(dxShape);
std::vector<float> resultDxData(dxSize, 0);
ret = aclrtMemcpy(resultDxData.data(), resultDxData.size() * sizeof(resultDxData[0]), dxDeviceAddr,
dxSize * sizeof(resultDxData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy dx result from device to host failed. ERROR: %d\n", ret); return ret);
for (int64_t i = 0; i < dxSize; i++) {
LOG_PRINT("result dx[%ld] is: %f\n", i, resultDxData[i]);
}
// Print the dh_prev result.
auto dhPrevSize = GetShapeSize(dhPrevShape);
std::vector<float> resultDhPrevData(dhPrevSize, 0);
ret = aclrtMemcpy(resultDhPrevData.data(), resultDhPrevData.size() * sizeof(resultDhPrevData[0]), dhPrevDeviceAddr,
dhPrevSize * sizeof(resultDhPrevData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy dh_prev result from device to host failed. ERROR: %d\n", ret); return ret);
for (int64_t i = 0; i < dhPrevSize; i++) {
LOG_PRINT("result dh_prev[%ld] is: %f\n", i, resultDhPrevData[i]);
}
// Print the dc_prev result.
auto dcPrevSize = GetShapeSize(dcPrevShape);
std::vector<float> resultDcPrevData(dcPrevSize, 0);
ret = aclrtMemcpy(resultDcPrevData.data(), resultDcPrevData.size() * sizeof(resultDcPrevData[0]), dcPrevDeviceAddr,
dcPrevSize * sizeof(resultDcPrevData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy dc_prev result from device to host failed. ERROR: %d\n", ret); return ret);
for (int64_t i = 0; i < dcPrevSize; i++) {
LOG_PRINT("result dc_prev[%ld] is: %f\n", i, resultDcPrevData[i]);
}
// Release aclTensor.
aclDestroyTensor(x);
aclDestroyTensor(y);
aclDestroyTensor(dy);
aclDestroyTensor(dh);
aclDestroyTensor(dc);
aclDestroyTensor(dx);
aclDestroyTensor(dhPrev);
aclDestroyTensor(dcPrev);
// Release tensorList.
aclDestroyTensorList(paramsList);
aclDestroyTensorList(initHcList);
aclDestroyTensorList(hList);
aclDestroyTensorList(cList);
aclDestroyTensorList(iList);
aclDestroyTensorList(jList);
aclDestroyTensorList(fList);
aclDestroyTensorList(oList);
aclDestroyTensorList(tanhCtList);
aclDestroyTensorList(dparamsList);
// Release Device resources.
aclrtFree(xDeviceAddr);
aclrtFree(wiDeviceAddr);
aclrtFree(whDeviceAddr);
aclrtFree(biDeviceAddr);
aclrtFree(bhDeviceAddr);
aclrtFree(yDeviceAddr);
aclrtFree(initHDeviceAddr);
aclrtFree(initCDeviceAddr);
aclrtFree(hDeviceAddr);
aclrtFree(cDeviceAddr);
aclrtFree(dyDeviceAddr);
aclrtFree(dhDeviceAddr);
aclrtFree(dcDeviceAddr);
aclrtFree(iDeviceAddr);
aclrtFree(jDeviceAddr);
aclrtFree(fDeviceAddr);
aclrtFree(oDeviceAddr);
aclrtFree(tanhCtDeviceAddr);
aclrtFree(dwiDeviceAddr);
aclrtFree(dwhDeviceAddr);
aclrtFree(dbiDeviceAddr);
aclrtFree(dbhDeviceAddr);
aclrtFree(dxDeviceAddr);
aclrtFree(dhPrevDeviceAddr);
aclrtFree(dcPrevDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}