Tensor Loops
tensor_loops.nr80 lines
tensor_loops.nr· neuro
// Tensors as `for` heads. A loop walks the leading axis: a rank-1 tensor steps through
// its elements, and a tensor of higher rank through its rows. The head picks what a step
// binds, as it does for a `Vec`. `&t` lends each step, `&mut t` lends it mutably, and a
// bare `t` consumes the tensor and hands over each element or row by value. A borrowed
// step lives for one iteration, and writing through a `&mut` step writes the tensor.
// The shape is part of the type, so each row of a [R, C] tensor is a [C] tensor.
func largest_row_sum<R, C>(m: &Tensor<i32, [R, C]>) -> i32 {
mut best = 0
for row in m {
val total = row.sum()
if total > best {
best = total
}
}
best
}
// Rows are written in place. `*row = ...` replaces a whole row, and `row[0]` one element.
func center(m: &mut Tensor<f64, [3, 2]>) {
for row in m {
val mean = row.sum() / 2.0
*row = row.map(|x: f64| -> f64 { x - mean })
}
}
func main() -> i32 {
val scores: Tensor<i32, [3, 4]> = [
[1, 2, 3, 4],
[9, 8, 7, 6],
[5, 5, 5, 5]
]
// A borrowed head leaves the tensor usable. `.enumerate()` counts the rows.
for (i, row) in (&scores).enumerate() {
println("row {i} sums to {row.sum()}")
}
println("largest row sum = {largest_row_sum(&scores)}")
mut points: Tensor<f64, [3, 2]> = [[1.0, 3.0], [10.0, 20.0], [-2.0, 2.0]]
center(&mut points)
println("centred = {points[0, 0]} {points[1, 0]} {points[2, 0]}")
// A rank-1 `&mut` head binds `&mut` elements.
mut weights: Tensor<i32, [4]> = [3, 1, 4, 1]
for (i, w) in (&mut weights).enumerate() {
*w = *w * 10 + i as i32
}
println("weights = {weights[0]} {weights[1]} {weights[2]} {weights[3]}")
// Nested loops reach one element at a time through rows lent in turn.
mut grid = Tensor::<i32, [2, 3]>::zeros()
for (r, row) in (&mut grid).enumerate() {
for (c, cell) in row.enumerate() {
*cell = (r * 3 + c) as i32
}
}
println("grid corner = {grid[1, 2]}")
// Adapters ride on a tensor head as on any other.
mut odd_squares = 0
for sq in (&weights).filter(|w: &i32| -> bool { *w % 2 == 1 }).map(|w: &i32| -> i32 { *w * *w }) {
odd_squares += sq
}
println("odd squares = {odd_squares}")
// By value, each row is its own tensor, so it can be kept past the loop. `scores` is
// gone afterwards.
mut kept: Vec<Tensor<i32, [4]>> = Vec::new()
for row in scores {
if row[0] > 1 {
kept.push(row)
}
}
println("kept rows = {kept.len()}, first starts with {kept[0][0]}")
val answer = grid.sum() + kept[1][3] + weights[3]
println("answer = {answer}")
answer
}
neuroc run tensor_loops.nr
row 0 sums to 10
row 1 sums to 30
row 2 sums to 20
largest row sum = 30
centred = -1.0 -5.0 -2.0
weights = 30 11 42 13
grid corner = 5
odd squares = 290
kept rows = 2, first starts with 9
answer = 33