aclnnThnnFusedLstmCell
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: Performs the subsequent computation after matrix multiplication in a single-step forward computation of a long short-term memory (LSTM) cell. Outputs the hidden state and cell state at the current time step, as well as the current forget gate, input gate, output gate, and candidate state for backward computation.
Formula:
Compute the gate activation values:
Update the cell state:
Update the hidden state:
Description of related symbols:
- Bias , ; zero if no bias is provided.
- Split evenly into 4 components along the last dimension, i.e.,
- Concatenate the four gate activation values along the last dimension into , i.e., .
- is the Sigmoid activation function, and is the element-wise product
Function Prototype
Each operator uses a two-phase API. Call the "aclnnThnnFusedLstmCellGetWorkspaceSize" API first to obtain the workspace size required for computation and the executor that contains the operator computation process, and then call the "aclnnThnnFusedLstmCell" API to perform the computation.
aclnnStatus aclnnThnnFusedLstmCellGetWorkspaceSize(
const aclTensor *inputGates,
const aclTensor *hiddenGates,
const aclTensor *cx,
const aclTensor *inputBiasOptional,
const aclTensor *hiddenBiasOptional,
aclTensor *hyOut,
aclTensor *cyOut,
aclTensor *storageOut,
uint64_t *workspaceSize,
aclOpExecutor **executor);aclnnStatus aclnnThnnFusedLstmCell(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
const aclrtStream stream)aclnnThnnFusedLstmCellGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor inputGates (aclTensor*) Input Values of the 4 gates of the input layer, namely the input gate, cell candidate, forget gate, and output gate. None. FLOAT, FLOAT16 ND (batch_size, 4*hidden_size) √ hiddenGates (aclTensor*) Input Values of the 4 gates of the hidden layer. None. FLOAT, FLOAT16 ND (batch_size, 4*hidden_size) √ cx (aclTensor*) Input Cell state of the previous time step. None. FLOAT, FLOAT16 ND (batch_size, hidden_size) √ inputBiasOptional (aclTensor*) Optional input. Optional input bias. Passing nullptr indicates no bias. None. FLOAT, FLOAT16 ND (4*hidden_size,) √ hiddenBiasOptional (aclTensor*) Optional input Optional hidden bias. Passing nullptr indicates no bias. Must be valid if inputBiasOptional is valid; otherwise, must be nullptr. FLOAT, FLOAT16 ND (4*hidden_size,) √ hyOut (aclTensor*) Output Hidden state at the current timestamp, that is, the output at the current timestamp. None. FLOAT, FLOAT16 ND (batch_size, hidden_size) √ cyOut (aclTensor*) Output Cell state at the current timestamp. None. FLOAT, FLOAT16 ND (batch_size, hidden_size) √ storageOut (aclTensor*) Output Activation values of the 4 gates, provided for backward computation. None. FLOAT, FLOAT16 ND (batch_size, 4 * hidden_size) √ workspaceSize (uint64_t*) Output Returns the workspace size to be allocated on the device. - - - - - executor (aclOpExecutor**) Output Returns the op executor, which 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 The input tensor is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type or data format of the parameter is out of the supported range. The dimension of the parameter is out of the supported range, or the shape does not satisfy the quantity relationship between parameters.
aclnnThnnFusedLstmCell
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address allocated on the device. workspaceSize Input Workspace size allocated on the device, obtained by the first-phase API aclnnThnnFusedLstmCellGetWorkspaceSize. executor Input Op executor that contains the operator computation flow. stream Input Stream for task execution. Return value
aclnnStatus: return status code. For details, see aclnn Error Codes.
Constraints
- Deterministic computation: aclnnThnnFusedLstmCell defaults to a deterministic implementation.
- The data types of all input and output parameters must be consistent.
Example
The following sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.
#include <iostream>
#include <cmath>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_thnn_fused_lstm_cell.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) {
auto size = GetShapeSize(shape) * sizeof(T);
// Call aclrtMalloc to request memory on the device
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);
// 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 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 device/stream. 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 the input and output, customized based on the API.
// Define variables.
int64_t batchSize = 3;
int64_t hiddenSize = 5;
// Shape definition.
std::vector<int64_t> biasShape = {hiddenSize * 4};
std::vector<int64_t> commonShape = {batchSize, hiddenSize};
std::vector<int64_t> gatesShape = {batchSize, 4 * hiddenSize};
// Input device address pointer.
void* inputGatesDeviceAddr = nullptr;
void* hiddenGatesDeviceAddr = nullptr;
void* cxDeviceAddr = nullptr;
// Output device address pointer.
void* hyDeviceAddr = nullptr;
void* cyDeviceAddr = nullptr;
void* storageDeviceAddr = nullptr;
// Input ACL Tensor pointers.
aclTensor* inputGates = nullptr;
aclTensor* hiddenGates = nullptr;
aclTensor* cx = nullptr;
aclTensor* inputBias = nullptr;
aclTensor* hiddenBias = nullptr;
// Output ACL Tensor pointers.
aclTensor* hy = nullptr;
aclTensor* cy = nullptr;
aclTensor* storage = nullptr;
std::vector<float> inputGatesHostData(batchSize * hiddenSize * 4, 1.0f);
std::vector<float> hiddenGatesHostData(batchSize * hiddenSize * 4, 1.0f);
std::vector<float> cxHostData(batchSize * hiddenSize, 1.0f);
std::vector<float> hyHostData(batchSize * hiddenSize, 0.0f);
std::vector<float> cyHostData(batchSize * hiddenSize, 0.0f);
std::vector<float> storageHostData(batchSize * hiddenSize * 4, 0.0f);
// Create the input aclTensor.
ret = CreateAclTensor(inputGatesHostData, gatesShape, &inputGatesDeviceAddr, aclDataType::ACL_FLOAT, &inputGates);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(hiddenGatesHostData, gatesShape, &hiddenGatesDeviceAddr, aclDataType::ACL_FLOAT, &hiddenGates);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(cxHostData, commonShape, &cxDeviceAddr, aclDataType::ACL_FLOAT, &cx);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the output aclTensor.
ret = CreateAclTensor(hyHostData, commonShape, &hyDeviceAddr, aclDataType::ACL_FLOAT, &hy);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(cyHostData, commonShape, &cyDeviceAddr, aclDataType::ACL_FLOAT, &cy);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(storageHostData, gatesShape, &storageDeviceAddr, aclDataType::ACL_FLOAT, &storage);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the aclnn API. Replace it with the specific API name.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API of aclnnThnnFusedLstmCell.
ret = aclnnThnnFusedLstmCellGetWorkspaceSize(inputGates, hiddenGates, cx, inputBias, hiddenBias, hy, cy, storage,
&workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnThnnFusedLstmCellGetWorkspaceSize 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 aclnnThnnFusedLstmCell.
ret = aclnnThnnFusedLstmCell(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnThnnFusedLstmCell failed. ERROR: %d\n", ret); return ret);
// 4. (boilerplate) Synchronously 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 value and copy the result from device memory to host memory. Modify the code based on the specific API definition.
// Print the hy result.
auto commonSize = GetShapeSize(commonShape);
std::vector<float> resultData(commonSize, 0);
ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), hyDeviceAddr,
commonSize * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy hy result from device to host failed. ERROR: %d\n", ret); return ret);
for (int64_t i = 0; i < commonSize and i < 10; i++) {
LOG_PRINT("result hy[%ld] is: %f\n", i, resultData[i]);
}
// Release the aclTensor.
aclDestroyTensor(inputGates);
aclDestroyTensor(hiddenGates);
aclDestroyTensor(cx);
aclDestroyTensor(hy);
aclDestroyTensor(cy);
aclDestroyTensor(storage);
// Release Device resources.
aclrtFree(inputGatesDeviceAddr);
aclrtFree(hiddenGatesDeviceAddr);
aclrtFree(cxDeviceAddr);
aclrtFree(hyDeviceAddr);
aclrtFree(cyDeviceAddr);
aclrtFree(storageDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}