aclnnScatterReduce&aclnnInplaceScatterReduce
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
NOTE:
Ascend 950PR&950DT products Support this API. The AICORE path supportsnone/add/mul. The availability of other reduction modes depends on the backend fallback capability.
Atlas A3 products AndAtlas A2 products currently support only the combination whereself/src/outisFLOAT32,reduce=1(add), andincludeSelf=true; other combinations of dtype, reduce, or includeSelf return a parameter error.
Function
Description: Writes or reduces values in tensor
srcinto tensorselfalong the specified axis and at the positions specified byindex.Reduction semantics defined by the API:
none: replacement writeadd: accumulationmul: cumulative multiplicationmax: maximum valuemin: minimum valuemean: average value- Actual support varies by product and must satisfy both the Applicable Products section above and the Constraints section in this document.
include_selfsemantics:include_self=true: the original values ofselfparticipate in the reduction.include_self=false: The original value ofselfdoes not participate in the reduction as the initial value; the firstsrcvalue is used as the initial value on the first hit.
API responsibility boundaries:
aclnnScatterReduce/aclnnInplaceScatterReduceuniformly handles reduction use cases that explicitly requireinclude_self. The available combinations are subject to product capability constraints.aclnnScatterAddis a shortcut API with fixedreduce=addandincludeSelf=true, and no longer handles use cases that explicitly passinclude_self.- If only the traditional
scatter/scatter_valuesemantics are required andinclude_selfis not explicitly exposed, useaclnnScatter/aclnnInplaceScatter/aclnnScatterValue/aclnnInplaceScatterValue.
Example: For a 3D tensor,
selfis updated as follows:out[index[i][j][k]][j][k] = src[i][j][k] # if dim == 0 && reduce == 0(none) out[i][index[i][j][k]][k] += src[i][j][k] # if dim == 1 && reduce == 1(add) out[i][j][index[i][j][k]] = max(out[i][j][index[i][j][k]], src[i][j][k]) # if dim == 2 && reduce == 3(max)The following requirements must be met during computation:
self,index, andsrcmust have the same number of dimensions.- For each dimension
d,index.size(d) <= src.size(d)must be satisfied. - For each dimension
d, ifd != dim,index.size(d) <= self.size(d)must be satisfied. - The value of
dimmust be in the range[-number of dimensions of self, number of dimensions of self-1]. - The number of dimensions of
selfshould be less than or equal to 8. - The values of
indexalong dimensiondimmust be in the range[0, self.size(dim)-1].
Function Prototype
aclnnScatterReduce and aclnnInplaceScatterReduce implement the same reduction scatter function. The usage differences are as follows. Select an appropriate operator based on your actual use case.
aclnnScatterReduce: a new output tensor object must be created to store the computation result.aclnnInplaceScatterReduce: no new output tensor object is required; the computation result is stored directly in the memory of the input tensor.
Each operator uses a two-phase API. Call the "aclnnScatterReduceGetWorkspaceSize" or "aclnnInplaceScatterReduceGetWorkspaceSize" API first to obtain the workspace size required for computation and the executor that contains the operator computation process, and then call the "aclnnScatterReduce" or "aclnnInplaceScatterReduce" API to perform computation.
aclnnStatus aclnnScatterReduceGetWorkspaceSize(
const aclTensor* self,
int64_t dim,
const aclTensor* index,
const aclTensor* src,
int64_t reduce,
bool includeSelf,
aclTensor* out,
uint64_t* workspaceSize,
aclOpExecutor** executor)aclnnStatus aclnnScatterReduce(
void* workspace,
uint64_t workspaceSize,
aclOpExecutor* executor,
const aclrtStream stream)aclnnStatus aclnnInplaceScatterReduceGetWorkspaceSize(
aclTensor* selfRef,
int64_t dim,
const aclTensor* index,
const aclTensor* src,
int64_t reduce,
bool includeSelf,
uint64_t* workspaceSize,
aclOpExecutor** executor)aclnnStatus aclnnInplaceScatterReduce(
void* workspace,
uint64_t workspaceSize,
aclOpExecutor* executor,
aclrtStream stream)aclnnScatterReduceGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor self (aclTensor*) Input The `self` in the formula. The data type must be consistent with src.
The number of dimensions must be the same as index and src.UINT8, INT8, INT16, INT32, INT64, BOOL, FLOAT16, FLOAT32, DOUBLE, COMPLEX64, COMPLEX128, BFLOAT16 ND 0-8 √ dim (int64_t) Input The dimension along which scatter is performed. The range is [-number of dimensions of self, number of dimensions of self - 1]. - - - - index (aclTensor*) Input Index tensor. The number of dimensions must be consistent with self and src. INT32, INT64 ND 0-8 √ src (aclTensor*) Input `src` in the formula. The data type must be consistent with self.
The number of dimensions must be the same as self and index.UINT8, INT8, INT16, INT32, INT64, BOOL, FLOAT16, FLOAT32, DOUBLE, COMPLEX64, COMPLEX128, BFLOAT16 ND 0-8 √ reduce (int64_t) Input Specifies the reduction operation to apply. Optional options and their corresponding int values are (none, 0), (add, 1), (mul, 2), (max, 3), (min, 4), and (mean, 5).
0 indicates replacement, 1 indicates accumulation, 2 indicates cumulative multiplication, 3 indicates taking the maximum, 4 indicates taking the minimum, and 5 indicates the mean.- - - - includeSelf (bool) Input Whether the original values in self participate in the reduction computation. true indicates that the original values participate in the reduction; false indicates that they do not. - - - - out (aclTensor*) Output Calculation result. The data type must be consistent with self.
The shape must be consistent with self.UINT8, INT8, INT16, INT32, INT64, BOOL, FLOAT16, FLOAT32, DOUBLE, COMPLEX64, COMPLEX128, BFLOAT16 ND 0-8 √ workspaceSize (uint64_t*) Output Returns the workspace size to be side-applied on the Device. - - - - - executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation process. - - - - - 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, index, src, or out is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type of self, index, src, or out is not within the supported range. The data types of self, src, and out are inconsistent. The numbers of dimensions of self, index, and src are inconsistent. The shapes of self and out are inconsistent. The value of dim is not within the range [-number of dimensions of self, number of dimensions of self - 1]. The number of dimensions of self exceeds 8. The shape does not meet the constraints: for each dimension d, index.size(d) <= src.size(d); and when d != dim, index.size(d) <= self.size(d). The value of reduce is not within the supported range and must be one of {0, 1, 2, 3, 4, 5}.
aclnnScatterReduce
Parameters:
Parameter Input/Output Description workspace Input Device side-applied workspace memory address. workspaceSize Input Device side-applied workspace size, obtained by the first-phase API aclnnScatterReduceGetWorkspaceSize. executor Input Op executor, contains the operator computation flow. stream Input Specifies the stream for task execution. Return value
aclnnStatus: return status code.For details, see aclnn return code.
aclnnInplaceScatterReduceGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor selfRef(aclTensor*) Input/Output Target tensor of scatter_reduce. shape must be consistent with the number of dimensions of index and src.
The data type must be consistent with the data type of src.
Supports empty tensors.UINT8, INT8, INT16, INT32, INT64, BOOL, FLOAT16, FLOAT32, DOUBLE, COMPLEX64, COMPLEX128, BFLOAT16 ND 0-8 √ dim (int64_t) Input Specifies the dimension along which the scatter_reduce operation is performed. The range is [-number of dimensions of selfRef, number of dimensions of selfRef - 1]. - - - - index(aclTensor*) Input Index tensor. Specifies the positions for scattering the src tensor into the selfRef tensor.
Supports empty tensors.INT32, INT64 ND 0-8 √ src (aclTensor*) Input Source tensor. The data type must be consistent with selfRef.
Supports empty tensors.UINT8, INT8, INT16, INT32, INT64, BOOL, FLOAT16, FLOAT32, DOUBLE, COMPLEX64, COMPLEX128, BFLOAT16 ND 0-8 √ reduce (int64_t) Input Reduction operation to apply. Optional operations: 0 indicates replacement, 1 indicates addition, 2 indicates multiplication, 3 indicates taking the maximum value, 4 indicates taking the minimum value, and 5 indicates taking the mean value. - - - - includeSelf (bool) Input Whether the original value in selfRef participates in the reduction computation. true indicates participation in the reduction; false indicates no participation. - - - - workspaceSize (uint64_t*) Output Returns the size of the workspace that needs to be side-applied on the Device. - - - - - executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - - Return value
aclnnStatus: return status code. See specifically 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 selfRef, index, or src is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type of selfRef, index, or src is not within the supported range. The data types of selfRef and src are inconsistent. The number of dimensions of selfRef, index, and src is inconsistent. The value of dim is not within the range of [-number of dimensions of selfRef, number of dimensions of selfRef - 1]. The number of dimensions of selfRef exceeds 8. The shape does not meet the constraints: for each dimension d, index.size(d) <= src.size(d); and when d != dim, index.size(d) <= selfRef.size(d). The value of reduce is not within the supported range. It must be one of {0, 1, 2, 3, 4, 5}.
aclnnInplaceScatterReduce
Parameters:
Parameter Input/Output Description workspace Input Device side-applied workspace memory address. workspaceSize Input Size of the workspace side-applied on the Device, obtained by the first-phase API aclnnInplaceScatterReduceGetWorkspaceSize. executor Input Op executor, which contains the operator computation flow. stream Input Specifies the stream for executing tasks. Return value
aclnnStatus: return status code.For details, see aclnn return code.
Constraints
- Deterministic computation:
- Whether the deterministic path is entered depends on the underlying backend capability and the upper-layer deterministic configuration.
- On
Atlas A2/Atlas A3, whenTilingContext::GetDeterministic()is true,none/addis not forced to single-core execution and retains multi-core scheduling;mul/min/max/meandisablescache-op/low-memoryand falls back to the single-core scheduling path of theScatterElementsV2legacy kernel. - On
<term>Ascend 950PR&950DT products</term>, the deterministic capability is handled by independent tiling / kernel branches, and the reduction range currently supported on the AICORE path isnone/add/mul.
- API boundary constraints:
- The APIs on this page explicitly pass through
includeSelfand serve as the unified common entry point for reduction scatter. - On
Atlas A2/Atlas A3, the APIs on this page currently support only the combination whereself/src/outisFLOAT32,reduce=1(add), andincludeSelf=true. - To use only the fixed
addsemantics without passing throughincludeSelf, useaclnnScatterAdd. aclnnScatter/aclnnInplaceScatterstill retain the traditionalnone/add/mulpath but do not explicitly pass throughinclude_self.
- The APIs on this page explicitly pass through
Example
The sample code is as follows and is for reference only. For details about the compilation and execution process, see Compile and Run Samples.
aclnnScatterReduce sample code:
#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_scatter_reduce.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) {
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);
auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
CHECK_RET(ret == ACL_SUCCESS, return ret);
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];
}
*tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
shape.data(), shape.size(), *deviceAddr);
return 0;
}
int main() {
int32_t deviceId = 0;
aclrtStream stream = nullptr;
auto ret = Init(deviceId, &stream);
CHECK_RET(ret == ACL_SUCCESS, return ret);
std::vector<int64_t> shape = {2, 3};
std::vector<float> selfHost = {1, 2, 3, 4, 5, 6};
std::vector<int64_t> indexHost = {0, 2, 1, 1, 0, 2};
std::vector<float> srcHost = {10, 20, 30, 40, 50, 60};
std::vector<float> outHost(6, 0);
void *selfDev = nullptr, *indexDev = nullptr, *srcDev = nullptr, *outDev = nullptr, *workspace = nullptr;
aclTensor *self = nullptr, *index = nullptr, *src = nullptr, *out = nullptr;
CHECK_RET(CreateAclTensor(selfHost, shape, &selfDev, ACL_FLOAT, &self) == ACL_SUCCESS, return -1);
CHECK_RET(CreateAclTensor(indexHost, shape, &indexDev, ACL_INT64, &index) == ACL_SUCCESS, return -1);
CHECK_RET(CreateAclTensor(srcHost, shape, &srcDev, ACL_FLOAT, &src) == ACL_SUCCESS, return -1);
CHECK_RET(CreateAclTensor(outHost, shape, &outDev, ACL_FLOAT, &out) == ACL_SUCCESS, return -1);
uint64_t workspaceSize = 0;
aclOpExecutor* executor = nullptr;
int64_t dim = 1;
int64_t reduce = 1; // add
bool includeSelf = true;
ret = aclnnScatterReduceGetWorkspaceSize(self, dim, index, src, reduce, includeSelf, out, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
if (workspaceSize > 0) {
ret = aclrtMalloc(&workspace, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
CHECK_RET(ret == ACL_SUCCESS, return ret);
}
ret = aclnnScatterReduce(workspace, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, return ret);
LOG_PRINT("aclnnScatterReduce run success.\n");
return 0;
}