Skip to content
fn

scatter_op

→TensorImplPtr
int scatter_op(const int & base, int dim, const int & indices, const int & src)

Python wrappers

Public Python APIs implemented by this engine symbol.

Overwrite-semantics scatter: out[...,idx,...]=src\mathrm{out}[..., \mathrm{idx}, ...] = \mathrm{src}.

A true overwrite on the backend's scatter_set kernel, every dtype — what x[key] = v and lucid.scatter run. It was a scatter-add of the delta src−base[idx]\mathrm{src} - \mathrm{base}[\mathrm{idx}], which is not one: NaN or inf in base survived the write, a tiny value rounded away against a large one, bool could not become False, and a repeated index summed.

Math

yi={srcjif i=idxj for some jbaseiotherwise y_i = \begin{cases} \mathrm{src}_j & \text{if } i = \mathrm{idx}_j \text{ for some } j \\ \mathrm{base}_i & \text{otherwise} \end{cases}

See Also

scatter_add_op — additive variant. scatter_set_op — index_copy's stricter-shaped entry to this op.

Parameters

baseTensorImplPtr
Tensor to scatter into. Provides the output shape and dtype.
dimint
Axis along which indices selects.
indicesTensorImplPtr
Integer tensor (int32 or int64) of base's rank, no larger than src on any axis nor than base on any but dim.
srcTensorImplPtr
Source values written into base at the positions given by indices; only the corner the index covers is read. Cast to base's dtype first.

Returns

TensorImplPtr

A new tensor with the same shape and dtype as base.

Raises

Failure
If any input is null, indices is not an integer dtype, or the shapes break the rule above.
IndexError
If dim is out of range, or (CPU) an index is.

Notes

A position named more than once keeps the value written last on the CPU, where each line along dim is written in index order — the reference's CPU behaviour. On Metal the writes race and which value survives is unspecified, as on the reference's GPU backends. int64 and complex64 scatter through the CPU on Metal (MLX has no 8-byte scatter there).

Backward, the reference's rule: base takes the gradient with the written positions zeroed, src the gradient gathered from where each element landed — every duplicate included. Differentiable twice.