Tensor Masks
tensor_masks.nr47 lines
tensor_masks.nr· neuro
// Tensor masks. A comparison between tensors, or between a tensor and a scalar, is
// element-wise and answers a `Tensor<bool, S>` under the broadcasting rules: one `bool` per
// element, never one for the whole tensor. Masks join with `&`, `|`, `^` and `~` (and `&=`,
// `|=`, `^=` in place), reduce with `.any()`, `.all()` and `.count()`, and pick between two
// values with `.select`. `.is_nan()` on a float tensor is its mask of NaN elements, and
// `lower_triangle()` / `upper_triangle()` build the standard square masks.
// Shape-generic: one body for every shape and float type. The comparison and `.select` read
// the borrowed `x`; an owned operand would be consumed, as by any tensor operator.
func relu<T: Float, S>(x: &Tensor<T, S>) -> Tensor<T, S> {
(x > T::zero()).select(x, T::zero())
}
func main() -> i32 {
val scores: Tensor<f32, [2, 3]> = [[0.5, -1.0, 2.0], [-0.25, 3.0, 0.0]]
val threshold: Tensor<f32, [3]> = [0.0, 0.0, 1.0]
// Each row is compared against `threshold`: a `[3]` broadcasts across the `[2, 3]`.
val above = &scores > &threshold
println("above: {above[0, 0]} {above[0, 1]} {above[0, 2]} {above[1, 0]} {above[1, 1]} {above[1, 2]}")
println("any {(&above).any()}, all {(&above).all()}, count {(&above).count()}")
// `if &scores == &threshold` would not compile: a condition needs one `bool`, so the
// whole-tensor question is asked with a reduction.
val same = (&scores == &scores).all()
println("equal to itself: {same}")
// Mask logic, then a select: kept where the mask holds, 0.0 elsewhere.
val negative = &scores < 0.0
mut flagged = &above | &negative
flagged ^= &negative
val kept = (&flagged).select(&scores, 0.0)
println("kept sum {kept.sum()}, relu sum {relu(&scores).sum()}")
// A NaN screen: `x - x` is NaN exactly where `x` is infinite or NaN.
val inf = 1.0 / 0.0
val readings: Tensor<f64, [4]> = [1.5, inf, inf - inf, -2.0]
val bad = (&readings - &readings).is_nan()
println("non-finite readings: {bad.count()}, NaN readings: {readings.is_nan().count()}")
// A causal mask: position i sees positions 0..=i.
val causal = Tensor::<bool, [4, 4]>::lower_triangle()
val weights = causal.select(Tensor::<f32, [4, 4]>::ones(), 0.0f32)
println("visible pairs {weights.sum()}, row 1 sees {weights[1, 0]} {weights[1, 1]} {weights[1, 2]}")
return (&above).count() as i32 * 10 + bad.count() as i32
}
neuroc run tensor_masks.nr
above: true false true false true false
any true, all false, count 3
equal to itself: true
kept sum 5.5, relu sum 5.5
non-finite readings: 2, NaN readings: 1
visible pairs 10.0, row 1 sees 1.0 1.0 0.0