aclnnTopKTopPSample
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 topK-topP-sample sampling calculation based on the input word frequency logits, topK/topP sampling parameters, and random sampling weight distribution q, and outputs the maximum word frequency logitsSelectIdx of each batch, and the word frequency distribution logitsTopKPSelect after topK-topP sampling.
The operator contains three sampling algorithms that can be enabled individually while keeping the upstream and downstream processing relationships unchanged (from the original input to the final output): TopK sampling, TopP sampling, and exponential sampling (referred to as Sample in this document). They can form eight computation scenarios. As shown in the following table:
Computation Scenario TopK Sampling TopP Sampling Exponential Sampling Note Softmax-Argmax Sampling × × × Applies Softmax to the input logits for each batch and takes the maximum result. TopK Sampling √ × × Takes the top topK[batch] maximum results from the input logits for each batch. TopP Sampling × √ × Sorts the input logits in descending order for each batch, and samples the first n results whose cumulative sum is greater than or equal to the topP[batch] value. Sample Sampling × × √ Applies Softmax to the input logits for each batch, divides by q, and takes the maximum result. TopK-TopP Sampling √ √ × Performs TopK sampling first, then TopP sampling on the input logits for each batch, and takes the maximum result. TopK-Sample Sampling √ × √ Performs TopK sampling first, then Sample sampling on the input logits for each batch, and takes the maximum result. TopP-Sample Sampling × √ √ Performs TopP sampling first, then Sample sampling on the input logits for each batch, and takes the maximum result. TopK-TopP-Sample Sampling √ √ √ Performs TopK sampling first, then TopP sampling, and finally Sample sampling on the input logits for each batch, and takes the maximum result. Formula: The input logits is a term frequency table of size [batch, voc_size], where each batch corresponds to an input sequence, and voc_size is the uniform length agreed upon for each batch.
Each row logits[batch][:] in logits executes different compute scenarios based on the corresponding topK[batch], topP[batch], and q[batch, :].
In the following formulas, b and v are used to denote indices along the batch and voc_size dimensions, respectively.TopK Sampling
- Uses segmented TopK merge sort with segment length v, where the TopK of block {s-1} is used to pre-filter the input of the current block {s}, progressively updating the TopK of a single batch to reduce redundant data and computation.
- topK[batch] corresponds to the k value sampled for the current batch. The valid range is 1≤topK[batch]≤min(voc_size[batch], 1024). If top[K] is out of the valid range, the topK sampling phase of the current batch is skipped, and the sorting of the current batch is also skipped; the input logits[batch] is directly passed to the next module.
- Split the current batch into several sub-segments and compute topKValue[b] in a rolling manner:
Where:
v denotes the preset fixed segment length for rolling topK:
- Generate the mask to be filtered.
- Set values below the threshold to -Inf via mask
- Use safe_softmax to convert the topK-filtered logits into a probability distribution along the last axis
- Computes the cumulative probability along the last axis (accumulating from the smallest probability).
TopP Sampling
If the preceding TopK sampling already produces sorted output results, computes the cumulative term frequency based on the TopK sampling output and performs truncation sampling according to TopP:
If TopK sampling is skipped, first perform softmax on the input logits[b]:
- Attempt to use topKGuess to perform rolling sort on logits and obtain the mask for computing topP:
- If the following condition is met before accessing the 1e4-th element of logitsValue[b], topKGuess is considered successful:
- If topKGuess fails, perform full sorting and cumsum on the current logitsValue[b], and truncate sampling by topP[b]:
- Set the positions to be filtered to -Inf, obtaining sortedValue[b][v]:
Take the first topK elements in each row of the filtered sortedValue[b][v], find the original indices of these elements in the input, and consolidate them into
logitsIdx:
Exponential sampling (Sample)
- If
isNeedLogits=true, select the sampled result based onlogitsIdxand output it tologitsTopKPSelect:
Perform exponential distribution sampling on
logitsSort:Take the maximum element of each batch from
probsOpt, and gather the input index of the corresponding element fromlogitsIdxas the outputlogitsSelectIdx:
Where 0 ≤ b < sortedValue.size(0) and 0 ≤ v < sortedValue.size(1).
Function Prototype
Each operator uses a two-phase API. First call the aclnnTopKTopPSampleGetWorkspaceSize API to obtain the workspace size required for the computation and the executor that contains the computation flow of the operator. Then call the aclnnTopKTopPSample API to perform the computation.
aclnnStatus aclnnTopKTopPSampleGetWorkspaceSize(
const aclTensor *logits,
const aclTensor *topK,
const aclTensor *topP,
const aclTensor *q,
double eps,
bool isNeedLogits,
int64_t topKGuess,
const aclTensor *logitsSelectIdx,
const aclTensor *logitsTopKPSelect,
uint64_t *workspaceSize,
aclOpExecutor **executor)
aclnnStatus aclnnTopKTopPSample(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)
aclnnTopKTopPSampleGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor logits Input Indicates the input word frequency to be sampled. The word frequency index is fixed to the last dimension, corresponding to `logits` in the formula. - Does not support empty tensors.
FLOAT16, BFLOAT16 ND 2 √ topK Input Indicates the k value for sampling in each batch. Corresponds to `topK[b]` in the formula. - Does not support empty tensors.
- The shape needs to be consistent with the first n-1 dimensions of `logits`.
INT32 ND 1 √ topP Input Indicates the p value sampled for each batch. Corresponds to `topP[b]` in the formula. - Does not support empty tensors.
- The shape needs to be consistent with the first n-1 dimensions of `logits`, and the data type needs to be consistent with `logits`.
FLOAT16, BFLOAT16 ND 1 √ q Input Indicates the exponential sampling matrix output by topK-topP sampling. Corresponding formula: `q`. - Does not support empty tensors.
- The shape needs to be consistent with `logits`.
FLOAT32 ND 2 √ eps Input Indicates the value for preventing division by zero in softmax and weighted sampling. It is recommended to set it to 1e-8. - DOUBLE - - - isNeedLogits Input Indicates the output condition for controlling logitsTopKPselect. Recommended value: 0. - BOOL - - - topKGuess Input Indicates each batch's candidate logits size when attempting topP partial traversal sampling of logits. Must be a positive integer. - INT64 - - - logitsSelectIdx Output Indicates the position index of the element with the maximum word frequency in each batch, max(probsOpt[batch, :]), in the input logits after the topK-topP-sample computation flow. - Does not support empty tensors.
- The shape must be the same as the first n-1 dimensions of `logits`.
INT64 ND 1 √ logitsTopKPSelect Output Indicates the remaining logits in the input logits that are not filtered out after the topK-topP computation process. - Does not support empty tensors.
- The shape needs to be consistent with the first n-1 dimensions of `logits`.
FLOAT32 ND 2 √ workspaceSize Output Returns the size of the workspace requested by the Device. - - - - - executor Output Returns the op executor containing the operator computation flow. - - - - - 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 Any of the input parameters logits, topK, and topP is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data types of logits, topK, topP, and q are not within the supported range. The dimensions or sizes of logits and q are inconsistent. The dimensions of topK and topP are inconsistent with the first n-1 dimensions of logits. The data types of logits and topP are inconsistent.
aclnnTopKTopPSample
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address requested by the Device. workspaceSize Input Size of the workspace requested by the Device, obtained by the first-phase API aclnnTopKTopPSampleGetWorkspaceSize. executor Input Op executor, which contains the operator computation flow. stream Input Stream for task execution. Return value
aclnnStatus: return status code. For details, see aclnn Error Codes.
Constraints
- Deterministic computation:
- aclnnTopKTopPSample defaults to a deterministic implementation.
- For logits, ensure that the value of each element after the operation is not smaller than the minimum valid value of FLOAT32. Otherwise, the corresponding Safe_softmax result will be 0, which may cause unexpected output of the operator.
- For all sampling parameters, their dimensions must satisfy batch > 0 and 0 < vocSize <= 2^20.
- topK and topP accept only non-negative values as valid input. Passing 0 or negative values does not skip the sampling of the corresponding batch; instead, it causes unexpected errors.
- The sizes and dimensions of logits, q, and logitsTopKPselect must be exactly the same.
- All dimensions of logits, topK, topP, and logitsSelectIdx except the last dimension must be in the same order and of the same size. Currently, logits can only be 2-dimensional, and topK, topP, and logitsSelectIdx must be 1-dimensional non-null tensors. Null tensors are not allowed as input for logits, topK, and topP. To skip the corresponding module, set the input according to the corresponding rules.
- To skip the topK module individually, pass a tensor of size [batch, 1] with each element set to an invalid value.
- If 1024 < topK[batch] < vocSize[batch], all valid elements of the current batch are selected and topK sampling is skipped.
- To skip the topP module individually, pass a tensor of size [batch, 1] with each element ≥ 1.
- To skip the sample module, pass
q=nullptr. To use the sample module, pass a tensor of size [batch, vocSize].
Example
The following sample code is 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_top_k_top_p_sample.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;
}
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 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 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;
}
int main() {
// 1. (boilerplate) Initialize device/stream. Refer to the acl API.
// 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. Customize the construction based on the API.
std::vector<int64_t> logitsShape = {48, 131072};
std::vector<int64_t> topKPShape = {48};
long long vocShapeSize = GetShapeSize(logitsShape);
long long batchShapeSize = GetShapeSize(topKPShape);
void* logitsDeviceAddr = nullptr;
void* topKDeviceAddr = nullptr;
void* topPDeviceAddr = nullptr;
void* qDeviceAddr = nullptr;
void* logitsSelectedIdxDeviceAddr = nullptr;
void* logitsTopKPSelectDeviceAddr = nullptr;
aclTensor* logits = nullptr;
aclTensor* topK = nullptr;
aclTensor* topP = nullptr;
aclTensor* q = nullptr;
aclTensor* logitsSelectIdx = nullptr;
aclTensor* logitsTopKPSelect = nullptr;
std::vector<int16_t> logitsHostData(48 * 131072, 1);
std::vector<int32_t> topKHostData(48, 128);
std::vector<int16_t> topPHostData(48, 1);
std::vector<float> qHostData(48 * 131072, 1.0f);
std::vector<int64_t> logitsSelectedIdxHostData(48, 0);
std::vector<float> logitsTopKPSelectHostData(48 * 131072, 0);
float eps=1e-8;
int64_t isNeedLogits=0;
int32_t topKGuess=32;
// Create the logits aclTensor.
ret = CreateAclTensor(logitsHostData, logitsShape, &logitsDeviceAddr, aclDataType::ACL_BF16, &logits);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the topK aclTensor.
ret = CreateAclTensor(topKHostData, topKPShape, &topKDeviceAddr, aclDataType::ACL_INT32, &topK);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the topP aclTensor.
ret = CreateAclTensor(topPHostData, topKPShape, &topPDeviceAddr, aclDataType::ACL_BF16, &topP);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the q aclTensor.
ret = CreateAclTensor(qHostData, logitsShape, &qDeviceAddr, aclDataType::ACL_FLOAT, &q);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the logitsSelected aclTensor.
ret = CreateAclTensor(logitsSelectedIdxHostData, topKPShape, &logitsSelectedIdxDeviceAddr, aclDataType::ACL_INT64, &logitsSelectIdx);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the logitsTopKPSelect aclTensor.
ret = CreateAclTensor(logitsTopKPSelectHostData, logitsShape, &logitsTopKPSelectDeviceAddr, aclDataType::ACL_FLOAT, &logitsTopKPSelect);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API, and change it to the specific API name.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API of aclnnTopKTopPSample.
ret = aclnnTopKTopPSampleGetWorkspaceSize(logits, topK, topP, q, eps, isNeedLogits, topKGuess, logitsSelectIdx, logitsTopKPSelect, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTopKTopPSampleGetWorkspaceSize 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 aclnnTopKTopPSample.
ret = aclnnTopKTopPSample(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTopKTopPSample 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. Copy the result in device memory to the host side. Modify the code according to the specific API definition.
auto size = GetShapeSize(topKPShape);
std::vector<int64_t> resultData(size, 0);
ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), logitsSelectedIdxDeviceAddr,
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);
for (int64_t i = 0; i < size; i++) {
LOG_PRINT("result[%ld] is: %lld\n", i, static_cast<long long>(resultData[i]));
}
// 6. Release the aclTensor. Modify the code according to the specific API definition.
aclDestroyTensor(logits);
aclDestroyTensor(topK);
aclDestroyTensor(topP);
aclDestroyTensor(q);
aclDestroyTensor(logitsSelectIdx);
aclDestroyTensor(logitsTopKPSelect);
// 7. Release Device resources. Modify it based on the specific API definition.
aclrtFree(logitsDeviceAddr);
aclrtFree(topKDeviceAddr);
aclrtFree(topPDeviceAddr);
aclrtFree(qDeviceAddr);
aclrtFree(logitsSelectedIdxDeviceAddr);
aclrtFree(logitsTopKPSelectDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}