Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 106 additions & 9 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,103 @@ val t2dNested = Tensor2(Axis[A], Axis[B]).fromArray(
)
```

### Conversion between Scala Seqs and Tensors with `toTensor1` / `toTensor2` / `toSeq`

The extension methods `toTensor1` and `toTensor2` convert a Scala `Seq` (`List`, `Vector`, a `map` result, ...)
into a tensor, and `toSeq` converts a `Tensor1` or `Tensor2` back. They are **opt-in**: `import dimwit.*` does not bring them in scope, they need `import dimwit.conversions.*`.

```scala
// ERROR: the conversions are not available without their import, in either direction
val notImported = Seq(1.0f, 2.0f).toTensor1(Axis[A])
val notImportedBack = t1d.toSeq
// error:
// value toTensor1 is not a member of Seq[Float]
// val notImported = Seq(1.0f, 2.0f).toTensor1(Axis[A])
// ^^^^^^^^^^^^^^^^^^^^^^^^^
// error:
// value toSeq is not a member of dimwit.tensor.Tensor[Tuple1[repl.MdocSession.MdocApp.A],
// dimwit.tensor.DType.Float32]
// val notImportedBack = t1d.toSeq
// ^^^^^^^^^
```

```scala
import dimwit.conversions.*

// The extent of the axis is the length of the Seq
val fromSeq1 = Seq(1.0f, 2.0f, 3.0f).toTensor1(Axis[A]) // Tensor1[A, Float32]
val fromList = List(1, 2, 3).toTensor1(Axis[A]) // Tensor1[A, Int32]
val fromMap = (1 to 4).map(_ * 0.5f).toTensor1(Axis[A]) // Tensor1[A, Float32]

// toTensor2: the outer Seq runs along the first axis, the inner Seqs (the rows) along the second
val fromSeq2 = Seq(Seq(1.0f, 2.0f, 3.0f), Seq(4.0f, 5.0f, 6.0f)).toTensor2(Axis[A], Axis[B]) // A -> 2, B -> 3

// As for fromArray, the value type is derived from the element type
// (Float -> Float32, Double -> Float64, Byte -> Int8, Short -> Int16, Int -> Int32, Long -> Int64, Boolean -> Bool),
// or given explicitly
val halfSeq = Seq(1.0f, 2.0f).toTensor1(Axis[A], VType[Float16])
val byteSeq2 = Seq(Seq(1, 2), Seq(3, 4)).toTensor2(Axis[A], Axis[B], VType[Int8])
```

```scala
// ERROR: the value type must fit the elements, Floats cannot become an integer tensor
val wrongVType = Seq(1.0f, 2.0f).toTensor1(Axis[A], VType[Int32])
// error:
// Operation only valid for Floating tensors.
// val wrongVType = Seq(1.0f, 2.0f).toTensor1(Axis[A], VType[Int32])
// ^
```

```scala
// ERROR at runtime: all rows of toTensor2 must have the same length
Seq(Seq(1.0f, 2.0f), Seq(3.0f)).toTensor2(Axis[A], Axis[B])
// java.lang.IllegalArgumentException: requirement failed: All rows along axis A must have the same length along axis B, but row 0 has length 2 and row 1 has length 1
// at scala.Predef$.require(Predef.scala:389)
// at dimwit.tensor.Tensor$package$Tensor2$Axes2TypedFactory.createShape(Tensor.scala:346)
// at dimwit.tensor.Tensor$package$Tensor2$Axes2TypedFactory.fromArray(Tensor.scala:355)
// at dimwit.tensor.Tensor$package$Tensor2$Axes2Factory.fromArray(Tensor.scala:333)
// at dimwit.conversions.SeqConversions$package$.floatSeqToTensor2(SeqConversions.scala:103)
// at repl.MdocSession$MdocApp.$init$$$anonfun$2(AGENTS.md:171)
```

`toSeq` is the reverse: a `Tensor1` becomes an `IndexedSeq` of its elements, a `Tensor2` an `IndexedSeq` of its rows.
The element type is the Scala type of the value type, e.g. `Float` for `Float32`. For other collections, convert the `Seq`.

```scala
val backToSeq = fromSeq1.toSeq // IndexedSeq[Float]
// backToSeq: IndexedSeq[Float] = ArraySeq(1.0F, 2.0F, 3.0F)
val backToRows = fromSeq2.toSeq // IndexedSeq[IndexedSeq[Float]], the rows along A
// backToRows: IndexedSeq[IndexedSeq[Float]] = Vector(
// ArraySeq(1.0F, 2.0F, 3.0F),
// ArraySeq(4.0F, 5.0F, 6.0F)
// )
val backToList = fromList.toSeq.toList // List[Int]
// backToList: List[Int] = List(1, 2, 3)
```

```scala
// ERROR: toSeq is only defined for Tensor1 and Tensor2
val rank3 = Tensor(Shape3(Axis[A] -> 1, Axis[B] -> 1, Axis[C] -> 1)).fill(0.0f).toSeq
// error:
// value toSeq is not a member of dimwit.tensor.Tensor[
// (repl.MdocSession.MdocApp.A, repl.MdocSession.MdocApp.B,
// repl.MdocSession.MdocApp.C),
// dimwit.tensor.DType.Float32].
// An extension method was tried, but could not be fully constructed:
//
// dimwit.conversions.toSeq()
//
// failed with:
//
// value toSeq: <overloaded dimwit.conversions.toSeq> does not take parameters
// val rank3 = Tensor(Shape3(Axis[A] -> 1, Axis[B] -> 1, Axis[C] -> 1)).fill(0.0f).toSeq
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```

**Note**: `toSeq` cannot be used inside `jit`, where the values of a traced tensor are unknown.

**Note**: For a `Range`, prefer `Tensor1(Axis[A]).fromRange(...)`, which creates the values in JAX without copying them from Scala.

### Identity Matrices with `eye`

`eye` is a creation method on the rank 2 factory: fix the shape first, then ask for the identity matrix.
Expand Down Expand Up @@ -472,10 +569,10 @@ val wrong = t.sum(Axis[C])
// Conflicting definitions:
// val t:
// dimwit.tensor.Tensor2[MdocApp0.this.A, MdocApp0.this.B,
// dimwit.tensor.DType.Float32] in class MdocApp0 at line 70 and
// dimwit.tensor.DType.Float32] in class MdocApp0 at line 81 and
// val t:
// dimwit.tensor.Tensor2[MdocApp0.this.A, MdocApp0.this.B,
// dimwit.tensor.DType.Float32] in class MdocApp0 at line 116
// dimwit.tensor.DType.Float32] in class MdocApp0 at line 127
//
```

Expand Down Expand Up @@ -517,10 +614,10 @@ val wrong = t + 5.0f // Use +! instead
// Conflicting definitions:
// val t:
// dimwit.tensor.Tensor2[MdocApp0.this.A, MdocApp0.this.B,
// dimwit.tensor.DType.Float32] in class MdocApp0 at line 70 and
// dimwit.tensor.DType.Float32] in class MdocApp0 at line 81 and
// val t:
// dimwit.tensor.Tensor2[MdocApp0.this.A, MdocApp0.this.B,
// dimwit.tensor.DType.Float32] in class MdocApp0 at line 125
// dimwit.tensor.DType.Float32] in class MdocApp0 at line 136
//
```

Expand Down Expand Up @@ -610,19 +707,19 @@ val wrong = m1.dot(Axis[B])(m2)
// Conflicting definitions:
// val m1:
// dimwit.tensor.Tensor2[MdocApp1.this.A, MdocApp1.this.B,
// dimwit.tensor.DType.Float32] in class MdocApp1 at line 147 and
// dimwit.tensor.DType.Float32] in class MdocApp1 at line 158 and
// val m1:
// dimwit.tensor.Tensor2[MdocApp1.this.A, MdocApp1.this.B,
// dimwit.tensor.DType.Float32] in class MdocApp1 at line 150
// dimwit.tensor.DType.Float32] in class MdocApp1 at line 161
//
// error:
// Conflicting definitions:
// val m2:
// dimwit.tensor.Tensor2[MdocApp1.this.B, MdocApp1.this.C,
// dimwit.tensor.DType.Float32] in class MdocApp1 at line 148 and
// dimwit.tensor.DType.Float32] in class MdocApp1 at line 159 and
// val m2:
// dimwit.tensor.Tensor2[MdocApp1.this.C, MdocApp1.this.D,
// dimwit.tensor.DType.Float32] in class MdocApp1 at line 151
// dimwit.tensor.DType.Float32] in class MdocApp1 at line 162
//
```

Expand Down Expand Up @@ -764,7 +861,7 @@ grid.select(Axis[A].at(3, 2))
// at dimwit.tensor.tensorops.StructuralExtensions$.windowExtents(StructuralOps.scala:762)
// at dimwit.tensor.tensorops.StructuralExtensions$.select(StructuralOps.scala:600)
// at dimwit.package$.select(package.scala:80)
// at repl.MdocSession$MdocApp17.$init$$$anonfun$4(AGENTS.md:739)
// at repl.MdocSession$MdocApp20.$init$$$anonfun$6(AGENTS.md:809)
```

---
Expand Down
136 changes: 136 additions & 0 deletions core/src/main/scala/dimwit/conversions/SeqConversions.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
package dimwit.conversions

import dimwit.tensor.*
import dimwit.tensor.DType.*
import dimwit.tensor.ValueTypeClasses.IsBoolean
import dimwit.tensor.ValueTypeClasses.IsFloating
import dimwit.tensor.ValueTypeClasses.IsInteger

import scala.annotation.targetName
import scala.collection.immutable.ArraySeq

/* Conversions between Scala sequences and tensors. They are opt-in: `import dimwit.conversions.*` makes them
* available, `import dimwit.*` does not.
*
* From Seqs to tensors, e.g. `Seq(1.0f, 2.0f).toTensor1(Axis[A])`: the value type is derived from the element type
* as for `fromArray` (Float to Float32, Double to Float64, Byte to Int8, Short to Int16, Int to Int32, Long to Int64,
* Boolean to Bool), or given explicitly, e.g. `Seq(1.0f, 2.0f).toTensor1(Axis[A], VType[Float16])`.
* For `toTensor2` the outer Seq runs along the first axis and the inner Seqs, the rows, along the second.
* All rows must have the same length, and there must be at least one row.
*
* From tensors to Seqs with `toSeq`, the reverse: `xs.toTensor1(Axis[A]).toSeq == xs`.
*/

extension (values: Seq[Boolean])
@targetName("booleanSeqToTensor1")
def toTensor1[L: Label](axis: Axis[L]): Tensor1[L, Bool] = Tensor1(axis).fromArray(values.toArray)
@targetName("booleanSeqToTensor1Typed")
def toTensor1[L: Label, V: IsBoolean](axis: Axis[L], vtype: VType[V]): Tensor1[L, V] = Tensor1(axis, vtype).fromArray(values.toArray)

extension (values: Seq[Byte])
@targetName("byteSeqToTensor1")
def toTensor1[L: Label](axis: Axis[L]): Tensor1[L, Int8] = Tensor1(axis).fromArray(values.toArray)
@targetName("byteSeqToTensor1Typed")
def toTensor1[L: Label, V: IsInteger](axis: Axis[L], vtype: VType[V]): Tensor1[L, V] = Tensor1(axis, vtype).fromArray(values.toArray)

extension (values: Seq[Short])
@targetName("shortSeqToTensor1")
def toTensor1[L: Label](axis: Axis[L]): Tensor1[L, Int16] = Tensor1(axis).fromArray(values.toArray)
@targetName("shortSeqToTensor1Typed")
def toTensor1[L: Label, V: IsInteger](axis: Axis[L], vtype: VType[V]): Tensor1[L, V] = Tensor1(axis, vtype).fromArray(values.toArray)

extension (values: Seq[Int])
@targetName("intSeqToTensor1")
def toTensor1[L: Label](axis: Axis[L]): Tensor1[L, Int32] = Tensor1(axis).fromArray(values.toArray)
@targetName("intSeqToTensor1Typed")
def toTensor1[L: Label, V: IsInteger](axis: Axis[L], vtype: VType[V]): Tensor1[L, V] = Tensor1(axis, vtype).fromArray(values.toArray)

extension (values: Seq[Long])
@targetName("longSeqToTensor1")
def toTensor1[L: Label](axis: Axis[L]): Tensor1[L, Int64] = Tensor1(axis).fromArray(values.toArray)
@targetName("longSeqToTensor1Typed")
def toTensor1[L: Label, V: IsInteger](axis: Axis[L], vtype: VType[V]): Tensor1[L, V] = Tensor1(axis, vtype).fromArray(values.toArray)

extension (values: Seq[Float])
@targetName("floatSeqToTensor1")
def toTensor1[L: Label](axis: Axis[L]): Tensor1[L, Float32] = Tensor1(axis).fromArray(values.toArray)
@targetName("floatSeqToTensor1Typed")
def toTensor1[L: Label, V: IsFloating](axis: Axis[L], vtype: VType[V]): Tensor1[L, V] = Tensor1(axis, vtype).fromArray(values.toArray)

extension (values: Seq[Double])
@targetName("doubleSeqToTensor1")
def toTensor1[L: Label](axis: Axis[L]): Tensor1[L, Float64] = Tensor1(axis).fromArray(values.toArray)
@targetName("doubleSeqToTensor1Typed")
def toTensor1[L: Label, V: IsFloating](axis: Axis[L], vtype: VType[V]): Tensor1[L, V] = Tensor1(axis, vtype).fromArray(values.toArray)

extension (values: Seq[Seq[Boolean]])
@targetName("booleanSeqToTensor2")
def toTensor2[L1: Label, L2: Label](axis1: Axis[L1], axis2: Axis[L2]): Tensor2[L1, L2, Bool] = Tensor2(axis1, axis2).fromArray(values.map(_.toArray).toArray)
@targetName("booleanSeqToTensor2Typed")
def toTensor2[L1: Label, L2: Label, V: IsBoolean](axis1: Axis[L1], axis2: Axis[L2], vtype: VType[V]): Tensor2[L1, L2, V] =
Tensor2(axis1, axis2, vtype).fromArray(values.map(_.toArray).toArray)

extension (values: Seq[Seq[Byte]])
@targetName("byteSeqToTensor2")
def toTensor2[L1: Label, L2: Label](axis1: Axis[L1], axis2: Axis[L2]): Tensor2[L1, L2, Int8] = Tensor2(axis1, axis2).fromArray(values.map(_.toArray).toArray)
@targetName("byteSeqToTensor2Typed")
def toTensor2[L1: Label, L2: Label, V: IsInteger](axis1: Axis[L1], axis2: Axis[L2], vtype: VType[V]): Tensor2[L1, L2, V] =
Tensor2(axis1, axis2, vtype).fromArray(values.map(_.toArray).toArray)

extension (values: Seq[Seq[Short]])
@targetName("shortSeqToTensor2")
def toTensor2[L1: Label, L2: Label](axis1: Axis[L1], axis2: Axis[L2]): Tensor2[L1, L2, Int16] = Tensor2(axis1, axis2).fromArray(values.map(_.toArray).toArray)
@targetName("shortSeqToTensor2Typed")
def toTensor2[L1: Label, L2: Label, V: IsInteger](axis1: Axis[L1], axis2: Axis[L2], vtype: VType[V]): Tensor2[L1, L2, V] =
Tensor2(axis1, axis2, vtype).fromArray(values.map(_.toArray).toArray)

extension (values: Seq[Seq[Int]])
@targetName("intSeqToTensor2")
def toTensor2[L1: Label, L2: Label](axis1: Axis[L1], axis2: Axis[L2]): Tensor2[L1, L2, Int32] = Tensor2(axis1, axis2).fromArray(values.map(_.toArray).toArray)
@targetName("intSeqToTensor2Typed")
def toTensor2[L1: Label, L2: Label, V: IsInteger](axis1: Axis[L1], axis2: Axis[L2], vtype: VType[V]): Tensor2[L1, L2, V] =
Tensor2(axis1, axis2, vtype).fromArray(values.map(_.toArray).toArray)

extension (values: Seq[Seq[Long]])
@targetName("longSeqToTensor2")
def toTensor2[L1: Label, L2: Label](axis1: Axis[L1], axis2: Axis[L2]): Tensor2[L1, L2, Int64] = Tensor2(axis1, axis2).fromArray(values.map(_.toArray).toArray)
@targetName("longSeqToTensor2Typed")
def toTensor2[L1: Label, L2: Label, V: IsInteger](axis1: Axis[L1], axis2: Axis[L2], vtype: VType[V]): Tensor2[L1, L2, V] =
Tensor2(axis1, axis2, vtype).fromArray(values.map(_.toArray).toArray)

extension (values: Seq[Seq[Float]])
@targetName("floatSeqToTensor2")
def toTensor2[L1: Label, L2: Label](axis1: Axis[L1], axis2: Axis[L2]): Tensor2[L1, L2, Float32] = Tensor2(axis1, axis2).fromArray(values.map(_.toArray).toArray)
@targetName("floatSeqToTensor2Typed")
def toTensor2[L1: Label, L2: Label, V: IsFloating](axis1: Axis[L1], axis2: Axis[L2], vtype: VType[V]): Tensor2[L1, L2, V] =
Tensor2(axis1, axis2, vtype).fromArray(values.map(_.toArray).toArray)

extension (values: Seq[Seq[Double]])
@targetName("doubleSeqToTensor2")
def toTensor2[L1: Label, L2: Label](axis1: Axis[L1], axis2: Axis[L2]): Tensor2[L1, L2, Float64] = Tensor2(axis1, axis2).fromArray(values.map(_.toArray).toArray)
@targetName("doubleSeqToTensor2Typed")
def toTensor2[L1: Label, L2: Label, V: IsFloating](axis1: Axis[L1], axis2: Axis[L2], vtype: VType[V]): Tensor2[L1, L2, V] =
Tensor2(axis1, axis2, vtype).fromArray(values.map(_.toArray).toArray)

// --- From tensors to Seqs ---
// The elements are read into a fresh array, which is wrapped without copying. Nothing else references it,
// so the result is a proper immutable IndexedSeq. Other collections are one call away, e.g. `t.toSeq.toList`.

extension [L, V, X](t: Tensor1[L, V])(using ev: HasScalar[V, X])
/** The elements of the vector, in order. Not available inside `jit`, as the values of a traced tensor are unknown. */
@targetName("tensor1ToSeq")
def toSeq: IndexedSeq[X] =
require(!t.isTracer, "Cannot convert a JAX Tracer to a Seq.")
ArraySeq.unsafeWrapArray(ev.readFlat(t.jaxValue))

extension [L1, L2, V, X](t: Tensor2[L1, L2, V])(using ev: HasScalar[V, X])
/** The rows of the matrix, i.e. the outer Seq runs along the first axis and the inner Seqs along the second,
* as for `toTensor2`. Not available inside `jit`, as the values of a traced tensor are unknown.
*/
@targetName("tensor2ToSeq")
def toSeq: IndexedSeq[IndexedSeq[X]] =
require(!t.isTracer, "Cannot convert a JAX Tracer to a Seq.")
val rows = t.shape.dimensions(0)
val columns = t.shape.dimensions(1)
val values = ev.readFlat(t.jaxValue)
IndexedSeq.tabulate(rows)(row => ArraySeq.unsafeWrapArray(values.slice(row * columns, (row + 1) * columns)))
43 changes: 31 additions & 12 deletions core/src/main/scala/dimwit/tensor/DType.scala
Original file line number Diff line number Diff line change
Expand Up @@ -138,18 +138,30 @@ enum DType(val name: String, val size: Int):
while i < arr.length do
db.put(arr(i).toDouble); i += 1

// --- Int32 Target ---
case (Int32, arr: Array[Int]) =>
buffer.asIntBuffer().put(arr)
case (Int32, arr: Array[Byte]) =>
val ib = buffer.asIntBuffer()
var i = 0;
while i < arr.length do
ib.put(arr(i).toInt); i += 1

// --- Int8 Target ---
case (Int8, arr: Array[Byte]) =>
buffer.put(arr)
// --- Signed integer targets from an array of the same width: bulk copy ---
case (Int8, arr: Array[Byte]) => buffer.put(arr)
case (Int16, arr: Array[Short]) => buffer.asShortBuffer().put(arr)
case (Int32, arr: Array[Int]) => buffer.asIntBuffer().put(arr)
case (Int64, arr: Array[Long]) => buffer.asLongBuffer().put(arr)

// --- Signed integer targets from an array of another width, e.g. Array[Byte] -> Int32, Array[Int] -> Int8 ---
case (Int8 | Int16 | Int32 | Int64, integers: (Array[Byte] | Array[Short] | Array[Int] | Array[Long])) =>
val get = longReader(integers)
val (min, max) = this match
case Int8 => (Byte.MinValue.toLong, Byte.MaxValue.toLong)
case Int16 => (Short.MinValue.toLong, Short.MaxValue.toLong)
case Int32 => (Int.MinValue.toLong, Int.MaxValue.toLong)
case _ => (Long.MinValue, Long.MaxValue)
var i = 0
while i < values.length do
val v = get(i)
require(v >= min && v <= max, s"Value $v at index $i is out of range for DType $name")
this match
case Int8 => buffer.put(v.toByte)
case Int16 => buffer.putShort(v.toShort)
case Int32 => buffer.putInt(v.toInt)
case _ => buffer.putLong(v)
i += 1

case (UInt8, arr: Array[Byte]) =>
buffer.put(arr) // Interpret bytes as unsigned when reading
Expand All @@ -167,6 +179,13 @@ enum DType(val name: String, val size: Int):

buffer.array()

/** Reads the elements of an array of integers as `Long`, without copying or boxing them. */
private def longReader(values: Array[Byte] | Array[Short] | Array[Int] | Array[Long]): Int => Long = values match
case arr: Array[Byte] => i => arr(i).toLong
case arr: Array[Short] => i => arr(i).toLong
case arr: Array[Int] => i => arr(i).toLong
case arr: Array[Long] => i => arr(i)

private def floatToFloat16(f: Float): Short =
// TODO replace with java.lang.Float.floatToFloat16 when we can require Java 20+
val bits = java.lang.Float.floatToIntBits(f)
Expand Down
12 changes: 11 additions & 1 deletion core/src/main/scala/dimwit/tensor/Tensor.scala
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,17 @@ object Tensor2:

class Axes2TypedFactory[L1: Label, L2: Label, V](axis1: Axis[L1], axis2: Axis[L2], vtype: VType[V]):

private def createShape[V](values: Array2D[V]): Shape2[L1, L2] = Shape2(AxisExtent(axis1, values.length), AxisExtent(axis2, values.head.length))
private def createShape[X](values: Array2D[X]): Shape2[L1, L2] =
val name1 = summon[Label[L1]].name
val name2 = summon[Label[L2]].name
require(values.nonEmpty, s"Cannot create a matrix without rows: the extent of axis $name2 is unknown")
val columns = values.head.length
val uneven = values.indexWhere(_.length != columns)
require(
uneven < 0,
s"All rows along axis $name1 must have the same length along axis $name2, but row 0 has length $columns and row $uneven has length ${values(uneven).length}"
)
Shape2(AxisExtent(axis1, values.length), AxisExtent(axis2, columns))

def fromArray(values: Array2D[Boolean])(using IsBoolean[V]): Tensor2[L1, L2, V] = Tensor(createShape(values), VType[V]).fromArray(values.flatten)
def fromArray(values: Array2D[Byte])(using IsInteger[V]): Tensor2[L1, L2, V] = Tensor(createShape(values), VType[V]).fromArray(values.flatten)
Expand Down
Loading
Loading