This document is relevant for: Trn2, Trn3
nki.isa.tensor_reduce#
- nki.isa.tensor_reduce(dst: NkiTensor, op, data: NkiTensor, axis, negate=False, keepdims=False, name=None, *, engine=engine.unknown)[source]#
Apply a reduction operation to the free axes of an input
datatile.The reduction operator is specified in the
opinput field (see Supported Math Operators for NKI ISA for a list of supported reduction operators).nisa.tensor_reducesupports two types of reduction operators: 1) bitvec operators (e.g., bitwise_and, bitwise_or) and 2) arithmetic operators (e.g., add, subtract, multiply).The reduction axes are specified in the
axisfield as an int or list of ints indicating which dimensions to reduce. The reduction axes must be the last contiguous free dimension(s) of the tile, ending at the final dimension. Axis 0 (partition axis) cannot be reduced.For example, given a 4D tile
(P, D1, D2, D3):axis=(3,)reduces onlyD3axis=(2, 3)reducesD2andD3axis=(1, 2, 3)reducesD1,D2, andD3
On Vector Engine, when the reduction
opis an arithmetic operator, the instruction can also multiply the output reduction results by-1.0before writing into the output tile, at no additional performance cost. This behavior is controlled by thenegateinput field.Memory types.
Both the input
dataanddsttiles can be in SBUF or PSUM on Vector Engine. GpSimd requires both tiles in SBUF.Data types.
For bitvec operators, the input/output data types must be integer types and Vector Engine treats all input elements as bit patterns without any data type casting. On Vector Engine, for arithmetic operators, the input/output data types can be any supported NKI data types, but the engine automatically casts input data types to float32 and performs the reduction operation in float32 math. The float32 reduction results are cast to the data type of
dst. See Type Casting for more information about type casting behavior.On NeuronCore-v3/v4,
engine=nki.isa.engine.gpsimdsupportsnl.add,nl.multiply,nl.minimum,nl.maximum,nl.abs_min, andnl.abs_maxwith matchingint32or matchinguint32input/output tiles in SBUF. GpSimd does not supportnegate, tensor indirection, or scalar/vector offset indirection for this instruction.GpSimd performs these reductions without converting the inputs to float32:
addandmultiplyare exact modulo2**32. Overflow wraps, and the result is interpreted in the input/output dtype.minimumandmaximumuse signed ordering forint32and unsigned ordering foruint32.For
int32,abs_minandabs_maxcompare signed int32 absolute-value keys, where the key wraps on overflow. They return the original signed input value, not its magnitude. In particular,key(-2**31) = -2**31; all other keys areabs(x). The accumulator starts with the first real input, and equal keys retain the first original value in reduction order. Thus, for[-2**31, 1],abs_minreturns-2**31andabs_maxreturns1. Both operations return-7for[-7, 7]and preserve a singleton input unchanged.For
uint32on GpSimd,abs_minandabs_maxare aliases ofminimumandmaximum, respectively.
Neither engine supports
int64oruint64input/output tiles fortensor_reduce.Engine selection.
Omitting
engineis equivalent toengine=nki.isa.engine.unknown. The public API resolves automatic selection before dispatching to a compiler or simulator backend. On NeuronCore-v3/v4, eligibleint32calls for all six operations above, and eligibleuint32calls foradd,multiply,minimum, andmaximum, select GpSimd. Eligibility requires matching input/output dtypes, both tiles in SBUF,negate=False, and no tensor or scalar/vector offset indirection. Other automatic calls use Vector Engine, subject to its existing operator, dtype, buffer, and addressing restrictions.Automatic
uint32abs_minandabs_maxremain on Vector Engine with float32 arithmetic. The unsigned aliases are applied only after GpSimd has been selected; requestengine=nki.isa.engine.gpsimdfor exact unsigned extrema. Vectorabs_minandabs_maxrequire NeuronCore-v4 or later; explicit Vector and automatic unsigned-absolute calls are rejected on earlier targets. Vectoradd,multiply,minimum, andmaximumremain available on NeuronCore-v2/v3/v4. Explicitengine=nki.isa.engine.vectorretains Vector’s float32 arithmetic even for matchingint32oruint32tiles.Layout.
nisa.tensor_reduceonly supports free axes reduction. Therefore, the partition dimension of the inputdatais considered the parallel compute dimension. To perform a partition axis reduction, we can either:invoke a
nisa.nc_transposeinstruction on the input tile and then thisnisa.tensor_reduceon the transposed tile, orinvoke
nisa.nc_matmulinstructions to multiply anl.ones([128, 1], dtype=data.dtype)tile as a stationary tensor with the input tile as a moving tensor. See more discussion on Tensor Engine alternative usage in Trainium architecture guide.
Tile size.
The partition dimension size of input
dataand outputdsttiles must be the same and must not exceed 128. The number of elements per partition ofdatamust not exceed the physical size of each SBUF partition. Bothdataanddstcan have at most four free dimensions (maximum rank 5, including the partition dimension). The number of elements per partition indstmust be consistent with theaxisfield. For example, ifaxisindicates all free dimensions ofdataare reduced, the number of elements per partition indstmust be 1.Tensor indirection.
On NeuronCore-v4 and later, both
dstanddatasupport tensor indirection (gather/scatter) by passing a view created with.indirect(index). Runs on the Vector engine.When operands are manually allocated, their base partitions must satisfy:
the
indexof every.indirect()view starts on a quadrant boundary (a multiple of 32);if
datauses.indirect(),datastarts on the same partition as itsindex;if
dstuses.indirect()anddatais in SBUF,dst’sindexstarts on the same partition asdata;if
dstuses.indirect()anddatais in PSUM and uses.indirect(),dst’sindexstarts on the same partition asdata’sindex.
Dynamic access patterns.
dataanddstmay each carry a dynamic access pattern built withnki.language.NkiTensor.ap(), whosestrideandcountslots hold anki.isa.NkiScalarread at runtime.The partition dimension (dim 0) is the exception, and both its
strideand itscountmust be Pythonintvalues, so put the dynamic slots on a free dimension.- Parameters:
dst – output tile of the reduction result
op – the reduction operator (see Supported Math Operators for NKI ISA for supported reduction operators)
data – the input tile to be reduced
axis – int or tuple/list of ints. The axis (or axes) along which to reduce; must be the last contiguous free dimension(s) ending at the final dim. For example, for a 4D tile
(P, D1, D2, D3): valid values are(3,),(2, 3), or(1, 2, 3). Axis 0 (partition dim) cannot be reduced.negate – if True, reduction result is multiplied by
-1.0; only applicable to arithmetic operators on Vector Engine. Must be False on GpSimd.keepdims – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.
name – optional instruction name
engine – keyword-only engine selection.
unknownpreserves automatic selection;vectorselects Vector Engine;gpsimdsupports the matching int32/uint32 reductions described above.
This document is relevant for: Trn2, Trn3