aclnnDequantRopeQuantKvcache

📄 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

  • Description: performs dequantization (optional) on the input tensor (x), splits the last axis by sizeSplits (the split lengths) into q, k, and vOut, applies rotary position embedding to q and k to generate qOut and kOut, and then quantizes kOut and vOut and updates them to kCacheRef and vCacheRef based on indices.

  • Formula:

    $$ dequantX = Dequant(x,weightScaleOptional,activationScaleOptional,biasOptional) $$
    $$ q,k,vOut = SplitTensor(dequantX,dim=-1,`sizeSplits`) $$
    $$ qOut,kOut = ApplyRotaryPosEmb(q,k,cos,sin) $$
    $$ quantK = Quant(kOut,scaleK,offsetKOptional) $$
    $$ quantV = Quant(vOut,scaleV,offsetVOptional) $$

    If cacheModeOptional is contiguous:

    $$ kCacheRef[i][indice[i]]=quantK[i] $$
    $$ vCacheRef[i][indice[i]]=quantV[i] $$

    If cacheModeOptional is page:

    $$ kCacheRefView=kCacheRef.view(-1,kCacheRef[-2],kCacheRef[-1]) $$
    $$ vCacheRefView=vCacheRef.view(-1,vCacheRef[-2],vCacheRef[-1]) $$
    $$ kCacheRefView[indices[i]]=quantK[i] $$
    $$ vCacheRefView[indices[i]]=quantV[i] $$

Function Prototype

Each operator uses a two-phase API. Call the "aclnnDequantRopeQuantKvcacheGetWorkspaceSize" API to obtain the input parameters and calculate the required workspace size based on the process, and then call the "aclnnDequantRopeQuantKvcache" API to perform the computation.

aclnnStatus aclnnDequantRopeQuantKvcacheGetWorkspaceSize(
  const aclTensor   *x,
  const aclTensor   *cos,
  const aclTensor   *sin,
  aclTensor         *kCacheRef,
  aclTensor         *vCacheRef,
  const aclTensor   *indices,
  const aclTensor   *scaleK,
  const aclTensor   *scaleV,
  const aclTensor   *offsetKOptional,
  const aclTensor   *offsetVOptional,
  const aclTensor   *weightScaleOptional,
  const aclTensor   *activationScaleOptional,
  const aclTensor   *biasOptional,
  const aclIntArray *sizeSplits,
  char              *quantModeOptional,
  char              *layoutOptional,
  bool               kvOutput,
  char              *cacheModeOptional,
  const aclTensor   *qOut,
  const aclTensor   *kOut,
  const aclTensor   *vOut,
  uint64_t          *workspaceSize,
  aclOpExecutor    **executor)
aclnnStatus aclnnDequantRopeQuantKvcache(
  void*          workspace,
  uint64_t       workspaceSize,
  aclOpExecutor* executor,
  aclrtStream    stream)

aclnnDequantRopeQuantKvcacheGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    x Input Input x in the formula, used for split. The shape is [B, S, H] or [B, H], where H=(Nq+Nkv+Nkv)*D. The last dimension of x is less than or equal to 4096 and aligned to 64. FLOAT16, BFLOAT16, INT32 ND 2-3 √
    cos Input Input cos in the formula, used for position encoding. The shape is [B, S, 1, D] when x has 3 dimensions and [B, D] when x has 2 dimensions. FLOAT16, BFLOAT16 ND 2, 4 √
    sin Input Input sin used for position encoding in the formula. The shape is [B, S, 1, D] when x has 3 dimensions and [B, D] when x has 2 dimensions. Consistent with cos. ND 2, 4 √
    kCacheRef Input Input kCacheRef for caching k in the formula. The shape is [C_1, C_2, Nkv, D]. INT8 ND 4 √
    vCacheRef Input Input vCacheRef used to cache v in the formula. The shape is [C_1, C_2, Nkv, D]. INT8 ND 4 √
    indices Input Input indices in the formula, indicating the token position information of Kvcache. The shape is [B*S] when cache_mode is page and x is 3-dimensional; otherwise, the shape is [B]. INT32 ND 1 √
    scaleK Input Input scaleK in the formula, used as the scale factor for quantizing k. The number of elements is Nkv*D. The recommended shape is [Nkv, D], and the one-dimensional flattened shape [Nkv*D] is also supported. FLOAT ND ≥1 √
    scaleV Input Input scaleV in the formula, which is the scale factor for quantizing v. The number of elements is Nkv*D. The recommended shape is [Nkv, D], and the one-dimensional flattened shape [Nkv*D] is also supported. FLOAT ND ≥1 √
    offsetKOptional Input The input offsetKOptional in the formula, used as the offset factor for quantizing k. The number of elements is Nkv*D. The recommended shape is [Nkv, D]. The flattened 1D shape [Nkv*D] is also supported. FLOAT ND ≥1 √
    offsetVOptional Input Input offsetVOptional in the formula, used as the offset factor for quantizing v. The number of elements is Nkv*D. The recommended shape is [Nkv, D]. The flattened 1D shape [Nkv*D] is also supported. FLOAT ND ≥1 √
    weightScaleOptional Input Input in the formula. weightScaleOptional indicates the weight scale factor for dequantization. Shape: [H]. FLOAT ND 1 √
    activationScaleOptional Input Input in the formula. activationScaleOptional indicates the activation scale factor for dequantization. The shape is [B*S] when x is 3-dimensional, and [B] when x is 2-dimensional. FLOAT ND 1 √
    biasOptional Input The bias input in the formula, used for dequantization, is biasOptional. The shape is [H]. FLOAT, FLOAT16, INT32, BFLOAT16 ND 1 √
    sizeSplits Input Indicates the lengths for splitting the input qkv. Size: 3, value: [Nq*D, Nkv*D, Nkv*D] AclIntArray - - -
    quantModeOptional Input Specifies the supported quantization types. Currently, only "static" is supported. CHAR - - -
    layoutOptional Input Indicates the supported data format. Currently, only "BSND" is supported. CHAR - - -
    kvOutput Input Boolean value on the host. Indicates whether to output kOut and vOut. If true, kOut and vOut with valid shapes are output; if false, the shapes of kOut and vOut are empty. BOOL - - -
    cacheModeOptional Input Specifies the update mode of kCacheRef. Currently, only "page" and "contiguous" are supported. The default is "contiguous". CHAR - - -
    qOut Output q after rotary position embedding in the formula. The shape is [B, S, Nq, D] when x is 3-dimensional and [B, Nq, D] when x is 2-dimensional. The data type is the same as that of cos and sin. FLOAT16, BFLOAT16 ND 3-4 ×
    kOut Output k after rotary position embedding in the formula. If kvOutput is true, the shape is [B, S, Nkv, D] when x is 3-dimensional, and [B, Nkv, D] when x is 2-dimensional; if kvOutput is false, the shape is empty. The data type is the same as that of cos and sin. FLOAT16, BFLOAT16 ND 1-4 ×
    vOut Output v obtained through the split in the formula. If kvOutput is true, the shape is [B, S, Nkv, D] when x is a 3D tensor and [B, Nkv, D] when x is a 2D tensor; if kvOutput is false, the shape is empty. The data type is the same as that of cos and sin. FLOAT16, BFLOAT16 ND 1-4 ×
    workspaceSize Output Returns the workspace size to be requested on the Device. - - - - -
    executor Output Returns the op executor, which contains the operator computation process. - - - - -
  • Return Value

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

    The first-phase API performs input parameter validation and returns an error in the following scenarios:

    Return Value Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 The input or output tensor is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data types of the inputs and outputs are out of the supported range.

aclnnDequantRopeQuantKvcache API

  • Parameters

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

    aclnnStatus: Return status codes. For details, see aclnn return codes.

Constraints

  1. Deterministic computation:

    • aclnnDequantRopeQuantKvcache defaults to a deterministic implementation.
  2. When cacheModeOptional is contiguous: dimension 0 of kCacheRef is greater than or equal to dimension 0 of x. If x is three-dimensional, the data values of indices are greater than or equal to 0 and less than or equal to dimension 1 of kCacheRef minus dimension 1 of x; if x is two-dimensional, the data values of indices are greater than or equal to 0 and less than or equal to dimension 1 of kCacheRef minus 1.

  3. When cacheModeOptional is page: the data values of indices are greater than or equal to 0, less than dimension 0 * dimension 1 of kCacheRef, and are not duplicated.

  4. When the input x is not INT32, the data types of x, cos, sin, and the outputs qOut, kOut, and vOut must be consistent. In this case, activationScaleOptional, weightScaleOptional, and biasOptional do not take effect.

  5. When the input x is INT32, the data types of cos, sin, and the outputs qOut, kOut, and vOut must be consistent. In this case, weightScaleOptional is mandatory, while activationScaleOptional and biasOptional are optional (biasOptional does not need to match the data type of other inputs).

  6. The last dimension of x must be less than or equal to 4096 and aligned to 64.

Example

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

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_dequant_rope_quant_kvcache.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;
}

void PrintOutResult(std::vector<int64_t> &shape, void** deviceAddr) {
  auto size = GetShapeSize(shape);
  std::vector<int8_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);
  for (int64_t i = 0; i < size; i++) {
    LOG_PRINT("mean result[%ld] is: %d\n", i, resultData[i]);
  }
}

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 the aclCreateTensor API to create an aclTensor.
  *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
                            shape.data(), shape.size(), *deviceAddr);
  return 0;
}

int main() {
  // 1. Boilerplate for device/stream initialization. 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 input and output based on the API definition.
  std::vector<int64_t> inputShape = {320, 1, 1280};
  std::vector<int64_t> cosShape = {320, 1, 1, 128};
  std::vector<int64_t> sinShape = {320, 1, 1, 128};
  std::vector<int64_t> kcacheShape = {320, 1280, 1, 128};
  std::vector<int64_t> vcacheShape = {320, 1280, 1, 128};
  std::vector<int64_t> indicesShape = {320};
  std::vector<int64_t> kscaleShape = {1, 128};
  std::vector<int64_t> vscaleShape = {1, 128};
  std::vector<int64_t> koffsetShape = {1, 128};
  std::vector<int64_t> voffsetShape = {1, 128};

  std::vector<int64_t> weightShape = {1280};
  std::vector<int64_t> activationShape = {320};
  std::vector<int64_t> biasShape = {1280};

  std::vector<int32_t> inputHostData(320 * 1280, 1);
  std::vector<int16_t> cosHostData(320 * 128, 1);
  std::vector<int16_t> sinHostData(320 * 128, 1);
  std::vector<int8_t> kcacheHostData(320 * 1280 * 128, 6);
  std::vector<int8_t> vcacheHostData(320 * 1280 * 128, 6);
  std::vector<int32_t> indicesHostData(320, 0);
  std::vector<float> kscaleHostData(128, 2);
  std::vector<float> vscaleHostData(128, 2);
  std::vector<float> koffsetHostData(128, 2);
  std::vector<float> voffsetHostData(128, 2);

  std::vector<float> weightHostData(1280, 2);
  std::vector<float> activationHostData(320, 2);
  std::vector<float> biasHostData(1280, 2);

  void* inputDeviceAddr = nullptr;
  void* cosDeviceAddr = nullptr;
  void* sinDeviceAddr = nullptr;
  void* kcacheDeviceAddr = nullptr;
  void* vcacheDeviceAddr = nullptr;
  void* indicesDeviceAddr = nullptr;
  void* kscaleDeviceAddr = nullptr;
  void* vscaleDeviceAddr = nullptr;
  void* koffsetDeviceAddr = nullptr;
  void* voffsetDeviceAddr = nullptr;

  void* weightDeviceAddr = nullptr;
  void* activationDeviceAddr = nullptr;
  void* biasDeviceAddr = nullptr;

  aclTensor* input = nullptr;
  aclTensor* cos = nullptr;
  aclTensor* sin = nullptr;
  aclTensor* kcache = nullptr;
  aclTensor* vcache = nullptr;
  aclTensor* indices = nullptr;
  aclTensor* kscale = nullptr;
  aclTensor* vscale = nullptr;
  aclTensor* koffset = nullptr;
  aclTensor* voffset = nullptr;
  aclTensor* weight = nullptr;
  aclTensor* activation = nullptr;
  aclTensor* bias = nullptr;

  ret = CreateAclTensor(inputHostData, inputShape, &inputDeviceAddr, aclDataType::ACL_INT32, &input);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(cosHostData, cosShape, &cosDeviceAddr, aclDataType::ACL_FLOAT16, &cos);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(sinHostData, sinShape, &sinDeviceAddr, aclDataType::ACL_FLOAT16, &sin);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(kcacheHostData, kcacheShape, &kcacheDeviceAddr, aclDataType::ACL_INT8, &kcache);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(vcacheHostData, vcacheShape, &vcacheDeviceAddr, aclDataType::ACL_INT8, &vcache);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(indicesHostData, indicesShape, &indicesDeviceAddr, aclDataType::ACL_INT32, &indices);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(kscaleHostData, kscaleShape, &kscaleDeviceAddr, aclDataType::ACL_FLOAT, &kscale);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(vscaleHostData, vscaleShape, &vscaleDeviceAddr, aclDataType::ACL_FLOAT, &vscale);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(koffsetHostData, koffsetShape, &koffsetDeviceAddr, aclDataType::ACL_FLOAT, &koffset);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(voffsetHostData, voffsetShape, &voffsetDeviceAddr, aclDataType::ACL_FLOAT, &voffset);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  ret = CreateAclTensor(weightHostData, weightShape, &weightDeviceAddr, aclDataType::ACL_FLOAT, &weight);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(activationHostData, activationShape, &activationDeviceAddr, aclDataType::ACL_FLOAT, &activation);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(biasHostData, biasShape, &biasDeviceAddr, aclDataType::ACL_FLOAT, &bias);
  CHECK_RET(ret == ACL_SUCCESS, return ret);


  std::vector<int64_t> qShape = {320,1,8,128};
  std::vector<int16_t> qHostData(320 * 8 * 128, 9);
  aclTensor* q = nullptr;
  void* qDeviceAddr = nullptr;
  std::vector<int64_t> kShape = {320,1,1,128};
  std::vector<int16_t> kHostData(320 * 128, 10);
  aclTensor* k = nullptr;
  void* kDeviceAddr = nullptr;
  std::vector<int64_t> vShape = {320,1,1, 128};
  std::vector<int16_t> vHostData(320 * 128, 10);
  aclTensor* v = nullptr;
  void* vDeviceAddr = nullptr;

  ret = CreateAclTensor(qHostData, qShape, &qDeviceAddr, aclDataType::ACL_FLOAT16, &q);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(kHostData, kShape, &kDeviceAddr, aclDataType::ACL_FLOAT16, &k);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(vHostData, vShape, &vDeviceAddr, aclDataType::ACL_FLOAT16, &v);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  std::vector<int64_t> splitData = {1024, 128, 128};
  aclIntArray *sizeSplits = aclCreateIntArray(splitData.data(), splitData.size());
  char quantMode[] = "static";
  char layout[] = "BSND";
  char cacheMode[] = "contiguous";

  // 3. Call the CANN operator library API. Replace it with the specific API.
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;

  // Call the first-phase API of aclnnDequantRopeQuantKvcache.
  ret = aclnnDequantRopeQuantKvcacheGetWorkspaceSize(input, cos, sin, kcache, vcache, indices, kscale, vscale, koffset,
                                                     voffset, weight, activation, bias, sizeSplits, quantMode, layout,
                                                     true, cacheMode, q, k, v, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnDequantRopeQuantKvcacheGetWorkspaceSize 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 aclnnDequantRopeQuantKvcache.
  ret = aclnnDequantRopeQuantKvcache(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnDequantRopeQuantKvcache failed. ERROR: %d\n", ret); return ret);

  // 4. Boilerplate: wait for the task execution to complete synchronously.
  ret = aclrtSynchronizeStream(stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);

  // 5. Obtain the output values and copy the result from device memory to host memory. Modify the code according to the specific API definition.
  PrintOutResult(kcacheShape, &kcacheDeviceAddr);
  PrintOutResult(vcacheShape, &vcacheDeviceAddr);

  // 6. Release aclTensor and aclIntArray. Modify the code according to the specific API definition.
  aclDestroyTensor(input);
  aclDestroyTensor(cos);
  aclDestroyTensor(sin);
  aclDestroyTensor(kcache);
  aclDestroyTensor(vcache);
  aclDestroyTensor(indices);
  aclDestroyTensor(kscale);
  aclDestroyTensor(vscale);
  aclDestroyTensor(koffset);
  aclDestroyTensor(voffset);
  aclDestroyTensor(weight);
  aclDestroyTensor(activation);
  aclDestroyTensor(bias);
  aclDestroyTensor(q);
  aclDestroyTensor(k);
  aclDestroyTensor(v);
  aclDestroyIntArray(sizeSplits);

  // 7. Release device resources.
  aclrtFree(inputDeviceAddr);
  aclrtFree(cosDeviceAddr);
  aclrtFree(sinDeviceAddr);
  aclrtFree(kcacheDeviceAddr);
  aclrtFree(vcacheDeviceAddr);
  aclrtFree(indicesDeviceAddr);
  aclrtFree(kscaleDeviceAddr);
  aclrtFree(vscaleDeviceAddr);
  aclrtFree(koffsetDeviceAddr);
  aclrtFree(voffsetDeviceAddr);
  aclrtFree(weightDeviceAddr);
  aclrtFree(activationDeviceAddr);
  aclrtFree(biasDeviceAddr);
  aclrtFree(qDeviceAddr);
  aclrtFree(kDeviceAddr);
  aclrtFree(vDeviceAddr);
  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();

  return 0;
}