aclnnSituGluGrad

View Source Code

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 gradient computation of the SiTU Gated Linear Unit (SiTU Gated Linear Unit) activation function. Computes the gradient grad_x of the input x based on the upstream gradient gradY and the forward input x.

  • Formula:

    For the given input tensor x (shape [..., cut], where cut is an even number and h = cut // 2) and the upstream gradient gradY (shape [..., h]), aclnnSituGluGrad performs the following computation:

    1. Split x into gate and up based on activateLeft (each with shape [..., h]).

    2. Compute the forward intermediates:

      t=tanh⁡(gateβ),s=σ(gate),situ_a=β⋅t⋅st = \tanh\left(\frac{gate}{\beta}\right), \quad s = \sigma(gate), \quad situ\_a = \beta \cdot t \cdot s

      When linearBeta > 0:

      up′=linearBeta⋅tanh⁡(uplinearBeta)up' = linearBeta \cdot \tanh\left(\frac{up}{linearBeta}\right)

      Otherwise, up' = up.

    3. Product rule:

      grad_situ_a=gradY⋅up′,grad_up′=gradY⋅situ_agrad\_situ\_a = gradY \cdot up', \quad grad\_up' = gradY \cdot situ\_a
    4. gate gradient:

      grad_gate=grad_situ_a⋅s⋅[(1−t2)+β⋅t⋅(1−s)]grad\_gate = grad\_situ\_a \cdot s \cdot \left[ (1 - t^2) + \beta \cdot t \cdot (1 - s) \right]
    5. up gradient:

      • When linearBeta > 0:
      grad_up=grad_up′⋅(1−tanh⁡2(uplinearBeta))grad\_up = grad\_up' \cdot \left(1 - \tanh^2\left(\frac{up}{linearBeta}\right)\right)
      • When linearBeta ≤ 0:
      grad_up=grad_up′grad\_up = grad\_up'
    6. Concatenate grad_gate and grad_up into grad_x based on activateLeft (with the same shape as x).

Function Prototype

Each operator uses a two-phase API. Call "aclnnSituGluGradGetWorkspaceSize" first to obtain the workspace size required for computation and the executor containing the operator computation flow. Then call "aclnnSituGluGrad" to perform computation.

aclnnStatus aclnnSituGluGradGetWorkspaceSize(
    const aclTensor *gradY,
    const aclTensor *x,
    int64_t dim,
    double beta,
    double linearBeta,
    bool activateLeft,
    const aclTensor *out,
    uint64_t *workspaceSize,
    aclOpExecutor **executor)
aclnnStatus aclnnSituGluGrad(
    void *workspace,
    uint64_t workspaceSize,
    aclOpExecutor *executor,
    aclrtStream stream)

aclnnSituGluGradGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Shape (shape) Non-contiguous Tensor
    gradY (aclTensor*) Input Input gradY in the formula, indicating the upstream gradient.
    • Supports empty tensor.
    • The shape is half of x in the dimension corresponding to input parameter dim, and consistent with x in other dimensions.
    • The data type is consistent with x.
    FLOAT, FLOAT16, BFLOAT16 ND 1-8 √
    x (aclTensor*) Input Input x in the formula, indicating the forward input.
    • Supports empty tensor (the output is the corresponding empty tensor).
    • The shape must be even on the dimension corresponding to input parameter dim.
    FLOAT, FLOAT16, BFLOAT16 ND 1-8 √
    dim (int64_t) Input Input dim in the formula, which indicates the dimension index for concatenating and splitting x. Value range: [-x.dim(), x.dim()-1]. - - - -
    beta (double) Input Input beta in the formula, the scaling coefficient of the SiTU gating part. A non-zero value is recommended. - - - -
    linearBeta (double) Input Input linearBeta in the formula. Scaling coefficient of linear tanh on the up path. If the value is less than or equal to 0, no transformation is performed on the up path. - - - - -
    activateLeft (bool) Input activateLeft in the formula, indicating whether gate is the first half when x is split. true indicates that gate is the first half and up is the second half; false indicates that gate is the second half and up is the first half. - - - -
    out(aclTensor*) Output grad_x in the formula, indicating the input gradient.
    • Supports empty tensors.
    • The shape is consistent with x.
    • The data type is consistent with x.
    FLOAT, FLOAT16, BFLOAT16 ND 1-8 ×
    workspaceSize (uint64_t*) Output Returns the workspace size to be allocated on the device. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor containing the operator computation process. - - - - -
  • Return Value

    aclnnStatus: return status code. For details, see aclnn Return Codes.

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

    Return Value Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 gradY, x, or out is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of gradY, x, or out is not within the supported range.
    The shape dimensions of gradY, x, or out are not within the supported range.
    dim is not within the specified value range, or the size of x along the dim dimension is not divisible by 2.
    The number of dimensions of gradY is not consistent with that of x, or the size of gradY along the dim dimension is not half of that of x.
    The data type of gradY does not match that of x.

aclnnSituGluGrad

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address requested on the device.
    workspaceSize Input Size of the workspace requested on the device, obtained by calling the first-phase API aclnnSituGluGradGetWorkspaceSize.
    executor Input Op executor containing the operator computation process.
    stream Input Stream for executing tasks.
  • Return Value

    aclnnStatus: Return status code. For details, see aclnn Return Codes.

Constraints

  • Deterministic computation: aclnnSituGluGrad defaults to a deterministic implementation.

Example

The following sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_situ_glu_grad.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: ACL 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);
    // Call aclrtMemcpy to copy data from the host to the device 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, 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.
    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.
    std::vector<int64_t> xShape = {2, 32};
    std::vector<int64_t> gradYShape = {2, 16};
    std::vector<int64_t> gradXShape = {2, 32};
    void* gradYDeviceAddr = nullptr;
    void* xDeviceAddr = nullptr;
    void* gradXDeviceAddr = nullptr;
    aclTensor* gradY = nullptr;
    aclTensor* x = nullptr;
    aclTensor* gradX = nullptr;
    std::vector<float> gradYHostData = {0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 11, 12, 13, 14, 15,
                                        16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31};
    std::vector<float> xHostData = {0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 11, 12, 13, 14, 15,
                                    16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
                                    32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
                                    48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63};
    std::vector<float> gradXHostData = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

    int64_t dim = -1;
    double beta = 1.0;
    double linearBeta = 0.0;
    bool activateLeft = true;
    // Create the gradY aclTensor.
    ret = CreateAclTensor(gradYHostData, gradYShape, &gradYDeviceAddr, aclDataType::ACL_FLOAT, &gradY);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the x aclTensor.
    ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT, &x);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the gradX aclTensor.
    ret = CreateAclTensor(gradXHostData, gradXShape, &gradXDeviceAddr, aclDataType::ACL_FLOAT, &gradX);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // 3. Call the CANN operator library API.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API of aclnnSituGluGrad.
    ret = aclnnSituGluGradGetWorkspaceSize(gradY, x, dim, beta, linearBeta, activateLeft, gradX,
                                            &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSituGluGradGetWorkspaceSize 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 aclnnSituGluGrad.
    ret = aclnnSituGluGrad(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSituGluGrad failed. ERROR: %d\n", ret); return ret);

    // 4. (boilerplate) Synchronize and wait until the task execution is 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 on the device side to the host side.
    auto size = GetShapeSize(gradXShape);
    std::vector<float> resultData(size, 0);
    ret = aclrtMemcpy(
        resultData.data(), resultData.size() * sizeof(resultData[0]), gradXDeviceAddr, 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 ret);
    for (int64_t i = 0; i < size; i++) {
        LOG_PRINT("result[%ld] is: %f\n", i, resultData[i]);
    }
    // 6. Release aclTensor.
    aclDestroyTensor(gradY);
    aclDestroyTensor(x);
    aclDestroyTensor(gradX);
    // 7. Release device resources.
    aclrtFree(gradYDeviceAddr);
    aclrtFree(xDeviceAddr);
    aclrtFree(gradXDeviceAddr);
    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return 0;
}