aclnnClippedSwigluGrad

📄 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: The backward operator of aclnnClippedSwiglu. It computes the gradient of input x, gradXOut.

  • Calculation Process:

    • Step 1: Axis merging and splitting (merge the axes of x and split it into x0 and x1)
    • Step 2: GroupIndex processing (optional) → Compute the number of valid rows
    • Step 3: Recompute the forward intermediate quantities
    • Step 4: Clamp backward propagation mask computation
    • Step 5: SwiGLU backward gradient computation
    • Step 6: Concatenate gradients for output
    • Step 7: GroupIndex zeroing (optional)
  • Formula for axis merging and splitting:

    Merge the axes of x based on the input parameter dim. The dimensions after merging are [pre, cut, after], where the cut axis is the axis to be split, and pre and after can be 1. Since the elements along the after axis are stored contiguously and the computation is element-wise, merge the cut axis with the after axis to obtain x with dimensions [pre, cut]. The dimensions of gradY after merging are [pre, cut/2].

    Split x based on the interleaved parameter:

    When interleaved is true, it represents odd-even splitting:

    x0[p,h]=x[p,2h],h∈[0,cut/2)\mathbf{x}_0[p, h] = \mathbf{x}[p, 2h], \quad h \in [0, \text{cut}/2) x1[p,h]=x[p,2h+1],h∈[0,cut/2)\mathbf{x}_1[p, h] = \mathbf{x}[p, 2h+1], \quad h \in [0, \text{cut}/2)

    When interleaved is false, it indicates front-back split:

    H=cut/2H = \text{cut} / 2 x0[p,h]=x[p,h],h∈[0,H)\mathbf{x}_0[p, h] = \mathbf{x}[p, h], \quad h \in [0, H) x1[p,h]=x[p,h+H],h∈[0,H)\mathbf{x}_1[p, h] = \mathbf{x}[p, h + H], \quad h \in [0, H)

    Where pp is the pre-dimension index, and hh is the half-width index after splitting.

  • GroupIndex processing formula (when groupIndex is provided):

    trunc=∑g=0G−1groupIndex[g]\text{trunc} = \sum_{g=0}^{G-1} \text{groupIndex}[g] validRows=min⁡(trunc,pre)\text{validRows} = \min(\text{trunc}, \text{pre})

    Where: GG is the number of elements in groupIndex, and all subsequent steps process only the first validRows\text{validRows} rows of data. When groupIndex is not provided, validRows=pre\text{validRows} = \text{pre}.

  • Formula for recomputing forward intermediate quantities:

    x0′=min⁡(x0,l)\mathbf{x}_0' = \min(\mathbf{x}_0, l) x1′=min⁡(max⁡(x1,−l),l)\mathbf{x}_1' = \min(\max(\mathbf{x}_1, -l), l) s=σ(α×x0′)=11+e−α×x0′s = \sigma(\alpha \times \mathbf{x}_0') = \frac{1}{1 + e^{-\alpha \times \mathbf{x}_0'}}

    Where: x0′\mathbf{x}_0' represents x0\mathbf{x}_0 with only the upper bound clamped, x1′\mathbf{x}_1' represents x1\mathbf{x}_1 with both bounds clamped, ss is the sigmoid activation value, α\alpha is the alpha parameter, and ll is the limit parameter.

  • Clamp backward propagation mask formula:

    maskx0=I(x0≤l)\text{mask}_{x_0} = \mathbb{I}(\mathbf{x}_0 \leq l) maskx1=I(−l≤x1≤l)\text{mask}_{x_1} = \mathbb{I}(-l \leq \mathbf{x}_1 \leq l)

    Where I\mathbb{I} is the indicator function, which is 1 if the condition is met and 0 otherwise.

  • SwiGLU backward gradient calculation formula:

    gradx0=grady×(x1′+bias)×s×(1+α×x0′×(1−s))×maskx0\mathbf{grad}_{x_0} = \mathbf{grad}_{y} \times (\mathbf{x}_1' + \text{bias}) \times s \times (1 + \alpha \times \mathbf{x}_0' \times (1 - s)) \times \text{mask}_{x_0} gradx1=grady×x0′×s×maskx1\mathbf{grad}_{x_1} = \mathbf{grad}_{y} \times \mathbf{x}_0' \times s \times \text{mask}_{x_1}

    Where: gradx0\mathbf{grad}_{x_0} is the gradient of x0\mathbf{x}_0, gradx1\mathbf{grad}_{x_1} is the gradient of x1\mathbf{x}_1, and grady\mathbf{grad}_{y} is gradY.

  • Gradient concatenation output formula:

    When interleaved is true:

    gradx[p,2h]=gradx0[p,h]\mathbf{grad}_{x}[p, 2h] = \mathbf{grad}_{x_0}[p, h] gradx[p,2h+1]=gradx1[p,h]\mathbf{grad}_{x}[p, 2h+1] = \mathbf{grad}_{x_1}[p, h]

    When interleaved is false:

    gradx[p,h]=gradx0[p,h],h∈[0,H)\mathbf{grad}_{x}[p, h] = \mathbf{grad}_{x_0}[p, h], \quad h \in [0, H) gradx[p,h+H]=gradx1[p,h],h∈[0,H)\mathbf{grad}_{x}[p, h+H] = \mathbf{grad}_{x_1}[p, h], \quad h \in [0, H)

    where gradx\mathbf{grad}_{x} is gradXOut.

  • GroupIndex zeroing formula (when groupIndex is provided):

    gradx[p,:]=gradx[p,:]×I(p<validRows)\mathbf{grad}_{x}[p, :] = \mathbf{grad}_{x}[p, :] \times \mathbb{I}(p < \text{validRows})

    Finally, reshape the output tensor gradXOut so that the number of its dimensions is the same as that of x before axis merging, and the size of each dimension is the same as that of x.

Function Prototype

Each operator uses a two-phase API. You must first call the "aclnnClippedSwigluGradGetWorkspaceSize" API to obtain the workspace size required for the computation and the executor containing the operator computation process, and then call the "aclnnClippedSwigluGrad" API to perform the computation.

aclnnStatus aclnnClippedSwigluGradGetWorkspaceSize(
    const aclTensor *gradY,
    const aclTensor *x,
    const aclTensor *groupIndexOptional,
    int64_t          dim,
    double           alpha,
    double           limit,
    double           bias,
    bool             interleaved,
    const aclTensor *gradXOut,
    uint64_t        *workspaceSize,
    aclOpExecutor   **executor)
aclnnStatus aclnnClippedSwigluGrad(
    void          *workspace,
    uint64_t       workspaceSize,
    aclOpExecutor *executor,
    aclrtStream    stream)

aclnnClippedSwigluGradGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    gradY (aclTensor*) Input Input gradY in the formula, representing the gradient of the forward output y. The dimensions must be greater than 0, and the size on the dimension specified by the input dim must be half of that of x. Other dimensions must be consistent with x. The data type must be consistent with x and gradXOut. Does not support empty Tensor, and the input does not support containing ±inf or nan. FLOAT, FLOAT16, BFLOAT16 ND 1-8 ×
    x (aclTensor*) Input Input x in the formula, which is the input of the forward operator. Used to recompute the forward intermediate values. The dimension must be greater than 0 and must be an even number in the dimension corresponding to input parameter dim. Does not support empty tensors. The input does not support containing ±inf or nan. FLOAT, FLOAT16, BFLOAT16 ND 1-8 ×
    groupIndexOptional (aclTensor*) Input The input groupIndex in the formula, representing the grouping case. Empty pointers are supported. If the pointer is not empty, the tensor must be 1-dimensional and elements must be greater than or equal to 0. The i-th element represents the number of x batches to be processed by the i-th group, and the sum of elements must be less than or equal to the product of all dimensions before the dim dimension prior to axis merging. Does not support empty tensors. The input does not support containing ±inf or nan. INT64 ND 1 ×
    dim (int64_t) Input Input dim in the formula, representing the dimension index for merging and splitting x. Value range: [-x.dim(), x.dim()-1]. - - - -
    alpha (double) Input Input alpha in the formula, which represents a variant of the parameter used by SwiGlu. It is recommended to be 1.702. - - - -
    limit (double) Input Input limit in the formula, representing the threshold value used by the SwiGlu variant. Must be greater than 0, recommended to be 7.0. - - - -
    bias (double) Input Input bias in the formula, representing the bias parameter used by the SwiGlu variant. Recommended to be 1.0. - - - -
    interleaved (bool) Input Input interleaved in the formula, indicating whether to split x in an odd-even manner. Setting it to true represents odd-even split of x, and setting it to false represents front-back split of x. - - - -
    gradXOut (aclTensor*) Output Output gradXOut in the formula. Does not support empty pointer. The shape must be consistent with x. Does not support empty tensor. FLOAT, FLOAT16, BFLOAT16 ND 1-8 ×
    workspaceSize (uint64_t*) Output Returns the size of the workspace to be applied on the Device side. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - -
  • 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:

    Error Code Error code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 Required parameters gradY/x/gradXOut are nullptr.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of an input or output is not within the supported range.
    ACLNN_ERR_INNER_TILING_ERROR 561002 The shape information of multiple input tensors is inconsistent, or an input attribute is not in the value range (see Parameters for details).

aclnnClippedSwigluGrad

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address applied on the Device side.
    workspaceSize Input Workspace size applied on the Device side, obtained by the first-phase API aclnnClippedSwigluGradGetWorkspaceSize.
    executor Input Op executor, which contains the operator computation flow.
    stream Input Stream for executing tasks.
  • Return value

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

Constraints

  • Deterministic computation: aclnnClippedSwigluGrad defaults to a deterministic implementation.

Example

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

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_clipped_swiglu_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)
{
    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);
    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);
    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);

    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];
    }

    *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
                              shape.data(), shape.size(), *deviceAddr);
    return 0;
}

int main()
{
    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);

    // x shape [2, 32], grad_y shape [2, 16], grad_x shape [2, 32]
    std::vector<int64_t> xShape = {2, 32};
    std::vector<int64_t> gradYShape = {2, 16};
    std::vector<int64_t> gradXOutShape = {2, 32};
    void* xDeviceAddr = nullptr;
    void* gradYDeviceAddr = nullptr;
    void* gradXOutDeviceAddr = nullptr;
    aclTensor* x = nullptr;
    aclTensor* gradY = nullptr;
    aclTensor* gradXOut = nullptr;

    std::vector<float> xHostData(64, 1.0f);
    std::vector<float> gradYHostData(32, 1.0f);
    std::vector<float> gradXOutHostData(64, 0.0f);

    int dim = -1;
    float alpha = 1.702;
    float limit = 7.0;
    float bias = 1.0;
    bool interleaved = true;

    ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT, &x);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(gradYHostData, gradYShape, &gradYDeviceAddr, aclDataType::ACL_FLOAT, &gradY);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(gradXOutHostData, gradXOutShape, &gradXOutDeviceAddr, aclDataType::ACL_FLOAT, &gradXOut);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    ret = aclnnClippedSwigluGradGetWorkspaceSize(gradY, x, nullptr, dim, alpha, limit, bias, interleaved, gradXOut,
                                                 &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnClippedSwigluGradGetWorkspaceSize failed. ERROR: %d\n", ret);
              return ret);

    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);
    }
    ret = aclnnClippedSwigluGrad(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnClippedSwigluGrad failed. ERROR: %d\n", ret); return ret);

    ret = aclrtSynchronizeStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);

    auto size = GetShapeSize(gradXOutShape);
    std::vector<float> resultData(size, 0);
    ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), gradXOutDeviceAddr,
                      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]);
    }

    aclDestroyTensor(x);
    aclDestroyTensor(gradY);
    aclDestroyTensor(gradXOut);
    aclrtFree(xDeviceAddr);
    aclrtFree(gradYDeviceAddr);
    aclrtFree(gradXOutDeviceAddr);
    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return 0;
}