aclnnConvertWeightToINT4Pack

📄 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

Preprocesses input weight data to convert the layout of low-bit data from sparse storage to tightly packed storage. When the data format of output weightInt4Pack is declared as FRACTAL_NZ, this operator converts the data format from ND to FRACTAL_NZ.

  • Atlas A2 products, Atlas A3 products: Packs weight input data of type INT32 into tightly packed INT4 data.
  • Ascend 950PR&950DT products: Pack the weight of type INT32 as tightly packed INT4, and pack the weight of type FLOAT as tightly packed FLOAT4_E2M1.

Function Prototype

Each operator uses a two-phase API. You must first call the "aclnnConvertWeightToINT4PackGetWorkspaceSize" API to obtain the workspace size required for the computation and the executor that contains the computation flow of the operator, and then call the "aclnnConvertWeightToINT4Pack" API to execute the computation.

aclnnStatus aclnnConvertWeightToINT4PackGetWorkspaceSize(
  const aclTensor *weight,
  aclTensor       *weightInt4Pack,
  uint64_t        *workspaceSize,
  aclOpExecutor   **executor)
aclnnStatus aclnnConvertWeightToINT4Pack(
  void            *workspace,
  uint64_t         workspaceSize,
  aclOpExecutor   *executor,
  aclrtStream      stream)

aclnnConvertWeightToINT4PackGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    weight Input Low-bit quantized weight of Matmul operators, with 4-bit weight values carried by 32-bit data. - INT32 ND 2-3 -
    weightInt4Pack Output Low-bit quantized weight of Matmul operators, with 4-bit weight values tightly packed. - INT4,INT32 ND,FRACTAL_NZ - -
    workspaceSize Output Returns the Device side-applied workspace size. - - - - -
    executor Output Returns the op executor, which contains the operator computation flow. - - - - -
  • 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 If a mandatory input, output, or attribute passed in is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The shape dimensions of the passed-in weight and weightInt4Pack do not meet requirements.
    The data types of the passed-in weight and weightInt4Pack are not within the supported range.
    The shape sizes of the passed-in weight and weightInt4Pack do not meet the constraints.
    An empty tensor is passed in.
    The Format of the input tensor is not ND.
    ACLNN_ERR_RUNTIME_ERROR 361001 An exception occurs when data is copied from the host to the device.
    An exception occurs when data is copied from the device to the host.

aclnnConvertWeightToINT4Pack

  • Parameters

    Parameter Input/Output Description
    workspace Input Address of the workspace memory side-applied on the Device.
    workspaceSize Input Size of the workspace memory side-applied on the Device, obtained by the first-phase API aclnnConvertWeightToINT4PackGetWorkspaceSize.
    executor Input Op executor, which contains the computation process of the operator.
    stream Input Specifies the stream that executes the task.
  • Return value

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

Constraints

  • Deterministic computation:

    • Atlas A2 products, Atlas A3 products, and Ascend 950PR&950DT products: aclnnConvertWeightToINT4Pack defaults to a deterministic implementation.
  • The data type and data format relationships between parameters are as follows:

    • Atlas A2 products, Atlas A3 products:
      weight Data Type weight Data Format weightInt4Pack Data Type weightInt4Pack Data Format weight shape weightInt4Pack view shape weightInt4Pack storage shape
      INT32 (carries INT4 type data, data representation range [-8, 7]) ND INT4 ND The last dimension is aligned to 2. Consistent with input weight, that is, (dim0, dim1). Same as view shape.
      INT32 (carries INT4 type data, with a data representation range of [-8, 7]) ND INT4 FRACTAL_NZ The last dimension is aligned to 2. Consistent with input weight, i.e., (dim0, dim1). (⌈dim1/64⌉, ⌈dim0/16⌉, 16, 64)
      INT32 (carrying INT4 type data, data representation range [-8, 7]). ND INT32 (1 INT32 data item stores 8 INT4 data items). ND The last dimension is aligned to 8. The last dimension is 1/8 of the last dimension of weight, i.e., (dim0, dim1/8). Same as view shape.
      INT32 (carrying INT4 type data, data representation range [-8, 7]). ND INT32 (1 INT32 data stores 8 INT4 data) FRACTAL_NZ The last dimension is aligned to 8. The last dimension is 1/8 of the last dimension of weight, i.e., (dim0, dim1/8). (⌈dim1/64⌉, ⌈dim0/16⌉, 16, 8)
    • Ascend 950PR&950DT products:
      weight Data Type weight Data Format weightInt4Pack Data Type weightInt4Pack Data Format weight shape weightInt4Pack view shape weightInt4Pack storage shape
      INT32 (carrying INT4 type data, data representation range [-8, 7]) or FLOAT (carrying FLOAT4_E2M1 type data, data representation range [-6.0, 6.0]) ND INT4 or FLOAT4_E2M1 ND The last dimension is aligned to 2. Consistent with the input weight, i.e., (dim0, dim1). Same as view shape
      INT32 (carrying INT4 type data, data representation range [-8, 7]) or FLOAT (carrying FLOAT4_E2M1 type data, data representation range [-6.0, 6.0]) ND INT4 or FLOAT4_E2M1 FRACTAL_NZ The last dimension is aligned to 2. Remains consistent with input weight, i.e., (dim0, dim1). (⌈dim1/16⌉, ⌈dim0/16⌉, 16, 16)
      INT32 (carrying INT4 type data, data representation range [-8, 7]) or FLOAT (carrying FLOAT4_E2M1 type data, data representation range [-6.0, 6.0]) ND INT32 (one INT32 data item stores 8 INT4 data items) or FLOAT (one FLOAT data item stores 8 FLOAT4_E2M1 data items) ND The last dimension is aligned to 8. The last dimension is 1/8 of the last dimension of weight, that is, (dim0, dim1/8). Same as view shape.
      INT32 (carrying data of the INT4 type, with a data representation range of [-8, 7]) or FLOAT (carrying data of the FLOAT4_E2M1 type, with a data representation range of [-6.0, 6.0]) ND INT32 (one INT32 data item stores 8 INT4 data items) or FLOAT (one FLOAT data item stores 8 FLOAT4_E2M1 data items) FRACTAL_NZ The last dimension is aligned to 8. The last dimension is 1/8 of the last dimension of weight, i.e. (dim0, dim1/8). (⌈dim1/16⌉, ⌈dim0/16⌉, 16, 2)
      INT32 (carries INT4 type data, data representation range [-8, 7]) ND INT4 (one INT32 data stores 8 INT4 data) FRACTAL_NZ The last dimension is aligned to 8. The last dimension is 1/8 of the last dimension of weight, i.e. (dim0, dim1/8). (⌈dim1/32⌉, ⌈dim0/16⌉, 16, 32)

Example

  • Atlas A2 products, Atlas A3 products: The following sample code is for reference only. For details about compilation and execution, see Compile and Run Samples. aclnnWeightQuantBatchMatmulV2 and aclnnWeightQuantBatchMatmulV3 APIs are available for pseudo-quantization. Here, aclnnWeightQuantBatchMatmulV2 is used as an example.

    #include <iostream>
    #include <vector>
    #include "acl/acl.h"
    #include "aclnnop/aclnn_cast.h"
    #include "aclnnop/aclnn_weight_quant_batch_matmul_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)
    
    #define CEIL_DIV(x, y) ((((x) + (y)) - 1) / (y))
    #define CEIL_ALIGN(x, y) ((((x) + (y)) - 1) / (y) * (y))
    
    int64_t GetShapeSize(const std::vector<int64_t>& shape) {
      int64_t shapeSize = 1;
      for (auto i : shape) {
        shapeSize *= i;
      }
      return shapeSize;
    }
    
    extern "C" aclnnStatus aclnnConvertWeightToINT4PackGetWorkspaceSize(const aclTensor *weight, aclTensor *weightInt4Pack,
        uint64_t *workspaceSize, aclOpExecutor **executor);
    
    extern "C" aclnnStatus aclnnConvertWeightToINT4Pack(void *workspace, uint64_t workspaceSize, aclOpExecutor *executor,
        aclrtStream stream);
    
    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 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 host data to 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;
    }
    
    template <typename T>
    int CreateAclTensorInt4(const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr,
                        aclDataType dataType, aclTensor** tensor, aclFormat format) {
      auto size = hostData.size() * 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 host data to 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.
      if (format == aclFormat::ACL_FORMAT_ND) {
        *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
                                  shape.data(), shape.size(), *deviceAddr);
      } else {
        std::vector<int64_t> nzShape;
        if (dataType == aclDataType::ACL_INT4) {
            nzShape = {CEIL_DIV(shape[1], 64), CEIL_DIV(shape[0], 16), 16, 64};
        } else {
            nzShape = {CEIL_DIV(shape[1], 64), CEIL_DIV(shape[0], 16), 16, 8};
        }
        *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0,
                                  aclFormat::ACL_FORMAT_FRACTAL_NZ, nzShape.data(), nzShape.size(), *deviceAddr);
      }
    
      return 0;
    }
    
    int main() {
      // 1. (Boilerplate) Initialize device/stream. Refer to the acl API manual.
      // 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);
      aclDataType weightInt4PackDtype = aclDataType::ACL_INT4;
      aclFormat weightFormat = aclFormat::ACL_FORMAT_FRACTAL_NZ;
      bool isWeightTransposed = true;
    
      // 2. Construct the input and output. Custom construction is required based on the API.
      int64_t m = 16;
      int64_t k = 72;
      int64_t n = 17;
      int64_t weightDim0 = k;
      int64_t weightDim1 = n;
      if (isWeightTransposed) {
        weightDim0 = n;
        weightDim1 = k;
      }
      std::vector<int64_t> xShape = {m, k};
      std::vector<int64_t> weightShape = {weightDim0, weightDim1};
      std::vector<int64_t> weightInt4PackShape;
      if (weightInt4PackDtype == aclDataType::ACL_INT4) {
        weightInt4PackShape = {weightDim0, weightDim1};
      } else {
        weightInt4PackShape = {weightDim0, weightDim1/8};
      }
      std::vector<int64_t> yShape = {m, n};
      void* xDeviceAddr = nullptr;
      void* weightDeviceAddr = nullptr;
      void* weightInt4PackDeviceAddr = nullptr;
      void* yDeviceAddr = nullptr;
      aclTensor* x = nullptr;
      aclTensor* weight = nullptr;
      aclTensor* weightInt4Pack = nullptr;
      aclTensor* y = nullptr;
      std::vector<float> xHostData(m * k, 1);
      std::vector<int32_t> weightHostData(k * n, 1);
      std::vector<float> yHostData(m * n, 0);
    
      std::vector<int64_t> antiquantScaleShape = {n};
      void* antiquantScaleDeviceAddr = nullptr;
      aclTensor* antiquantScale = nullptr;
      std::vector<float> antiquantScaleHostData(n, 1);
    
      // Create x aclTensor.
      ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT, &x);
      CHECK_RET(ret == ACL_SUCCESS, return ret);
      // Create weight aclTensor.
      ret = CreateAclTensor(weightHostData, weightShape, &weightDeviceAddr, aclDataType::ACL_INT32, &weight);
      CHECK_RET(ret == ACL_SUCCESS, return ret);
      if (weightInt4PackDtype == aclDataType::ACL_INT4) {
        std::vector<int8_t> weightInt4PackHostData(n * k / 2, 0); // One int8 data stores 2 int4 data, so divide by 2 here.
        if (weightFormat == aclFormat::ACL_FORMAT_FRACTAL_NZ) {
          weightInt4PackHostData.resize(CEIL_ALIGN(weightDim1/2, 32) * CEIL_ALIGN(weightDim0, 16), 0);
        }
        // Create weightInt4Pack aclTensor.
        ret = CreateAclTensorInt4(weightInt4PackHostData, weightInt4PackShape, &weightInt4PackDeviceAddr,
                                  weightInt4PackDtype, &weightInt4Pack, weightFormat);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
      } else {
        std::vector<int32_t> weightInt4PackHostData(n * k / 8, 1); // One int32 data stores 8 int4 data, so divide by 8 here.
        if (weightFormat == aclFormat::ACL_FORMAT_FRACTAL_NZ) {
          weightInt4PackHostData.resize(CEIL_ALIGN(weightDim1/8, 8) * CEIL_ALIGN(weightDim0, 16), 0);
          ret = CreateAclTensorInt4(weightInt4PackHostData, weightInt4PackShape, &weightInt4PackDeviceAddr,
                                    weightInt4PackDtype, &weightInt4Pack, weightFormat);
        } else {
            // Create weightInt4Pack aclTensor.
            ret = CreateAclTensor(weightInt4PackHostData, weightInt4PackShape, &weightInt4PackDeviceAddr,
                                  weightInt4PackDtype, &weightInt4Pack);
        }
        CHECK_RET(ret == ACL_SUCCESS, return ret);
      }
      // Create y aclTensor.
      ret = CreateAclTensor(yHostData, yShape, &yDeviceAddr, aclDataType::ACL_FLOAT, &y);
      CHECK_RET(ret == ACL_SUCCESS, return ret);
      // Create antiquantScale aclTensor.
      ret = CreateAclTensor(antiquantScaleHostData, antiquantScaleShape, &antiquantScaleDeviceAddr, aclDataType::ACL_FLOAT, &antiquantScale);
      CHECK_RET(ret == ACL_SUCCESS, return ret);
    
      // Create xFp16 aclTensor.
      void* xFp16DeviceAddr = nullptr;
      aclTensor* xFp16 = nullptr;
      ret = CreateAclTensor(xHostData, xShape, &xFp16DeviceAddr, aclDataType::ACL_FLOAT16, &xFp16);
      CHECK_RET(ret == ACL_SUCCESS, return ret);
      // Create antiquantScale aclTensor.
      void* antiquantScaleFp16DeviceAddr = nullptr;
      aclTensor* antiquantScaleFp16 = nullptr;
      ret = CreateAclTensor(antiquantScaleHostData, antiquantScaleShape, &antiquantScaleFp16DeviceAddr, aclDataType::ACL_FLOAT16, &antiquantScaleFp16);
      CHECK_RET(ret == ACL_SUCCESS, return ret);
      // Create yFp16 aclTensor.
      void* yFp16DeviceAddr = nullptr;
      aclTensor* yFp16 = nullptr;
      ret = CreateAclTensor(yHostData, yShape, &yFp16DeviceAddr, aclDataType::ACL_FLOAT16, &yFp16);
      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;
      void* workspaceAddr = nullptr;
    
      // Convert weight from int32 to int4pack.
      ret = aclnnConvertWeightToINT4PackGetWorkspaceSize(weight, weightInt4Pack, &workspaceSize, &executor);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnConvertWeightToINT4PackGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
      ret = aclnnConvertWeightToINT4Pack(workspaceAddr, workspaceSize, executor, stream);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnConvertWeightToINT4Pack failed. ERROR: %d\n", ret); return ret);
    
      // If weight is in the transpose use case and the weightInt4Pack shape is NZ, call aclInitTensor to convert it to a non-contiguous tensor.
      if (isWeightTransposed && weightFormat == aclFormat::ACL_FORMAT_FRACTAL_NZ) {
        std::vector<int64_t> strides(weightInt4PackShape.size(), 1);
        for (int64_t i = weightInt4PackShape.size() - 2; i >= 0; i--) {
            strides[i] = weightInt4PackShape[i + 1] * strides[i + 1];
        }
        std::swap(strides[0], strides[1]);
        std::swap(weightInt4PackShape[0], weightInt4PackShape[1]);
        std::vector<int64_t> nzShape = {CEIL_DIV(k, 64), CEIL_DIV(n, 16), 16, 8};
        if (weightInt4PackDtype == aclDataType::ACL_INT4) {
            nzShape[3] = 64;
        }
        aclInitTensor(weightInt4Pack, weightInt4PackShape.data(), weightInt4PackShape.size(), weightInt4PackDtype, strides.data(), 0,
                      weightFormat, nzShape.data(), nzShape.size(), weightInt4PackDeviceAddr);
      }
    
      // Call cast to generate the FP16 input.
      ret = aclnnCastGetWorkspaceSize(x, aclDataType::ACL_FLOAT16, xFp16, &workspaceSize, &executor);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCastGetWorkspaceSize0 failed. ERROR: %d\n", ret); return ret);
      // Allocate device memory based on the workspaceSize computed by the first-phase API.
    
      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 = aclnnCast(workspaceAddr, workspaceSize, executor, stream);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCast0 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);
    
      ret = aclnnCastGetWorkspaceSize(antiquantScale, aclDataType::ACL_FLOAT16, antiquantScaleFp16, &workspaceSize, &executor);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCastGetWorkspaceSize1 failed. ERROR: %d\n", ret); return ret);
      // Allocate device memory based on the workspaceSize computed by the first-phase API.
    
      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 = aclnnCast(workspaceAddr, workspaceSize, executor, stream);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCast1 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);
    
      // Call the aclnnWeightQuantBatchMatmulV2 first-phase API.
      ret = aclnnWeightQuantBatchMatmulV2GetWorkspaceSize(xFp16, weightInt4Pack, antiquantScaleFp16, nullptr, nullptr, nullptr, nullptr, 0, yFp16, &workspaceSize, &executor);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnWeightQuantBatchMatmulV2GetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
      // Allocate device memory based on the workspaceSize computed by the first-phase API.
    
      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 aclnnWeightQuantBatchMatmulV2 second-phase API.
      ret = aclnnWeightQuantBatchMatmulV2(workspaceAddr, workspaceSize, executor, stream);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnWeightQuantBatchMatmulV2 failed. ERROR: %d\n", ret); return ret);
    
      // 4. (boilerplate) Synchronize and 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);
    
    // Convert the output to FP32.
      ret = aclnnCastGetWorkspaceSize(yFp16, aclDataType::ACL_FLOAT, y, &workspaceSize, &executor);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCastGetWorkspaceSize2 failed. ERROR: %d\n", ret); return ret);
      // Allocate device memory based on the workspaceSize computed by the first-phase API.
    
      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 = aclnnCast(workspaceAddr, workspaceSize, executor, stream);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCast2 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);
    
      // 5. Obtain the output value and copy the result in device-side memory to the host side. Modify it based on the specific API definition.
      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 < size; i++) {
        LOG_PRINT("result[%ld] is: %f\n", i, resultData[i]);
      }
    
      // 6. Release aclTensor and aclScalar. Modify it based on the specific API definition.
      aclDestroyTensor(x);
      aclDestroyTensor(weight);
      aclDestroyTensor(weightInt4Pack);
      aclDestroyTensor(antiquantScale);
      aclDestroyTensor(y);
      aclDestroyTensor(xFp16);
      aclDestroyTensor(antiquantScaleFp16);
      aclDestroyTensor(yFp16);
    
      // 7. Release device resources.
      aclrtFree(xDeviceAddr);
      aclrtFree(weightDeviceAddr);
      aclrtFree(weightInt4PackDeviceAddr);
      aclrtFree(antiquantScaleDeviceAddr);
      aclrtFree(yDeviceAddr);
      aclrtFree(xFp16DeviceAddr);
      aclrtFree(antiquantScaleFp16DeviceAddr);
      aclrtFree(yFp16DeviceAddr);
    
      if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
      }
      aclrtDestroyStream(stream);
      aclrtResetDevice(deviceId);
      aclFinalize();
    
      return 0;
    }
  • Ascend 950PR&950DT products:

    The sample code below (INT32 input) is for reference only. For details about compilation and execution, see Compile and Run Samples. For the FRACTAL_NZ use case on Ascend 950, call the aclnnWeightQuantBatchMatmulNz API. Here, aclnnWeightQuantBatchMatmulNz is used as an example.

    #include <iostream>
    #include <memory>
    #include <vector>
    #include "acl/acl.h"
    #include "aclnnop/aclnn_cast.h"
    #include "aclnnop/aclnn_convert_weight_to_int4_pack.h"
    #include "aclnnop/aclnn_weight_quant_batch_matmul_nz.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)
    
    #define CEIL_DIV(x, y) ((((x) + (y)) - 1) / (y))
    
    int64_t GetShapeSize(const std::vector<int64_t>& shape) {
      int64_t shapeSize = 1;
      for (auto i : shape) {
        shapeSize *= i;
      }
      return shapeSize;
    }
    
    // Boilerplate for resource initialization.
    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;
    }
    
    // Create an aclTensor in ND format with contiguous layout, and copy hostData to the device.
    // The device-side memory size is allocated based on the actual byte size of hostData (each element occupies sizeof(T) bytes).
    template <typename T>
    int CreateAclTensor(const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr,
                        aclDataType dataType, aclTensor** tensor) {
      auto size = hostData.size() * 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);
    
      // 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;
    }
    
    // Create an aclTensor with tightly packed 4bit (INT4/FLOAT4_E2M1) data and FRACTAL_NZ storage format.
    // Pass in the logical shape as the original ND matrix (k, n); on Ascend 950, the storageShape of NZ is (ceil(n/16), ceil(k/16), 16, 16),
    // each block contains 16 * 16 4bit data items (occupying 128 bytes), and device-side memory is allocated based on the size of storageShape,
    // hostData is the packed byte data (2 int4 values stored in 1 int8); copy only hostData.size() bytes,
    // the tail alignment part does not need initialization; after aclnnConvertWeightToINT4Pack is called, the entire memory block is rewritten.
    template <typename T>
    int CreateAclTensorNz(const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr,
                          aclDataType dataType, aclTensor** tensor) {
      auto size = CEIL_DIV(shape[1], 16) * CEIL_DIV(shape[0], 16) * 128;
      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, hostData.size() * sizeof(T), hostData.data(), hostData.size() * sizeof(T),
                        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; compute the storageShape based on the NZ block layout.
      std::vector<int64_t> nzShape = {CEIL_DIV(shape[1], 16), CEIL_DIV(shape[0], 16), 16, 16};
      *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0,
                                aclFormat::ACL_FORMAT_FRACTAL_NZ, nzShape.data(), nzShape.size(), *deviceAddr);
      return 0;
    }
    
    int main() {
      // 1. (Boilerplate) Initialize the device/stream. For details, see the acl API documentation.
      // 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 inputs and outputs.
      // This example is for the NZ use case: the storage format of weightInt4Pack is FRACTAL_NZ, and matmul needs to call the aclnnWeightQuantBatchMatmulNz API.
      // (On Ascend 950, the weight of the aclnnWeightQuantBatchMatmulV2/V3 APIs supports only the ND format.)
      // Computation scale: x is (m, k), weight is (k, n), and y is (m, n).
      // All input data are 1, all antiquantScale values are 1, and each element of the expected y is k.
      int64_t m = 16;
      int64_t k = 64;
      int64_t n = 64;
      std::vector<int64_t> xShape = {m, k};
      std::vector<int64_t> weightShape = {k, n};
      std::vector<int64_t> weightInt4PackShape = {k, n}; // Shape of INT4, passed in as the number of elements.
      std::vector<int64_t> antiquantScaleShape = {n};    // Shape of scale in the perchannel use case: (n,).
      std::vector<int64_t> yShape = {m, n};
    
      std::vector<float> xHostData(m * k, 1);
      std::vector<int32_t> weightHostData(k * n, 1); // INT32 weight, where each int32 carries 1 int4 value.
      std::vector<float> antiquantScaleHostData(n, 1);
      std::vector<float> yHostData(m * n, 0);
      // After INT4 is tightly packed, 2 int4 values are stored in 1 int8; the number of host data items is half the number of weight elements.
      std::vector<int8_t> weightInt4PackHostData(k * n / 2, 0);
    
      // 3. Create the input and output aclTensors. Both aclTensors and device memory are managed by unique_ptr and are automatically released when exiting through any path.
      // Create the x aclTensor (FP32).
      void* xDeviceAddr = nullptr;
      aclTensor* x = nullptr;
      ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT, &x);
      CHECK_RET(ret == ACL_SUCCESS, return ret);
      std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> xTensorPtr(x, aclDestroyTensor);
      std::unique_ptr<void, aclError (*)(void*)> xDeviceAddrPtr(xDeviceAddr, aclrtFree);
      // Create the weight aclTensor (INT32).
      void* weightDeviceAddr = nullptr;
      aclTensor* weight = nullptr;
      ret = CreateAclTensor(weightHostData, weightShape, &weightDeviceAddr, aclDataType::ACL_INT32, &weight);
      CHECK_RET(ret == ACL_SUCCESS, return ret);
      std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> weightTensorPtr(weight, aclDestroyTensor);
      std::unique_ptr<void, aclError (*)(void*)> weightDeviceAddrPtr(weightDeviceAddr, aclrtFree);
      // Create the weightInt4Pack aclTensor (INT4, FRACTAL_NZ) to store the packed weight.
      void* weightInt4PackDeviceAddr = nullptr;
      aclTensor* weightInt4Pack = nullptr;
      ret = CreateAclTensorNz(weightInt4PackHostData, weightInt4PackShape, &weightInt4PackDeviceAddr,
                              aclDataType::ACL_INT4, &weightInt4Pack);
      CHECK_RET(ret == ACL_SUCCESS, return ret);
      std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> weightInt4PackTensorPtr(weightInt4Pack, aclDestroyTensor);
      std::unique_ptr<void, aclError (*)(void*)> weightInt4PackDeviceAddrPtr(weightInt4PackDeviceAddr, aclrtFree);
      // Create the antiquantScale aclTensor (FP32).
      void* antiquantScaleDeviceAddr = nullptr;
      aclTensor* antiquantScale = nullptr;
      ret = CreateAclTensor(antiquantScaleHostData, antiquantScaleShape, &antiquantScaleDeviceAddr,
                            aclDataType::ACL_FLOAT, &antiquantScale);
      CHECK_RET(ret == ACL_SUCCESS, return ret);
      std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> antiquantScaleTensorPtr(antiquantScale, aclDestroyTensor);
      std::unique_ptr<void, aclError (*)(void*)> antiquantScaleDeviceAddrPtr(antiquantScaleDeviceAddr, aclrtFree);
      // Create the y aclTensor (FP32).
      void* yDeviceAddr = nullptr;
      aclTensor* y = nullptr;
      ret = CreateAclTensor(yHostData, yShape, &yDeviceAddr, aclDataType::ACL_FLOAT, &y);
      CHECK_RET(ret == ACL_SUCCESS, return ret);
      std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> yTensorPtr(y, aclDestroyTensor);
      std::unique_ptr<void, aclError (*)(void*)> yDeviceAddrPtr(yDeviceAddr, aclrtFree);
      // Create the xFp16 aclTensor (FP16). matmul requires x and antiquantScale to have consistent data types.
      void* xFp16DeviceAddr = nullptr;
      aclTensor* xFp16 = nullptr;
      ret = CreateAclTensor(xHostData, xShape, &xFp16DeviceAddr, aclDataType::ACL_FLOAT16, &xFp16);
      CHECK_RET(ret == ACL_SUCCESS, return ret);
      std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> xFp16TensorPtr(xFp16, aclDestroyTensor);
      std::unique_ptr<void, aclError (*)(void*)> xFp16DeviceAddrPtr(xFp16DeviceAddr, aclrtFree);
      // Create the antiquantScaleFp16 aclTensor (FP16).
      void* antiquantScaleFp16DeviceAddr = nullptr;
      aclTensor* antiquantScaleFp16 = nullptr;
      ret = CreateAclTensor(antiquantScaleHostData, antiquantScaleShape, &antiquantScaleFp16DeviceAddr,
                            aclDataType::ACL_FLOAT16, &antiquantScaleFp16);
      CHECK_RET(ret == ACL_SUCCESS, return ret);
      std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> antiquantScaleFp16TensorPtr(antiquantScaleFp16, aclDestroyTensor);
      std::unique_ptr<void, aclError (*)(void*)> antiquantScaleFp16DeviceAddrPtr(antiquantScaleFp16DeviceAddr, aclrtFree);
      // Create the yFp16 aclTensor (FP16), the output of matmul.
      void* yFp16DeviceAddr = nullptr;
      aclTensor* yFp16 = nullptr;
      ret = CreateAclTensor(yHostData, yShape, &yFp16DeviceAddr, aclDataType::ACL_FLOAT16, &yFp16);
      CHECK_RET(ret == ACL_SUCCESS, return ret);
      std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> yFp16TensorPtr(yFp16, aclDestroyTensor);
      std::unique_ptr<void, aclError (*)(void*)> yFp16DeviceAddrPtr(yFp16DeviceAddr, aclrtFree);
    
      // 4. Call aclnnConvertWeightToINT4Pack to convert the weight in INT32 sparse storage to tightly packed INT4.
      // When weightInt4Pack is in FRACTAL_NZ format, the operator also completes the ND-to-NZ layout conversion internally; this operator does not require workspace.
      uint64_t workspaceSize = 0;
      aclOpExecutor* executor = nullptr;
      void* workspaceAddr = nullptr;
      std::unique_ptr<void, aclError (*)(void*)> workspaceAddrPtr(nullptr, aclrtFree);
      ret = aclnnConvertWeightToINT4PackGetWorkspaceSize(weight, weightInt4Pack, &workspaceSize, &executor);
      CHECK_RET(ret == ACL_SUCCESS,
                LOG_PRINT("aclnnConvertWeightToINT4PackGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
      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);
        workspaceAddrPtr.reset(workspaceAddr);
      }
      ret = aclnnConvertWeightToINT4Pack(workspaceAddr, workspaceSize, executor, stream);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnConvertWeightToINT4Pack failed. ERROR: %d\n", ret); return ret);
      workspaceAddr = nullptr;
      workspaceAddrPtr.reset();
    
      // Subsequent operators request workspace as needed: the first-phase API returns workspaceSize, and workspace is allocated before the second-phase API is executed and automatically released by unique_ptr.
    
      // 5. Call aclnnCast to convert x from FP32 to FP16.
      ret = aclnnCastGetWorkspaceSize(x, aclDataType::ACL_FLOAT16, xFp16, &workspaceSize, &executor);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCastGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
      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);
        workspaceAddrPtr.reset(workspaceAddr);
      }
      ret = aclnnCast(workspaceAddr, workspaceSize, executor, stream);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCast failed. ERROR: %d\n", ret); return ret);
      workspaceAddr = nullptr;
      workspaceAddrPtr.reset();
    
      // Call aclnnCast to convert antiquantScale from FP32 to FP16.
      ret = aclnnCastGetWorkspaceSize(antiquantScale, aclDataType::ACL_FLOAT16, antiquantScaleFp16, &workspaceSize,
                                      &executor);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCastGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
      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);
        workspaceAddrPtr.reset(workspaceAddr);
      }
      ret = aclnnCast(workspaceAddr, workspaceSize, executor, stream);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCast failed. ERROR: %d\n", ret); return ret);
      workspaceAddr = nullptr;
      workspaceAddrPtr.reset();
    
      // 6. Call aclnnWeightQuantBatchMatmulNz to perform pseudo-quantization matmul. Passing 0 to antiquantGroupSize indicates a perchannel use case.
      ret = aclnnWeightQuantBatchMatmulNzGetWorkspaceSize(xFp16, weightInt4Pack, antiquantScaleFp16, nullptr, nullptr,
                                                          nullptr, nullptr, 0, yFp16, &workspaceSize, &executor);
      CHECK_RET(ret == ACL_SUCCESS,
                LOG_PRINT("aclnnWeightQuantBatchMatmulNzGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
      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);
        workspaceAddrPtr.reset(workspaceAddr);
      }
      ret = aclnnWeightQuantBatchMatmulNz(workspaceAddr, workspaceSize, executor, stream);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnWeightQuantBatchMatmulNz failed. ERROR: %d\n", ret); return ret);
      workspaceAddr = nullptr;
      workspaceAddrPtr.reset();
    
      // 7. Call aclnnCast to convert the output from FP16 to FP32.
      ret = aclnnCastGetWorkspaceSize(yFp16, aclDataType::ACL_FLOAT, y, &workspaceSize, &executor);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCastGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
      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);
        workspaceAddrPtr.reset(workspaceAddr);
      }
      ret = aclnnCast(workspaceAddr, workspaceSize, executor, stream);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCast failed. ERROR: %d\n", ret); return ret);
      workspaceAddr = nullptr;
      workspaceAddrPtr.reset();
    
      // 8. (Boilerplate) Synchronize and wait for task execution to complete, copy the result from the device to the host, and print it.
      ret = aclrtSynchronizeStream(stream);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
      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 < size; i++) {
        LOG_PRINT("result[%ld] is: %f\n", i, resultData[i]);
      }
    
      // 9. (Boilerplate) Release the stream and other resources. The aclTensor and device memory have been automatically released by unique_ptr.
      aclrtDestroyStream(stream);
      aclrtResetDevice(deviceId);
      aclFinalize();
    
      return 0;
    }
  • Ascend 950PR&950DT products: The following sample code (FLOAT input) is for reference only. For details about the compilation and execution procedure, see Compile and Run Samples. For the FRACTAL_NZ use case on Ascend 950, the aclnnWeightQuantBatchMatmulNz API must be called. Here, aclnnWeightQuantBatchMatmulNz is used as an example.

    #include <iostream>
    #include <memory>
    #include <vector>
    #include "acl/acl.h"
    #include "aclnnop/aclnn_cast.h"
    #include "aclnnop/aclnn_convert_weight_to_int4_pack.h"
    #include "aclnnop/aclnn_weight_quant_batch_matmul_nz.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)
    
    #define CEIL_DIV(x, y) ((((x) + (y)) - 1) / (y))
    
    int64_t GetShapeSize(const std::vector<int64_t>& shape) {
      int64_t shapeSize = 1;
      for (auto i : shape) {
        shapeSize *= i;
      }
      return shapeSize;
    }
    
    // Boilerplate for resource initialization.
    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;
    }
    
    // Create an aclTensor with a contiguous ND format, and copy hostData to the device side.
    // The device-side memory size is allocated based on the actual number of bytes of hostData (each element occupies sizeof(T) bytes).
    template <typename T>
    int CreateAclTensor(const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr,
                        aclDataType dataType, aclTensor** tensor) {
      auto size = hostData.size() * 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);
    
      // Compute continuous tensor strides.
      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;
    }
    
    // Create a 4-bit tightly packed (INT4/FLOAT4_E2M1) aclTensor in FRACTAL_NZ storage format.
    // Pass in the logical shape as the original ND matrix (k, n). On Ascend 950, the storageShape of NZ is (ceil(n/16), ceil(k/16), 16, 16),
    // each block contains 16 * 16 4-bit data (128 bytes), and the device-side memory is allocated based on the storageShape size.
    // hostData is the packed byte data (2 4-bit values are stored in 1 int8), and only hostData.size() bytes are copied,
    // the tail alignment part requires no initialization, and the entire memory block is overwritten after aclnnConvertWeightToINT4Pack is called.
    template <typename T>
    int CreateAclTensorNz(const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr,
                          aclDataType dataType, aclTensor** tensor) {
      auto size = CEIL_DIV(shape[1], 16) * CEIL_DIV(shape[0], 16) * 128;
      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, hostData.size() * sizeof(T), hostData.data(), hostData.size() * sizeof(T),
                        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 the aclTensor. Compute storageShape based on the NZ block layout.
      std::vector<int64_t> nzShape = {CEIL_DIV(shape[1], 16), CEIL_DIV(shape[0], 16), 16, 16};
      *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0,
                                aclFormat::ACL_FORMAT_FRACTAL_NZ, nzShape.data(), nzShape.size(), *deviceAddr);
      return 0;
    }
    
    int main() {
      // 1. (Boilerplate) Device/stream initialization. For details, see the acl API manual.
      // Set deviceId based on your 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.
      // This example is for the NZ use case: the storage format of weightInt4Pack is FRACTAL_NZ. For matmul, call the aclnnWeightQuantBatchMatmulNz API.
      // (On Ascend 950, the weight of the aclnnWeightQuantBatchMatmulV2/V3 APIs supports only the ND format.)
      // Computation scale: x is (m, k), weight is (k, n), y is (m, n), and antiquantScale is (ceil(k/groupSize), n).
      // All input data are 1 and antiquantScale values are all 1. Each element of y is expected to be k.
      int64_t m = 16;
      int64_t k = 64;
      int64_t n = 64;
      int64_t antiquantGroupSize = 32; // groupSize of the pergroup use case
      std::vector<int64_t> xShape = {m, k};
      std::vector<int64_t> weightShape = {k, n};
      std::vector<int64_t> weightInt4PackShape = {k, n}; // The shape of FLOAT4_E2M1 is passed in as the number of elements.
      std::vector<int64_t> antiquantScaleShape = {k / antiquantGroupSize, n}; // In the pergroup use case, the shape of scale is (ceil(k/groupSize), n).
      std::vector<int64_t> yShape = {m, n};
    
      std::vector<float> xHostData(m * k, 1);
      std::vector<float> weightHostData(k * n, 1); // FLOAT weight, where each float carries 1 fp4 data.
      // Use uint8 to carry float8_e8m0 data. 0b01111111 represents 1.0 of fp8_e8m0.
      std::vector<uint8_t> antiquantScaleHostData(k * n / antiquantGroupSize, 0b01111111);
      std::vector<float> yHostData(m * n, 0);
      // After FLOAT4_E2M1 is tightly packed, 2 fp4 values are stored in 1 int8. The number of host data items is half the number of weight elements.
      std::vector<int8_t> weightInt4PackHostData(k * n / 2, 0);
    
      // 3. Create the input and output aclTensors. Both the aclTensors and device memory are managed by unique_ptr and automatically released on any exit path.
      // Create the x aclTensor (FP32).
      void* xDeviceAddr = nullptr;
      aclTensor* x = nullptr;
      ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT, &x);
      CHECK_RET(ret == ACL_SUCCESS, return ret);
      std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> xTensorPtr(x, aclDestroyTensor);
      std::unique_ptr<void, aclError (*)(void*)> xDeviceAddrPtr(xDeviceAddr, aclrtFree);
      // Create the weight aclTensor (INT32).
      void* weightDeviceAddr = nullptr;
      aclTensor* weight = nullptr;
      ret = CreateAclTensor(weightHostData, weightShape, &weightDeviceAddr, aclDataType::ACL_FLOAT, &weight);
      CHECK_RET(ret == ACL_SUCCESS, return ret);
      std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> weightTensorPtr(weight, aclDestroyTensor);
      std::unique_ptr<void, aclError (*)(void*)> weightDeviceAddrPtr(weightDeviceAddr, aclrtFree);
      // Create the weightInt4Pack aclTensor (FLOAT4_E2M1, FRACTAL_NZ) to store the packed weight.
      void* weightInt4PackDeviceAddr = nullptr;
      aclTensor* weightInt4Pack = nullptr;
      ret = CreateAclTensorNz(weightInt4PackHostData, weightInt4PackShape, &weightInt4PackDeviceAddr,
                              aclDataType::ACL_FLOAT4_E2M1, &weightInt4Pack);
      CHECK_RET(ret == ACL_SUCCESS, return ret);
      std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> weightInt4PackTensorPtr(weightInt4Pack, aclDestroyTensor);
      std::unique_ptr<void, aclError (*)(void*)> weightInt4PackDeviceAddrPtr(weightInt4PackDeviceAddr, aclrtFree);
      // Create the antiquantScaleFp8 aclTensor (FLOAT8_E8M0), which is used directly by matmul without conversion.
      void* antiquantScaleFp8DeviceAddr = nullptr;
      aclTensor* antiquantScaleFp8 = nullptr;
      ret = CreateAclTensor(antiquantScaleHostData, antiquantScaleShape, &antiquantScaleFp8DeviceAddr,
                            aclDataType::ACL_FLOAT8_E8M0, &antiquantScaleFp8);
      CHECK_RET(ret == ACL_SUCCESS, return ret);
      std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> antiquantScaleFp8TensorPtr(antiquantScaleFp8, aclDestroyTensor);
      std::unique_ptr<void, aclError (*)(void*)> antiquantScaleFp8DeviceAddrPtr(antiquantScaleFp8DeviceAddr, aclrtFree);
      // Create the y aclTensor (FP32).
      void* yDeviceAddr = nullptr;
      aclTensor* y = nullptr;
      ret = CreateAclTensor(yHostData, yShape, &yDeviceAddr, aclDataType::ACL_FLOAT, &y);
      CHECK_RET(ret == ACL_SUCCESS, return ret);
      std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> yTensorPtr(y, aclDestroyTensor);
      std::unique_ptr<void, aclError (*)(void*)> yDeviceAddrPtr(yDeviceAddr, aclrtFree);
      // Create the xFp16 aclTensor (FP16). When antiquantScale is FLOAT8_E8M0, the data type of x supports FLOAT16.
      void* xFp16DeviceAddr = nullptr;
      aclTensor* xFp16 = nullptr;
      ret = CreateAclTensor(xHostData, xShape, &xFp16DeviceAddr, aclDataType::ACL_FLOAT16, &xFp16);
      CHECK_RET(ret == ACL_SUCCESS, return ret);
      std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> xFp16TensorPtr(xFp16, aclDestroyTensor);
      std::unique_ptr<void, aclError (*)(void*)> xFp16DeviceAddrPtr(xFp16DeviceAddr, aclrtFree);
      // Create the yFp16 aclTensor (FP16), which is the output of matmul.
      void* yFp16DeviceAddr = nullptr;
      aclTensor* yFp16 = nullptr;
      ret = CreateAclTensor(yHostData, yShape, &yFp16DeviceAddr, aclDataType::ACL_FLOAT16, &yFp16);
      CHECK_RET(ret == ACL_SUCCESS, return ret);
      std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> yFp16TensorPtr(yFp16, aclDestroyTensor);
      std::unique_ptr<void, aclError (*)(void*)> yFp16DeviceAddrPtr(yFp16DeviceAddr, aclrtFree);
    
      // 4. Call aclnnConvertWeightToINT4Pack to convert the weight from FLOAT sparse storage to tightly packed FLOAT4_E2M1 storage.
      // When weightInt4Pack is in FRACTAL_NZ format, the operator also performs the ND-to-NZ layout conversion internally. This operator does not require a workspace.
      uint64_t workspaceSize = 0;
      aclOpExecutor* executor = nullptr;
      void* workspaceAddr = nullptr;
      std::unique_ptr<void, aclError (*)(void*)> workspaceAddrPtr(nullptr, aclrtFree);
      ret = aclnnConvertWeightToINT4PackGetWorkspaceSize(weight, weightInt4Pack, &workspaceSize, &executor);
      CHECK_RET(ret == ACL_SUCCESS,
                LOG_PRINT("aclnnConvertWeightToINT4PackGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
      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);
        workspaceAddrPtr.reset(workspaceAddr);
      }
      ret = aclnnConvertWeightToINT4Pack(workspaceAddr, workspaceSize, executor, stream);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnConvertWeightToINT4Pack failed. ERROR: %d\n", ret); return ret);
      workspaceAddr = nullptr;
      workspaceAddrPtr.reset();
    
      // For subsequent operators, allocate workspace as needed: the first-phase API returns workspaceSize, which is allocated before the second-phase API executes and automatically released by unique_ptr.
    
      // 5. Call aclnnCast to convert x from FP32 to FP16.
      ret = aclnnCastGetWorkspaceSize(x, aclDataType::ACL_FLOAT16, xFp16, &workspaceSize, &executor);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCastGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
      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);
        workspaceAddrPtr.reset(workspaceAddr);
      }
      ret = aclnnCast(workspaceAddr, workspaceSize, executor, stream);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCast failed. ERROR: %d\n", ret); return ret);
      workspaceAddr = nullptr;
      workspaceAddrPtr.reset();
    
      // 5. Call aclnnWeightQuantBatchMatmulNz to perform pseudo-quantization matmul. antiquantGroupSize is the groupSize of the pergroup use case.
      ret = aclnnWeightQuantBatchMatmulNzGetWorkspaceSize(xFp16, weightInt4Pack, antiquantScaleFp8, nullptr, nullptr,
                                                          nullptr, nullptr, antiquantGroupSize, yFp16, &workspaceSize,
                                                          &executor);
      CHECK_RET(ret == ACL_SUCCESS,
                LOG_PRINT("aclnnWeightQuantBatchMatmulNzGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
      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);
        workspaceAddrPtr.reset(workspaceAddr);
      }
      ret = aclnnWeightQuantBatchMatmulNz(workspaceAddr, workspaceSize, executor, stream);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnWeightQuantBatchMatmulNz failed. ERROR: %d\n", ret); return ret);
      workspaceAddr = nullptr;
      workspaceAddrPtr.reset();
    
      // 6. Call aclnnCast to convert the output from FP16 to FP32.
      ret = aclnnCastGetWorkspaceSize(yFp16, aclDataType::ACL_FLOAT, y, &workspaceSize, &executor);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCastGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
      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);
        workspaceAddrPtr.reset(workspaceAddr);
      }
      ret = aclnnCast(workspaceAddr, workspaceSize, executor, stream);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCast failed. ERROR: %d\n", ret); return ret);
      workspaceAddr = nullptr;
      workspaceAddrPtr.reset();
    
      // 7. (Boilerplate) Synchronize and wait for task execution to complete, copy the result from device to host, and print it.
      ret = aclrtSynchronizeStream(stream);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
      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 < size; i++) {
        LOG_PRINT("result[%ld] is: %f\n", i, resultData[i]);
      }
    
      // 8. (Boilerplate) Release the stream and other resources. The aclTensor and device memory have been automatically released by unique_ptr.
      aclrtDestroyStream(stream);
      aclrtResetDevice(deviceId);
      aclFinalize();
    
      return 0;
    }
    <!-- end id14 -->