aclnnTransposeBatchMatMulWeightNz

📄 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: Computes matrix multiplication between tensor x1 and tensor x2. Only x1 in ND format and x2 in NZ format are supported, and only 3-dimensional x1 and 5-dimensional x2 are supported. The tensors support transpose, and the transpose sequence changes according to the input sequence. permX1 represents the transpose sequence of tensor x1, and permX2 represents the transpose sequence of tensor x2. The dimension with a sequence value of 0 is the batch dimension, and the other two dimensions perform matrix multiplication.

  • Example: (viewshape perspective corresponding to the conversion of x2 from NZ to ND)

    • When the shape of x1 is (B, M, K), the shape of x2 is (B, K, N), scale is None, and batchSplitFactor equals 1, the shape of the computed output out is (M, B, N).
    • When the shape of x1 is (B, M, K), the shape of x2 is (B, K, N), scale is not None, and batchSplitFactor equals 1, the shape of the computed output out is (M, 1, B * N).
    • When the shape of x1 is (B, M, K), the shape of x2 is (B, K, N), scale is None, and batchSplitFactor is greater than 1, the shape of the compute output out is (batchSplitFactor, M, B * N / batchSplitFactor).

Function Prototype

Each operator uses a two-phase API. You must first call the "aclnnTransposeBatchMatMulWeightNzGetWorkspaceSize" API to obtain the input parameters and calculate the required workspace size based on the process, and then call the "aclnnTransposeBatchMatMulWeightNz" API to execute the computation.

aclnnStatus aclnnTransposeBatchMatMulWeightNzGetWorkspaceSize(
    const aclTensor    *x1,
    const aclTensor    *x2,
    const aclTensor    *bias,
    const aclTensor    *scale,
    const aclIntArray  *permX1,
    const aclIntArray  *permX2,
    const aclIntArray  *permY,
    int8_t             cubeMathType,
    const int32_t      batchSplitFactor,
    aclTensor          *out,
    uint64_t           *workspaceSize,
    aclOpExecutor      **executor)
aclnnStatus aclnnTransposeBatchMatMulWeightNz(
    void               *workspace,
    uint64_t           workspaceSize,
    aclOpExecutor      *executor,
    const aclrtStream  stream)

aclnnTransposeBatchMatMulWeightNzGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Shape Non-contiguous Tensor
    x1 Input Represents the first matrix in matrix multiplication.
    • The data type must be consistent with x2 as required by the data type deduction rules (see Deduction Relationship and Constraints).
    • Data type deduction is not supported when x1 and x2 are BFLOAT16 and FLOAT16 respectively.
    • Data type deduction is not supported when x1 and x2 are BFLOAT16 and FLOAT32 respectively.
    BFLOAT16, FLOAT16 ND 3 √
    x2 Input Represents the second matrix in matrix multiplication.
    • The data type must satisfy the data type deduction rules with x1 (see Deduction Relationship and Constraints).
    • The Reduce dimension of x2 must be equal to the Reduce dimension of x1 in size.
    • Data type deduction is not supported when x1 and x2 are BFLOAT16 and FLOAT16 respectively.
    • Dimensions of NZ format: (b, n1, k1, k0, n0), where k0 = 16 and n0 = 16. k in the x1 shape and k1 in the x2 shape must satisfy the following relationship: ceil(k, k0) = k1. n1 in the x2 shape and n in out satisfy the following relationship: ceil(n, n0) = n1.
    BFLOAT16, FLOAT16 NZ 5 √
    bias Input Represents the bias matrix for matrix multiplication.
    • Reserved parameter, currently not supported.
    BFLOAT16, FLOAT16, FLOAT32 - - -
    scale Input (optional) Represents the quantization coefficient of the output matrix, which can be enabled when the input is FLOAT16 and the output is INT8.
    • Only 1D shapes are supported, and the shape must be equal to [b*n].
    INT64, UINT64 ND 1 √
    permX1 Input Represents the transpose sequence of the first matrix in the matrix multiplication.
    • Supports [0, 1, 2] and [1, 0, 2].
    INT64 - 1 -
    permX2 Input Represents the transpose sequence of the second matrix in the matrix multiplication.
    • Supports [0, 1, 2] and [0, 2, 1].
    INT64 - 1 -
    permY Input Represents the transpose sequence of the output matrix of the matrix multiplication.
    • Supports [1, 0, 2].
    INT64 - 1 -
    cubeMathType Input Specifies the compute logic of the Cube unit. If the input data types have a deduction relationship, this parameter is applied to the derived data type by default. The enumeration values are as follows:
    • 0: KEEP_DTYPE, which keeps the input data type for computation.
    • 1: ALLOW_FP32_DOWN_PRECISION, which supports converting input data to lower precision for computation. When the input data type is FLOAT32, it is converted to HFLOAT32 for computation. When the data is of another data type, the input type is kept for computation.
    • 2: USE_FP16, which supports converting input to FLOAT16 precision for computation. This option is not supported when the input data type is BFLOAT16.
    • 3: USE_HF32, which supports converting input to data type HFLOAT32 for computation. When the input data type is FLOAT32, it is converted to HFLOAT32 for computation.
    INT8 - - -
    batchSplitFactor Input Specifies the split size of dimension B in the output matrix of matrix multiplication.
    • Value range: [1, B], and B must be divisible by batchSplitFactor.
    • When scale is not empty, batchSplitFactor can only be 1.
    INT32 - - -
    out Output Output matrix of the matrix multiplication, which is out in the formula.
    • The data type must be consistent with the data type of x1 and x2 after deduction (see also Deduction Relationship and Constraints).
    • When scale is not empty, the output shape is (M, 1, B * N).
    • When batchSplitFactor is greater than 1, the output shape of out is (batchSplitFactor, M, B * N / batchSplitFactor).
      • Example 1: For M, K, N, B = 32, 512, 128, 16 and batchSplitFactor = 2, the output shape of out is (2, 32, 1024).
      • Example 2: For M, K, N, B = 32, 512, 128, 16 and batchSplitFactor = 4, the output shape of out is (4, 32, 512).
    BFLOAT16, FLOAT16, INT8 ND 3 -
    workspaceSize Output Returns the workspace size to be applied for on the Device side. - - - - -
    executor Output Returns the op executor that 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:

    Return Value Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 x1, x2, or out is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of x1, x2, or out is not in the supported range.
    The second dimension of x1 is not equal to the first dimension of x2.
    The dimension size of the ViewShape of x1 or x2 is not equal to 3.
    The StorageFormat of x2 is not FORMAT_FRACTAL_NZ.
    The data type of scale is not in the supported range.
    The value of batchSplitFactor is not in the supported range.

aclnnTransposeBatchMatMulWeightNz

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the Device side.
    workspaceSize Input Size of the workspace allocated on the Device side, obtained by the first-phase API aclnnTransposeBatchMatMulWeightNzGetWorkspaceSize.
    executor Input Executor of the op, including the computation process of the operator.
    stream Input Stream for executing tasks.
  • Return value

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

Constraints

  • Deterministic computation description:
    • aclnnTransposeBatchMatMulWeightNz defaults to a deterministic implementation.
  • Atlas A2 products, Atlas A3 products:
    • The value range of B is [1, 65536), and the value range of N is [1, 65536).
    • When the input shape of x1 is (B, M, K), K <= 65535; when the input shape of x1 is (M, B, K), B * K <= 65535.
    • In the ND format corresponding to the NZ format of x2, the second and third dimensions must be divisible by 16.
    • The StorageFormat of x2 must be NZ format.
    • x1 and x2 must have the same dtype.
    • permX2 only supports input [0, 1, 2].
    • When scale is not empty, the product of B and N must be less than 65536, and only the type deduction with input FLOAT16 and output INT8 is supported.
  • Ascend 950PR&950DT products:
    • permX2 supports input [0, 1, 2] and [0, 2, 1].
    • When scale is not empty, batchSplitFactor must equal 1, and only type inference with FLOAT16 input and INT8 output is supported.
  • x1 supports only 3 dimensions, and x2 supports only the Ascend private format. Before calling this API, complete the conversion of x2 from ND to the Ascend private format.
  • The case where either of the last two axes of x2 is 1 is not supported, that is, k=1 or n=1.

Example

  • Atlas A2 products, Atlas A3 products: In the use case where x1 and x2 are of the float16 data type and x2 is in NZ format, the sample code is as follows, for reference only. For details about compilation and execution, see Compile and Run Samples.

    #include <iostream>
    #include <memory>
    #include <vector>
    #include <cmath>
    #include "acl/acl.h"
    #include "aclnnop/aclnn_transpose_batch_mat_mul.h"
    #include "aclnnop/aclnn_trans_matmul_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;
    }
    
    // Convert the FP16 uint16_t representation to the float representation.
    float Fp16ToFloat(uint16_t h)
    {
        int s = (h >> 15) & 0x1;  // sign
        int e = (h >> 10) & 0x1F; // exponent
        int f = h & 0x3FF;        // fraction
        if (e == 0) {
            // Zero or Denormal
            if (f == 0) {
                return s ? -0.0f : 0.0f;
            }
            // Denormals
            float sig = f / 1024.0f;
            float result = sig * pow(2, -24);
            return s ? -result : result;
        } else if (e == 31) {
            // Infinity or NaN
            return f == 0 ? (s ? -INFINITY : INFINITY) : NAN;
        }
        // Normalized
        float result = (1.0f + f / 1024.0f) * pow(2, e - 15);
        return s ? -result : result;
    }
    
    int Init(int32_t deviceId, aclrtStream* stream)
    {
        // Boilerplate for 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 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 CreateAclTensorWeight(
        const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr, aclDataType dataType,
        aclTensor** tensor)
    {
        auto size = static_cast<uint64_t>(GetShapeSize(shape));
    
        const aclIntArray* mat2Size = aclCreateIntArray(shape.data(), shape.size());
        auto ret = aclnnCalculateMatmulWeightSizeV2(mat2Size, aclDataType::ACL_FLOAT16, &size);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCalculateMatmulWeightSizeV2 failed. ERROR: %d\n", ret); return ret);
        size *= sizeof(T);
    
        // Call aclrtMalloc to allocate memory on the device.
        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.
        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);
    
        // Calculate 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];
        }
    
        std::vector<int64_t> storageShape;
        storageShape.push_back(GetShapeSize(shape));
    
        // Call aclCreateTensor to create an aclTensor.
        *tensor = aclCreateTensor(
            shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND, storageShape.data(),
            storageShape.size(), *deviceAddr);
        return 0;
    }
    
    int main()
    {
        // 1. (Boilerplate) Device/stream initialization. For details, see the acl API reference.
        // Set deviceId based on the actual device.
        int32_t deviceId = 0;
        aclrtStream stream;
        auto ret = Init(deviceId, &stream);
        // Handle the check as required.
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
    
        // 2. Construct inputs and outputs. Customize the construction based on the API.
        int32_t M = 32;
        int32_t K = 512;
        int32_t N = 128;
        int32_t Batch = 16;
        std::vector<int64_t> x1Shape = {M, Batch, K};
        std::vector<int64_t> x2Shape = {Batch, K, N};
        std::vector<int64_t> outShape = {M, Batch, N};
        std::vector<int64_t> permX1Series = {1, 0, 2};
        std::vector<int64_t> permX2Series = {0, 1, 2};
        std::vector<int64_t> permYSeries = {1, 0, 2};
        void* x1DeviceAddr = nullptr;
        void* x2DeviceAddr = nullptr;
        void* outDeviceAddr = nullptr;
        aclTensor* x1 = nullptr;
        aclTensor* x2 = nullptr;
        aclTensor* out = nullptr;
        // Use uint16_t to store float16 data.
        std::vector<uint16_t> x1HostData(GetShapeSize(x1Shape), 0x3C00); // 1.0 in float16
        std::vector<uint16_t> x2HostData(GetShapeSize(x2Shape), 0x3C00); // 1.0 in float16
        std::vector<uint16_t> outHostData(GetShapeSize(outShape), 0);
        int8_t cubeMathType = 0; // Consistent with BMMV3
        int32_t batchSplitFactor = 1;
    
        // Create x1 aclTensor (ND format).
        ret = CreateAclTensor(x1HostData, x1Shape, &x1DeviceAddr, aclDataType::ACL_FLOAT16, &x1);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        // Create x2 aclTensor (for NZ format).
        ret = CreateAclTensorWeight(x2HostData, x2Shape, &x2DeviceAddr, aclDataType::ACL_FLOAT16, &x2);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        // Create out aclTensor (ND format).
        ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT16, &out);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
    
        aclIntArray* permX1 = aclCreateIntArray(permX1Series.data(), permX1Series.size());
        aclIntArray* permX2 = aclCreateIntArray(permX2Series.data(), permX2Series.size());
        aclIntArray* permY = aclCreateIntArray(permYSeries.data(), permYSeries.size());
    
        // 3. Call TransWeight first to convert x2 to NZ format.
        uint64_t transWorkspaceSize = 0;
        aclOpExecutor* transExecutor = nullptr;
        ret = aclnnTransMatmulWeightGetWorkspaceSize(x2, &transWorkspaceSize, &transExecutor);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTransMatmulWeightGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
    
        // Allocate device memory based on the workspaceSize computed by the first-phase API.
        void* transWorkspaceAddr = nullptr;
        if (transWorkspaceSize > 0) {
            ret = aclrtMalloc(&transWorkspaceAddr, transWorkspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
            CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate trans workspace failed. ERROR: %d\n", ret); return ret);
        }
    
        // Call the second-phase API aclnnTransMatmulWeight.
        ret = aclnnTransMatmulWeight(transWorkspaceAddr, transWorkspaceSize, transExecutor, stream);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTransMatmulWeight failed. ERROR: %d\n", ret); return ret);
    
        // 4. Call the dedicated TBMM Weight NZ API.
        uint64_t tbmmWorkspaceSize = 0;
        aclOpExecutor* tbmmExecutor = nullptr;
        ret = aclnnTransposeBatchMatMulWeightNzGetWorkspaceSize(
            x1, x2, (const aclTensor*)nullptr, (const aclTensor*)nullptr, permX1, permX2, permY, cubeMathType,
            batchSplitFactor, out, &tbmmWorkspaceSize, &tbmmExecutor);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTransposeBatchMatMulWeightNzGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
    
        // Allocate device memory based on the workspaceSize computed by the first-phase API.
        void* tbmmWorkspaceAddr = nullptr;
        if (tbmmWorkspaceSize > 0) {
            ret = aclrtMalloc(&tbmmWorkspaceAddr, tbmmWorkspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
            CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate TBMM workspace failed. ERROR: %d\n", ret); return ret);
        }
    
        // Call the aclnnTransposeBatchMatMulWeightNz second-phase API.
        ret = aclnnTransposeBatchMatMulWeightNz(tbmmWorkspaceAddr, tbmmWorkspaceSize, tbmmExecutor, stream);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTransposeBatchMatMulWeightNz failed. ERROR: %d\n", ret); return ret);
    
        // 5. (Boilerplate) Synchronously wait for task execution to complete.
        ret = aclrtSynchronizeStream(stream);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
    
        // 6. Obtain the output value and copy the result from Device memory to the Host side.
        auto size = GetShapeSize(outShape);
        std::vector<uint16_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);
    
        // Print the result (convert uint16_t to float for display).
        int64_t max_print_size = 8;
        for (int64_t i = 0; i < max_print_size; i++) {
            float fp16Float = Fp16ToFloat(resultData[i]);
            LOG_PRINT("result[%ld] is: %f\n", i, fp16Float);
        }
    
        // 7. Release aclTensor and resources.
        aclDestroyTensor(x1);
        aclDestroyTensor(x2);
        aclDestroyTensor(out);
        aclDestroyIntArray(permX1);
        aclDestroyIntArray(permX2);
        aclDestroyIntArray(permY);
    
        // 8. Release device resources.
        aclrtFree(x1DeviceAddr);
        aclrtFree(x2DeviceAddr);
        aclrtFree(outDeviceAddr);
    
        if (transWorkspaceSize > 0) {
            aclrtFree(transWorkspaceAddr);
        }
        if (tbmmWorkspaceSize > 0) {
            aclrtFree(tbmmWorkspaceAddr);
        }
    
        aclrtDestroyStream(stream);
        aclrtResetDevice(deviceId);
        aclFinalize();
        return 0;
    }
  • Ascend 950PR&950DT products: The following example code is for the case where the data types of x1 and x2 are float16 and x2 is in NZ format, for reference only. For details about compilation and execution, see Compile and Run Samples.

    #include <iostream>
    #include <vector>
    #include <cmath>
    #include "acl/acl.h"
    #include "aclnnop/aclnn_transpose_batch_mat_mul.h"
    #include "aclnnop/aclnn_npu_format_cast.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;
    }
    
    // Convert the uint16_t representation of FP16 to the float representation.
    float Fp16ToFloat(uint16_t h)
    {
        int s = (h >> 15) & 0x1;  // sign
        int e = (h >> 10) & 0x1F; // exponent
        int f = h & 0x3FF;        // fraction
        if (e == 0) {
            // Zero or Denormal
            if (f == 0) {
                return s ? -0.0f : 0.0f;
            }
            // Denormals
            float sig = f / 1024.0f;
            float result = sig * pow(2, -24);
            return s ? -result : result;
        } else if (e == 31) {
            // Infinity or NaN
            return f == 0 ? (s ? -INFINITY : INFINITY) : NAN;
        }
        // Normalized
        float result = (1.0f + f / 1024.0f) * pow(2, e - 15);
        return s ? -result : result;
    }
    
    int Init(int32_t deviceId, aclrtStream* stream)
    {
        // Boilerplate: initialize resources.
        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-side 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-side data to Device-side 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 CreateAclTensorWithFormat(
        const std::vector<T>& hostData, const std::vector<int64_t>& shape, int64_t** storageShape,
        uint64_t* storageShapeSize, void** deviceAddr, aclDataType dataType, aclTensor** tensor, aclFormat format)
    {
        auto size = hostData.size() * sizeof(T);
        // Call aclrtMalloc to allocate device-side 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-side data to device-side 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];
        }
    
        *tensor = aclCreateTensor(
            shape.data(), shape.size(), dataType, strides.data(), 0, format, *storageShape, *storageShapeSize, *deviceAddr);
        return 0;
    }
    
    int main()
    {
        // 1. (Boilerplate) Initialize device/stream. For details, see the acl API manual.
        // Set deviceId based on the actual device.
        int32_t deviceId = 0;
        aclrtStream stream;
        auto ret = Init(deviceId, &stream);
        // Handle the check as needed.
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
    
        // 2. Construct the input and output. Custom construction is required based on the API.
        int32_t M = 32;
        int32_t K = 512;
        int32_t N = 128;
        int32_t Batch = 16;
        std::vector<int64_t> x1Shape = {M, Batch, K};
        std::vector<int64_t> x2Shape = {Batch, K, N};
        std::vector<int64_t> outShape = {M, Batch, N};
        std::vector<int64_t> permX1Series = {1, 0, 2};
        std::vector<int64_t> permX2Series = {0, 1, 2};
        std::vector<int64_t> permYSeries = {1, 0, 2};
    
        void* x1DeviceAddr = nullptr;
        void* x2DeviceAddr = nullptr;
        void* outDeviceAddr = nullptr;
        void* x2NzDeviceAddr = nullptr;
        aclTensor* x1 = nullptr;
        aclTensor* x2 = nullptr;
        aclTensor* out = nullptr;
        aclTensor* x2NZ = nullptr;
    
        // Use the uint16_t type to store float16 data.
        std::vector<uint16_t> x1HostData(GetShapeSize(x1Shape), 0x3C00); // 1.0 in float16
        std::vector<uint16_t> x2HostData(GetShapeSize(x2Shape), 0x3C00); // 1.0 in float16
        std::vector<uint16_t> outHostData(GetShapeSize(outShape), 0);
        int8_t cubeMathType = 0; // Consistent with BMMV3
        int32_t batchSplitFactor = 1;
    
        // Create the x1 aclTensor (ND format).
        ret = CreateAclTensor(x1HostData, x1Shape, &x1DeviceAddr, aclDataType::ACL_FLOAT16, &x1);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
    
        // Create the x2 aclTensor (ND format).
        ret = CreateAclTensor(x2HostData, x2Shape, &x2DeviceAddr, aclDataType::ACL_FLOAT16, &x2);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
    
        // Create the out aclTensor (ND format).
        ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT16, &out);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
    
        aclIntArray* permX1 = aclCreateIntArray(permX1Series.data(), permX1Series.size());
        aclIntArray* permX2 = aclCreateIntArray(permX2Series.data(), permX2Series.size());
        aclIntArray* permY = aclCreateIntArray(permYSeries.data(), permYSeries.size());
    
        // 3. Convert the weight tensor from ND to NZ by calling the npu_foramt_cast API.
        aclDataType additionalDtype = aclDataType::ACL_FLOAT16;
        aclDataType srcDtype = aclDataType::ACL_FLOAT16;
        int64_t* dstShape = nullptr;
        uint64_t dstShapeSize = 0;
        int actualFormat;
        aclOpExecutor* executor = nullptr;
    
        uint64_t formatCastWorkspaceSize = 0;
        uint64_t tbmmWorkspaceSize = 0;
        void* formatCastWorkspaceAddr = nullptr;
        void* tbmmWorkspaceAddr = nullptr;
        // Compute the shape and format of the target tensor.
        ret = aclnnNpuFormatCastCalculateSizeAndFormat(x2, 29, additionalDtype, &dstShape, &dstShapeSize, &actualFormat);
        CHECK_RET(
            ret == ACL_SUCCESS, LOG_PRINT("aclnnNpuFormatCastCalculateSizeAndFormat failed. ERROR: %d\n", ret); return ret);
    
        ret = CreateAclTensorWithFormat(
            x2HostData, x2Shape, &dstShape, &dstShapeSize, &x2NzDeviceAddr, srcDtype, &x2NZ,
            static_cast<aclFormat>(actualFormat));
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("CreateAclTensorWithFormat failed. ERROR: %d\n", ret); return ret);
    
        // Call the first-phase API aclnnNpuFormatCastGetWorkspaceSize.
        ret = aclnnNpuFormatCastGetWorkspaceSize(x2, x2NZ, &formatCastWorkspaceSize, &executor);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnNpuFormatCastGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
    
        // Allocate device memory based on the workspaceSize computed by the first-phase API.
        if (formatCastWorkspaceSize > 0) {
            ret = aclrtMalloc(&formatCastWorkspaceAddr, formatCastWorkspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
            CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate format cast workspace failed. ERROR: %d\n", ret); return ret);
        }
    
        // Call the second-phase API aclnnNpuFormatCast.
        ret = aclnnNpuFormatCast(formatCastWorkspaceAddr, formatCastWorkspaceSize, executor, stream);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnNpuFormatCast failed. ERROR: %d\n", ret); return ret);
    
        // 4. Synchronize and wait for the format conversion task to finish.
        ret = aclrtSynchronizeStream(stream);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
    
        // 5. Call the dedicated TBMM Weight NZ API.
        ret = aclnnTransposeBatchMatMulWeightNzGetWorkspaceSize(
            x1, x2NZ, (const aclTensor*)nullptr, (const aclTensor*)nullptr, permX1, permX2, permY, cubeMathType,
            batchSplitFactor, out, &tbmmWorkspaceSize, &executor);
        CHECK_RET(
            ret == ACL_SUCCESS, LOG_PRINT("aclnnTransposeBatchMatMulWeightNzGetWorkspaceSize failed. ERROR: %d\n", ret);
            return ret);
    
        // Allocate device memory based on the workspaceSize computed by the first-phase API.
        if (tbmmWorkspaceSize > 0) {
            ret = aclrtMalloc(&tbmmWorkspaceAddr, tbmmWorkspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
            CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate TBMM workspace failed. ERROR: %d\n", ret); return ret);
        }
    
        // Call the second-phase API aclnnTransposeBatchMatMulWeightNz.
        ret = aclnnTransposeBatchMatMulWeightNz(tbmmWorkspaceAddr, tbmmWorkspaceSize, executor, stream);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTransposeBatchMatMulWeightNz failed. ERROR: %d\n", ret); return ret);
    
        // 6. (Boilerplate) Synchronize and wait for the task to finish.
        ret = aclrtSynchronizeStream(stream);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
    
        // 7. Obtain the output value and copy the result from device memory to the host.
        auto size = GetShapeSize(outShape);
        std::vector<uint16_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);
    
        // Print the result.
        int64_t max_print_size = 8;
        for (int64_t i = 0; i < max_print_size; i++) {
            float fp16Float = Fp16ToFloat(resultData[i]);
            LOG_PRINT("result[%ld] is: %f\n", i, fp16Float);
        }
    
        // 8. Release the aclTensor and resources.
        aclDestroyTensor(x1);
        aclDestroyTensor(x2);
        aclDestroyTensor(x2NZ);
        aclDestroyTensor(out);
        aclDestroyIntArray(permX1);
        aclDestroyIntArray(permX2);
        aclDestroyIntArray(permY);
    
        // 9. Release the device resources.
        aclrtFree(x1DeviceAddr);
        aclrtFree(x2DeviceAddr);
        aclrtFree(x2NzDeviceAddr);
        aclrtFree(outDeviceAddr);
        if (formatCastWorkspaceSize > 0) {
            aclrtFree(formatCastWorkspaceAddr);
        }
        if (tbmmWorkspaceSize > 0) {
            aclrtFree(tbmmWorkspaceAddr);
        }
        aclrtDestroyStream(stream);
        aclrtResetDevice(deviceId);
        aclFinalize();
        return 0;
    }