Tensor Gather
tensor_gather.nr34 lines
tensor_gather.nr· neuro
// Indexing a tensor by a tensor of indices. `t.gather(ids)` reads the rows `ids` names and lays
// them out in the shape of `ids`: a `[V, D]` table gathered by `[B, S]` indices is `[B, S, D]`.
// `.gather(ids, axis: k)` picks along another axis instead. Indices are `i32`, the type
// `.argmax` and `.argsort` answer with, and each one is checked against its axis: an index past
// the end, or a negative one, panics at the call.
func main() -> i32 {
// An embedding lookup: one row of the table per token.
val table: Tensor<f32, [vocab: 4, dim: 2]> = [[0.0, 0.5], [1.0, 1.5], [2.0, 2.5], [3.0, 3.5]]
val tokens: Tensor<i32, [batch: 2, seq: 3]> = [[1, 3, 3], [0, 2, 1]]
val embedded = table.gather(&tokens)
println("embedded: {embedded[0, 1, 1]} {embedded[1, 2, 0]} {embedded.sum()}")
// The result keeps the names of both: `[batch, seq, dim]`.
println("by name: {embedded.sum(axis: seq)[0, 0]}")
// Along another axis, columns come in any order and may repeat.
val m: Tensor<i32, [2, 3]> = [[10, 20, 30], [40, 50, 60]]
val order: Tensor<i32, [4]> = [2, 0, 0, 1]
val cols = (&m).gather(&order, axis: -1)
println("columns: {cols[0, 0]} {cols[1, 3]} {cols.sum()}")
// Indices from `.argsort` reorder rows: here by each row's smallest score, largest first.
val scores: Tensor<f32, [3, 2]> = [[0.25, 9.0], [0.75, 8.0], [0.125, 7.0]]
val ranking = (&scores).min(axis: 1).argsort(axis: 0, descending: true)
val ranked = (&scores).gather(&ranking)
println("ranked: {ranked[0, 0]} {ranked[2, 1]}")
// A mask gathers like any other tensor.
val keep: Tensor<bool, [4]> = [true, false, false, true]
println("mask: {keep.gather(&tokens).count()}")
embedded.sum() as i32
}
neuroc run tensor_gather.nr
embedded: 3.5 1.0 23.0
by name: 7.0
columns: 30 50 260
ranked: 0.75 7.0
mask: 3