aclnnMatmulEmuSplitWeight

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: Simulates FP32-precision matrix multiplication by fusing dual BF16 GEMM paths. The FP32 weight is split offline into the high BF16 weight and the low residual BF16 weight. During inference, two BF16 GEMMs are performed and linearly combined. Activations remain BF16 throughout, and both matrix multiplications run on the Cube.

  • Formula:

    Y=X×Whigh+scale×(X×Wlow)Y = X \times W_{high} + scale \times (X \times W_{low})

    Where XX is the BF16 activation matrix, WhighW_{high} is the high-order weight obtained by truncating the FP32 weight to BF16, WlowW_{low} is the low-order residual weight obtained by dividing the FP32 weight residual by scale and truncating it to BF16, and scalescale is the scaling factor (typically 1/256=0.00390625).

  • Offline weight splitting formula:

    Whigh=BF16(Wfp32)W_{high} = \text{BF16}(W_{fp32}) Wlow=BF16(Wfp32−Whigh.float()scale)W_{low} = \text{BF16}\left(\frac{W_{fp32} - W_{high}.float()}{scale}\right)

Function Prototype

Each operator uses a two-phase API. First call "aclnnMatmulEmuSplitWeightGetWorkspaceSize" to obtain the workspace size required for computation and the executor that contains the operator computation flow, and then call "aclnnMatmulEmuSplitWeight" to perform the computation.

aclnnStatus aclnnMatmulEmuSplitWeightGetWorkspaceSize(
  const aclTensor *x,
  const aclTensor *wHigh,
  const aclTensor *wLow,
  const aclTensor *y,
  float            wLowScale,
  int8_t           yDtype,
  uint64_t        *workspaceSize,
  aclOpExecutor   **executor)
aclnnStatus aclnnMatmulEmuSplitWeight(
  void            *workspace,
  uint64_t         workspaceSize,
  aclOpExecutor   *executor,
  aclrtStream      stream)

aclnnMatmulEmuSplitWeightGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension Non-contiguous
    x Input Represents the activation matrix, corresponding to $X$ in the formula.
  • The data type must be BF16.
  • BFLOAT16 ND 2 √
    wHigh Input Represents the high-order weight, corresponding to $W_{high}$ in the formula.
  • The data type must be BF16, the same as that of x.
  • BFLOAT16 ND 2 √
    wLow Input Low-order residual weight, corresponding to $W_{low}$ in the formula.
  • The data type must be BF16, the same as that of x.
  • The shape must be exactly the same as that of wHigh.
  • BFLOAT16 ND 2 √
    wLowScale Input Scale factor, corresponding to scale in the formula.
  • Only 1/256 (0.00390625) is supported.
  • float - - -
    yDtype Input Output data type identifier.
  • Only 0 (FP32) is supported.
  • int8_t - - -
    y Output Represents the output matrix of the computation, corresponding to $Y$ in the formula.
  • Only FP32 output is supported (yDtype=0).
  • shape is [M, N].
  • FLOAT32 ND 2 √
    workspaceSize Output Returns the workspace size that the user needs to allocate on the Device side. - - - - -
    executor Output Returns the op executor containing 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:

    Return Value Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 The input x, wHigh, wLow, or y is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of x, wHigh, or wLow is not BFLOAT16.
    The data type of y is not FLOAT32.
    yDtype is not 0.
    wLowScale is NaN or Inf, or wLowScale is not equal to 1/256 (0.00390625).
    The data format of the input is not ND.
    The input is not 2D, or the K dimensions do not match (the K dimension of x is inconsistent with that of wHigh/wLow), or the shape of wLow is inconsistent with that of wHigh, or the shape of y does not match [M, N], or M, K, N are not within (0, INT32_MAX].

aclnnMatmulEmuSplitWeight

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the device.
    workspaceSize Input Size of the workspace allocated on the device, obtained by calling the first-phase API aclnnMatmulEmuSplitWeightGetWorkspaceSize.
    executor Input Op executor, which contains the operator computation process.
    stream Input Stream that specifies the task to be executed.
  • Return value

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

Constraints

  • Ascend 950PR&950DT products: aclnnMatmulEmuSplitWeight defaults to a deterministic implementation.
  • Atlas A2 products, Atlas A3 products: aclnnMatmulEmuSplitWeight defaults to a deterministic implementation.
  • Shape constraints:
    • M, K, and N are in the range (0, INT32_MAX].
  • Transpose: The aclnn API itself does not accept a transpose attribute. If transposition is required, the caller should perform permute on the tensor before passing it in. The operator supports non-contiguous tensors, so no additional contiguous operation is required.

Example

The sample code is as follows and 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_matmul_emu_split_weight.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() {
  // 1. Initialize the device/stream.
  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 inputs and outputs.
  // x: BF16 [128, 256], wHigh/wLow: BF16 [256, 128], y: FP32 [128, 128]
  std::vector<int64_t> xShape = {128, 256};
  std::vector<int64_t> wShape = {256, 128};
  std::vector<int64_t> yShape = {128, 128};
  void* xDeviceAddr = nullptr;
  void* wHighDeviceAddr = nullptr;
  void* wLowDeviceAddr = nullptr;
  void* yDeviceAddr = nullptr;
  aclTensor* x = nullptr;
  aclTensor* wHigh = nullptr;
  aclTensor* wLow = nullptr;
  aclTensor* y = nullptr;

  // Construct BF16 data (float is used as a placeholder here; pass BF16 data in actual use).
  std::vector<float> xHostData(128 * 256, 1.0f);
  std::vector<float> wHighHostData(256 * 128, 1.0f);
  std::vector<float> wLowHostData(256 * 128, 0.0f);
  std::vector<float> yHostData(128 * 128, 0.0f);

  ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_BF16, &x);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(wHighHostData, wShape, &wHighDeviceAddr, aclDataType::ACL_BF16, &wHigh);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(wLowHostData, wShape, &wLowDeviceAddr, aclDataType::ACL_BF16, &wLow);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(yHostData, yShape, &yDeviceAddr, aclDataType::ACL_FLOAT, &y);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // 3. Call aclnnMatmulEmuSplitWeight.
  // wLowScale: scale factor. Only 1/256 (0.00390625) is supported.
  // yDtype: output data type. Only 0 (FP32) is supported.
  float wLowScale = 0.00390625f;
  int8_t yDtype = 0;
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor = nullptr;

  ret = aclnnMatmulEmuSplitWeightGetWorkspaceSize(x, wHigh, wLow, y, wLowScale, yDtype, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMatmulEmuSplitWeightGetWorkspaceSize 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 = aclnnMatmulEmuSplitWeight(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMatmulEmuSplitWeight failed. ERROR: %d\n", ret); return ret);

  // 4. Wait synchronously 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.
  auto size = GetShapeSize(yShape);
  std::vector<float> resultData(size, 0);
  ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), yDeviceAddr,
                    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 < std::min(size, 16L); i++) {
    LOG_PRINT("result[%ld] is: %f\n", i, resultData[i]);
  }

  // 6. Release resources.
  aclDestroyTensor(x);
  aclDestroyTensor(wHigh);
  aclDestroyTensor(wLow);
  aclDestroyTensor(y);
  aclrtFree(xDeviceAddr);
  aclrtFree(wHighDeviceAddr);
  aclrtFree(wLowDeviceAddr);
  aclrtFree(yDeviceAddr);
  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();
  return 0;
}