aclnnBidirectionLSTM
Applicable Products
Ascend 950PR&950DT products : Not supported
Atlas A3 products : Not supported
Atlas A2 products : Not supported
Atlas 200I/500 A2 inference products : Not supported
Atlas inference products : Supported
Atlas training products : Not 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 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 first call the "aclnnBidirectionLSTMGetWorkspaceSize" API to obtain the input parameters and calculate the required workspace size based on the procedure, and then call the "aclnnBidirectionLSTM" API to perform the computation.
aclnnStatus aclnnBidirectionLSTMGetWorkspaceSize(
const aclTensor *x,
const aclTensor *initH,
const aclTensor *initC,
const aclTensor *wIh,
const aclTensor *wHh,
const aclTensor *bIhOptional,
const aclTensor *bHhOptional,
const aclTensor *wIhReverseOptional,
const aclTensor *wHhReverseOptional,
const aclTensor *bIhReverseOptional,
const aclTensor *bHhReverseOptional,
int64_t numLayers,
bool isbias,
bool batchFirst,
bool bidirection,
const aclTensor *yOut,
const aclTensor *outputHOut,
const aclTensor *outputCOut,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnBidirectionLSTM(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnBidirectionLSTMGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor x (aclTensor*) Input Input vector of the LSTM unit, which is x in the formula. - Supports empty tensor.
- The shape supports 3D (time_step, batch_size, input_size). Here, `time_step` indicates the time dimension; `batch_size` indicates the number of batches to process at each time step; `input_size` indicates the number of input features.
FLOAT16 ND 3 √ initH (aclTensor*) Input Initial hidden status, which is h in the formula. - Supports empty tensor.
- Supports 3D shape (num_layers, batch_size, hidden_size) or, when bidirection is True, (2 * num_layers, batch_size, hidden_size). Here, `num_layers` corresponds to the parameter `numLayers` and indicates the number of LSTM layers; `hidden_size` indicates the number of features in the hidden status.
FLOAT16 ND 3 √ initC (aclTensor*) Input Initial cell status, c in the formula. - Supports empty tensor.
- Supports 3D shape (num_layers, batch_size, hidden_size) or, when bidirection is True, (2 * num_layers, batch_size, hidden_size).
FLOAT16 ND 3 √ wIh (aclTensor*) Input Input-hidden weight, W in the formula. - Supports empty tensor.
- Supports 2D shape (4 * hidden_size, input_size).
FLOAT16 ND 2 √ wHh (aclTensor*) Input hidden-hidden weight, W in the formula. - Supports empty tensors.
- Shape supports 2D (4 * hidden_size, hidden_size).
FLOAT16 ND 2 √ bIhOptional (aclTensor*) Input input-hidden bias, b in the formula. - Supports empty tensors.
- shape supports 1D (4 * hidden_size).
FLOAT16 ND 1 √ bHhOptional (aclTensor*) Input hidden-hidden bias, b in the formula. - Supports empty tensors.
- Supports 1D shape (4 * hidden_size).
FLOAT16 ND 1 √ wIhReverseOptional (aclTensor*) Input Reverse input-hidden weight, W in the formula. - Supports empty tensors.
- Supports 2D shape (4 * hidden_size, input_size).
FLOAT16 ND 2 √ wHhReverseOptional(aclTensor*) Input Reverse hidden-hidden weight, which is W in the formula. - Supports empty Tensor.
- Supports 2D shape (4 * hidden_size, hidden_size).
FLOAT16 ND 2 √ bIhReverseOptional (aclTensor*) Input Reverse input-hidden bias, which is b in the formula. - Supports empty tensors.
- Supports 1D shape (4 * hidden_size).
FLOAT16 ND 1 √ bHhReverseOptional (aclTensor*) Input Reverse hidden-hidden bias, b in the formula. - Supports empty tensors.
- Shape supports 1D (4 * hidden_size).
FLOAT16 ND 1 √ numLayers (int64_t) Input Indicates the number of LSTM layers. Currently, only 1 is supported. - - - - isbias (bool) Input Indicates whether bias is used. - - - - - batchFirst (bool) Input Indicates whether batch is the first dimension. Only false is supported currently. - - - - bidirection (bool) Input Indicates whether the computation is bidirectional. - - - - - yOut (aclTensor*) Output Output vector of the LSTM unit. The shape supports 3D (time_step, batch_size, hidden_size) or, when bidirection is True, (time_step, batch_size, 2 * hidden_size). FLOAT16 ND 3 √ outputHOut(aclTensor*) Output Final hidden status, h in the formula. The shape supports 3D (num_layers, batch_size, hidden_size) or (2 * num_layers, batch_size, hidden_size) when bidirection is True. FLOAT16 ND 3 √ outputCOut (aclTensor*) Output Final cell status, c in the formula. The shape supports 3D (num_layers, batch_size, hidden_size) or (2 * num_layers, batch_size, hidden_size) when bidirection is True. FLOAT16 ND 3 √ workspaceSize (uint64_t*) Output Returns the size of the workspace to be applied for on the Device side. - - - - - executor (aclOpExecutor**) Output Returns the op executor that contains 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 a passed-in parameter is a required input, output, or required attribute and is a null pointer. |
| ACLNN_ERR_PARAM_INVALID | 161002 | If a passed-in parameter is of the aclTensor type and its data type is not within the supported range. |
| ACLNN_ERR_INNER_TILING_ERROR | 561002 | If the passed-in parameter type is aclTensor and its shape does not match the preceding parameter descriptions. |
aclnnBidirectionLSTM
Parameters:
Parameter Input/Output Description workspace Input The workspace memory address applied on the Device side. workspaceSize Input The workspace size applied on the Device side, obtained by the first-phase API aclnnBidirectionLSTMGetWorkspaceSize. executor Input The op executor, which contains the operator computation flow. stream Input Stream used to execute tasks. Return value
aclnnStatus: return status code. For details, see aclnn Error Codes.
Constraints
- Deterministic computation:
- aclnnBidirectionLSTM defaults to a deterministic implementation.
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 <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_bidirection_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(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("mean result[%ld] is: %f\n", i, resultData[i]);
}
}
int Init(int32_t deviceId, aclrtStream* stream) {
// Boilerplate for resource initialization.
auto ret = aclInit(nullptr);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret);
ret = aclrtSetDevice(deviceId);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret);
ret = aclrtCreateStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret);
return 0;
}
template <typename T>
int CreateAclTensor(const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr,
aclDataType dataType, aclTensor** tensor) {
auto size = GetShapeSize(shape) * sizeof(T);
// Call aclrtMalloc to allocate memory on the device side
auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);
// Call aclrtMemcpy to copy data from the host side to the 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);
// Calculate the strides of a 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;
}
int main() {
// 1. (Boilerplate) Initialize the device/stream. For details, see the acl API manual
// 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 inputs and outputs. The construction needs to be customized according to the API
int time_step = 2;
int batch_size = 32;
int input_size = 32;
int hidden_size = 32;
int64_t numLayers = 1;
bool isbias = true;
bool batchFirst = false;
bool bidirection = true;
std::vector<int64_t> selfShape = {time_step, batch_size, input_size};
std::vector<int64_t> weightHIShape = {4 * hidden_size, input_size};
std::vector<int64_t> weightHHShape = {4 * hidden_size, hidden_size};
std::vector<int64_t> initHShape = {2, batch_size, hidden_size};
std::vector<int64_t> initCShape = {2, batch_size, hidden_size};
std::vector<int64_t> biasHIShape = {4 * hidden_size};
std::vector<int64_t> biasHHShape = {4 * hidden_size};
std::vector<int64_t> outShape = {time_step, batch_size, 2 * hidden_size};
std::vector<int64_t> outHShape = {2, batch_size, hidden_size};
std::vector<int64_t> outCShape = {2, batch_size, hidden_size};
void* selfDeviceAddr = nullptr;
void* weightHIDeviceAddr = nullptr;
void* weightHHDeviceAddr = nullptr;
void* weightHIReverseDeviceAddr = nullptr;
void* weightHHReverseDeviceAddr = nullptr;
void* initHDeviceAddr = nullptr;
void* initCDeviceAddr = nullptr;
void* biasHIDeviceAddr = nullptr;
void* biasHHDeviceAddr = nullptr;
void* biasHIReverseDeviceAddr = nullptr;
void* biasHHReverseDeviceAddr = nullptr;
void* outDeviceAddr = nullptr;
void* outHDeviceAddr = nullptr;
void* outCDeviceAddr = nullptr;
aclTensor* self = nullptr;
aclTensor* weightHI = nullptr;
aclTensor* weightHH = nullptr;
aclTensor* weightHIReverse = nullptr;
aclTensor* weightHHReverse = nullptr;
aclTensor* biasHI = nullptr;
aclTensor* biasHH = nullptr;
aclTensor* biasHIReverse = nullptr;
aclTensor* biasHHReverse = nullptr;
aclTensor* initH = nullptr;
aclTensor* initC = nullptr;
aclTensor* out = nullptr;
aclTensor* outH = nullptr;
aclTensor* outC = nullptr;
std::vector<uint16_t> selfHostData(GetShapeSize(selfShape));
std::vector<uint16_t> weightHIHostData(GetShapeSize(weightHIShape));
std::vector<uint16_t> weightHHHostData(GetShapeSize(weightHHShape));
std::vector<uint16_t> biasHIHostData(GetShapeSize(biasHIShape));
std::vector<uint16_t> biasHHHostData(GetShapeSize(biasHHShape));
std::vector<uint16_t> initHHostData(GetShapeSize(initHShape));
std::vector<uint16_t> initCHostData(GetShapeSize(initCShape));
std::vector<uint16_t> outHostData(GetShapeSize(outShape));
std::vector<uint16_t> outHHostData(GetShapeSize(outHShape));
std::vector<uint16_t> outCHostData(GetShapeSize(outCShape));
ret = CreateAclTensor(selfHostData, selfShape, &selfDeviceAddr, aclDataType::ACL_FLOAT16, &self);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(weightHIHostData, weightHIShape, &weightHIDeviceAddr, aclDataType::ACL_FLOAT16, &weightHI);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(weightHHHostData, weightHHShape, &weightHHDeviceAddr, aclDataType::ACL_FLOAT16, &weightHH);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(initHHostData, initHShape, &initHDeviceAddr, aclDataType::ACL_FLOAT16, &initH);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(initCHostData, initCShape, &initCDeviceAddr, aclDataType::ACL_FLOAT16, &initC);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(biasHIHostData, biasHIShape, &biasHIDeviceAddr, aclDataType::ACL_FLOAT16, &biasHI);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(biasHHHostData, biasHHShape, &biasHHDeviceAddr, aclDataType::ACL_FLOAT16, &biasHH);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(weightHIHostData, weightHIShape, &weightHIReverseDeviceAddr, aclDataType::ACL_FLOAT16, &weightHIReverse);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(weightHHHostData, weightHHShape, &weightHHReverseDeviceAddr, aclDataType::ACL_FLOAT16, &weightHHReverse);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(biasHIHostData, biasHIShape, &biasHIReverseDeviceAddr, aclDataType::ACL_FLOAT16, &biasHIReverse);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(biasHHHostData, biasHHShape, &biasHHReverseDeviceAddr, aclDataType::ACL_FLOAT16, &biasHHReverse);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT16, &out);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(outHHostData, outHShape, &outHDeviceAddr, aclDataType::ACL_FLOAT16, &outH);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(outCHostData, outCShape, &outCDeviceAddr, aclDataType::ACL_FLOAT16, &outC);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API. Replace it with the specific API name
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API of aclnnBidirectionLSTM
ret = aclnnBidirectionLSTMGetWorkspaceSize(self, initH, initC, weightHI, weightHH,
biasHI, biasHH, weightHIReverse, weightHHReverse, biasHIReverse, biasHHReverse,
numLayers, isbias, batchFirst, bidirection,
out, outH, outC,
&workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnBidirectionLSTMGetWorkspaceSize 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 aclnnBidirectionLSTM.
ret = aclnnBidirectionLSTM(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnBidirectionLSTM failed. ERROR: %d\n", ret); return ret);
// 4. (boilerplate) Synchronize and wait for the task 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 result from device memory to host memory. Modify it according to the specific API definition.
PrintOutResult(outShape, &outDeviceAddr);
PrintOutResult(outHShape, &outHDeviceAddr);
PrintOutResult(outCShape, &outCDeviceAddr);
// 6. Release the aclTensor and aclScalar. Modify it according to the specific API definition.
aclDestroyTensor(self);
aclDestroyTensor(weightHI);
aclDestroyTensor(weightHH);
aclDestroyTensor(initH);
aclDestroyTensor(initC);
aclDestroyTensor(biasHI);
aclDestroyTensor(biasHH);
aclDestroyTensor(weightHIReverse);
aclDestroyTensor(weightHHReverse);
aclDestroyTensor(biasHIReverse);
aclDestroyTensor(biasHHReverse);
aclDestroyTensor(out);
aclDestroyTensor(outH);
aclDestroyTensor(outC);
// 7. Release device resources.
aclrtFree(selfDeviceAddr);
aclrtFree(weightHIDeviceAddr);
aclrtFree(weightHHDeviceAddr);
aclrtFree(initHDeviceAddr);
aclrtFree(initCDeviceAddr);
aclrtFree(biasHIDeviceAddr);
aclrtFree(biasHHDeviceAddr);
aclrtFree(weightHIReverseDeviceAddr);
aclrtFree(weightHHReverseDeviceAddr);
aclrtFree(biasHIReverseDeviceAddr);
aclrtFree(biasHHReverseDeviceAddr);
aclrtFree(outDeviceAddr);
aclrtFree(outHDeviceAddr);
aclrtFree(outCDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}