aclnnSwiGluQuantV2

📄 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: Adds a quant operation after the SwiGlu activation function to perform SwiGluQuant computation on input x, supporting int8 or int4 quantized output.

  • Description of API differences: Compared with the aclnnSwiGluQuant API, aclnnSwiGluQuantV2 newly supports the cumsum mode and count mode for groupIndexOptional, with different modes controlled by groupListType; newly supports non-MoE scenarios (groupIndexOptional passes null); and newly supports int8 or int4 quantized output yOut, with different quantized output data types controlled by dstType.

  • Operator support scope: Currently, SwiGluQuant supports MoE scenarios (with groupIndexOptional passed) and non-MoE scenarios (groupIndexOptional passed as null). The inputs x and group_index of SwiGluQuant come from the outputs of the GroupedMatMul operator and MoeInitRouting. The group_index parameter enables MoE group-based dynamic quantization, static per-tensor quantization, and static per-channel quantization.

  • Dynamic quantization formula for MoE scenarios:

    Act=SwiGlu(x)=Swish(A)∗BYtmp0=Act[0 ⁣:g[0], ⁣:]∗smooth_scales[0 ⁣:g[0], ⁣:],i=0Ytmpi=Act[g[i] ⁣:g[i+1], ⁣:]∗smooth_scales[g[i] ⁣:g[i+1], ⁣:],i∈(0,G)∩Zscale=dstTypeScale/row_max(abs(Ytmp))Act = SwiGlu(x) = Swish(A)*B \\ Y_{tmp}^0 = Act[0\colon g[0],\colon] * smooth\_scales[0\colon g[0],\colon], i=0 \\ Y_{tmp}^i = Act[g[i]\colon g[i+1], \colon] * smooth\_scales[g[i]\colon g[i+1], \colon], i \in (0, G) \cap \mathbb{Z}\\ scale=dstTypeScale/row\_max(abs(Y_{tmp})) Y=Cast(Mul(Ytmp,Scale))Y = Cast(Mul(Y_{tmp}, Scale))

    Where A represents the first half of input x, B represents the second half of input x, g represents group_index, and G is the number of groups in group_index. For int8 quantization, dstTypeScale=127dstTypeScale = 127 (127 is the maximum value of int8); for int4 quantization, dstTypeScale=7dstTypeScale = 7 (7 is the maximum value of int4).

  • Static quantization formula for MoE scenarios:

    Act=SwiGLU(x)=Swish(A)∗BYtmp0=Act(0 ⁣:g[0], ⁣:)∗smooth_scales[0 ⁣:g[0], ⁣:]+offsets[0 ⁣:g[0], ⁣:],i=0Ytmpi=Act[g[i] ⁣:g[i+1], ⁣:]∗smooth_scales[g[i] ⁣:g[i+1], ⁣:]+offsets[g[i] ⁣:g[i+1], ⁣:],i∈(0,G)∩ZAct = SwiGLU(x) = Swish(A)*B \\ Y_{tmp}^0 = Act(0\colon g[0],\colon) * smooth\_scales[0\colon g[0],\colon] + offsets[0\colon g[0],\colon], i=0 \\ Y_{tmp}^i = Act[g[i]\colon g[i+1], \colon] * smooth\_scales[g[i]\colon g[i+1], \colon] + offsets[g[i]\colon g[i+1], \colon], i \in (0, G) \cap \mathbb{Z}\\ Y=Cast(Ytmp)Y = Cast(Y_{tmp})

    Where A represents the first half of input x, B represents the second half of input x, g represents group_index, and G is the number of groups in group_index.

  • Non-MoE scenario (groupIndexOptional is passed null) dynamic quantization formula:

    Act=SwiGLU(x)=Swish(A)∗BYtmp=Act∗smooth_scales(0, ⁣:)scale=dstTypeScale/row_max(abs(Ytmp))Act = SwiGLU(x) = Swish(A)*B \\ Y_{tmp} = Act* smooth\_scales(0,\colon)\\ scale=dstTypeScale/row\_max(abs(Y_{tmp})) Y=Cast(Mul(Ytmp,Scale))Y = Cast(Mul(Y_{tmp}, Scale))

    Where A represents the first half of input x, B represents the second half of input x. For int8 quantization, dstTypeScale=127dstTypeScale = 127 (127 is the maximum value of int8); for int4 quantization, dstTypeScale=7dstTypeScale = 7 (7 is the maximum value of int4).

  • Non-MoE scenario (groupIndexOptional is passed null) static quantization formula:

    Act=SwiGLU(x)=Swish(A)∗BYtmp=Act∗smooth_scales(0, ⁣:)+offsets(0, ⁣:)Act = SwiGLU(x) = Swish(A)*B \\ Y_{tmp} = Act * smooth\_scales(0,\colon) + offsets(0,\colon) \\ Y=Cast(Ytmp)Y = Cast(Y_{tmp})

    Where A represents the first half of input x, and B represents the second half of input x.

Function Prototype

Each operator uses a two-phase API. Call the "aclnnSwiGluQuantV2GetWorkspaceSize" API first to obtain the workspace size required for the computation and the executor that contains calculation flow of the operator, and then call the "aclnnSwiGluQuantV2" API to execute the computation.

aclnnStatus aclnnSwiGluQuantV2GetWorkspaceSize(
  const aclTensor *x,
  const aclTensor *smoothScalesOptional,
  const aclTensor *offsetsOptional,
  const aclTensor *groupIndexOptional,
  bool             activateLeft,
  char            *quantModeOptional,
  int64_t          groupListType,
  int64_t          dstType,
  const aclTensor *yOut,
  const aclTensor *scaleOut,
  uint64_t        *workspaceSize,
  aclOpExecutor  **executor)
aclnnStatus aclnnSwiGluQuantV2(
  void            *workspace,
  uint64_t         workspaceSize,
  aclOpExecutor   *executor,
  aclrtStream      stream)

aclnnSwiGluQuantV2GetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    x (aclTensor*) Input Input data to be processed, x in the formula.
    • The last dimension of x must be a multiple of 2, and x must have more than 1 dimension.
    • Currently only supports a last dimension length of x not greater than 8192.
    • When dstType is 29 (indicating that yOut is the INT4 quantized output), the last dimension of x must be a multiple of 4.
    FLOAT16, BFLOAT16, FLOAT ND - ×
    smoothScalesOptional (aclTensor*) Input smooth_scales for quantization, that is, smooth_scales in the formula.
    • Empty tensors are not supported.
    • Supported shapes are [G, N] and [G, ], where G represents the number of groupIndex groups and N is half the size of the last dimension of compute input x.
    FLOAT ND - ×
    offsetsOptional (aclTensor*) Input offsets in the formula.
    • This parameter does not take effect during dynamic quantization. Simply pass an empty pointer.
    • In static quantization: the data type supports FLOAT.
    • In per_channel mode, the supported shape is [G, N].
    • In per_tensor mode, the supported shape is [G, ], and the data type and shape must remain consistent with smoothScalesOptional.
    FLOAT ND - ×
    groupIndexOptional (aclTensor*) Input group_index required for MoE grouping, which is the group_index in the formula. shape: [G, ]. Elements in group_index must be non-decreasing, and the maximum value must not exceed the product of the sizes of all dimensions of input x except the last dimension; G must not exceed this product. INT32 ND -
    activateLeft (bool) Input Represents whether the left matrix participates in the computation. The user must pass the parameter. - - - - -
    quantModeOptional (char*) Input Compute input. User must pass parameters: "static" represents static quantization, "dynamic" represents dynamic quantization, and "dynamic_msd" represents dynamic MSD quantization. Currently only supports "dynamic" dynamic quantization and "static" static quantization. Static quantization only supports per_tensor quantization and per_channel quantization. - - - -
    groupListType (int64_t) Input Compute input. The user must pass the parameter. Currently only supports 0 indicating the cumsum mode and 1 indicating the count mode. - - - -
    dstType (int64_t) Input Compute input. The user must pass the parameter. 2 indicates that yOut is the int8 quantized output, and 29 indicates that yOut is the int4 quantized output. Currently only inputs 2 and 29 are supported, with a default value of 2. - - - -
    yOut (aclTensor*) Output Output tensor. The size of the last dimension of the output yOut shape is half of the last dimension of the compute input x, and the other dimensions remain consistent with x. INT8, INT4 ND - ×
    scaleOut (aclTensor*) Output Output tensor. Compared with compute input x, the shape of output scaleOut excludes the last dimension, and other dimensions remain consistent with compute input x. FLOAT ND - ×
    workspaceSize (uint64_t*) Output Returns the workspace size to be applied on the Device side. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the operator calculation process. - - - - -
  • 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 passed-in x or yOut is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of the input or output is not within the supported range.
    The dimension of the input or output is not within the supported range.
    quantModeOptional is not within the specified value range.
    groupListType is not within the specified value range.
    dstType is not within the specified value range.

aclnnSwiGluQuantV2

  • 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 calling the first-phase API aclnnSwiGluQuantV2GetWorkspaceSize.
    executor Input Op executor, which contains the calculation flow of the operator.
    stream Input Stream for task execution.
  • Return value

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

Constraints

  • Deterministic computation:
    • aclnnSwiGluQuantV2 defaults to a deterministic implementation.

Example

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

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_swi_glu_quant_v2.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, 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.
  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 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) device/stream initialization. Refer to the acl API.
  // Fill in 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 input and output. Custom construction is required based on the API.
  std::vector<int64_t> xShape = {3, 32};
  std::vector<int64_t> smoothScalesShape = {2, 16};
  std::vector<int64_t> groupIndexShape = {2};
  std::vector<int64_t> outShape = {3, 16};
  std::vector<int64_t> scaleShape = {3};
  void* xDeviceAddr = nullptr;
  void* smoothScalesDeviceAddr = nullptr;
  void* groupIndexDeviceAddr = nullptr;
  void* outDeviceAddr = nullptr;
  void* scaleDeviceAddr = nullptr;
  aclTensor* x = nullptr;
  aclTensor* smoothScales = nullptr;
  aclTensor* groupIndex = nullptr;
  aclTensor* out = nullptr;
  aclTensor* scale = nullptr;
  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, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
                                  83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95};
  std::vector<float> smoothScalesHostData = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
                                      1, 1, 1, 1, 1, 1, 1, 1};
  std::vector<int32_t> groupIndexHostData = {1, 3};
  std::vector<int8_t> outHostData = {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};
  std::vector<float> scaleHostData = {0, 0, 0};

  // Create the x aclTensor.
  ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT, &x);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the smoothScales aclTensor.
  ret = CreateAclTensor(smoothScalesHostData, smoothScalesShape, &smoothScalesDeviceAddr, aclDataType::ACL_FLOAT, &smoothScales);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the groupIndex aclTensor.
  ret = CreateAclTensor(groupIndexHostData, groupIndexShape, &groupIndexDeviceAddr, aclDataType::ACL_INT32, &groupIndex);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the out aclTensor.
  ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_INT8, &out);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the scale aclTensor.
  ret = CreateAclTensor(scaleHostData, scaleShape, &scaleDeviceAddr, aclDataType::ACL_FLOAT, &scale);
  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 aclnnSwiGluQuantV2.
  ret = aclnnSwiGluQuantV2GetWorkspaceSize(x, smoothScales, nullptr, groupIndex, false, "dynamic", 0, 2, out, scale, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSwiGluQuantV2GetWorkspaceSize 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 aclnnSwiGluQuantV2.
  ret = aclnnSwiGluQuantV2(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSwiGluQuantV2 failed. ERROR: %d\n", ret); return ret);

  // 4. (boilerplate) Synchronously wait for the 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 value and copy the result on the device side to the host side. Modify it based on the specific API definition.
  auto size = GetShapeSize(outShape);
  std::vector<int8_t> resultData(size, 0);
  ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), outDeviceAddr, 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: %d\n", i, resultData[i]);
  }
  // 6. Release the aclTensor and aclScalar. Modify it based on the specific API definition.
  aclDestroyTensor(x);
  aclDestroyTensor(smoothScales);
  aclDestroyTensor(groupIndex);
  aclDestroyTensor(out);
  aclDestroyTensor(scale);
  // 7. Release the device resources. Modify it based on the specific API definition.
  aclrtFree(xDeviceAddr);
  aclrtFree(smoothScalesDeviceAddr);
  aclrtFree(groupIndexDeviceAddr);
  aclrtFree(outDeviceAddr);
  aclrtFree(scaleDeviceAddr);
  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();
  return 0;
}