aclnnThnnFusedLstmCell

Applicable Products

ProductSupported
Ascend 950PR/Ascend 950DT×
Atlas A3 training products/Atlas A3 inference products√
Atlas A2 training products/Atlas A2 inference products√
Atlas 200I/500 A2 inference products×
Atlas inference products×
Atlas training products×

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:

    b=bih+bhhgates=inputGates+hiddenGates+biout=σ(gatesi)gout=tanh⁡(gatesg)fout=σ(gatesf)oout=σ(gateso)\begin{aligned} b &= b_{ih} + b_{hh} \\ gates &= inputGates + hiddenGates + b \\ i_{out} &= \sigma(gates_{i}) \\ g_{out} &= \tanh(gates_{g}) \\ f_{out} &= \sigma(gates_{f}) \\ o_{out} &= \sigma(gates_{o}) \end{aligned}

    Update the cell state:

    cyout=fout⊙cx+iout⊙goutcy_{out} = f_{out} \odot cx + i_{out} \odot g_{out}

    Update the hidden state:

    tanhc=tanh⁡(cyout)hyout=oout⊙tanhc\begin{aligned} tanhc &= \tanh(cy_{out}) \\ hy_{out} &= o_{out} \odot tanhc \end{aligned}

    Description of related symbols:

    • Bias bih=inputBiasOptionalb_{ih} = \text{inputBiasOptional}, bhh=hiddenBiasOptionalb_{hh} = \text{hiddenBiasOptional}; zero if no bias is provided.

    • Split gatesgates evenly into four components along the last dimension, i.e., gates→split[gatesi,gatesg,gatesf,gateso]gates \xrightarrow{\text{split}} [gates_i, gates_g, gates_f, gates_o].

    • Concatenate the four gate activation values along the last dimension into storageOut\text{storageOut}, i.e., [iout,gout,fout,oout]→concatstorageOut[i_{out}, g_{out}, f_{out}, o_{out}] \xrightarrow{\text{concat}} \text{storageOut}.

    • σ\sigma is the Sigmoid activation function, and ⊙\odot denotes element-wise product.

Function Prototype

Each operator is divided into a two-phase API. The "aclnnThnnFusedLstmCellGetWorkspaceSize" API must be called first to obtain the workspace size required for computation and the executor that encapsulates the operator computation flow. Then, the "aclnnThnnFusedLstmCell" API is called 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 four gates in the input layer: input gate, cell candidate, forget gate, and output gate. None. FLOAT, FLOAT16 ND (batch_size, 4*hidden_size) √
    hiddenGates (aclTensor*) Input Values of the four gates of the hidden layer. None. FLOAT, FLOAT16 ND (batch_size, 4*hidden_size) √
    cx (aclTensor*) Input Cell state from 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 layer bias. When nullptr is passed, it indicates no bias. When inputBiasOptional is valid, hiddenBiasOptional must also be valid; otherwise, it must be nullptr. FLOAT, FLOAT16 ND (4*hidden_size,) √
    hyOut (aclTensor*) Output Hidden state at the current time step, i.e., the output at the current time step. None. FLOAT, FLOAT16 ND (batch_size, hidden_size) √
    cyOut (aclTensor*) Output Cell state at the current time step. None. FLOAT, FLOAT16 ND (batch_size, hidden_size) √
    storageOut (aclTensor*) Output Activation values of the four 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 side. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - -
  • Return value

    aclnnStatus: return code. For details, see aclnn Return Code.

    The first-phase API performs input parameter validation and returns an error in the following scenarios:

    Return 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 not within the supported range.
    The dimension of the parameter is not within the supported range, or the shape does not satisfy the quantitative relationship between parameters.

aclnnThnnFusedLstmCell

  • Parameters:

    Parameter Input/Output Description
    workspace Input Address of the workspace memory applied for on the Device side.
    workspaceSize Input Size of the workspace applied for on the Device side, obtained through the first-phase API aclnnThnnFusedLstmCellGetWorkspaceSize.
    executor Input Operator executor, which contains the operator computation flow.
    stream Input Specifies the stream for task execution.
  • Return value

aclnnStatus: return code. For details, see aclnn Return Code.

Constraints

  • Deterministic computation: aclnnThnnFusedLstmCell defaults to a deterministic implementation.

  • The data types of all input and output parameters must be consistent.

Example

The following provides example code for reference only. For details about compilation and running, 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 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);
  // Copy host-side data to device-side memory by calling aclrtMemcpy.
  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. 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. Customize the construction based on the API interface.
  // Define variables.
  int64_t batchSize = 3;
  int64_t hiddenSize = 5;

  // Define shapes.
  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 pointer.
  aclTensor* inputGates = nullptr;
  aclTensor* hiddenGates = nullptr;
  aclTensor* cx = nullptr;
  aclTensor* inputBias = nullptr;
  aclTensor* hiddenBias = nullptr;

  // Output ACL Tensor pointer.
  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 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);
  // Apply for 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) Synchronize and wait for 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 from the device memory to the host memory. Modify this step based on the API definition of the specific API.
  // 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]);
  }

  // Destroy the aclTensor.
  aclDestroyTensor(inputGates);
  aclDestroyTensor(hiddenGates);
  aclDestroyTensor(cx);
  aclDestroyTensor(hy);
  aclDestroyTensor(cy);
  aclDestroyTensor(storage);

  // Release the 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;
}