fn

nansum

Tensor
nansum(x: Tensor, dim: int | Sequence[int] | None = ..., keepdim: bool = ...)
source

Sum the tensor, treating NaN entries as zero.

A NaN-safe variant of lucid.sum. NaN values are replaced by 0 before the reduction, so they neither contaminate the result nor contribute to it.

Parameters

xTensor
Input tensor (any floating-point dtype).
dimint | Sequence[int] | None
Axis or axes along which to sum. None (default) reduces over the entire tensor.
keepdimbool
If True, retains the reduced dimensions with size 1. Defaults to False.

Returns

Tensor

Reduced tensor.

Notes

With S\mathcal{S} the set of indices being reduced and 1xi is NaN\mathbb{1}_{x_i \text{ is NaN}} an indicator,

nansum(x)=iS(11xi is NaN)xi.\text{nansum}(x) = \sum_{i \in \mathcal{S}} (1 - \mathbb{1}_{x_i \text{ is NaN}}) \cdot x_i.

The gradient at NaN positions is zero — those entries contribute nothing to the forward sum, so they cannot influence it through perturbation.

Examples

>>> import lucid
>>> import math
>>> x = lucid.tensor([1.0, math.nan, 3.0])
>>> lucid.nansum(x)
Tensor(4.)