aclnnTurboQuant

View Source Code

Applicable Products

  • Ascend 950PR&950DT products: Not 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

TurboQuant normalizes the KV latent of MLA by token, and generates 4-bit quantization indices based on the 16 ascending Lloyd-Max codebook centroids. It also outputs the L2 norm scale for each token.

For row i of the input latent, the calculation is as follows:

scalei=∑dlatenti,d2+10−16scale_i = \sqrt{\sum_d latent_{i,d}^2 + 10^{-16}} ui,d=latenti,d/scaleiu_{i,d} = latent_{i,d} / scale_i nibblei,d=∑b=014[ui,d≥(centroidsb+centroidsb+1)/2]nibble_{i,d} = \sum_{b=0}^{14} [u_{i,d} \ge (centroids_b + centroids_{b+1}) / 2] yi,k=nibblei,2k∣(nibblei,2k+1≪4)y_{i,k} = nibble_{i,2k} | (nibble_{i,2k+1} \ll 4)

Each operator uses a two-phase API. First call aclnnTurboQuantGetWorkspaceSize to obtain the workspace size and executor, and then call aclnnTurboQuant to perform the calculation.

Function Prototype

aclnnStatus aclnnTurboQuantGetWorkspaceSize(
  const aclTensor *latent,
  const aclTensor *centroids,
  const aclTensor *y,
  const aclTensor *scale,
  uint64_t        *workspaceSize,
  aclOpExecutor   **executor)
aclnnStatus aclnnTurboQuant(
  void          *workspace,
  uint64_t      workspaceSize,
  aclOpExecutor *executor,
  aclrtStream   stream)

aclnnTurboQuantGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    latent (const aclTensor*) Input KV latent to be compressed, corresponding to latent in the formula.
    • Null tensors are supported.
    • Must be FLOAT32, 2D, with the last dimension of 512.
    • Must have completed signed Hadamard rotation and not be normalized.
    FLOAT32 ND [numTokens, 512] ×
    centroids (const aclTensor*) Input Centroids of the Lloyd-Max codebook, corresponding to centroids in the formula.
    • Does not support null Tensor.
    • Must be a 1D tensor with exactly 16 FLOAT32 elements, sorted in ascending order.
    FLOAT32 ND [16] ×
    y (const aclTensor*) Output Packed 4bit index, corresponding to y in the formula.
    • Does not support null Tensor.
    • Must be created in advance.
    • The low nibble stores the index of even dimensions.
    UINT8 ND [numTokens, 256] ×
    scale (const aclTensor*) Output L2 norm of each token, corresponding to scale in the formula.
    • Does not support null tensors.
    • Must be created in advance.
    FLOAT16 ND [numTokens] ×
    workspaceSize (uint64_t*) Output Returns the workspace size that needs to be requested on the Device. - - - - -
    executor (aclOpExecutor**) Output Returns op executor, which contains the calculation process of the operator. - - - - -
  • Return value

    aclnnStatus: Returned status code. For details, see aclnn return code.

    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 latent, centroids, y, scale, workspaceSize, or executor is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of latent or centroids is not within the supported range.
    The rank of latent is not 2, or the shape of centroids is not [16].
    The shape of latent does not meet the check conditions (numTokens is less than -1, or headDim is not 512 and not -1).
    The shape of y or scale is inconsistent with the inferred result.
    ACLNN_ERR_RUNTIME_ERROR 361001 The current platform is not within the supported platform range.

aclnnTurboQuant

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address requested by the Device side.
    workspaceSize Input Workspace size requested by the Device side, obtained by calling the first-phase API aclnnTurboQuantGetWorkspaceSize.
    executor Input Executor that contains the operator calculation process.
    stream Input Specifies the stream for executing the task.
  • Return value

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

Constraints

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

Example

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

#include <cmath>
#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_turbo_quant.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)

constexpr int64_t NUM_TOKENS = 2;
constexpr int64_t HEAD_DIM = 512;
constexpr int64_t PACKED_BYTES = HEAD_DIM / 2;
constexpr int64_t N_CENT = 16;

int64_t GetShapeSize(const std::vector<int64_t>& shape)
{
    int64_t shapeSize = 1;
    for (auto i : shape) {
        shapeSize *= i;
    }
    return shapeSize;
}

void PrintOutResult(std::vector<int64_t>& shape, void** deviceAddr)
{
    auto size = GetShapeSize(shape);
    std::vector<uint8_t> resultData(size, 0);
    auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), *deviceAddr,
                           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);
    // Print only the first 8 bytes of the first y; each byte carries 2 4-bit quantized values.
    for (int64_t i = 0; i < 8; i++) {
        LOG_PRINT("y[0][%ld] is: %u\n", i, static_cast<uint32_t>(resultData[i]));
    }
}

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);

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

    // 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);
    CHECK_RET(*tensor != nullptr, LOG_PRINT("aclCreateTensor failed. dtype=%d, rank=%zu, bytes=%ld\n",
                                            static_cast<int>(dataType), shape.size(), size);
              return 1);
    return 0;
}

int main()
{
    // 1. (Boilerplate) device/stream initialization. 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);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

    // 2. Construct inputs and outputs. The construction must be customized based on the API.
    std::vector<int64_t> latentShape = {NUM_TOKENS, HEAD_DIM};
    std::vector<int64_t> centroidsShape = {N_CENT};
    std::vector<int64_t> yShape = {NUM_TOKENS, PACKED_BYTES};
    std::vector<int64_t> scaleShape = {NUM_TOKENS};

    void* latentDeviceAddr = nullptr;
    void* centroidsDeviceAddr = nullptr;
    void* yDeviceAddr = nullptr;
    void* scaleDeviceAddr = nullptr;

    aclTensor* latent = nullptr;
    aclTensor* centroids = nullptr;
    aclTensor* y = nullptr;
    aclTensor* scale = nullptr;

    // latent has undergone signed Hadamard rotation and is not normalized. Fill it with a deterministic value here.
    std::vector<float> latentHostData(NUM_TOKENS * HEAD_DIM);
    for (int64_t i = 0; i < NUM_TOKENS * HEAD_DIM; i++) {
        latentHostData[i] = std::sin(static_cast<float>(i) * 0.01f) / std::sqrt(static_cast<float>(HEAD_DIM));
    }
    // The codebook must be in ascending order, taking the 16 Lloyd-Max centers on N(0, 1/HEAD_DIM) as values.
    std::vector<float> centroidsHostData = {
        -0.1209128f, -0.0911112f, -0.0711246f, -0.0551360f, -0.0413207f, -0.0287497f, -0.0170049f, -0.0056868f,
        0.0054729f,  0.0168041f,  0.0285761f,  0.0410862f,  0.0549298f,  0.0710182f,  0.0911537f,  0.1203780f};
    std::vector<uint8_t> yHostData(NUM_TOKENS * PACKED_BYTES, 0);
    std::vector<uint16_t> scaleHostData(NUM_TOKENS, 0);

    // Create the latent aclTensor.
    ret = CreateAclTensor(latentHostData, latentShape, &latentDeviceAddr, aclDataType::ACL_FLOAT, &latent);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the centroids aclTensor.
    ret = CreateAclTensor(centroidsHostData, centroidsShape, ¢roidsDeviceAddr, aclDataType::ACL_FLOAT, ¢roids);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the y aclTensor.
    ret = CreateAclTensor(yHostData, yShape, &yDeviceAddr, aclDataType::ACL_UINT8, &y);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(scaleHostData, scaleShape, &scaleDeviceAddr, aclDataType::ACL_FLOAT16, &scale);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // 3. Call the CANN operator library API, and change it to the actual API name.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor = nullptr;

    // Call the first-phase API of aclnnTurboQuant.
    ret = aclnnTurboQuantGetWorkspaceSize(latent, centroids, y, scale, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTurboQuantGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);

    // Allocate device memory based on the workspaceSize calculated by the first-phase API.
    void* workspaceAddr = nullptr;
    if (workspaceSize > 0) {
        ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
    }

    // Call the second-phase API of aclnnTurboQuant.
    ret = aclnnTurboQuant(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTurboQuant failed. ERROR: %d\n", ret); return ret);

    // 4. (boilerplate) Synchronously wait for the task execution to finish.
    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 from device memory to the host.
    //    Modify based on the specific API definition.
    PrintOutResult(yShape, &yDeviceAddr);

    // 6. Release aclTensor. Modify based on the specific API definition.
    aclDestroyTensor(latent);
    aclDestroyTensor(centroids);
    aclDestroyTensor(y);
    aclDestroyTensor(scale);

    // 7. Release device resources.
    aclrtFree(latentDeviceAddr);
    aclrtFree(centroidsDeviceAddr);
    aclrtFree(yDeviceAddr);
    aclrtFree(scaleDeviceAddr);
    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();

    return 0;
}