aclnnStridedSlice

📄 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: Extracts a sub-tensor from the input tensor based on the specified start position, end position, and stride.
  • Formula: In the specified dimension dimdim, extracts a sub-tensor outout from the input tensor selfself based on the specified start position beginbegin, end position endend, and stride stridesstrides. beginbegin and endend can take values outside [0,self.shape[dim]][0, self.shape[dim]]. After taking a value, it is converted to a valid value according to the following formula, assuming self.shape[dim] = N:begin={0,if  begin<−NN,if  begin>=N(begin+N)%N,otherwisebegin = \begin{cases} &0, & if\;begin < -N \\ &N, & if\;begin >= N\\ &(begin+N) \% N, & otherwise \end{cases} end={N,if  end>=Nbegin,else  if  (end+N)%N<begin(end+N)%N,otherwiseend = \begin{cases} &N, & if\; end >= N\\ &begin, & else\;if\; (end+N)\%N < begin \\ &(end+N)\%N, & otherwise\\ \end{cases} out.shapeout.shape differs from self.shapeself.shape only on the dim axis, and is consistent on other axes:out.shape[dim]=⌊end−begin+strides−1strides⌋out.shape[dim] = ⌊\frac{end - begin + strides - 1}{strides}⌋ If a mask parameter exists, out.shape is further calculated according to the following rules: beginMaskbeginMask: the beginbegin of the index dimension whose specified bitbit is 1 is ignored, endMaskendMask: the endend of the index dimension whose specified bitbit is 1 is ignored, ellipsisMaskellipsisMask: all subsequent dimensions are selected starting from the index dimension whose specified bitbit is 1, until a specified beginbegin is encountered, newAxisMasknewAxisMask: a dimension of size 1 is added to the shapeshape at the index dimension whose specified bitbit is 1, shrinkAxisMaskshrinkAxisMask: the index dimension whose specified bitbit is 1 is forcibly reduced to 1.

Function Prototype

Each operator uses a two-phase API. Call "aclnnStridedSliceGetWorkspaceSize" first to obtain the workspace size required for computation and the executor that contains operator computation processes. Then call "aclnnStridedSlice" to perform the computation.

aclnnStatus aclnnStridedSliceGetWorkspaceSize(
    const aclTensor   *self,
    const aclIntArray *begin,
    const aclIntArray *end,
    const aclIntArray *strides,
    int64_t           beginMask,
    int64_t           endMask,
    int64_t           ellipsisMask,
    int64_t           newAxisMask,
    int64_t           shrinkAxisMask,
    aclTensor         *out,
    uint64_t          *workspaceSize,
    aclOpExecutor     **executor)
aclnnStatus aclnnStridedSlice(
    void          *workspace,
    uint64_t       workspaceSize,
    aclOpExecutor *executor,
    aclrtStream    stream)

aclnnStridedSliceGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (Shape) Non-contiguous Tensor
    self Input Input tensor. The data type of self must be consistent with that of out. INT8, UINT8, INT16, UINT16, INT32, UINT32, INT64, UINT64, FLOAT, FLOAT16, BF16, BOOL, COMPLEX32, COMPLEX64, HIFLOAT8, FLOAT8_E5M2, FLOAT8_E4M3FN ND 0-8 √
    begin Input Start value of each dimension. The begin/end/strides array lengths must be consistent. INT32, INT64 - - -
    end Input End value of each dimension. The begin/end/strides array lengths must be consistent. INT32, INT64 - - -
    strides Input Stride for selecting values at each point in each dimension. Array lengths of begin/end/strides must be consistent, and strides values cannot be 0. INT32, INT64 - - -
    beginMask Input This value specifies that the begin on the index dimension whose corresponding bit is 1 is ignored. - INT64 - - -
    endMask Input This value specifies that the end of the index dimension corresponding to the bit set to 1 is ignored. - INT64 - - -
    ellipsisMask Input Full selection starts from the index dimension corresponding to the bit set to 1 and stops when the specified begin is encountered. ellipsisMask can have only one bit set to 1. INT64 - - -
    newAxisMask Input Inserts a new dimension of size 1 at the index dimension corresponding to the bit set to 1. - INT64 - - -
    shrinkAxisMask Input Forces the index dimension corresponding to a bit set to 1 to be reduced to 1. The strides corresponding to the indexes whose bits are set to 1 in shrinkAxisMask must be greater than 0, that is, positive numbers. INT64 - - -
    out Output Output tensor. The data types of self and out must be consistent. INT8, UINT8, INT16, UINT16, INT32, UINT32, INT64, UINT64, FLOAT, FLOAT16, BF16, BOOL, COMPLEX32, COMPLEX64, HIFLOAT8, FLOAT8_E5M2, FLOAT8_E4M3FN ND - √
    workspaceSize Output Returns the workspace size of Device side application. - - - - -
    executor Output Returns the op executor, which contains operator computation flow. - - - - -
  • Return value:

    aclnnStatus: return status 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 self, begin, end, strides, or out is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of self or out is not supported.
    The data types of self and out are inconsistent.
    self has more than 8 dimensions.
    The array lengths of begin, end, and strides are inconsistent.
    strides contains an element that equals 0.
    The dimensions of out do not match those of inferShape.
    The product model is not within the supported range.
    More than one bit in ellipsisMask is 1.
    For the index whose bit in shrinkAxisMask is 1, the corresponding strides value is less than 0.

aclnnStridedSlice

  • Parameters:

    Parameter Input/Output Description
    workspace Input Address of the workspace memory applied on the Device side.
    workspaceSize Input Workspace size applied on the Device side, obtained by the first-phase API aclnnStridedSliceGetWorkspaceSize.
    executor Input op executor, contains the operator computation process.
    stream Input Specifies the Stream for executing tasks.
  • Return value:

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

Constraints

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

Example

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

/**
 * Copyright (c) 2025 Huawei Technologies Co., Ltd.
 * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
 * CANN Open Software License Agreement Version 2.0 (the "License").
 * Please refer to the License for details. You may not use this file except in compliance with the License.
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
 * See LICENSE in the root of the software repository for the full text of the License.
 */
#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_strided_slice.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. 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 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. For details, see the acl API documentation.
    // Set 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.
    std::vector<int64_t> selfShape = {4, 3};
    std::vector<int64_t> outShape = {2, 2};
    void* selfDeviceAddr = nullptr;
    void* outDeviceAddr = nullptr;
    aclTensor* self = nullptr;
    aclIntArray* begin = nullptr;
    aclIntArray* end = nullptr;
    aclIntArray* strides = nullptr;
    aclTensor* out = nullptr;

    std::vector<float> selfHostData = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
    std::vector<int64_t> beginData = {1, 1};
    std::vector<int64_t> endData = {3, 3};
    std::vector<int64_t> stridesData = {1, 1};
    std::vector<float> outHostData(4, 0);
    int64_t beginMask = 0;
    int64_t endMask = 0;
    int64_t ellipsisMask = 0;
    int64_t newAxisMask = 0;
    int64_t shrinkAxisMask = 0;

    // 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 aclIntArray.
    begin = aclCreateIntArray(beginData.data(), 2);
    CHECK_RET(begin != nullptr, return ret);
    end = aclCreateIntArray(endData.data(), 2);
    CHECK_RET(end != nullptr, return ret);
    strides = aclCreateIntArray(stridesData.data(), 2);
    CHECK_RET(strides != nullptr, return ret);

    // 3. Call the CANN operator library API. Replace it with the actual API name.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API aclnnStridedSliceGetWorkspaceSize.
    ret = aclnnStridedSliceGetWorkspaceSize(
        self, begin, end, strides, beginMask, endMask, ellipsisMask, newAxisMask, shrinkAxisMask, out, &workspaceSize,
        &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnStridedSliceGetWorkspaceSize 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 aclnnStridedSlice.
    ret = aclnnStridedSlice(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnStridedSlice 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 device memory to the host. Modify it based on the actual 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 it based on the actual API definition.
    aclDestroyTensor(self);
    aclDestroyIntArray(begin);
    aclDestroyIntArray(end);
    aclDestroyIntArray(strides);
    aclDestroyTensor(out);

    // 7. Release device resources.
    aclrtFree(selfDeviceAddr);
    aclrtFree(outDeviceAddr);
    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();

    return 0;
}