From f6bcdaecc3412d8d0c234253bb1bea323a1ac000 Mon Sep 17 00:00:00 2001 From: Marcel Luethi Date: Sun, 29 Nov 2026 11:51:52 +0100 Subject: [PATCH] Add Idx value type for positions along an axis So far, indices were represented as ordinary int32 values. This introduces an explicit value type Idx[L], which marks a value as a position along the axis L and records that axis in its type (at runtime it is still an int32). This adds type safety, as positions can only be used along their own axis, but more importantly it communicates the intent of argmax, argmin, argsort, Random.permutation and Categorical, which now return Idx. Breaking changes: - These results are no longer Int32; use asInt32 for arithmetic on them. - Axis[L].at with a vector of indices requires Tensor1[L2, Idx[L]]; convert plain integers with Idx.fromInt32(Axis[L]). The existing TypedIndex (the per-element index used by fromFunction) meant something else and is renamed to ElementIndex. --- AGENTS.md | 280 +++++++++++++++++- core/src/main/scala/dimwit/package.scala | 2 +- .../src/main/scala/dimwit/random/Random.scala | 5 +- .../stats/UnivariateDistributions.scala | 14 +- core/src/main/scala/dimwit/tensor/Axis.scala | 25 +- core/src/main/scala/dimwit/tensor/Idx.scala | 30 ++ .../src/main/scala/dimwit/tensor/Tensor.scala | 20 +- .../dimwit/tensor/ValueTypeClasses.scala | 10 + .../tensor/tensorops/AlongAxisOps.scala | 10 +- .../tensor/tensorops/ReductionOps.scala | 13 +- .../tensor/tensorops/StructuralOps.scala | 8 +- .../tensor/tensorops/Tensor0Extensions.scala | 12 + .../scala/dimwit/random/RandomSuite.scala | 29 +- .../dimwit/stats/DistributionSuite.scala | 7 +- .../test/scala/dimwit/tensor/IdxSuite.scala | 119 ++++++++ .../dimwit/tensor/TensorCreationSuite.scala | 2 +- .../tensor/TensorOpsReductionSuite.scala | 8 +- .../tensor/TensorOpsStructureSuite.scala | 12 +- .../src/main/scala/dimwit/basic/KMeans.scala | 12 +- mdocs/AGENTS.md | 60 +++- 20 files changed, 590 insertions(+), 88 deletions(-) create mode 100644 core/src/main/scala/dimwit/tensor/Idx.scala create mode 100644 core/src/test/scala/dimwit/tensor/IdxSuite.scala diff --git a/AGENTS.md b/AGENTS.md index 691d8153..01555cde 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -531,9 +531,9 @@ println(s"Sum along B: ${sumB}") // [6.0, 15.0] val meanA = data.mean(Axis[A]) // [2.5, 3.5, 4.5] val meanB = data.mean(Axis[B]) // [2.0, 5.0] -// Argmax / Argmin (returns indices) -val argmaxB: Tensor1[A, Int32] = data.argmax(Axis[B]) -val argminB: Tensor1[A, Int32] = data.argmin(Axis[B]) +// Argmax / Argmin (returns positions along the reduced axis, see "Positions along an Axis") +val argmaxB: Tensor1[A, Idx[B]] = data.argmax(Axis[B]) +val argminB: Tensor1[A, Idx[B]] = data.argmin(Axis[B]) ``` **Error: Reducing on non-existent axis** @@ -782,7 +782,8 @@ val gridPicked = grid.select(Axis[A].at(Seq(3, 0))) // rows 3, 0 val gridTupled = grid.select(Axis[A].at((3, 0))) // the same, note the double parentheses // Vector of indices, like jnp.take: the axis is replaced by the axis of the indices -val order = Tensor1(Axis[C]).fromArray(Array(2, 0, 2)) +// The positions must be along B (Idx[B]); integers are converted with Idx.fromInt32 +val order: Tensor1[C, Idx[B]] = Idx.fromInt32(Axis[B])(Tensor1(Axis[C]).fromArray(Array(2, 0, 2))) val gridGathered: Tensor2[A, C, Float32] = grid.select(Axis[B].at(order)) // Window of static size, like jax.lax.dynamic_slice: keeps the axis with the window size as extent @@ -864,6 +865,277 @@ grid.select(Axis[A].at(3, 2)) // at repl.MdocSession$MdocApp20.$init$$$anonfun$6(AGENTS.md:809) ``` +### Positions along an Axis: `Idx[L]` + +A position along the axis `L` is a value of type `Idx[L]`, e.g. `Tensor1[A, Idx[B]]` holds for each position along +`A` a position along `B`. At runtime an `Idx[L]` is an `int32`; the label is only part of the type, so a position +can only be used along the axis it belongs to. `argmax`, `argmin`, `argsort`, `Random.permutation` and +`Categorical.sample` produce positions. `Axis[L].at(...)` accepts a vector of positions only as `Idx[L]`; a single +index or the start of a window may also be a plain `Tensor0[Int32]`, e.g. the index of a `foriLoop`. + +```scala +// argmax gives positions along the reduced axis B ... +val maxColumn: Tensor1[A, Idx[B]] = grid.argmax(Axis[B]) + +// ... which select along B, here the maximum of each row +val rowMax = zipvmap(Axis[A])(grid, maxColumn)((row, b) => row(Axis[B].at(b))) + +// argsort gives the permutation of the axis that sorts it +val column = Tensor1(Axis[B]).fromArray(Array(3.0f, 1.0f, 2.0f)) +val sorted = column(Axis[B].at(column.argsort(Axis[B]))) + +// A random permutation of A shuffles along A +val shuffledRows = grid(Axis[A].at(dimwit.random.Random.permutation(grid.extent(Axis[A]))(dimwit.random.Random.Key(0)))) + +// Positions from outside DimWit: Idx(axis)(index) and Idx.fromInt32(axis)(tensor); asInt32 converts back. +// They are not checked: as for Int32 indices, JAX clamps or skips out-of-bounds positions +val column2: Tensor0[Idx[B]] = Idx(Axis[B])(2) +val picked: Tensor1[C, Idx[B]] = Idx.fromInt32(Axis[B])(Tensor1(Axis[C]).fromArray(Array(2, 0))) +val pickedColumns: Tensor2[A, C, Float32] = grid(Axis[B].at(picked)) +val asIntegers: Tensor1[C, Int32] = picked.asInt32 + +// Positions can be compared, e.g. to find the rows whose maximum is in column 2 +val maxInColumn2: Tensor1[A, Bool] = maxColumn.elementEquals_!(column2) +``` + +```scala +// ERROR: a position along B cannot select along A +val wrongAxis = grid(Axis[A].at(maxColumn)) +// error: +// None of the overloaded alternatives of method at in class Axis with types +// [I <: NonEmptyTuple] +// (indices: I): dimwit.tensor.AxisAtTupleIndices[MdocApp1.this.A, I] +// (start: dimwit.tensor.Tensor0[dimwit.tensor.Idx[MdocApp1.this.A]], windowSize: +// Int): dimwit.tensor.AxisAtWindow[MdocApp1.this.A] +// (start: dimwit.tensor.Tensor0[dimwit.tensor.DType.Int32], windowSize: Int): +// dimwit.tensor.AxisAtWindow[MdocApp1.this.A] +// (start: Int, windowSize: Int): dimwit.tensor.AxisAtWindow[MdocApp1.this.A] +// (indices: Seq[Int]): dimwit.tensor.AxisAtIndices[MdocApp1.this.A] +// (range: Range): dimwit.tensor.AxisAtRange[MdocApp1.this.A] +// [L2] +// (indices: dimwit.tensor.Tensor1[L2, dimwit.tensor.Idx[MdocApp1.this.A]]): +// dimwit.tensor.AxisAtTensorIndices[MdocApp1.this.A, L2] +// (index: dimwit.tensor.Tensor0[dimwit.tensor.Idx[MdocApp1.this.A]]): +// dimwit.tensor.AxisAtTensorIndex[MdocApp1.this.A] +// (index: dimwit.tensor.Tensor0[dimwit.tensor.DType.Int32]): +// dimwit.tensor.AxisAtTensorIndex[MdocApp1.this.A] +// (index: Int): dimwit.tensor.AxisAtIndex[MdocApp1.this.A] +// match arguments ((MdocApp1.this.maxColumn : +// dimwit.tensor.Tensor1[MdocApp1.this.A, dimwit.tensor.Idx[MdocApp1.this.B]])) +// val wrongAxis = grid(Axis[A].at(maxColumn)) +// ^^^^^^^^^^ +// error: +// value apply is not a member of dimwit.tensor.Tensor2[MdocApp1.this.A, MdocApp1.this.B, +// dimwit.tensor.DType.Float32]. +// An extension method was tried, but could not be fully constructed: +// +// apply(this.grid) +// +// failed with: +// +// Ambiguous overload. The overloaded alternatives of method apply in package dimwit with types +// [T <: Tuple, V] +// (tensor: dimwit.tensor.Tensor[T, V]) +// [L] +// (selector: dimwit.tensor.AxisAtIndex[L]) +// (using ev: dimwit.tensor.ShapeTypeHelpers.AxisRemover[T, L], labels: +// dimwit.tensor.Labels[ev.RemainingAxes]): +// dimwit.tensor.Tensor[ev.RemainingAxes, V] +// [T <: Tuple, V] +// (tensor: dimwit.tensor.Tensor[T, V]) +// [L] +// (selector: dimwit.tensor.AxisAtTensorIndex[L]) +// (using ev: dimwit.tensor.ShapeTypeHelpers.AxisRemover[T, L], labels: +// dimwit.tensor.Labels[ev.RemainingAxes]): +// dimwit.tensor.Tensor[ev.RemainingAxes, V] +// [T <: Tuple, V] +// (tensor: dimwit.tensor.Tensor[T, V]) +// [L] +// (selector: dimwit.tensor.AxisAtRange[L]) +// (using axisIndex: dimwit.tensor.ShapeTypeHelpers.AxisIndex[T, L], labels +// : dimwit.tensor.Labels[T]): dimwit.tensor.Tensor[T, V] +// [T <: Tuple, V] +// (tensor: dimwit.tensor.Tensor[T, V]) +// [L] +// (selector: dimwit.tensor.AxisAtIndices[L]) +// (using axisIndex: dimwit.tensor.ShapeTypeHelpers.AxisIndex[T, L], labels +// : dimwit.tensor.Labels[T]): dimwit.tensor.Tensor[T, V] +// [T <: Tuple, V] +// (tensor: dimwit.tensor.Tensor[T, V]) +// [L, I <: NonEmptyTuple] +// (selector: dimwit.tensor.AxisAtTupleIndices[L, I]) +// (using axisIndex: dimwit.tensor.ShapeTypeHelpers.AxisIndex[T, L], labels +// : dimwit.tensor.Labels[T]): dimwit.tensor.Tensor[T, V] +// [T <: Tuple, V] +// (tensor: dimwit.tensor.Tensor[T, V]) +// [L, L2] +// (selector: dimwit.tensor.AxisAtTensorIndices[L, L2]) +// (using ev: dimwit.tensor.ShapeTypeHelpers.AxisReplacer[T, L, L2], labels +// : dimwit.tensor.Labels[ev.NewShape]): +// dimwit.tensor.Tensor[ev.NewShape, V] +// [T <: Tuple, V] +// (tensor: dimwit.tensor.Tensor[T, V]) +// [L] +// (selector: dimwit.tensor.AxisAtWindow[L]) +// (using axisIndex: dimwit.tensor.ShapeTypeHelpers.AxisIndex[T, L], labels +// : dimwit.tensor.Labels[T]): dimwit.tensor.Tensor[T, V] +// all match arguments ((MdocApp1.this.grid : +// dimwit.tensor.Tensor2[MdocApp1.this.A, MdocApp1.this.B, +// dimwit.tensor.DType.Float32] +// ))() +// val wrongAxis = grid(Axis[A].at(maxColumn)) +// ^^^^ +``` + +```scala +// ERROR: a vector of plain Int32 indices is not accepted, convert it with Idx.fromInt32 +val unchecked = grid(Axis[B].at(Tensor1(Axis[C]).fromArray(Array(2, 0)))) +// error: +// None of the overloaded alternatives of method at in class Axis with types +// [I <: NonEmptyTuple] +// (indices: I): dimwit.tensor.AxisAtTupleIndices[MdocApp1.this.B, I] +// (start: dimwit.tensor.Tensor0[dimwit.tensor.Idx[MdocApp1.this.B]], windowSize: +// Int): dimwit.tensor.AxisAtWindow[MdocApp1.this.B] +// (start: dimwit.tensor.Tensor0[dimwit.tensor.DType.Int32], windowSize: Int): +// dimwit.tensor.AxisAtWindow[MdocApp1.this.B] +// (start: Int, windowSize: Int): dimwit.tensor.AxisAtWindow[MdocApp1.this.B] +// (indices: Seq[Int]): dimwit.tensor.AxisAtIndices[MdocApp1.this.B] +// (range: Range): dimwit.tensor.AxisAtRange[MdocApp1.this.B] +// [L2] +// (indices: dimwit.tensor.Tensor1[L2, dimwit.tensor.Idx[MdocApp1.this.B]]): +// dimwit.tensor.AxisAtTensorIndices[MdocApp1.this.B, L2] +// (index: dimwit.tensor.Tensor0[dimwit.tensor.Idx[MdocApp1.this.B]]): +// dimwit.tensor.AxisAtTensorIndex[MdocApp1.this.B] +// (index: dimwit.tensor.Tensor0[dimwit.tensor.DType.Int32]): +// dimwit.tensor.AxisAtTensorIndex[MdocApp1.this.B] +// (index: Int): dimwit.tensor.AxisAtIndex[MdocApp1.this.B] +// match arguments (dimwit.tensor.Tensor1[MdocApp1.this.C, dimwit.tensor.DType.Int32]) +// val unchecked = grid(Axis[B].at(Tensor1(Axis[C]).fromArray(Array(2, 0)))) +// ^^^^^^^^^^ +// error: +// value apply is not a member of dimwit.tensor.Tensor2[MdocApp1.this.A, MdocApp1.this.B, +// dimwit.tensor.DType.Float32]. +// An extension method was tried, but could not be fully constructed: +// +// apply(this.grid) +// +// failed with: +// +// Ambiguous overload. The overloaded alternatives of method apply in package dimwit with types +// [T <: Tuple, V] +// (tensor: dimwit.tensor.Tensor[T, V]) +// [L] +// (selector: dimwit.tensor.AxisAtIndex[L]) +// (using ev: dimwit.tensor.ShapeTypeHelpers.AxisRemover[T, L], labels: +// dimwit.tensor.Labels[ev.RemainingAxes]): +// dimwit.tensor.Tensor[ev.RemainingAxes, V] +// [T <: Tuple, V] +// (tensor: dimwit.tensor.Tensor[T, V]) +// [L] +// (selector: dimwit.tensor.AxisAtTensorIndex[L]) +// (using ev: dimwit.tensor.ShapeTypeHelpers.AxisRemover[T, L], labels: +// dimwit.tensor.Labels[ev.RemainingAxes]): +// dimwit.tensor.Tensor[ev.RemainingAxes, V] +// [T <: Tuple, V] +// (tensor: dimwit.tensor.Tensor[T, V]) +// [L] +// (selector: dimwit.tensor.AxisAtRange[L]) +// (using axisIndex: dimwit.tensor.ShapeTypeHelpers.AxisIndex[T, L], labels +// : dimwit.tensor.Labels[T]): dimwit.tensor.Tensor[T, V] +// [T <: Tuple, V] +// (tensor: dimwit.tensor.Tensor[T, V]) +// [L] +// (selector: dimwit.tensor.AxisAtIndices[L]) +// (using axisIndex: dimwit.tensor.ShapeTypeHelpers.AxisIndex[T, L], labels +// : dimwit.tensor.Labels[T]): dimwit.tensor.Tensor[T, V] +// [T <: Tuple, V] +// (tensor: dimwit.tensor.Tensor[T, V]) +// [L, I <: NonEmptyTuple] +// (selector: dimwit.tensor.AxisAtTupleIndices[L, I]) +// (using axisIndex: dimwit.tensor.ShapeTypeHelpers.AxisIndex[T, L], labels +// : dimwit.tensor.Labels[T]): dimwit.tensor.Tensor[T, V] +// [T <: Tuple, V] +// (tensor: dimwit.tensor.Tensor[T, V]) +// [L, L2] +// (selector: dimwit.tensor.AxisAtTensorIndices[L, L2]) +// (using ev: dimwit.tensor.ShapeTypeHelpers.AxisReplacer[T, L, L2], labels +// : dimwit.tensor.Labels[ev.NewShape]): +// dimwit.tensor.Tensor[ev.NewShape, V] +// [T <: Tuple, V] +// (tensor: dimwit.tensor.Tensor[T, V]) +// [L] +// (selector: dimwit.tensor.AxisAtWindow[L]) +// (using axisIndex: dimwit.tensor.ShapeTypeHelpers.AxisIndex[T, L], labels +// : dimwit.tensor.Labels[T]): dimwit.tensor.Tensor[T, V] +// all match arguments ((MdocApp1.this.grid : +// dimwit.tensor.Tensor2[MdocApp1.this.A, MdocApp1.this.B, +// dimwit.tensor.DType.Float32] +// ))() +// val unchecked = grid(Axis[B].at(Tensor1(Axis[C]).fromArray(Array(2, 0)))) +// ^^^^ +``` + +```scala +// ERROR: there is no arithmetic on positions, convert with asInt32 first +val shifted = column2 + column2 +// error: +// Operation only valid for Numeric (Int or Float) tensors.. +// I found: +// +// dimwit.tensor.ValueTypeClasses.IsNumber.given_IsNumber_V[ +// dimwit.tensor.Idx[MdocApp1.this.B]]( +// /* missing */ +// summon[ +// dimwit.tensor.ValueTypeClasses.IsInteger[ +// dimwit.tensor.Idx[MdocApp1.this.B]] +// ] +// ) +// +// But no implicit values were found that match type dimwit.tensor.ValueTypeClasses.IsInteger[dimwit.tensor.Idx[MdocApp1.this.B]]. +// val shifted = column2 + column2 +// ^^^^^^^ +``` + +**Note**: `Idx[L]` records the axis, not its extent. A position is only meaningful for a tensor whose axis `L` has the +extent the position was computed for, e.g. not after `select(Axis[L].at(0 until 2))`. + --- ## Functional Patterns diff --git a/core/src/main/scala/dimwit/package.scala b/core/src/main/scala/dimwit/package.scala index a3a4d08c..739d482a 100644 --- a/core/src/main/scala/dimwit/package.scala +++ b/core/src/main/scala/dimwit/package.scala @@ -42,7 +42,7 @@ package object dimwit: val name: String = s"${labelA.name}+${labelB.name}" // Export tensor and related types - export dimwit.tensor.{Tensor, Tensor0, Tensor1, Tensor2, Tensor3, Tensor4, TypedIndex} + export dimwit.tensor.{Tensor, Tensor0, Tensor1, Tensor2, Tensor3, Tensor4, ElementIndex, Idx} export dimwit.tensor.{Shape, Shape0, Shape1, Shape2, Shape3} export dimwit.tensor.DType export dimwit.tensor.DType.{BFloat16, Float16, Float32, Float64, Int8, Int16, Int32, Int64, UInt8, UInt16, UInt32, Bool} diff --git a/core/src/main/scala/dimwit/random/Random.scala b/core/src/main/scala/dimwit/random/Random.scala index 18b2c0d5..3dd4a13d 100644 --- a/core/src/main/scala/dimwit/random/Random.scala +++ b/core/src/main/scala/dimwit/random/Random.scala @@ -3,7 +3,6 @@ package dimwit.random import dimwit.tensortree.TensorTree import dimwit.jax.Jax import dimwit.python.PyBridge.liftPyTensor -import dimwit.tensor.DType.Int32 import dimwit.* import dimwit.tensor.TupleHelpers.TupleNOf import dimwit.tensor.* @@ -81,9 +80,9 @@ object Random: * @param key * The random key * @return - * A 1D tensor containing a random permutation of [0, 1, ..., n-1] + * A random permutation of the positions [0, 1, ..., n-1] along the axis */ - def permutation[L: Label](dim: AxisExtent[L])(key: Key): Tensor1[L, Int32] = + def permutation[L: Label](dim: AxisExtent[L])(key: Key): Tensor1[L, Idx[L]] = liftPyTensor(Jax.jrandom.permutation(key.jaxKey, dim.size)) object Key: diff --git a/core/src/main/scala/dimwit/stats/UnivariateDistributions.scala b/core/src/main/scala/dimwit/stats/UnivariateDistributions.scala index 61850868..8c934501 100644 --- a/core/src/main/scala/dimwit/stats/UnivariateDistributions.scala +++ b/core/src/main/scala/dimwit/stats/UnivariateDistributions.scala @@ -1,7 +1,6 @@ package dimwit.stats import dimwit.DType.Float32 -import dimwit.DType.Int32 import dimwit.* import dimwit.jax.Jax import dimwit.python.PyBridge.liftPyTensor @@ -14,17 +13,18 @@ import dimwit.python.PyBridge.liftPyTensor */ type UnivariateDistribution[V] = Distribution[EmptyTuple, V] -class Categorical[L: Label](val probs: Tensor1[L, Prob]) extends UnivariateDistribution[Int32]: +/** Distribution over the positions along the axis `L`, with the probability of each position given by `probs`. */ +class Categorical[L: Label](val probs: Tensor1[L, Prob]) extends UnivariateDistribution[Idx[L]]: private val logProbs: Tensor1[L, LogProb] = probs.log - override def logProb(x: Tensor0[Int32]): Tensor0[LogProb] = - // JAX clamps out-of-range indices (and wraps negative ones), so values outside 0..K-1 are masked explicitly - val indexed: Tensor0[LogProb] = liftPyTensor(logProbs.jaxValue.__getitem__(x.jaxValue)) - val inRange = (x >= Tensor0(0)) and (x < Tensor0(probs.shape.dimensions(0))) + override def logProb(x: Tensor0[Idx[L]]): Tensor0[LogProb] = + val i = x.asInt32 + val indexed: Tensor0[LogProb] = liftPyTensor(logProbs.jaxValue.__getitem__(i.jaxValue)) + val inRange = (i >= Tensor0(0)) and (i < Tensor0(probs.shape.dimensions(0))) where(inRange, indexed, LogProb(Tensor0(Float.NegativeInfinity))) - override def sample(key: Key): Tensor0[Int32] = + override def sample(key: Key): Tensor0[Idx[L]] = liftPyTensor(Jax.jrandom.categorical(key.jaxKey, logProbs.jaxValue)) object Categorical: diff --git a/core/src/main/scala/dimwit/tensor/Axis.scala b/core/src/main/scala/dimwit/tensor/Axis.scala index 4168b1ae..22c2949e 100644 --- a/core/src/main/scala/dimwit/tensor/Axis.scala +++ b/core/src/main/scala/dimwit/tensor/Axis.scala @@ -10,18 +10,28 @@ import scala.annotation.targetName /** Instances of this class represent an axis in a tensor with a specific label `L`. * Axis objects are used whenever an axis needs to be selected at the value level, * such as when indexing into a tensor or defining the shape of a tensor. + * + * Positions given as tensors use the index type. Whenever they are Scala literals + * (plain number, range, ...) they are plain integers */ final class Axis[L: Label]: def extent(size: Int): AxisExtent[L] = AxisExtent(this, size) def ->(size: Int): AxisExtent[L] = this.extent(size) def at(index: Int): AxisAtIndex[L] = AxisAtIndex(this, index) + def at(index: Tensor0[Int32]): AxisAtTensorIndex[L] = AxisAtTensorIndex(this, index) + @targetName("atIdx") + def at(index: Tensor0[Idx[L]]): AxisAtTensorIndex[L] = AxisAtTensorIndex(this, index.asType(VType[Int32])) + @targetName("atIdxIndices") + def at[L2](indices: Tensor1[L2, Idx[L]]): AxisAtTensorIndices[L, L2] = AxisAtTensorIndices(this, indices) + def at(range: Range): AxisAtRange[L] = AxisAtRange(this, range) def at(indices: Seq[Int]): AxisAtIndices[L] = AxisAtIndices(this, indices) - def at(index: Tensor0[Int32]): AxisAtTensorIndex[L] = AxisAtTensorIndex(this, index) - @targetName("atTensorIndices") - def at[L2](indices: Tensor1[L2, Int32]): AxisAtTensorIndices[L, L2] = AxisAtTensorIndices(this, indices) def at(start: Int, windowSize: Int): AxisAtWindow[L] = AxisAtWindow(this, start, windowSize) def at(start: Tensor0[Int32], windowSize: Int): AxisAtWindow[L] = AxisAtWindow(this, start, windowSize) + + /** Window of `windowSize` positions starting at a position along this axis. */ + @targetName("atIdxWindow") + def at(start: Tensor0[Idx[L]], windowSize: Int): AxisAtWindow[L] = AxisAtWindow(this, start.asType(VType[Int32]), windowSize) def at[I <: NonEmptyTuple](indices: I): AxisAtTupleIndices[L, I] = AxisAtTupleIndices(this, indices) def as[U](newAxis: Axis[U]): (Axis[L], Axis[U]) = (this, newAxis) @@ -36,9 +46,10 @@ case class AxisExtent[L: Label](axis: Axis[L], size: Int): def *[L2: Label](other: AxisExtent[L2]): AxisExtent[L |*| L2] = AxisExtent(Axis[L |*| L2], size * other.size) -/** Provides typed access to the indices. I.e. the user can write `idx(Axis[A])` to get the index along axis A. +/** The position of an element in all axes of `T`, as passed to `fromFunction`: `idx(Axis[A])` is its position along A. + * It lives on the Scala side; for positions held in a tensor see [[Idx]]. */ -class TypedIndex[T <: Tuple](private[dimwit] val coordInts: IndexedSeq[Int]): +class ElementIndex[T <: Tuple](private[dimwit] val coordInts: IndexedSeq[Int]): def apply[L](axis: Axis[L])(using ev: AxisIndex[T, L]): Int = coordInts(ev.index) @@ -60,8 +71,8 @@ case class AxisAtIndices[L](axis: Axis[L], indices: Seq[Int]) extends AxisSelect /* Represent an axis selection by a tensor containing indices. This allows for dynamic indexing based on the contents of the tensor. */ case class AxisAtTensorIndex[L](axis: Axis[L], index: Tensor0[Int32]) extends AxisSelector[L] -/* Represent an axis selection by a vector of indices. The selected axis is replaced by the axis of the vector. */ -case class AxisAtTensorIndices[L, L2](axis: Axis[L], indices: Tensor1[L2, Int32]) extends AxisSelector[L] +/* Represent an axis selection by a vector of positions along the axis. The selected axis is replaced by the axis of the vector. */ +case class AxisAtTensorIndices[L, L2](axis: Axis[L], indices: Tensor1[L2, Idx[L]]) extends AxisSelector[L] /** Represent an axis selection by a window of `windowSize` consecutive indices from `start`. * The start may be a tensor, also a traced one (e.g. a loop index under `jit`); the size is static. diff --git a/core/src/main/scala/dimwit/tensor/Idx.scala b/core/src/main/scala/dimwit/tensor/Idx.scala new file mode 100644 index 00000000..ddcb9541 --- /dev/null +++ b/core/src/main/scala/dimwit/tensor/Idx.scala @@ -0,0 +1,30 @@ +package dimwit.tensor + +import dimwit.jax.Jax +import dimwit.tensor.DType.Int32 +import dimwit.tensor.ValueTypeClasses.IsIndex + +/** The value type Idx[L] of positions along the axis with label `L`. + * This is used to distinguish plain int32 from indices. It also stores the axis to + * which this index applies. Thus it allows for type level checks. + */ +sealed trait Idx[L] + +object Idx: + + /* An index is currently only defined for Int#2 */ + given isIndex[L]: IsIndex[Idx[L]] with + def dtype: DType = DType.Int32 + + /* The scala type of an index is a Scala Int */ + given hasScalar[L]: HasScalar[Idx[L], Int] with + def readFlat(jv: Jax.PyDynamic): Array[Int] = ArrayReader.readIntArray(jv) + def classTag: scala.reflect.ClassTag[Int] = scala.reflect.ClassTag.Int + + /** Create an Index for the given axis */ + def apply[L](axis: Axis[L])(index: Int): Tensor0[Idx[L]] = + Tensor(Jax.jnp.array(index, dtype = Jax.jnp.int32)) + + /** Interprets the integers of `t` as positions along the axis `L`. */ + def fromInt32[T <: Tuple: Labels, L](axis: Axis[L])(t: Tensor[T, Int32]): Tensor[T, Idx[L]] = + t.asType(VType[Idx[L]]) diff --git a/core/src/main/scala/dimwit/tensor/Tensor.scala b/core/src/main/scala/dimwit/tensor/Tensor.scala index 9504481a..9c24d06e 100644 --- a/core/src/main/scala/dimwit/tensor/Tensor.scala +++ b/core/src/main/scala/dimwit/tensor/Tensor.scala @@ -11,7 +11,7 @@ import dimwit.tensor.ValueTypeClasses.IsBoolean import dimwit.tensor.ValueTypeClasses.IsFloating import dimwit.tensor.ValueTypeClasses.IsInteger import dimwit.tensor.ValueTypeClasses.IsNumber -import dimwit.tensor.TypedIndex +import dimwit.tensor.ElementIndex import dimwit.tensor.VType import me.shadaj.scalapy.py import me.shadaj.scalapy.py.SeqConverters @@ -113,25 +113,25 @@ object Tensor: * using the provided function. */ @targetName("fromFunctionFloat") - def fromFunction(f: TypedIndex[T] => Float): Tensor[T, Float32] = + def fromFunction(f: ElementIndex[T] => Float): Tensor[T, Float32] = Tensor(shape, VType[Float32]).fromArray(Tensor.tabulate(shape.dimensions, f)) @targetName("fromFunctionDouble") - def fromFunction(f: TypedIndex[T] => Double): Tensor[T, Float64] = + def fromFunction(f: ElementIndex[T] => Double): Tensor[T, Float64] = Tensor(shape, VType[Float64]).fromArray(Tensor.tabulate(shape.dimensions, f)) @targetName("fromFunctionByte") - def fromFunction(f: TypedIndex[T] => Byte): Tensor[T, Int8] = + def fromFunction(f: ElementIndex[T] => Byte): Tensor[T, Int8] = Tensor(shape, VType[Int8]).fromArray(Tensor.tabulate(shape.dimensions, f)) @targetName("fromFunctionShort") - def fromFunction(f: TypedIndex[T] => Short): Tensor[T, Int16] = + def fromFunction(f: ElementIndex[T] => Short): Tensor[T, Int16] = Tensor(shape, VType[Int16]).fromArray(Tensor.tabulate(shape.dimensions, f)) @targetName("fromFunctionInt") - def fromFunction(f: TypedIndex[T] => Int): Tensor[T, Int32] = + def fromFunction(f: ElementIndex[T] => Int): Tensor[T, Int32] = Tensor(shape, VType[Int32]).fromArray(Tensor.tabulate(shape.dimensions, f)) @targetName("fromFunctionLong") - def fromFunction(f: TypedIndex[T] => Long): Tensor[T, Int64] = + def fromFunction(f: ElementIndex[T] => Long): Tensor[T, Int64] = Tensor(shape, VType[Int64]).fromArray(Tensor.tabulate(shape.dimensions, f)) @targetName("fromFunctionBoolean") - def fromFunction(f: TypedIndex[T] => Boolean): Tensor[T, Bool] = + def fromFunction(f: ElementIndex[T] => Boolean): Tensor[T, Bool] = Tensor(shape, VType[Bool]).fromArray(Tensor.tabulate(shape.dimensions, f)) /** Factory for creating tensors with a specific shape and a given value type @@ -184,10 +184,10 @@ object Tensor: def fromArray(values: Array[Double])(using IsFloating[V]): Tensor[T, V] = ArrayWriter.fromArray[T, V](other.shape, values) /** Computes per-element values via eager Scala-side iteration. Used by [[ShapedFactory.fromFunction]]. */ - private[tensor] def tabulate[T <: Tuple, V: scala.reflect.ClassTag](dims: List[Int], f: TypedIndex[T] => V): Array[V] = + private[tensor] def tabulate[T <: Tuple, V: scala.reflect.ClassTag](dims: List[Int], f: ElementIndex[T] => V): Array[V] = val strides = dims.scanRight(1)(_ * _).tail Array.tabulate(dims.product) { flatIdx => - f(TypedIndex[T](IndexedSeq.tabulate(dims.length)(d => (flatIdx / strides(d)) % dims(d)))) + f(ElementIndex[T](IndexedSeq.tabulate(dims.length)(d => (flatIdx / strides(d)) % dims(d)))) } private[dimwit] def apply[T <: Tuple: Labels, V](jaxValue: Jax.PyDynamic): Tensor[T, V] = new Tensor(jaxValue) diff --git a/core/src/main/scala/dimwit/tensor/ValueTypeClasses.scala b/core/src/main/scala/dimwit/tensor/ValueTypeClasses.scala index 023f411a..c5a70fbb 100644 --- a/core/src/main/scala/dimwit/tensor/ValueTypeClasses.scala +++ b/core/src/main/scala/dimwit/tensor/ValueTypeClasses.scala @@ -51,3 +51,13 @@ object ValueTypeClasses: object IsBoolean: def apply[V](using ev: IsBoolean[V]): IsBoolean[V] = ev + + /** Type class marker for positions along an axis, i.e. `Idx[L]`. + * Deliberately not an `IsNumber`: positions can be compared, but there is no arithmetic on them. + */ + @implicitNotFound("Operation only valid for tensors of positions (Idx[L]).") + trait IsIndex[V] extends HasDType[V]: + def dtype: DType + + object IsIndex: + def apply[V](using ev: IsIndex[V]): IsIndex[V] = ev diff --git a/core/src/main/scala/dimwit/tensor/tensorops/AlongAxisOps.scala b/core/src/main/scala/dimwit/tensor/tensorops/AlongAxisOps.scala index 2fe8bac8..23c88f33 100644 --- a/core/src/main/scala/dimwit/tensor/tensorops/AlongAxisOps.scala +++ b/core/src/main/scala/dimwit/tensor/tensorops/AlongAxisOps.scala @@ -2,7 +2,7 @@ package dimwit.tensor.tensorops import dimwit.jax.Jax import dimwit.tensor.Axis -import dimwit.tensor.DType.Int32 +import dimwit.tensor.Idx import dimwit.tensor.Label import dimwit.tensor.Labels import dimwit.tensor.ShapeTypeHelpers.AxisIndex @@ -24,8 +24,8 @@ private[dimwit] object AlongAxisTensor1Ops: def sort[L: Label, V: IsNumber](t: Tensor1[L, V]): Tensor1[L, V] = Tensor(Jax.jnp.sort(t.jaxValue, axis = 0)) - /** returns the indices that would sort the Tensor1 `t`. */ - def argsort[L: Label, V: IsNumber](t: Tensor1[L, V]): Tensor1[L, Int32] = + /** returns the positions that would sort the Tensor1 `t`, i.e. the permutation of `L` that sorts it. */ + def argsort[L: Label, V: IsNumber](t: Tensor1[L, V]): Tensor1[L, Idx[L]] = Tensor(Jax.jnp.argsort(t.jaxValue, axis = 0)) /** computes the cumulative sum of the Tensor1 `t`. */ @@ -72,7 +72,7 @@ private[dimwit] object AlongAxisOps: t.vapply(axis)(AlongAxisTensor1Ops.roll(shift)) /** returns the indices that would sort `t` along the specified axis. */ - def argsort[T <: Tuple: Labels, V: IsNumber, L: Label](t: Tensor[T, V], axis: Axis[L])(using AxisIndex[T, L]): Tensor[T, Int32] = + def argsort[T <: Tuple: Labels, V: IsNumber, L: Label](t: Tensor[T, V], axis: Axis[L])(using AxisIndex[T, L]): Tensor[T, Idx[L]] = t.vapply(axis)(AlongAxisTensor1Ops.argsort) /** sorts `t` along the specified axis. */ @@ -123,7 +123,7 @@ private[dimwit] object AlongAxisExtensions: extension [T <: Tuple: Labels, V: IsNumber](t: Tensor[T, V]) /** Returns a tensor of indices that would sort `t` along the specified axis */ - def argsort[L: Label](axis: Axis[L])(using AxisIndex[T, L]): Tensor[T, Int32] = + def argsort[L: Label](axis: Axis[L])(using AxisIndex[T, L]): Tensor[T, Idx[L]] = AlongAxisOps.argsort(t, axis) /** sorts the tensor `t` along the specified axis */ diff --git a/core/src/main/scala/dimwit/tensor/tensorops/ReductionOps.scala b/core/src/main/scala/dimwit/tensor/tensorops/ReductionOps.scala index c0787fa2..fdbf2470 100644 --- a/core/src/main/scala/dimwit/tensor/tensorops/ReductionOps.scala +++ b/core/src/main/scala/dimwit/tensor/tensorops/ReductionOps.scala @@ -3,6 +3,7 @@ package dimwit.tensor.tensorops import dimwit.jax.Jax import dimwit.tensor.Axis import dimwit.tensor.DType.Int32 +import dimwit.tensor.Idx import dimwit.tensor.Label import dimwit.tensor.Labels import dimwit.tensor.ShapeTypeHelpers.AxesRemover @@ -35,12 +36,12 @@ private[dimwit] object ReductionOps: def min[T <: Tuple: Labels, V: IsNumber, L: Label](t: Tensor[T, V], axis: Axis[L])(using ev: AxisRemover[T, L], l: Labels[ev.RemainingAxes]): Tensor[ev.RemainingAxes, V] = Tensor(Jax.jnp.min(t.jaxValue, axis = ev.index)) def min[T <: Tuple: Labels, V: IsNumber, Inputs <: Tuple](t: Tensor[T, V], axes: Inputs)(using ev: AxesRemover[T, UnwrapAxes[Inputs]], l: Labels[ev.RemainingAxes]): Tensor[ev.RemainingAxes, V] = Tensor(Jax.jnp.min(t.jaxValue, axis = ev.indices.toPythonProxy)) - /** returns the index of the maximum of `t` along the specified axis or axes. */ - def argmax[T <: Tuple: Labels, V: IsNumber, L: Label](t: Tensor[T, V], axis: Axis[L])(using ev: AxisRemover[T, L], l: Labels[ev.RemainingAxes]): Tensor[ev.RemainingAxes, Int32] = Tensor(Jax.jnp.argmax(t.jaxValue, axis = ev.index)) + /** returns the position of the maximum of `t` along the specified axis, or the flat index for several axes. */ + def argmax[T <: Tuple: Labels, V: IsNumber, L: Label](t: Tensor[T, V], axis: Axis[L])(using ev: AxisRemover[T, L], l: Labels[ev.RemainingAxes]): Tensor[ev.RemainingAxes, Idx[L]] = Tensor(Jax.jnp.argmax(t.jaxValue, axis = ev.index)) def argmax[T <: Tuple: Labels, V: IsNumber, Inputs <: Tuple](t: Tensor[T, V], axes: Inputs)(using ev: AxesRemover[T, UnwrapAxes[Inputs]], l: Labels[ev.RemainingAxes]): Tensor[ev.RemainingAxes, Int32] = Tensor(Jax.jnp.argmax(t.jaxValue, axis = ev.indices.toPythonProxy)) - /** returns the index of the minimum of `t` along the specified axis or axes. */ - def argmin[T <: Tuple: Labels, V: IsNumber, L: Label](t: Tensor[T, V], axis: Axis[L])(using ev: AxisRemover[T, L], l: Labels[ev.RemainingAxes]): Tensor[ev.RemainingAxes, Int32] = Tensor(Jax.jnp.argmin(t.jaxValue, axis = ev.index)) + /** returns the position of the minimum of `t` along the specified axis, or the flat index for several axes. */ + def argmin[T <: Tuple: Labels, V: IsNumber, L: Label](t: Tensor[T, V], axis: Axis[L])(using ev: AxisRemover[T, L], l: Labels[ev.RemainingAxes]): Tensor[ev.RemainingAxes, Idx[L]] = Tensor(Jax.jnp.argmin(t.jaxValue, axis = ev.index)) def argmin[T <: Tuple: Labels, V: IsNumber, Inputs <: Tuple](t: Tensor[T, V], axes: Inputs)(using ev: AxesRemover[T, UnwrapAxes[Inputs]], l: Labels[ev.RemainingAxes]): Tensor[ev.RemainingAxes, Int32] = Tensor(Jax.jnp.argmin(t.jaxValue, axis = ev.indices.toPythonProxy)) /** computes the mean of `t` (over all elements, or) along the specified axis or axes. */ @@ -94,11 +95,11 @@ private[dimwit] object ReductionExtensions: /** argument of the maximum of the tensor `t` along the specified axes, returning a new tensor with those axes removed. */ def argmax[Inputs <: Tuple](axes: Inputs)(using ev: AxesRemover[T, UnwrapAxes[Inputs]], l: Labels[ev.RemainingAxes]): Tensor[ev.RemainingAxes, Int32] = ReductionOps.argmax(t, axes) - def argmax[L: Label](axis: Axis[L])(using ev: AxisRemover[T, L], l: Labels[ev.RemainingAxes]): Tensor[ev.RemainingAxes, Int32] = ReductionOps.argmax(t, axis) + def argmax[L: Label](axis: Axis[L])(using ev: AxisRemover[T, L], l: Labels[ev.RemainingAxes]): Tensor[ev.RemainingAxes, Idx[L]] = ReductionOps.argmax(t, axis) /** argument of the minimum of the tensor `t` along the specified axes, returning a new tensor with those axes removed. */ def argmin[Inputs <: Tuple](axes: Inputs)(using ev: AxesRemover[T, UnwrapAxes[Inputs]], l: Labels[ev.RemainingAxes]): Tensor[ev.RemainingAxes, Int32] = ReductionOps.argmin(t, axes) - def argmin[L: Label](axis: Axis[L])(using ev: AxisRemover[T, L], l: Labels[ev.RemainingAxes]): Tensor[ev.RemainingAxes, Int32] = ReductionOps.argmin(t, axis) + def argmin[L: Label](axis: Axis[L])(using ev: AxisRemover[T, L], l: Labels[ev.RemainingAxes]): Tensor[ev.RemainingAxes, Idx[L]] = ReductionOps.argmin(t, axis) // --------------------------------------------------------- // IsFloat operations (IsFloat or IsInt) diff --git a/core/src/main/scala/dimwit/tensor/tensorops/StructuralOps.scala b/core/src/main/scala/dimwit/tensor/tensorops/StructuralOps.scala index 88dfdc07..10fb2cb7 100644 --- a/core/src/main/scala/dimwit/tensor/tensorops/StructuralOps.scala +++ b/core/src/main/scala/dimwit/tensor/tensorops/StructuralOps.scala @@ -538,7 +538,7 @@ private[dimwit] object StructuralExtensions: /** Select the tensor at an index given by a tensor along an axis, removing the axis. * The index may be traced, e.g. a loop index under `jit`. * - * @param selector of the form `Axis[L].at(index: Tensor0[Int32])` + * @param selector of the form `Axis[L].at(index: Tensor0[Idx[L]])` or `Axis[L].at(index: Tensor0[Int32])` */ def select[L](selector: AxisAtTensorIndex[L])(using ev: AxisRemover[T, L], @@ -579,7 +579,7 @@ private[dimwit] object StructuralExtensions: /** Select the tensor at the indices of a vector along an axis, like `jnp.take`. * The axis is replaced by the axis of the indices. Out-of-bounds indices yield NaN for floating tensors. * - * @param selector of the form `Axis[L].at(indices: Tensor1[L2, Int32])` + * @param selector of the form `Axis[L].at(indices: Tensor1[L2, Idx[L]])` */ def select[L, L2](selector: AxisAtTensorIndices[L, L2])(using ev: AxisReplacer[T, L, L2], @@ -638,7 +638,7 @@ private[dimwit] object StructuralExtensions: /** A copy of the tensor with new values at an index given by a tensor along an axis. The index may be traced. * An out-of-bounds index leaves the tensor unchanged. * - * @param selector of the form `Axis[L].at(index: Tensor0[Int32])` + * @param selector of the form `Axis[L].at(index: Tensor0[Idx[L]])` or `Axis[L].at(index: Tensor0[Int32])` * @param value the new values, with the shape of `tensor.select(selector)` */ def updated[L](selector: AxisAtTensorIndex[L])(using @@ -688,7 +688,7 @@ private[dimwit] object StructuralExtensions: /** A copy of the tensor with new values at the indices of a vector along an axis. Out-of-bounds indices are skipped; * for repeated indices, it is unspecified which of their values is written. * - * @param selector of the form `Axis[L].at(indices: Tensor1[L2, Int32])` + * @param selector of the form `Axis[L].at(indices: Tensor1[L2, Idx[L]])` * @param value the new values, with the shape of `tensor.select(selector)` */ def updated[L, L2](selector: AxisAtTensorIndices[L, L2])(using diff --git a/core/src/main/scala/dimwit/tensor/tensorops/Tensor0Extensions.scala b/core/src/main/scala/dimwit/tensor/tensorops/Tensor0Extensions.scala index 6a691c0a..61596e11 100644 --- a/core/src/main/scala/dimwit/tensor/tensorops/Tensor0Extensions.scala +++ b/core/src/main/scala/dimwit/tensor/tensorops/Tensor0Extensions.scala @@ -1,8 +1,11 @@ package dimwit.tensor.tensorops import dimwit.tensor.DType.* +import dimwit.tensor.Idx import dimwit.tensor.Tensor0 +import scala.annotation.targetName + private[dimwit] object Tensor0Extensions: private inline def checkTracer[V, R](scalar: Tensor0[V]): Unit = @@ -47,6 +50,15 @@ private[dimwit] object Tensor0Extensions: checkTracer(scalar) scalar.jaxValue.item().as[Int] + extension [L](scalar: Tensor0[Idx[L]]) + /** return the position as an Int. + * Attention! Breaks the computational graph. + */ + @targetName("itemIdx") + def item: Int = + checkTracer(scalar) + scalar.jaxValue.item().as[Int] + extension (scalar: Tensor0[Int64]) /** return the underlying Long value of the scalar tensor. * Attention! Breaks the computational graph. diff --git a/core/src/test/scala/dimwit/random/RandomSuite.scala b/core/src/test/scala/dimwit/random/RandomSuite.scala index 13c92431..cdee10a2 100644 --- a/core/src/test/scala/dimwit/random/RandomSuite.scala +++ b/core/src/test/scala/dimwit/random/RandomSuite.scala @@ -1,6 +1,7 @@ package dimwit.random import dimwit.* +import dimwit.conversions.* import dimwit.jax.Jax import me.shadaj.scalapy.py @@ -61,29 +62,23 @@ class RandomSuite extends DimwitTest: vmapResults should approxEqual(individualResults) - it("permutation creates valid permutation of indices"): + it("permutation creates valid permutation of positions"): val key = Random.Key(789) val n = 10 - val perm = Random.permutation(Axis[A] -> n)(key) + val perm: Tensor1[A, Idx[A]] = Random.permutation(Axis[A] -> n)(key) // Check that the permutation has the correct length perm.shape should equal(Shape(Axis[A] -> n)) - // Check that all elements are in range [0, n-1] - val minVal = perm.min.item - val maxVal = perm.max.item - minVal should be >= 0 - maxVal should be < n - - // Check that all elements are unique (sum of unique permutation = sum of 0..n-1) - val expectedSum = (n * (n - 1)) / 2 - perm.sum.item shouldBe expectedSum - - // Check that it's actually permuted (with very high probability it won't be identical) - // By checking the first element is not 0 (fails 1/10 of the time, but good enough) - val original = Tensor1(Axis[A]).fromArray((0 until n).toArray) - val isIdentity = (perm === original).item - isIdentity shouldBe false + // Check that it contains every position along A exactly once + perm.toSeq.sorted shouldBe (0 until n) + + // Applying the permutation to the identity gives the permutation itself + val identity: Tensor1[A, Idx[A]] = Idx.fromInt32(Axis[A])(Tensor1(Axis[A]).fromRange(0 until n)) + (identity(Axis[A].at(perm)) === perm).item shouldBe true + + // Check that it's actually permuted (for this key it is not the identity) + (perm === identity).item shouldBe false it("permutation with take can shuffle tensor rows"): val key = Random.Key(101112) diff --git a/core/src/test/scala/dimwit/stats/DistributionSuite.scala b/core/src/test/scala/dimwit/stats/DistributionSuite.scala index 420e5fa6..84db4e22 100644 --- a/core/src/test/scala/dimwit/stats/DistributionSuite.scala +++ b/core/src/test/scala/dimwit/stats/DistributionSuite.scala @@ -474,7 +474,7 @@ class DistributionSuite extends DimwitTest: describe("Categorical"): it("logProb matches expected value"): val probs = Prob(Tensor(Shape(Axis[A] -> 4)).fromArray(Array(0.1f, 0.2f, 0.3f, 0.4f))) - val x = Tensor0(2) + val x = Idx(Axis[A])(2) val dist = Categorical(probs) val scalaLogProb = dist.logProb(x) @@ -485,9 +485,10 @@ class DistributionSuite extends DimwitTest: val probs = Prob(Tensor(Shape(Axis[A] -> 4)).fromArray(Array(0.1f, 0.2f, 0.3f, 0.4f))) val dist = Categorical(probs) + // Positions out of range can only be made with an unchecked cast (or for an axis A of another extent). // JAX would clamp 4 to the last index and wrap -1 around to it, giving log(0.4) - dist.logProb(Tensor0(4)).asFloat.item should be(Float.NegativeInfinity) - dist.logProb(Tensor0(-1)).asFloat.item should be(Float.NegativeInfinity) + dist.logProb(Tensor0(4).asType(VType[Idx[A]])).asFloat.item should be(Float.NegativeInfinity) + dist.logProb(Tensor0(-1).asType(VType[Idx[A]])).asFloat.item should be(Float.NegativeInfinity) it("sample distribution matches probabilities"): val probs = Prob(Tensor(Shape(Axis[A] -> 4)).fromArray(Array(0.1f, 0.2f, 0.3f, 0.4f))) diff --git a/core/src/test/scala/dimwit/tensor/IdxSuite.scala b/core/src/test/scala/dimwit/tensor/IdxSuite.scala new file mode 100644 index 00000000..c8125f6d --- /dev/null +++ b/core/src/test/scala/dimwit/tensor/IdxSuite.scala @@ -0,0 +1,119 @@ +package dimwit.tensor + +import dimwit.* +import dimwit.conversions.* +import dimwit.random.Random +import dimwit.stats.{Categorical, Prob} + +class IdxSuite extends DimwitTest: + + // value at (a, b) is 10a + b + val grid = Tensor2(Axis[A], Axis[B]).fromArray(Array.tabulate(2, 3)((a, b) => 10.0f * a + b)) + + describe("creation"): + + it("Idx(axis)(index) creates a position, stored as int32"): + val i = Idx(Axis[B])(2) + i.item shouldBe 2 + i.dtype shouldBe DType.Int32 + + it("fromInt32 turns integers into positions along an axis, keeping their values"): + val positions: Tensor1[C, Idx[B]] = Idx.fromInt32(Axis[B])(Tensor1(Axis[C]).fromArray(Array(2, 0, 1))) + positions.toSeq shouldBe Seq(2, 0, 1) + + it("asInt32 converts back"): + Idx(Axis[B])(2).asInt32 shouldEqual Tensor0(2) + + it("there is no Int fill, fromArray or literal for Idx"): + "Tensor(Shape1(Axis[A] -> 2), VType[Idx[B]]).fill(0)" shouldNot compile + "Tensor1(Axis[A], VType[Idx[B]]).fromArray(Array(0, 1))" shouldNot compile + "Tensor0(VType[Idx[B]])(0)" shouldNot compile + + describe("operations"): + + it("positions can be compared"): + val p = Idx.fromInt32(Axis[B])(Tensor1(Axis[C]).fromArray(Array(2, 0, 1))) + val one = Idx(Axis[B])(1) + (p >! one).toSeq shouldBe Seq(true, false, false) + p.elementEquals_!(one).toSeq shouldBe Seq(false, false, true) + + it("there is no arithmetic on positions"): + val p = Idx(Axis[B])(1) + "p + p" shouldNot compile + "p.sum" shouldNot compile + + it("positions along different axes cannot be mixed"): + val pb = Idx(Axis[B])(1) + val pa = Idx(Axis[A])(1) + "pa < pb" shouldNot compile + + it("where, stack and jit work with positions"): + val p0 = Idx(Axis[B])(0) + val p2 = Idx(Axis[B])(2) + where(Tensor0(true), p2, p0).item shouldBe 2 + stack(Seq(p0, p2), Axis[C]).toSeq shouldBe Seq(0, 2) + jit((p: Tensor0[Idx[B]]) => p)(p2).item shouldBe 2 + + describe("selecting"): + + it("select at a position along the axis"): + val maxColumn: Tensor0[Idx[B]] = grid(Axis[A].at(0)).argmax(Axis[B]) // row 0 is [0, 1, 2] + grid.select(Axis[B].at(maxColumn)).toSeq shouldBe Seq(2.0f, 12.0f) + + it("select at positions along the axis replaces the axis"): + val positions = Idx.fromInt32(Axis[B])(Tensor1(Axis[C]).fromArray(Array(2, 0))) + val res: Tensor2[A, C, Float32] = grid.select(Axis[B].at(positions)) + res.toSeq shouldBe Seq(Seq(2.0f, 0.0f), Seq(12.0f, 10.0f)) + + it("updated at a position along the axis"): + val firstRow: Tensor0[Idx[A]] = grid.sum(Axis[B]).argmin(Axis[A]) // row 0 has the smallest sum + val res = grid.updated(Axis[A].at(firstRow))(Tensor(Shape1(Axis[B] -> 3)).fill(-1.0f)) + res.toSeq shouldBe Seq(Seq(-1.0f, -1.0f, -1.0f), Seq(10.0f, 11.0f, 12.0f)) + + it("window starting at a position along the axis"): + val start: Tensor0[Idx[B]] = Tensor1(Axis[B]).fromArray(Array(5.0f, 1.0f, 3.0f)).argmin(Axis[B]) // 1 + grid.select(Axis[B].at(start, 2)).toSeq shouldBe Seq(Seq(1.0f, 2.0f), Seq(11.0f, 12.0f)) + + it("positions along another axis are rejected"): + val pa = Idx(Axis[A])(1) + "grid.select(Axis[B].at(pa))" shouldNot compile + val pas = Idx.fromInt32(Axis[A])(Tensor1(Axis[C]).fromArray(Array(1, 0))) + "grid.select(Axis[B].at(pas))" shouldNot compile + + it("a scalar Int32 index is still accepted, e.g. a loop index"): + grid.select(Axis[B].at(Tensor0(2))).toSeq shouldBe Seq(2.0f, 12.0f) + + it("a vector of Int32 indices is rejected, it must be converted with fromInt32"): + val ints = Tensor1(Axis[C]).fromArray(Array(2, 0)) + "grid.select(Axis[B].at(ints))" shouldNot compile + grid.select(Axis[B].at(Idx.fromInt32(Axis[B])(ints))).toSeq shouldBe Seq(Seq(2.0f, 0.0f), Seq(12.0f, 10.0f)) + + describe("producers"): + + it("argmax and argmin give positions along the reduced axis"): + val maxB: Tensor1[A, Idx[B]] = grid.argmax(Axis[B]) + val minA: Tensor1[B, Idx[A]] = grid.argmin(Axis[A]) + maxB.toSeq shouldBe Seq(2, 2) + minA.toSeq shouldBe Seq(0, 0, 0) + + it("argmax can select along the reduced axis, e.g. the maximum of each row"): + val maxB = grid.argmax(Axis[B]) + val rowMax = zipvmap(Axis[A])(grid, maxB)((row, i) => row.select(Axis[B].at(i))) + rowMax shouldEqual grid.max(Axis[B]) + + it("argsort gives a permutation of the sorted axis"): + val v = Tensor1(Axis[B]).fromArray(Array(3.0f, 1.0f, 2.0f)) + val order: Tensor1[B, Idx[B]] = v.argsort(Axis[B]) + v.select(Axis[B].at(order)) shouldEqual v.sort(Axis[B]) + + it("permutation gives positions along its axis"): + val perm: Tensor1[A, Idx[A]] = Random.permutation(Axis[A] -> 2)(Random.Key(0)) + perm.toSeq.sorted shouldBe Seq(0, 1) + grid.select(Axis[A].at(perm)).shape shouldBe grid.shape + + it("Categorical samples positions along its axis"): + val dist = Categorical(Prob(Tensor1(Axis[B]).fromArray(Array(0.0f, 0.0f, 1.0f)))) + val sample: Tensor0[Idx[B]] = dist.sample(Random.Key(0)) + sample.item shouldBe 2 + grid.select(Axis[B].at(sample)).toSeq shouldBe Seq(2.0f, 12.0f) + "grid.select(Axis[A].at(sample))" shouldNot compile diff --git a/core/src/test/scala/dimwit/tensor/TensorCreationSuite.scala b/core/src/test/scala/dimwit/tensor/TensorCreationSuite.scala index 8eb3e5a4..9abd14e7 100644 --- a/core/src/test/scala/dimwit/tensor/TensorCreationSuite.scala +++ b/core/src/test/scala/dimwit/tensor/TensorCreationSuite.scala @@ -186,7 +186,7 @@ class TensorCreationSuite extends DimwitTest: it("can be consumed as gather indices by select"): val t = Tensor1(Axis[A]).fromArray(Array(10.0f, 20.0f, 30.0f)) - t.select(Axis[A].at(Tensor1(Axis[B]).fromRange(0 until 3))) shouldEqual Tensor1(Axis[B]).fromArray(Array(10.0f, 20.0f, 30.0f)) + t.select(Axis[A].at(Idx.fromInt32(Axis[A])(Tensor1(Axis[B]).fromRange(0 until 3)))) shouldEqual Tensor1(Axis[B]).fromArray(Array(10.0f, 20.0f, 30.0f)) describe("linspace"): diff --git a/core/src/test/scala/dimwit/tensor/TensorOpsReductionSuite.scala b/core/src/test/scala/dimwit/tensor/TensorOpsReductionSuite.scala index bae94798..0870fcfb 100644 --- a/core/src/test/scala/dimwit/tensor/TensorOpsReductionSuite.scala +++ b/core/src/test/scala/dimwit/tensor/TensorOpsReductionSuite.scala @@ -117,11 +117,11 @@ class TensorOpsReductionSuite extends DimwitTest: it("argmax axis A"): val res = t2.argmax(axis = Axis[A]) - res shouldEqual Tensor.like(res).fromArray(Array(1, 1, 1)) + res shouldEqual Tensor1(Axis[B]).fromArray(Array(1, 1, 1)) it("argmax axis B"): val res = t2.argmax(axis = Axis[B]) - res shouldEqual Tensor.like(res).fromArray(Array(2, 2)) + res shouldEqual Tensor1(Axis[A]).fromArray(Array(2, 2)) it("argmin"): withClue("JAX default to flatten tensor for argmin without axis is not supported."): @@ -129,11 +129,11 @@ class TensorOpsReductionSuite extends DimwitTest: it("argmin axis A"): val res = t2.argmin(axis = Axis[A]) - res shouldEqual Tensor.like(res).fromArray(Array(0, 0, 0)) + res shouldEqual Tensor1(Axis[B]).fromArray(Array(0, 0, 0)) it("argmin axis B"): val res = t2.argmin(axis = Axis[B]) - res shouldEqual Tensor.like(res).fromArray(Array(0, 0)) + res shouldEqual Tensor1(Axis[A]).fromArray(Array(0, 0)) describe("Boolean Reductions"): it("all"): diff --git a/core/src/test/scala/dimwit/tensor/TensorOpsStructureSuite.scala b/core/src/test/scala/dimwit/tensor/TensorOpsStructureSuite.scala index 86d6fe14..7db1086f 100644 --- a/core/src/test/scala/dimwit/tensor/TensorOpsStructureSuite.scala +++ b/core/src/test/scala/dimwit/tensor/TensorOpsStructureSuite.scala @@ -381,7 +381,7 @@ class TensorOpsStructureSuite extends DimwitTest: it("can be applied to the tensor like select"): val ab = Tensor2(Axis[A], Axis[B]).fromArray(Array.tabulate(3, 4)((a, b) => 10f * a + b)) - val indices = Tensor1(Axis[C]).fromArray(Array(2, 0)) + val indices = Idx.fromInt32(Axis[B])(Tensor1(Axis[C]).fromArray(Array(2, 0))) ab(Axis[A].at(1)) should approxEqual(ab.select(Axis[A].at(1))) ab(Axis[A].at(Tensor0(1))) should approxEqual(ab.select(Axis[A].at(Tensor0(1)))) ab(Axis[A].at(0 until 2)) should approxEqual(ab.select(Axis[A].at(0 until 2))) @@ -477,7 +477,7 @@ class TensorOpsStructureSuite extends DimwitTest: // Shape: A=2, B=3, the value at (a, b) is 10a + b val ab = Tensor2(Axis[A], Axis[B]).fromArray(Array.tabulate(2, 3)((a, b) => 10f * a + b)) - val indices = Tensor1(Axis[C]).fromArray(Array(2, 0, 2, 1)) + val indices = Idx.fromInt32(Axis[B])(Tensor1(Axis[C]).fromArray(Array(2, 0, 2, 1))) it("selects at the indices and replaces the axis by the axis of the indices"): val sliced = ab.select(Axis[B].at(indices)) @@ -485,17 +485,17 @@ class TensorOpsStructureSuite extends DimwitTest: sliced should approxEqual(Tensor2(Axis[A], Axis[C]).fromArray(Array(Array(2f, 0f, 2f, 1f), Array(12f, 10f, 12f, 11f)))) it("keeps the axis when the indices have the same axis"): - val permutation = Tensor1(Axis[B]).fromArray(Array(2, 0, 1)) + val permutation = Idx.fromInt32(Axis[B])(Tensor1(Axis[B]).fromArray(Array(2, 0, 1))) ab.select(Axis[B].at(permutation)) should approxEqual(Tensor2(Axis[A], Axis[B]).fromArray(Array(Array(2f, 0f, 1f), Array(12f, 10f, 11f)))) it("updates at the indices"): val zeros = Tensor(ab.shape).fill(0f) - val positions = Tensor1(Axis[C]).fromArray(Array(2, 0)) + val positions = Idx.fromInt32(Axis[B])(Tensor1(Axis[C]).fromArray(Array(2, 0))) val values = Tensor2(Axis[A], Axis[C]).fromArray(Array(Array(1f, 2f), Array(3f, 4f))) zeros.updated(Axis[B].at(positions))(values) should approxEqual(Tensor2(Axis[A], Axis[B]).fromArray(Array(Array(2f, 0f, 1f), Array(4f, 0f, 3f)))) it("updated is the inverse of select for distinct indices"): - val permutation = Tensor1(Axis[B]).fromArray(Array(2, 0, 1)) + val permutation = Idx.fromInt32(Axis[B])(Tensor1(Axis[B]).fromArray(Array(2, 0, 1))) Tensor(ab.shape).fill(0f).updated(Axis[B].at(permutation))(ab.select(Axis[B].at(permutation))) should approxEqual(ab) describe("roll"): @@ -534,7 +534,7 @@ class TensorOpsStructureSuite extends DimwitTest: ab.focus(Axis[B].at(2)).focus(Axis[A].at(1)).updated(-1f) should approxEqual(written) it("writes where the chained select reads, for every selector"): - val idx = Tensor1(Axis[C]).fromArray(Array(3, 0)) + val idx = Idx.fromInt32(Axis[B])(Tensor1(Axis[C]).fromArray(Array(3, 0))) ab.focus(Axis[A].at(0 to 2 by 2)).focus(Axis[B].at(idx)).updated(Tensor(Shape(Axis[A] -> 2, Axis[C] -> 2)).fill(-1f)) should approxEqual( Tensor2(Axis[A], Axis[B]).fromArray(Array(Array(-1f, 1f, 2f, -1f), Array(10f, 11f, 12f, 13f), Array(-1f, 21f, 22f, -1f))) ) diff --git a/examples/src/main/scala/dimwit/basic/KMeans.scala b/examples/src/main/scala/dimwit/basic/KMeans.scala index 6747cf14..671b0c85 100644 --- a/examples/src/main/scala/dimwit/basic/KMeans.scala +++ b/examples/src/main/scala/dimwit/basic/KMeans.scala @@ -45,7 +45,7 @@ trait CenterBasedClustering( def assignPoints( points: Tensor2[Point, Dim, Float32], centers: Tensor2[Cluster, Dim, Float32] - ): Tensor1[Point, Int32] = + ): Tensor1[Point, Idx[Cluster]] = val distances = pairwiseDistances(points, centers) distances.argmin(Axis[Cluster]) @@ -57,10 +57,11 @@ trait CenterBasedClustering( */ private def calcCenters( points: Tensor2[Point, Dim, Float32], - assignments: Tensor1[Point, Int32] + assignments: Tensor1[Point, Idx[Cluster]] ): Tensor2[Cluster, Dim, Float32] = val centers = (0 until nClusters).map: clusterIndex => - val clusterMembershipMask = assignments.elementEquals(Tensor.like(assignments).fill(clusterIndex)) + val cluster = Idx(Axis[Cluster])(clusterIndex) + val clusterMembershipMask = assignments.elementEquals_!(cluster) calcCenter(where(clusterMembershipMask.broadcastTo(points.shape), points, Tensor.like(points).fill(Float.NaN))) stack(centers, Axis[Cluster]) @@ -160,7 +161,6 @@ object KMeans: println(f"Inertia (within-cluster sum of distances): $inertia%.2f\n") // ── Report discovered clusters ───────────────────────────────────────────── - val nTotal = n * k println(s"Discovered centers (${name}) vs true centers:") println(f" ${"cluster"}%-9s ${"centroid (x,y)"}%-22s ${"true center"}%-16s size") println(" " + "─" * 65) @@ -172,10 +172,10 @@ object KMeans: val cy = center(Axis[Dim].at(1)).item // Cluster size: count points whose assignment equals c. - // elementEquals produces [Point, Bool]; asFloat32 then sum gives a count. + // elementEquals_! with the position c produces [Point, Bool]; asFloat32 then sum gives a count. val clusterSize = assignments - .elementEquals(Tensor(Shape(Axis[Point] -> nTotal)).fill(c)) + .elementEquals_!(Idx(Axis[Cluster])(c)) .asFloat32.sum.item.toInt val tc = trueCenters(c) diff --git a/mdocs/AGENTS.md b/mdocs/AGENTS.md index ddb646f5..57a2bb0b 100644 --- a/mdocs/AGENTS.md +++ b/mdocs/AGENTS.md @@ -414,9 +414,9 @@ println(s"Sum along B: ${sumB}") // [6.0, 15.0] val meanA = data.mean(Axis[A]) // [2.5, 3.5, 4.5] val meanB = data.mean(Axis[B]) // [2.0, 5.0] -// Argmax / Argmin (returns indices) -val argmaxB: Tensor1[A, Int32] = data.argmax(Axis[B]) -val argminB: Tensor1[A, Int32] = data.argmin(Axis[B]) +// Argmax / Argmin (returns positions along the reduced axis, see "Positions along an Axis") +val argmaxB: Tensor1[A, Idx[B]] = data.argmax(Axis[B]) +val argminB: Tensor1[A, Idx[B]] = data.argmin(Axis[B]) ``` **Error: Reducing on non-existent axis** @@ -562,7 +562,8 @@ val gridPicked = grid.select(Axis[A].at(Seq(3, 0))) // rows 3, 0 val gridTupled = grid.select(Axis[A].at((3, 0))) // the same, note the double parentheses // Vector of indices, like jnp.take: the axis is replaced by the axis of the indices -val order = Tensor1(Axis[C]).fromArray(Array(2, 0, 2)) +// The positions must be along B (Idx[B]); integers are converted with Idx.fromInt32 +val order: Tensor1[C, Idx[B]] = Idx.fromInt32(Axis[B])(Tensor1(Axis[C]).fromArray(Array(2, 0, 2))) val gridGathered: Tensor2[A, C, Float32] = grid.select(Axis[B].at(order)) // Window of static size, like jax.lax.dynamic_slice: keeps the axis with the window size as extent @@ -613,6 +614,57 @@ val gridWrongValue = grid.updated(Axis[A].at(0))(grid) grid.select(Axis[A].at(3, 2)) ``` +### Positions along an Axis: `Idx[L]` + +A position along the axis `L` is a value of type `Idx[L]`, e.g. `Tensor1[A, Idx[B]]` holds for each position along +`A` a position along `B`. At runtime an `Idx[L]` is an `int32`; the label is only part of the type, so a position +can only be used along the axis it belongs to. `argmax`, `argmin`, `argsort`, `Random.permutation` and +`Categorical.sample` produce positions. `Axis[L].at(...)` accepts a vector of positions only as `Idx[L]`; a single +index or the start of a window may also be a plain `Tensor0[Int32]`, e.g. the index of a `foriLoop`. + +```scala mdoc:silent +// argmax gives positions along the reduced axis B ... +val maxColumn: Tensor1[A, Idx[B]] = grid.argmax(Axis[B]) + +// ... which select along B, here the maximum of each row +val rowMax = zipvmap(Axis[A])(grid, maxColumn)((row, b) => row(Axis[B].at(b))) + +// argsort gives the permutation of the axis that sorts it +val column = Tensor1(Axis[B]).fromArray(Array(3.0f, 1.0f, 2.0f)) +val sorted = column(Axis[B].at(column.argsort(Axis[B]))) + +// A random permutation of A shuffles along A +val shuffledRows = grid(Axis[A].at(dimwit.random.Random.permutation(grid.extent(Axis[A]))(dimwit.random.Random.Key(0)))) + +// Positions from outside DimWit: Idx(axis)(index) and Idx.fromInt32(axis)(tensor); asInt32 converts back. +// They are not checked: as for Int32 indices, JAX clamps or skips out-of-bounds positions +val column2: Tensor0[Idx[B]] = Idx(Axis[B])(2) +val picked: Tensor1[C, Idx[B]] = Idx.fromInt32(Axis[B])(Tensor1(Axis[C]).fromArray(Array(2, 0))) +val pickedColumns: Tensor2[A, C, Float32] = grid(Axis[B].at(picked)) +val asIntegers: Tensor1[C, Int32] = picked.asInt32 + +// Positions can be compared, e.g. to find the rows whose maximum is in column 2 +val maxInColumn2: Tensor1[A, Bool] = maxColumn.elementEquals_!(column2) +``` + +```scala mdoc:fail +// ERROR: a position along B cannot select along A +val wrongAxis = grid(Axis[A].at(maxColumn)) +``` + +```scala mdoc:fail +// ERROR: a vector of plain Int32 indices is not accepted, convert it with Idx.fromInt32 +val unchecked = grid(Axis[B].at(Tensor1(Axis[C]).fromArray(Array(2, 0)))) +``` + +```scala mdoc:fail +// ERROR: there is no arithmetic on positions, convert with asInt32 first +val shifted = column2 + column2 +``` + +**Note**: `Idx[L]` records the axis, not its extent. A position is only meaningful for a tensor whose axis `L` has the +extent the position was computed for, e.g. not after `select(Axis[L].at(0 until 2))`. + --- ## Functional Patterns