aclnnAdvanceStep

📄 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:

    vLLM is a high-performance LLM inference and serving framework focused on optimizing the inference efficiency of large-scale language models. Its core features include PageAttention and efficient memory management. The primary function of the advance_step operator is to advance the inference step, i.e., updating the model state at each generation step and generating new inputTokens, inputPositions, seqLens, and slotMapping, thereby improving efficiency for vLLM inference.

  • Formula:

    blockIdxistheindexofthekernelwherethecurrentcodeisexecuted.blockIdx is the index of the kernel where the current code is executed. blockTablesStride=blockTables.stride(0)blockTablesStride = blockTables.stride(0) inputTokens[blockIdx]=sampledTokenIds[blockIdx]inputTokens[blockIdx] = sampledTokenIds[blockIdx] inputPositions[blockIdx]=seqLens[blockIdx]inputPositions[blockIdx] = seqLens[blockIdx] seqLens[blockIdx]=seqLens[blockIdx]+1seqLens[blockIdx] = seqLens[blockIdx] + 1 slotMapping[blockIdx]=(blockTables[blockIdx]+blockTablesStride∗blockIdx)∗blockSize+(seqLens[blockIdx]%blockSize)slotMapping[blockIdx] = (blockTables[blockIdx] + blockTablesStride * blockIdx) * blockSize + (seqLens[blockIdx] \% blockSize)

Function Prototype

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

aclnnStatus aclnnAdvanceStepGetWorkspaceSize(
  const aclTensor *inputTokens,
  const aclTensor *sampledTokenIds,
  const aclTensor *inputPositions,
  const aclTensor *seqLens,
  const aclTensor *slotMapping,
  const aclTensor *blockTables,
  int64_t          numSeqs,
  int64_t          numQueries,
  int64_t          blockSize,
  uint64_t        *workspaceSize,
  aclOpExecutor  **executor)
aclnnStatus aclnnAdvanceStep(
  void            *workspace,
  uint64_t         workspaceSize,
  aclOpExecutor   *executor,
  aclrtStream      stream)

aclnnAdvanceStepGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    inputTokens (aclTensor*) Input Input/output parameter for the pending AdvanceStep calculation. It is the output inputTokens in the formula, used to update the token value in the vLLM model.
    • Empty tensors are not supported.
    • The shape length and numSeqs must be consistent.
    • The value range is positive integers greater than 0.
    INT64 ND 1 ×
    sampledTokenIds (aclTensor*) Input Input parameter for the pending AdvanceStep calculation, used to store the token ID. It is the input sampledTokenIds in the formula.
    • Empty tensors are not supported.
    • The first dimension of shape and numQueries are consistent in length, and the second dimension is 1.
    • The value range is positive integers greater than 0.
    INT64 ND 2 ×
    inputPositions (aclTensor*) Input/Output Input/output parameter of the pending AdvanceStep calculation, which is the output inputPositions in the formula, used to record the index of tokens.
    • Empty tensors are not supported.
    • The shape length and numSeqs are consistent.
    • The value range is positive integers greater than 0.
    INT64 ND 2 ×
    seqLens (aclTensor*) Input/Output Input/output parameter pending AdvanceStep calculation, used to record the length of seq under each blockIdx, i.e., the input/output seqLens in the formula.
    • Empty Tensor not supported.
    • The shape length is consistent with numSeqs.
    • The value range is positive integers greater than 0.
    INT64 ND 1 ×
    slotMapping (aclTensor*) Input/Output Input/Output parameter for the pending AdvanceStep calculation. Output slotMapping in the formula, used to map the position of a token value in a sequence to a physical location.
    • Empty tensors are not supported.
    • The shape length and numSeqs are consistent.
    • The value range is positive integers greater than 0.
    INT64 ND 1 ×
    blockTables (aclTensor*) Input Input for the pending AdvanceStep calculation, used to record the physical block IDs of blocks under different blockIdx. It is the input blockTables in the formula.
    • Empty tensors are not supported.
    • The first dimension length of shape and numSeqs are consistent, and the second dimension is greater than (the maximum value in seqLens)/blockSize.
    • The value range is positive integers greater than 0.
    INT64 ND 2 ×
    numSeqs (int64_t) Input Records the number of input seqs. The size is consistent with the length of seqLens.
    • The value range is a positive integer less than 200000000.
    • The value of numSeqs is greater than the value of input numQueries.
    - - - -
    numQueries (int64_t) Input Records the number of input queries. The size is consistent with the length of the first dimension of sampledTokenIds. The value range is a positive integer greater than 0. - - - -
    blockSize (int64_t) Input Size of each block, corresponding to blockSize in the formula. The value range is positive integers greater than 0. - - - -
    workspaceSize (uint64_t*) Output Returns the workspace size requested by Device. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation process. - - - - -
  • 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 The input inputTokens, sampledTokenIds, inputPositions, seqLens, slotMapping, or blockTables is a null pointer.
ACLNN_ERR_PARAM_INVALID 161002 The data type of inputTokens, sampledTokenIds, inputPositions, seqLens, slotMapping, and blockTables is not within the supported range.
aclnnAdvanceStepGetWorkspaceSize failed 561002 The length of the first dimension of the shape of input inputTokens, inputPositions, seqLens, slotMapping, and blockTables is not consistent with numSeqs.
The first dimension of input sampledTokenIds is not consistent with numQueries, or the second dimension is not 1.
The value of input numSeqs is less than or equal to the value of input numQueries.

aclnnAdvanceStep

  • 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 the first-phase API aclnnAdvanceStepGetWorkspaceSize.
    executor Input Op executor, containing the operator computation flow.
    stream Input Specifies the stream for executing tasks.
  • Return value

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

Constraints

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

Example

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

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_advance_step.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<int64_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("advanceStep result[%ld] is: %ld\n", i, resultData[i]);
    }
}

int Init(int64_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 request 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);

    // 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);
    return 0;
}

int main() {
    // 1. (Boilerplate) Device/stream initialization. For details, see 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);

    // 2. Construct the input and output. Custom construction is required based on the API.
    std::vector<int64_t> inputShape = {8};
    std::vector<int64_t> input2Shape = {4,1};
    std::vector<int64_t> inputHostData = {0, 1, 2, 3, 4, 5, 6, 7};
    std::vector<int64_t> input2HostData = {0, 1, 2, 3};

    void* input1DeviceAddr = nullptr;
    aclTensor* input1 = nullptr;
    void* input2DeviceAddr = nullptr;
    aclTensor* input2 = nullptr;
    void* input3DeviceAddr = nullptr;
    aclTensor* input3 = nullptr;
    void* input4DeviceAddr = nullptr;
    aclTensor* input4 = nullptr;
    void* input5DeviceAddr = nullptr;
    aclTensor* input5 = nullptr;
    void* input6DeviceAddr = nullptr;
    aclTensor* input6 = nullptr;
    // Create the input aclTensor.
    ret = CreateAclTensor(inputHostData, inputShape, &input1DeviceAddr, aclDataType::ACL_INT64, &input1);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    ret = CreateAclTensor(input2HostData, input2Shape, &input2DeviceAddr, aclDataType::ACL_INT64, &input2);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(inputHostData, inputShape, &input3DeviceAddr, aclDataType::ACL_INT64, &input3);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(inputHostData, inputShape, &input4DeviceAddr, aclDataType::ACL_INT64, &input4);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(inputHostData, inputShape, &input5DeviceAddr, aclDataType::ACL_INT64, &input5);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(inputHostData, inputShape, &input6DeviceAddr, aclDataType::ACL_INT64, &input6);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    int64_t numseq = 8;
    int64_t numqueries = 4;
    int64_t blocksize = 2;

    // 3. Call the CANN operator library API. Modify it to the specific API name.
    uint64_t workspaceSize = 16 * 1024 * 1024;
    aclOpExecutor* executor;

    // Call the first-phase API of aclnnAdvanceStep.
    ret = aclnnAdvanceStepGetWorkspaceSize(
    input1,input2,input3,input4,input5,input6,
    numseq,numqueries,blocksize,
    &workspaceSize,
    &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnAdvanceStepGetWorkspaceSize 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 aclnnAdvanceStep.
    ret = aclnnAdvanceStep(
    workspaceAddr,
    workspaceSize,
    executor,
    stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnAdvanceStep failed. ERROR: %d\n", ret); return ret);

    // 4. (Boilerplate) Synchronously wait for the task to complete.
    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 results on the device side to the host side. Modify as required by the specific API definition.
    PrintOutResult(inputShape, &input1DeviceAddr);
    PrintOutResult(inputShape, &input3DeviceAddr);
    PrintOutResult(inputShape, &input4DeviceAddr);
    PrintOutResult(inputShape, &input5DeviceAddr);

    // 6. Release aclTensor and aclTensor. Modify as required by the specific API definition.
    aclDestroyTensor(input1);
    aclDestroyTensor(input2);
    aclDestroyTensor(input3);
    aclDestroyTensor(input4);
    aclDestroyTensor(input5);
    aclDestroyTensor(input6);

    // 7. Release device resources. Modify as required by the specific API definition.
    aclrtFree(input1DeviceAddr);
    aclrtFree(input2DeviceAddr);
    aclrtFree(input3DeviceAddr);
    aclrtFree(input4DeviceAddr);
    aclrtFree(input5DeviceAddr);
    aclrtFree(input6DeviceAddr);
    if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();

    return 0;
}