aclnnLSTM
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 : Supported
Atlas training products : Supported
Function
- Description: The LSTM (Long Short-Term Memory) network is a special type of recurrent neural network (RNN) model. Performs LSTM network computation, receives an input sequence and initial states, and returns an output sequence and final states.
- Formula:
- : Input vector of the LSTM unit.
- : forget gate activation vector.
- : input gate and update gate activation vector.
- : output gate activation vector.
- : Hidden state vector, also known as the output vector of the LSTM unit.
- : cell input activation vector.
- : cell state vector.
- : weight matrices and bias vector parameters learned during training.
Function Prototype
Each operator uses a two-phase API. You must call the "aclnnLSTMGetWorkspaceSize" API first to obtain the input parameters and calculate the required workspace size according to the process, and then call the "aclnnLSTM" API to perform the computation.
aclnnStatus aclnnLSTMGetWorkspaceSize(
const aclTensor *input,
const aclTensorList *params,
const aclTensorList *hx,
const aclTensor *batchSizes,
bool hasBias,
int64_t numLayers,
double dropout,
bool train,
bool bidirectional,
bool batchFirst,
aclTensor *output,
aclTensor *hy,
aclTensor *cy,
aclTensorList *iOut,
aclTensorList *jOut,
aclTensorList *fOut,
aclTensorList *oOut,
aclTensorList *hOut,
aclTensorList *cOut,
aclTensorList *tanhCOut,
uint64_t *workspaceSize,
aclOpExecutor **executor);aclnnStatus aclnnLSTM(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnLSTMGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor Input Input Input vector of the LSTM unit. - If batchSizes is a null pointer:
The shape format depends on the batchFirst parameter:- batchFirst=False: (time_step, batch_size, input_size)
- batchFirst=True: (batch_size, time_step, input_size)
- If valid batchSizes is passed in:
Shape format: (time_step * batch_size, input_size)
Description: The memory layout is the same as that of (time_step, batch_size, input_size).
FLOAT16, FLOAT32 ND 3 √ params Input Indicates the list of weight and bias tensors in the LSTM operation. - num_layers: corresponds to the parameter numLayers, indicating the number of LSTM layers;
- D: D=2 when bidirection=True, otherwise D=1;
- B: B=2 when has_biases=True, otherwise B=1.
- weight_ih_0: input weight parameter of layer 0, shape=(4 * hidden_size, cur_input_size)
Note: cur_input_size is the number of input features for each layer (first layer=input_size; subsequent layers=hidden_size; bidirectional=2*hidden_size) - weight_hh_0: hidden layer weight parameter of layer 0, shape=(4 * hidden_size, hidden_size)
- bias_ih_0: input weight bias of layer 0, shape=(4 * hidden_size)
- bias_hh_0: hidden layer weight bias of layer 0, shape=(4 * hidden_size)
List length calculation formula: 2 * D * B * num_layers
Special use case (bidirection=True and has_biases=True):
Parameter arrangement: [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]
Description of core parameters (taking layer 0 as an example):
FLOAT16, FLOAT32 ND / √ hx Optional input Indicates the list of initial hidden and cell states in the LSTM operation. The list length is 2. Each shape in the list supports three dimensions (D * num_layers, batch_size, hidden_size). If the input is empty, the initial hidden and cell states are 0. FLOAT16, FLOAT32 ND / √ batchSizes Optional input Indicates the number of valid batches actually participating in the computation at each time step. If nullptr is passed in, the input is fixed-length mode data; otherwise, it is variable-length mode. The shape is (time_step,). The elements must be sorted in descending order, the element values must be positive integers and must not exceed the total batch count, and the first element value must be equal to the total batch count. INT64 ND 1 √ hasBias Input Indicates whether there are biases. / BOOL ND / √ numLayers Input Indicates the number of LSTM layers. / INT64 ND / √ dropout Input Indicates the probability of the random mask. This function is currently not supported. DOUBLE ND 1 √ train Input Indicates whether it is the training mode. When train = True, intermediate results are saved for backward propagation during forward LSTM computation. When train = False, intermediate results are not saved in the forward computation. BOOL ND / √ bidirectional Input Indicates whether it is bidirectional. / BOOL ND / √ batchFirst Input Indicates whether the input data format is batch-first (B, T, H). / BOOL ND / √ Output Output Indicates the output of each time step in the last layer of the LSTM operation. - If a null pointer is passed in for batchSizes:
When batchFirst=False, a three-dimensional shape (time_step, batch_size, D * hidden_size) is supported; otherwise, a three-dimensional shape (batch_size, time_step, D * hidden_size) is supported. - If a valid batchSizes is passed in:
The shape must be (time_step, batch_size, D * hidden_size).
FLOAT16, FLOAT32 ND 3 √ hy Output Indicates the hidden state of the last time step of each layer in performing the LSTM operation (output of formula (7)). shape supports three-dimensional (D * num_layers, batch_size, hidden_size). FLOAT16, FLOAT32 ND 3 √ cy Output Indicates the Cell state at the last time step of each layer in the LSTM operation (output of formula (5)). shape supports three-dimensional (D * num_layers, batch_size, hidden_size). FLOAT16, FLOAT32 ND 3 √ hy Output Indicates the hidden layer at the last time step of each layer in the LSTM operation (the output of formula (7)). shape supports three-dimensional (D * num_layers, batch_size, hidden_size) FLOAT16, FLOAT32 ND 3 √ cy Output Indicates the Cell state (output of formula (5)) of the last time step of each layer in performing the LSTM operation. Shape supports three-dimensional (D * num_layers, batch_size, hidden_size). FLOAT16, FLOAT32 ND 3 √ iOut Output Indicates the activation value of the input gate of each layer in the LSTM operation (sigmoid output, output of formula (2)). The list length is D * num_layers. Each shape in the list supports three-dimensional (time_step, batch_size, hidden_size). When train=False, there is no output value. FLOAT16, FLOAT32 ND 3 √ jOut Output Indicates the candidate cell state of each layer in the LSTM operation (tanh output, output of formula (4)). The list length is D * num_layers, and each shape in the list supports three-dimensional (time_step, batch_size, hidden_size). When train=False, there is no output value. FLOAT16, FLOAT32 ND 3 √ fOut Output Indicates the activation value of the forget gate of each layer in performing the LSTM operation (sigmoid output, output of formula (1)). The list length is D * num_layers, and each shape in the list supports three-dimensional (time_step, batch_size, hidden_size). When train=False, there is no output value. FLOAT16, FLOAT32 ND 3 √ oOut Output Indicates the activation value of the output gate of each layer in performing the LSTM operation (sigmoid output, output of formula (3)). The list length is D * num_layers. Each shape in the list supports three dimensions (time_step, batch_size, hidden_size). When train=False, there is no output value. FLOAT16, FLOAT32 ND 3 √ hOut Output Indicates the hidden state (the output of formula (7)) of each layer in the LSTM operation. The list length is D * num_layers. Each shape in the list supports three dimensions (time_step, batch_size, hidden_size). When train=False, there is no output value. FLOAT16, FLOAT32 ND / √ cOut Output Indicates the final Cell state of each layer in the LSTM operation (the output of formula (5)). The list length is D * num_layers. Each shape in the list supports three dimensions (time_step, batch_size, hidden_size). When train=False, there is no output value. FLOAT16, FLOAT32 ND / √ tanhCOut Output Indicates the output of the final cell state of each layer in the LSTM operation after the tanh activation function (the output of formula (6)). The list length is D * num_layers. Each shape in the list supports three dimensions (time_step, batch_size, hidden_size). When train=False, there is no output value. FLOAT16, FLOAT32 ND / √ workspaceSize Output Returns the workspace size required for the Device side application. - - - - - executor Output Returns the op executor, which contains the operator computation process. - - - - - - If batchSizes is a null pointer:
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 a required input, output, or required attribute and is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 If the passed-in parameter is aclTensor or aclTensorList and its data type is not within the supported range. If the passed-in parameter is of type aclTensor or aclTensorList and the data types are different. If the passed-in parameter is of type aclTensor or aclTensorList and the shape does not meet the corresponding shape requirements. numLayers is not greater than 0.
aclnnLSTM
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address allocated on the Device side. workspaceSize Input Size of the workspace allocated on the Device side, obtained by calling the first-phase API aclnnLSTMGetWorkspaceSize. executor Input Op executor, including the operator computation process. stream Input Specifies the stream for task execution. Return value
aclnnStatus: return status code. For details, see aclnn Error Codes.
Constraints
- Deterministic computation:
- aclnnLSTM defaults to a deterministic implementation.
- All inputs and outputs that support FLOAT16 and FLOAT32 types must have the same data type.
Example
The following sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.
/**
* Copyright (c) 2026 Huawei Technologies Co., Ltd.
* This program is free software, you can redistribute it and/or modify it under the terms and conditions of
* CANN Open Software License Agreement Version 2.0 (the "License").
* Please refer to the License for details. You may not use this file except in compliance with the License.
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
* See LICENSE in the root of the software repository for the full text of the License.
*/
/**
* @file main.cpp
*/
#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_lstm.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::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 result from device to host failed. ERROR: %d\n", ret); return);
for (int64_t i = 0; i < size; i++) {
LOG_PRINT("result[%ld] is: %f\n", i, resultData[i]);
}
}
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)
{
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 on the host side to the memory on the device side.
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.
*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) Initialize device/stream. For details, see the list of AscendCL APIs.
// Set deviceId based on the actual device in use.
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 inputs and outputs, which need to be custom-built based on the API.
int time_step = 1;
int batch_size = 1;
int hidden_size = 1;
int input_size = hidden_size;
int64_t numLayers = 1;
bool isbias = false;
bool batchFirst = false;
bool bidirection = false;
bool isTraining = true;
int64_t d_scale = bidirection == true ? 2 : 1;
std::vector<int64_t> inputShape = {time_step, batch_size, input_size};
std::vector<int64_t> outputShape = {time_step, batch_size, d_scale * hidden_size};
std::vector<int64_t> hycyShape = {numLayers * d_scale, batch_size, hidden_size};
std::vector<std::vector<int64_t>> paramsListShape = {};
std::vector<std::vector<int64_t>> outIListShape = {};
std::vector<std::vector<int64_t>> outJListShape = {};
std::vector<std::vector<int64_t>> outFListShape = {};
std::vector<std::vector<int64_t>> outOListShape = {};
std::vector<std::vector<int64_t>> outHListShape = {};
std::vector<std::vector<int64_t>> outCListShape = {};
std::vector<std::vector<int64_t>> outTanhCListShape = {};
auto cur_input_size = input_size;
for (int i = 0; i < numLayers; i++) {
paramsListShape.push_back({hidden_size * 4, cur_input_size});
paramsListShape.push_back({hidden_size * 4, hidden_size});
outIListShape.push_back({time_step, batch_size, hidden_size});
outJListShape.push_back({time_step, batch_size, hidden_size});
outFListShape.push_back({time_step, batch_size, hidden_size});
outOListShape.push_back({time_step, batch_size, hidden_size});
if (isTraining == true) {
outHListShape.push_back({time_step, batch_size, hidden_size});
outCListShape.push_back({time_step, batch_size, hidden_size});
} else {
outHListShape.push_back({batch_size, hidden_size});
outCListShape.push_back({batch_size, hidden_size});
}
outTanhCListShape.push_back({time_step, batch_size, hidden_size});
cur_input_size = hidden_size;
}
void* inputDeviceAddr = nullptr;
void* paramsListDeviceAddr[2 * numLayers];
void* outputDeviceAddr = nullptr;
void* hyDeviceAddr = nullptr;
void* cyDeviceAddr = nullptr;
void* outIListDeviceAddr[numLayers];
void* outJListDeviceAddr[numLayers];
void* outFListDeviceAddr[numLayers];
void* outOListDeviceAddr[numLayers];
void* outHListDeviceAddr[numLayers];
void* outCListDeviceAddr[numLayers];
void* outTanhCListDeviceAddr[numLayers];
aclTensor* input = nullptr;
aclTensorList* params = nullptr;
aclTensor* output = nullptr;
aclTensor* hy = nullptr;
aclTensor* cy = nullptr;
aclTensorList* outIList = nullptr;
aclTensorList* outJList = nullptr;
aclTensorList* outFList = nullptr;
aclTensorList* outOList = nullptr;
aclTensorList* outHList = nullptr;
aclTensorList* outCList = nullptr;
aclTensorList* outTanhCList = nullptr;
std::vector<float> inputHostData(GetShapeSize(inputShape), 1);
ret = CreateAclTensor<float>(inputHostData, inputShape, &inputDeviceAddr, aclDataType::ACL_FLOAT, &input);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensorList<float>(paramsListShape, paramsListDeviceAddr, aclDataType::ACL_FLOAT, ¶ms, 1.0);
CHECK_RET(ret == ACL_SUCCESS, return ret);
std::vector<float> outputHostData(GetShapeSize(outputShape), 1);
ret = CreateAclTensor<float>(outputHostData, outputShape, &outputDeviceAddr, aclDataType::ACL_FLOAT, &output);
CHECK_RET(ret == ACL_SUCCESS, return ret);
std::vector<float> hycyHostData(GetShapeSize(hycyShape), 1);
ret = CreateAclTensor<float>(hycyHostData, hycyShape, &hyDeviceAddr, aclDataType::ACL_FLOAT, &hy);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor<float>(hycyHostData, hycyShape, &cyDeviceAddr, aclDataType::ACL_FLOAT, &cy);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensorList<float>(outIListShape, outIListDeviceAddr, aclDataType::ACL_FLOAT, &outIList, 0.0);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensorList<float>(outJListShape, outJListDeviceAddr, aclDataType::ACL_FLOAT, &outJList, 0.0);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensorList<float>(outFListShape, outFListDeviceAddr, aclDataType::ACL_FLOAT, &outFList, 0.0);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensorList<float>(outOListShape, outOListDeviceAddr, aclDataType::ACL_FLOAT, &outOList, 0.0);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensorList<float>(outHListShape, outHListDeviceAddr, aclDataType::ACL_FLOAT, &outHList, 0.0);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensorList<float>(outCListShape, outCListDeviceAddr, aclDataType::ACL_FLOAT, &outCList, 0.0);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensorList<float>(
outTanhCListShape, outTanhCListDeviceAddr, aclDataType::ACL_FLOAT, &outTanhCList, 0.0);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API, which needs to be changed to the specific API name.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API aclnnLSTM.
ret = aclnnLSTMGetWorkspaceSize(
input, params, nullptr, nullptr, isbias, numLayers, 0.0, isTraining, bidirection, batchFirst, output, hy, cy,
outIList, outJList, outFList, outOList, outHList, outCList, outTanhCList, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnLSTMGetWorkspaceSize 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 aclnnLSTM.
ret = aclnnLSTM(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnLSTM failed. ERROR: %d\n", ret); return ret);
// 4. (boilerplate) Synchronize and wait for the task execution to end.
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 result from the device-side memory to the host side. Modify them based on the definition of the specific API.
PrintOutResult(outputShape, &outputDeviceAddr);
// 6. Release aclTensor and aclTensorList. Modify them based on the definition of the specific API.
aclDestroyTensor(input);
aclDestroyTensorList(params);
aclDestroyTensor(output);
aclDestroyTensor(hy);
aclDestroyTensor(cy);
aclDestroyTensorList(outIList);
aclDestroyTensorList(outJList);
aclDestroyTensorList(outFList);
aclDestroyTensorList(outOList);
aclDestroyTensorList(outHList);
aclDestroyTensorList(outCList);
aclDestroyTensorList(outTanhCList);
// // 7. Release device resources.
aclrtFree(inputDeviceAddr);
aclrtFree(outputDeviceAddr);
aclrtFree(hyDeviceAddr);
aclrtFree(cyDeviceAddr);
for (int i = 0; i < numLayers; i++) {
aclrtFree(outIListDeviceAddr[i]);
aclrtFree(outJListDeviceAddr[i]);
aclrtFree(outFListDeviceAddr[i]);
aclrtFree(outOListDeviceAddr[i]);
aclrtFree(outHListDeviceAddr[i]);
aclrtFree(outCListDeviceAddr[i]);
aclrtFree(outTanhCListDeviceAddr[i]);
}
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}