aclnnRepeat

📄 View Source Code

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: Replicates the input tensor along each dimension by the number of times specified in repeats.

  • Example: Assume the input tensor is [[a,b],[c,d],[e,f]] with shape [3,2], and repeats is (2,4). The resulting tensor has shape [6,8] with the following values:

    >>> x = torch.tensor([[a,b],[c,d],[e,f]])
    >>> x.repeat(2,4)
    tensor([[a,b,a,b,a,b,a,b],
            [c,d,c,d,c,d,c,d],
            [e,f,e,f,e,f,e,f],
            [a,b,a,b,a,b,a,b],
            [c,d,c,d,c,d,c,d],
            [e,f,e,f,e,f,e,f],
            ])
  • When repeats is (2,4,2), meaning the number of elements in repeats is greater than the number of dimensions in the tensor, the output tensor is equivalent to the following operation: first, expand the shape of the input tensor to the same number of dimensions as repeats: [1,3,2], then expand according to the corresponding dimensions and the values of repeats, resulting in an output tensor shape of [2,12,4], as shown below:

    >>> x.repeat(2,4,2)
    tensor([[[a,b,a,b],
            [c,d,c,d],
            [e,f,e,f],
            [a,b,a,b],
            [c,d,c,d],
            [e,f,e,f],
            [a,b,a,b],
            [c,d,c,d],
            [e,f,e,f],
            [a,b,a,b],
            [c,d,c,d],
            [e,f,e,f]],
    
            [[a,b,a,b],
            [c,d,c,d],
            [e,f,e,f],
            [a,b,a,b],
            [c,d,c,d],
            [e,f,e,f],
            [a,b,a,b],
            [c,d,c,d],
            [e,f,e,f],
            [a,b,a,b],
            [c,d,c,d],
            [e,f,e,f]]])
  • The following conditions must be met during computation:

    • The number of parameters in repeats must not be less than the number of dimensions of the input tensor.

    • The values in repeats must be greater than or equal to 0.

Function Prototype

Each operator is divided into a two-phase API. The "aclnnRepeatGetWorkspaceSize" API must be called first to obtain the workspace size required for computation and the executor that encapsulates the operator computation flow. Then, the "aclnnRepeat" API is called to perform the computation.

aclnnStatus aclnnRepeatGetWorkspaceSize(
    const aclTensor   *self,
    const aclIntArray *repeats,
    aclTensor         *out,
    uint64_t          *workspaceSize,
    aclOpExecutor    **executor)
aclnnStatus aclnnRepeat(
    void          *workspace,
    uint64_t       workspaceSize,
    aclOpExecutor *executor,
    aclrtStream    stream)

aclnnRepeatGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Shape Non-contiguous Tensor
    self (aclTensor*) Input - - FLOAT, DOUBLE, FLOAT16, COMPLEX64, COMPLEX128, UINT8, INT8, INT16, INT32, INT64, UINT16, UINT32, UINT64, BOOL, BFLOAT16, HIFLOAT8, FLOAT8_E5M2, FLOAT8_E4M3FN ND ≤8 √
    repeats (aclIntArray*) Input - Specifies the number of times to repeat the input tensor along each dimension. The number of parameters cannot exceed 8.
    Currently, repeating along more than four dimensions simultaneously is not supported. For detailed constraints, see Constraints.
    INT64 - - -
    out (aclTensor*) Output - - Same as self. ND ≤8 √
    workspaceSize (uint64_t*) Output Returns the workspace size to be requested on the Device. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - -
    • Atlas A2 training products/Atlas A2 inference products, Atlas A3 training products/Atlas A3 inference products: HIFLOAT8, FLOAT8_E5M2, and FLOAT8_E4M3FN are not supported.

    • Atlas training products and Atlas inference products: The data types BFLOAT16, HIFLOAT8, FLOAT8_E5M2, and FLOAT8_E4M3FN are not supported.

  • Return Value

    aclnnStatus: return 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 self or out is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type or data format of self and out is not within the supported range.
    The types of self and out do not match.
    The number of elements in the repeats parameter is less than the dimension of the input tensor.
    The repeats parameter contains a value less than 0.
    The number of dimensions of self exceeds 8.
    The number of elements in the repeats parameter exceeds 8.
    ACLNN_ERR_INNER_NULLPTR 561103 Kernel execution failed, and the intermediate result is null.
    Repeat is performed on more than four dimensions simultaneously.

aclnnRepeat

  • Parameters

    Parameter Input/Output Description
    workspace Input Address of the workspace memory applied on the Device side.
    workspaceSize Input Size of the workspace applied on the Device side, obtained through the first-phase API aclnnRepeatGetWorkspaceSize.
    executor Input Operator executor, which contains the operator computation process.
    stream Input Specifies the stream for task execution.
  • Return Value

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

Constraints

  • Deterministic computation:

    • aclnnRepeat defaults to a deterministic implementation.

The internal broadcast kernel of the repeat function has a maximum limit of 8 dimensions. Scenarios where the expanded dimensions exceed 8 are not supported. Details are as follows: Constraint 1. When a repeat operation is required on the first axis, repeat operations on up to 4 dimensions are supported (i.e., the number of non-1 repeat parameters does not exceed 4).

 x.repeat(2, 3, 4, 5, 6)  # Not supported. A validation error is reported because the first axis has a repeat value of 2 and there are 5 non-1 repeat parameters.
 x.repeat(2, 3, 1, 5, 6)  # Supported. The first axis has a repeat value of 2 and there are 4 non-1 repeat parameters.

Constraint 2: When repeat is not required for the first axis, repeat operations on up to three dimensions are supported (i.e., no more than three non-1 repeat parameters).

 x.repeat(1, 3, 4, 5, 6)  # Not supported. Validation reports an error because the first axis has repeat=1 and there are four non-1 repeat parameters.
 x.repeat(1, 3, 1, 5, 6)  # Supported. The first axis has repeat=1 and there are three non-1 repeat parameters.

Example

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

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_repeat.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 shape_size = 1;
    for (auto i: shape) {
        shape_size *= i;
    }
    return shape_size;
}

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 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);

  // Copy data from the host to the device memory by calling aclrtMemcpy.
  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];
  }

  // Create an aclTensor by calling aclCreateTensor.
  *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
                            shape.data(), shape.size(), *deviceAddr);
  return 0;
}

template <typename T>
void aclCreateIntArrayP(const std::vector<T>& hostData, aclIntArray** intArray) {
  *intArray = aclCreateIntArray(hostData.data(), hostData.size());
}

int main() {
  // 1. (Boilerplate) Initialize the device/stream. See the ACL API manual.
  // Set deviceId based on the actual device.
  int32_t deviceId = 0;
  aclrtStream stream;
  auto ret = Init(deviceId, &stream);
  // Handle the check based on your needs.
  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> selfShape = {3, 2};
  std::vector<int64_t> outShape = {2, 12, 4};
  std::vector<int64_t> repeatsArray = {2, 4, 2};
  void* selfDeviceAddr = nullptr;
  void* outDeviceAddr = nullptr;
  aclTensor* self = nullptr;
  aclTensor* out = nullptr;
  aclIntArray* repeat = nullptr;
  std::vector<float> selfHostData(GetShapeSize(selfShape), 1);
  std::vector<float> outHostData(GetShapeSize(outShape), 1);
  // Create the self aclTensor.
  ret = CreateAclTensor(selfHostData, selfShape, &selfDeviceAddr, aclDataType::ACL_FLOAT, &self);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the out aclTensor.
  ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT, &out);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // Create the normalizedShape aclIntArray.
  aclCreateIntArrayP(repeatsArray, &repeat);

  // 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 aclnnRepeat.
  ret = aclnnRepeatGetWorkspaceSize(self, repeat, out, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnRepeatGetWorkspaceSize 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 aclnnRepeat.
  ret = aclnnRepeat(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnRepeat failed. ERROR: %d\n", ret); return ret);

  // 4. (Boilerplate) Synchronize and 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.
  auto size = GetShapeSize(outShape);
  std::vector<float> resultData(size, 0);
  ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), outDeviceAddr,
                    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: %f\n", i, resultData[i]);
  }

  // 6. Release aclTensor. Modify based on the specific API definition.
  aclDestroyTensor(self);
  aclDestroyTensor(out);
  aclDestroyIntArray(repeat);

  // 7. Release device resources. Modify based on the specific API definition.
  aclrtFree(selfDeviceAddr);
  aclrtFree(outDeviceAddr);
  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();
  return 0;
}