aclnnKdaInputProj

📄 View Source Code

Applicable Products

  • Ascend 950PR&950DT products: Supported
  • Atlas A3 products: Not supported
  • Atlas A2 products: Not supported
  • Atlas 200I/500 A2 inference products: Not supported
  • Atlas inference products: Not supported
  • Atlas training products: Not supported

Function

  • Description: Pre-processing computation of Recurrent KDA in inference use cases. Projects the input $x$ to obtain qkv, beta, gate, and g, respectively:
    • Stage1: AIC computes X @ W_beta, X @ W_gate, and X @ W_g in parallel (BF16 Cube, FP32 accumulation); AIV executes DynamicMxQuant in parallel.
    • Stage2: AIV performs element-wise Sigmoid on beta and writes the result back in FP32; AIC executes QuantMatmul(qkv).
  • Formula:
    $$ \mathbf{beta}_{raw} = X W_{\beta}^{\mathrm{T}},\quad \mathbf{gate} = X W_{gate}^{\mathrm{T}},\quad \mathbf{g} = X W_{g}^{\mathrm{T}} $$
    $$ \mathbf{beta} = \sigma(\mathbf{beta}_{raw}) = \frac{1}{1 + e^{-\mathbf{beta}_{raw}}} $$
    $$ \mathbf{qkv} = \mathrm{QuantMatmul}\bigl(\mathrm{DynamicMxQuant}(X),\; W_{qkv},\; \mathrm{weight\_qkv\_scale}\bigr) $$
    where $X$ is a $[T,K]$ BF16 tensor; gate/g are BF16; beta is kept in FP32 before Sigmoid is applied.

Function Prototype

Each operator uses a two-phase API. First, call the "aclnnKdaInputProjGetWorkspaceSize" API to obtain the input parameters and calculate the required workspace size according to the process. Then, call the "aclnnKdaInputProj" API to perform the computation.

aclnnStatus aclnnKdaInputProjGetWorkspaceSize(
  const aclTensor *x,
  const aclTensor *weightQkv,
  const aclTensor *weightBeta,
  const aclTensor *weightGate,
  const aclTensor *weightG,
  const aclTensor *weightQkvScale,
  const aclTensor *qkvOut,
  const aclTensor *betaOut,
  const aclTensor *gateOut,
  const aclTensor *gOut,
  uint64_t        *workspaceSize,
  aclOpExecutor  **executor)
aclnnStatus aclnnKdaInputProj(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnKdaInputProjGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    x Input Hidden layer input, which is $X$ in the corresponding formula. Required. Does not support empty tensors. The input-side API performs AutoContiguous internally. BFLOAT16 ND [T, K] ×
    weightQkv Input qkv projection weight, which is $W_{qkv}$ in the corresponding formula. Required. Does not support empty tensors. The K dimension must match that of x. FLOAT8_E4M3FN ND [K, N_qkv] √
    weightBeta Input Projection weight of beta, corresponding to $W_{\beta}$ in the formula. Required. Does not support empty tensors. The K dimension must match that of x. BFLOAT16 ND [K, N_beta] √
    weightGate Input gate projection weight, corresponding to $W_{gate}$ in the formula. Required. Does not support an empty tensor. The K dimension must match the K dimension of x. BFLOAT16 ND [K, N_gate] √
    weightG Input Projection weight of g, corresponding to $W_{g}$ in the formula. Required. Does not support empty tensors. The K dimension must match the K dimension of x. BFLOAT16 ND [K, N_g] √
    weightQkvScale Input MX quantization scale factor of weightQkv. The last dimension is packed in high-low order. Required. Does not support empty tensors. The last dimension is fixed to 2. The MX block size is 64. FLOAT8_E8M0 ND [N_qkv, Ceil(K/64), 2] if weightQkv is a transposed view; otherwise [Ceil(K/64), N_qkv, 2] √
    qkvOut Output qkv projection output. BFLOAT16 ND [T, N_qkv] ×
    betaOut Output Output obtained by applying Sigmoid after beta projection, i.e., $\mathbf{beta}$ in the corresponding formula. Caller pre-allocation. Output is FP32. FLOAT ND [T, N_beta] ×
    gateOut Output gate projection output, corresponding to $\mathbf{gate}$ in the formula. Caller pre-allocation. BFLOAT16 ND [T, N_gate] ×
    gOut Output g projection output, corresponding to $\mathbf{g}$ in the formula. Caller pre-allocation. BFLOAT16 ND [T, N_g] ×
    workspaceSize Output parameter Returns the size of the workspace that needs to be side-applied on the Device. - - - - -
    executor Output parameter Returns the op executor that contains the operator computation flow. - - - - -
  • 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:

    Return Value Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 A required parameter is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The shape or dtype of the input parameter is not in the supported range, or the K dimension of the weight is not consistent with x.
    ACLNN_ERR_RUNTIME_ERROR 361001 An exception occurs when the API calls the npu runtime interface for memory operations.
    ACLNN_ERR_INNER_TILING_ERROR 561002 An exception occurs during tiling, and the dtype or shape of the input parameter is incorrect.

aclnnKdaInputProj

  • Parameters

    Parameter Input/Output Description
    workspace Input Memory address of the workspace applied on the Device side. A null pointer can be passed in when workspaceSize is 0.
    workspaceSize Input Size of the workspace applied on the Device side, obtained by the first-phase API aclnnKdaInputProjGetWorkspaceSize.
    executor Input Op executor, containing the operator computation flow.
    stream Input Stream for executing tasks.
  • Return Value

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

Constraints

  • Deterministic computation:
    • aclnnKdaInputProj defaults to a deterministic implementation.
  • Meanings and constraints of shape fields
    • T: number of tokens, greater than 0.
    • K: hidden size, greater than 0.
    • N_qkv / N_beta / N_gate / N_g: number of output features for each projection, greater than 0.
  • Data type constraints
    • x, weightBeta, weightGate, weightG, gateOut, gOut, qkvOut: BF16.
    • weightQkv: FLOAT8_E4M3FN.
    • weightQkvScale: FLOAT8_E8M0.
    • betaOut: FLOAT.

Example

The following sample code is for reference only. For details about the compilation and execution procedure, see Compile and Run Samples. For the complete source code, see test_aclnn_kda_input_proj.cpp.

#include <cstdint>
#include <cstdio>
#include <vector>
#include "acl/acl.h"
#include "aclnn/acl_meta.h"
#include "aclnnop/aclnn_kda_input_proj.h"

#define CHECK_RET(cond, return_expr) \
  do {                               \
    if (!(cond)) {                   \
      return_expr;                   \
    }                                \
  } while (0)

#define LOG_PRINT(message, ...) printf(message, ##__VA_ARGS__)

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

int Init(int32_t deviceId, aclrtStream *stream)
{
    auto ret = aclInit(nullptr);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret);
    ret = aclrtSetDevice(deviceId);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret);
    ret = aclrtCreateStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret);
    return 0;
}

template <typename T>
int CreateAclTensor(const std::vector<T> &hostData, const std::vector<int64_t> &shape, void **deviceAddr,
                    aclDataType dataType, aclTensor **tensor)
{
    auto size = GetShapeSize(shape) * static_cast<int64_t>(sizeof(T));
    auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);
    ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);
    std::vector<int64_t> strides(shape.size(), 1);
    for (int64_t i = static_cast<int64_t>(shape.size()) - 2; i >= 0; --i) {
        strides[i] = shape[i + 1] * strides[i + 1];
    }
    *tensor = aclCreateTensor(shape.data(), static_cast<int64_t>(shape.size()), dataType, strides.data(), 0,
                              ACL_FORMAT_ND, shape.data(), static_cast<int64_t>(shape.size()), *deviceAddr);
    return 0;
}

int main()
{
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = Init(deviceId, &stream);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    const int64_t T = 1;
    const int64_t K = 256;
    const int64_t Nqkv = 128;
    const int64_t Nbeta = 16;
    const int64_t Ngate = 32;
    const int64_t Ng = 32;
    const int64_t mxK = (K + 63) / 64;

    std::vector<int64_t> xShape = {T, K};
    std::vector<int64_t> wQkvShape = {K, Nqkv};
    std::vector<int64_t> wBetaShape = {K, Nbeta};
    std::vector<int64_t> wGateShape = {K, Ngate};
    std::vector<int64_t> wGShape = {K, Ng};
    std::vector<int64_t> weightQkvScaleShape = {mxK, Nqkv, 2};
    std::vector<int64_t> qkvShape = {T, Nqkv};
    std::vector<int64_t> betaShape = {T, Nbeta};
    std::vector<int64_t> gateShape = {T, Ngate};
    std::vector<int64_t> gShape = {T, Ng};

    std::vector<uint16_t> xHost(T * K, 0x3F80);
    std::vector<uint8_t> wQkvHost(Nqkv * K, 0);
    std::vector<uint16_t> wBetaHost(Nbeta * K, 0);
    std::vector<uint16_t> wGateHost(Ngate * K, 0);
    std::vector<uint16_t> wGHost(Ng * K, 0);
    std::vector<uint8_t> weightQkvScaleHost(Nqkv * mxK * 2, 0);
    std::vector<uint16_t> qkvHost(T * Nqkv, 0);
    std::vector<float> betaHost(T * Nbeta, 0.0f);
    std::vector<uint16_t> gateHost(T * Ngate, 0);
    std::vector<uint16_t> gHost(T * Ng, 0);

    void *xDev = nullptr, *wQkvDev = nullptr, *wBetaDev = nullptr, *wGateDev = nullptr, *wGDev = nullptr;
    void *weightQkvScaleDev = nullptr, *qkvDev = nullptr, *betaDev = nullptr, *gateDev = nullptr, *gDev = nullptr;
    aclTensor *x = nullptr, *wQkv = nullptr, *wBeta = nullptr, *wGate = nullptr, *wG = nullptr;
    aclTensor *weightQkvScale = nullptr, *qkv = nullptr, *beta = nullptr, *gate = nullptr, *g = nullptr;

    CreateAclTensor(xHost, xShape, &xDev, ACL_BF16, &x);
    CreateAclTensor(wQkvHost, wQkvShape, &wQkvDev, ACL_FLOAT8_E4M3FN, &wQkv);
    CreateAclTensor(wBetaHost, wBetaShape, &wBetaDev, ACL_BF16, &wBeta);
    CreateAclTensor(wGateHost, wGateShape, &wGateDev, ACL_BF16, &wGate);
    CreateAclTensor(wGHost, wGShape, &wGDev, ACL_BF16, &wG);
    CreateAclTensor(weightQkvScaleHost, weightQkvScaleShape, &weightQkvScaleDev, ACL_FLOAT8_E8M0, &weightQkvScale);
    CreateAclTensor(qkvHost, qkvShape, &qkvDev, ACL_BF16, &qkv);
    CreateAclTensor(betaHost, betaShape, &betaDev, ACL_FLOAT, &beta);
    CreateAclTensor(gateHost, gateShape, &gateDev, ACL_BF16, &gate);
    CreateAclTensor(gHost, gShape, &gDev, ACL_BF16, &g);

    uint64_t workspaceSize = 0;
    aclOpExecutor *executor = nullptr;
    ret = aclnnKdaInputProjGetWorkspaceSize(x, wQkv, wBeta, wGate, wG, weightQkvScale, qkv, beta, gate, g, &workspaceSize,
                                         &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("GetWorkspaceSize failed. ERROR: %d\n", ret); return ret);

    void *workspace = nullptr;
    if (workspaceSize > 0) {
        ret = aclrtMalloc(&workspace, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
    }
    ret = aclnnKdaInputProj(workspace, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnKdaInputProj failed. ERROR: %d\n", ret); return ret);
    ret = aclrtSynchronizeStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    aclDestroyTensor(x);
    aclDestroyTensor(wQkv);
    aclDestroyTensor(wBeta);
    aclDestroyTensor(wGate);
    aclDestroyTensor(wG);
    aclDestroyTensor(weightQkvScale);
    aclDestroyTensor(qkv);
    aclDestroyTensor(beta);
    aclDestroyTensor(gate);
    aclDestroyTensor(g);
    aclrtFree(xDev);
    aclrtFree(wQkvDev);
    aclrtFree(wBetaDev);
    aclrtFree(wGateDev);
    aclrtFree(wGDev);
    aclrtFree(weightQkvScaleDev);
    aclrtFree(qkvDev);
    aclrtFree(betaDev);
    aclrtFree(gateDev);
    aclrtFree(gDev);
    if (workspace != nullptr) {
        aclrtFree(workspace);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return 0;
}