aclnnExpandIntoJaggedPermute

Applicable Products

ProductSupported
Ascend 950PR/Ascend 950DT×
Atlas A3 training products/Atlas A3 inference products√
Atlas A2 training products/Atlas A2 inference products√
Atlas 200I/500 A2 inference products×
Atlas inference products×
Atlas training products×

Function

  • Description: Expands the permutation indices of sparse data from the table dimension to the batch dimension, applicable to scenarios where sparse features have different batch sizes across different ranks.

  • Formula:

len=outputOffset[i+1]−outputOffset[i]len = outputOffset[i+1] - outputOffset[i] outputPermuteOut[outputOffset[i]:outputOffset[i+1]]=arange(inputOffset[permute[i]],inputOffset[permute[i]]+len)outputPermuteOut[outputOffset[i]:outputOffset[i+1]] = arange(inputOffset[permute[i]],inputOffset[permute[i]]+len)

Function Prototype

Each operator uses a two-phase API. You must first call the "aclnnExpandIntoJaggedPermuteGetWorkspaceSize" API to obtain the workspace size required for computation and the executor that encapsulates the operator computation process, and then call the "aclnnExpandIntoJaggedPermute" API to perform the computation.

aclnnStatus aclnnExpandIntoJaggedPermuteGetWorkspaceSize(
    const aclTensor *permute,
    const aclTensor *inputOffset,
    const aclTensor *outputOffset,
    int64_t          outputSize,
    const aclTensor *outputPermuteOut,
    uint64_t        *workspaceSize,
    aclOpExecutor  **executor)
aclnnStatus aclnnExpandIntoJaggedPermute(
    void          *workspace,
    uint64_t       workspaceSize,
    aclOpExecutor *executor,
    aclrtStream    stream)

aclnnExpandIntoJaggedPermuteGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (Shape) Non-contiguous Tensor
    Permute Input The input permute in the formula, representing the table-level permutation index. Must be a one-dimensional tensor with values in the range [0, inputLen-1]. INT32 ND inputLen √
    inputOffset Input Represents inputOffset in the formula, which is the mutually exclusive offset of the table-level length. Specifies a one-dimensional tensor whose values are strictly monotonically increasing and whose last value equals outputSize. Same as permute. ND inputLen+1 √
    outputOffset Input outputOffset in the formula, representing the first shared expert. Must be a one-dimensional tensor whose values are strictly monotonically increasing and whose last value equals outputSize. Same as permute. ND inputLen+1 √
    outputSize Input. Represents the length of the output result. - INT32, INT64 - - -
    outputPermute Output Output in the formula. The shape is (outputSize). Same as permute. ND - √
    workspaceSize Output Returns the workspace size to be requested on the Device side. - - - - -
    executor Output Returns the operator executor, which contains the operator computation flow. - - - - -
  • Return value

    aclnnStatus: return 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 input, output, or attribute is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type or data format of the input or output is not within the supported range.
    ACLNN_ERR_INNER_TILING_ERROR 561002 Shape information mismatch between multiple input tensors.
    Shape information mismatch between input attributes and input tensors.

aclnnExpandIntoJaggedPermute

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address applied for on the Device side.
    workspaceSize Input Workspace size applied for on the Device side, obtained from the first-phase API aclnnExpandIntoJaggedPermuteGetWorkspaceSize.
    executor InputOperator executor, which contains the operator computation flow.
    stream Input Specifies the stream for task execution.
  • Return Value

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

Constraints

  • Deterministic computation:

    • aclnnExpandIntoJaggedPermute defaults to a deterministic implementation.
  1. inputOffset and outputOffset must have the same shape.

  2. permute, inputOffset, outputOffset, and outputPermuteOut must have the same data type.

  3. The values of outputOffset must be strictly monotonically increasing, and the last value equals outputSize.

Example

The following provides example code for reference only. For details about compilation and running, see Compile and Run Samples.

#include "aclnnop/aclnn_expand_into_jagged_permute.h"
#include <iostream>
#include <vector>
#include <sys/stat.h>
#include <fstream>
#include <fcntl.h>
#include <unistd.h>
#include <cstdio>
#include <cassert>
#include <iomanip>
#include <unistd.h>
#include "acl/acl.h"
#include "aclnn/acl_meta.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;
}

template <typename T>
bool ReadFile(const std::string &filePath, std::vector<int64_t> shape, std::vector<T>& hostData)
{
    size_t fileSize = 1;
    for (int64_t i : shape){
        fileSize *= i;
    }
    std::ifstream file(filePath, std::ios::binary);
    if (!file.is_open()) {
        std::cerr << "Unable to open file." << std::endl;
        return 1;
    }
    // Obtain the file size.
    file.seekg(0, std::ios::end);
    file.seekg(0, std::ios::beg);
    hostData.resize(fileSize);
    if (file.read(reinterpret_cast<char*>(hostData.data()), fileSize * sizeof(T))) {
    } else {
        std::cerr << "Failed to read file." << std::endl;
        return 1;
    }
    file.close();
    return true;
}

template <typename T>
bool WriteFile(const std::string &filePath, int64_t size, std::vector<T>& hostData)
{
    int fd = open(filePath.c_str(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
    if (fd < 0) {
        LOG_PRINT("Open file failed. path = %s", filePath.c_str());
        return false;
    }

    size_t writeSize = write(fd, reinterpret_cast<char*>(hostData.data()), size * sizeof(T));
    (void)close(fd);
    if (writeSize != size * sizeof(T)) {
        LOG_PRINT("Write file Failed.");
        return false;
    }

    return true;
}
void PrintOutResult(std::vector<int64_t>& shape, void** deviceAddr)
{
    auto size = GetShapeSize(shape);
    std::vector<float> 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 < 10; i++) {
        LOG_PRINT("result[%ld] is: %f\n", i, 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 apply for 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 a 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) Initialize the device/stream. See the ACL API.
  // Fill in the deviceId based on your 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. Customize the construction based on the API interface.
  std::vector<int64_t> permuteShape = {3};
  std::vector<int64_t>inputOffsetsShape = {4};
  std::vector<int64_t> outputOffsetsShape = {4};
  std::vector<int64_t> outputPermuteShape= {6};
  void* permuteDeviceAddr = nullptr;
  void* inputOffsetsDeviceAddr = nullptr;
  void* outputOffsetsDeviceAddr = nullptr;
  void* outputPermuteDeviceAddr = nullptr;

  aclTensor* permute = nullptr;
  aclTensor* inputOffsets = nullptr;
  aclTensor* outputOffsets = nullptr;
  aclTensor* outputPermute = nullptr;
  int64_t outputSize = 6;

  std::vector<int32_t> permuteHostData = {1, 0, 2};
  std::vector<int32_t> inputOffsetsHostData = {0, 3, 5, 8};
  std::vector<int32_t>outputOffsetsHostData = {0, 2, 4, 6};
  std::vector<int32_t> outputPermuteHostData = {3, 4, 0, 1, 5, 6};

  ret = CreateAclTensor(permuteHostData, permuteShape,
                        &permuteDeviceAddr, aclDataType::ACL_INT32,
                        &permute);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(inputOffsetsHostData, inputOffsetsShape, &inputOffsetsDeviceAddr,
                      aclDataType::ACL_INT32, &inputOffsets);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(outputOffsetsHostData, outputOffsetsShape, &outputOffsetsDeviceAddr,
                      aclDataType::ACL_INT32, &outputOffsets);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  ret = CreateAclTensor(outputPermuteHostData , outputPermuteShape , &outputPermuteDeviceAddr,
                      aclDataType::ACL_INT32, &outputPermute);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

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

  // Call the first-phase API of aclnnExpandIntoJaggedPermute.
  ret = aclnnExpandIntoJaggedPermuteGetWorkspaceSize(permute, inputOffsets, outputOffsets,
                                               outputSize, outputPermute, &workspaceSize, &executor);
  CHECK_RET(
      ret == ACL_SUCCESS,
      LOG_PRINT("aclnnExpandIntoJaggedPermuteGetWorkspaceSize failed. ERROR: %d\n", ret);
      return ret);

  // Apply for 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 aclnnExpandIntoJaggedPermute.
  ret = aclnnExpandIntoJaggedPermute(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS,
            LOG_PRINT("aclnnExpandIntoJaggedPermute failed. ERROR: %d\n", ret);
            return ret);

  // 4. (Boilerplate) Synchronously wait for task execution to complete.
  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 the device memory to the host memory. Modify based on the specific API definition.
  PrintOutResult(outputPermuteShape, &outputPermuteDeviceAddr);

  // 6. Release aclTensor and aclScalar. Modify based on the specific API definition.
  aclDestroyTensor(permute);
  aclDestroyTensor(inputOffsets);
  aclDestroyTensor(outputOffsets);
  aclDestroyTensor(outputPermute);

  // 7. Release device resources.
  aclrtFree(permuteDeviceAddr);
  aclrtFree(inputOffsetsDeviceAddr);
  aclrtFree(outputOffsetsDeviceAddr);
  aclrtFree(outputPermuteDeviceAddr);

  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();

  return 0;
}