diff --git a/AGENTS.md b/AGENTS.md index 9fcb294..691d815 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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: 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. @@ -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 // ``` @@ -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 // ``` @@ -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 // ``` @@ -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) ``` --- diff --git a/core/src/main/scala/dimwit/conversions/SeqConversions.scala b/core/src/main/scala/dimwit/conversions/SeqConversions.scala new file mode 100644 index 0000000..7097f5b --- /dev/null +++ b/core/src/main/scala/dimwit/conversions/SeqConversions.scala @@ -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))) diff --git a/core/src/main/scala/dimwit/tensor/DType.scala b/core/src/main/scala/dimwit/tensor/DType.scala index 77eb17c..0781df0 100644 --- a/core/src/main/scala/dimwit/tensor/DType.scala +++ b/core/src/main/scala/dimwit/tensor/DType.scala @@ -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 @@ -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) diff --git a/core/src/main/scala/dimwit/tensor/Tensor.scala b/core/src/main/scala/dimwit/tensor/Tensor.scala index f9af852..9504481 100644 --- a/core/src/main/scala/dimwit/tensor/Tensor.scala +++ b/core/src/main/scala/dimwit/tensor/Tensor.scala @@ -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) diff --git a/core/src/test/scala/dimwit/conversions/SeqConversionsSuite.scala b/core/src/test/scala/dimwit/conversions/SeqConversionsSuite.scala new file mode 100644 index 0000000..ac4fdf7 --- /dev/null +++ b/core/src/test/scala/dimwit/conversions/SeqConversionsSuite.scala @@ -0,0 +1,141 @@ +package dimwit + +import dimwit.* +import dimwit.conversions.* +import scala.collection.immutable.ArraySeq +import scala.compiletime.testing.typeCheckErrors + +class SeqConversionsSuite extends DimwitTest: + + def withJaxX64Support[R](block: => R): R = + import me.shadaj.scalapy.py + val jaxConfig = py.module("jax").config + val current = jaxConfig.jax_enable_x64.as[Boolean] + jaxConfig.update("jax_enable_x64", true) + val res = block + jaxConfig.update("jax_enable_x64", current) + res + + describe("toTensor1"): + + it("derives the value type from the element type"): + Seq(true, false).toTensor1(Axis[A]).dtype shouldBe DType.Bool + Seq(1.toByte, 2.toByte).toTensor1(Axis[A]).dtype shouldBe DType.Int8 + Seq(1.toShort, 2.toShort).toTensor1(Axis[A]).dtype shouldBe DType.Int16 + Seq(1, 2).toTensor1(Axis[A]).dtype shouldBe DType.Int32 + Seq(1.0f, 2.0f).toTensor1(Axis[A]).dtype shouldBe DType.Float32 + withJaxX64Support: + Seq(1L, 2L).toTensor1(Axis[A]).dtype shouldBe DType.Int64 + Seq(1.0, 2.0).toTensor1(Axis[A]).dtype shouldBe DType.Float64 + + it("keeps the values and their order"): + val t: Tensor1[A, Float32] = Seq(3.0f, 1.0f, 2.0f).toTensor1(Axis[A]) + t.shape shouldBe Shape1(Axis[A] -> 3) + t.toArray shouldBe Array(3.0f, 1.0f, 2.0f) + + it("accepts any Seq"): + List(1, 2, 3).toTensor1(Axis[A]).toArray shouldBe Array(1, 2, 3) + Vector(1, 2, 3).toTensor1(Axis[A]).toArray shouldBe Array(1, 2, 3) + ArraySeq(1, 2, 3).toTensor1(Axis[A]).toArray shouldBe Array(1, 2, 3) + (1 to 3).toTensor1(Axis[A]).toArray shouldBe Array(1, 2, 3) + (1 to 3).map(_ * 0.5f).toTensor1(Axis[A]).toArray shouldBe Array(0.5f, 1.0f, 1.5f) + + it("takes the value type explicitly"): + Seq(1.0f, 2.0f).toTensor1(Axis[A], VType[Float16]).dtype shouldBe DType.Float16 + Seq(1, 2).toTensor1(Axis[A], VType[Int8]).dtype shouldBe DType.Int8 + Seq(true).toTensor1(Axis[A], VType[Bool]).dtype shouldBe DType.Bool + + it("converts an empty Seq to an axis of extent 0"): + Seq.empty[Float].toTensor1(Axis[A]).shape shouldBe Shape1(Axis[A] -> 0) + + describe("toTensor2"): + + it("derives the value type from the element type"): + Seq(Seq(true), Seq(false)).toTensor2(Axis[A], Axis[B]).dtype shouldBe DType.Bool + Seq(Seq(1.toByte), Seq(2.toByte)).toTensor2(Axis[A], Axis[B]).dtype shouldBe DType.Int8 + Seq(Seq(1.toShort), Seq(2.toShort)).toTensor2(Axis[A], Axis[B]).dtype shouldBe DType.Int16 + Seq(Seq(1), Seq(2)).toTensor2(Axis[A], Axis[B]).dtype shouldBe DType.Int32 + Seq(Seq(1.0f), Seq(2.0f)).toTensor2(Axis[A], Axis[B]).dtype shouldBe DType.Float32 + withJaxX64Support: + Seq(Seq(1L), Seq(2L)).toTensor2(Axis[A], Axis[B]).dtype shouldBe DType.Int64 + Seq(Seq(1.0), Seq(2.0)).toTensor2(Axis[A], Axis[B]).dtype shouldBe DType.Float64 + + it("uses the inner Seqs as rows"): + val t: Tensor2[A, B, Float32] = Seq(Seq(1.0f, 2.0f, 3.0f), Seq(4.0f, 5.0f, 6.0f)).toTensor2(Axis[A], Axis[B]) + t.shape shouldBe Shape2(Axis[A] -> 2, Axis[B] -> 3) + t.toArray shouldBe Array(Array(1.0f, 2.0f, 3.0f), Array(4.0f, 5.0f, 6.0f)) + + it("accepts any Seq of Seqs"): + List(Vector(1, 2), Vector(3, 4)).toTensor2(Axis[A], Axis[B]).toArray shouldBe Array(Array(1, 2), Array(3, 4)) + (0 until 2).map(i => (0 until 3).map(j => 10 * i + j)).toTensor2(Axis[A], Axis[B]).toArray shouldBe + Array(Array(0, 1, 2), Array(10, 11, 12)) + + it("takes the value type explicitly"): + Seq(Seq(1.0f, 2.0f)).toTensor2(Axis[A], Axis[B], VType[Float16]).dtype shouldBe DType.Float16 + Seq(Seq(1, 2)).toTensor2(Axis[A], Axis[B], VType[Int8]).dtype shouldBe DType.Int8 + + it("allows rows of length 0"): + Seq(Seq.empty[Float], Seq.empty[Float]).toTensor2(Axis[A], Axis[B]).shape shouldBe Shape2(Axis[A] -> 2, Axis[B] -> 0) + + it("rejects rows of different lengths"): + val error = intercept[IllegalArgumentException]: + Seq(Seq(1.0f, 2.0f), Seq(3.0f), Seq(4.0f, 5.0f, 6.0f)).toTensor2(Axis[A], Axis[B]) + error.getMessage should include("row 0 has length 2 and row 1 has length 1") + + it("rejects a Seq without rows"): + val error = intercept[IllegalArgumentException]: + Seq.empty[Seq[Float]].toTensor2(Axis[A], Axis[B]) + error.getMessage should include("extent of axis B is unknown") + + describe("toSeq"): + + it("reads the elements of a Tensor1 in order"): + val xs: IndexedSeq[Float] = Tensor1(Axis[A]).fromArray(Array(3.0f, 1.0f, 2.0f)).toSeq + xs shouldBe Seq(3.0f, 1.0f, 2.0f) + + it("reads a Tensor2 as rows along the first axis"): + val rows: IndexedSeq[IndexedSeq[Int]] = Tensor2(Axis[A], Axis[B]).fromArray(Array(Array(1, 2, 3), Array(4, 5, 6))).toSeq + rows shouldBe Seq(Seq(1, 2, 3), Seq(4, 5, 6)) + + it("is the reverse of toTensor1 and toTensor2"): + val xs = List(1.5f, -2.0f, 0.25f) + xs.toTensor1(Axis[A]).toSeq shouldBe xs + Seq(true, false).toTensor1(Axis[A]).toSeq shouldBe Seq(true, false) + val rows = Vector(Vector(1L, 2L), Vector(3L, 4L), Vector(5L, 6L)) + withJaxX64Support: + rows.toTensor2(Axis[A], Axis[B]).toSeq shouldBe rows + + it("handles axes of extent 0"): + Seq.empty[Int].toTensor1(Axis[A]).toSeq shouldBe empty + Tensor(Shape2(Axis[A] -> 2, Axis[B] -> 0)).fill(0.0f).toSeq shouldBe Seq(Seq.empty, Seq.empty) + Tensor(Shape2(Axis[A] -> 0, Axis[B] -> 3)).fill(0.0f).toSeq shouldBe empty + + it("converts to other collections via the Seq"): + Tensor1(Axis[A]).fromArray(Array(1, 2, 3)).toSeq.toList shouldBe List(1, 2, 3) + + it("fails inside jit, where the values are unknown"): + val f = jit((t: Tensor1[A, Float32]) => + t.toSeq + t + ) + val error = intercept[Exception](f(Tensor1(Axis[A]).fromArray(Array(1.0f)))) + error.getMessage should include("Cannot convert a JAX Tracer to a Seq") + + describe("Tensor2 fromArray"): + it("rejects ragged rows even if the total number of values fits"): + // 3 rows, the first of length 2, and 6 values in total: used to become a wrong 3x2 matrix + intercept[IllegalArgumentException]: + Tensor2(Axis[A], Axis[B]).fromArray(Array(Array(1.0f, 2.0f), Array(3.0f), Array(4.0f, 5.0f, 6.0f))) + + describe("compile errors"): + it("does not compile for unsupported element types"): + typeCheckErrors("""Seq("a", "b").toTensor1(Axis[A])""") should not be empty + typeCheckErrors("""Seq(Seq("a")).toTensor2(Axis[A], Axis[B])""") should not be empty + + it("does not compile for a value type that does not fit the elements"): + typeCheckErrors("Seq(1.0f, 2.0f).toTensor1(Axis[A], VType[Int32])") should not be empty + typeCheckErrors("Seq(1, 2).toTensor1(Axis[A], VType[Float32])") should not be empty + typeCheckErrors("Seq(Seq(1.0f)).toTensor2(Axis[A], Axis[B], VType[Bool])") should not be empty + + it("does not compile without a label for the axis"): + typeCheckErrors("Seq(1.0f).toTensor1(Axis[String])") should not be empty diff --git a/core/src/test/scala/dimwit/tensor/TensorCreationSuite.scala b/core/src/test/scala/dimwit/tensor/TensorCreationSuite.scala index 68d6173..8eb3e5a 100644 --- a/core/src/test/scala/dimwit/tensor/TensorCreationSuite.scala +++ b/core/src/test/scala/dimwit/tensor/TensorCreationSuite.scala @@ -67,6 +67,26 @@ class TensorCreationSuite extends DimwitTest: val floatTensorFromDouble2 = Tensor(Shape2(Axis[A] -> 2, Axis[B] -> 2), VType[Float32]).fromArray(Array(1.0, 2.0, 3.0, 4.0)) floatTensorFromDouble2.dtype shouldBe DType.Float32 + describe("fromArray with integers"): + it("Short and Long arrays default to Int16 and Int64"): + val shorts = Tensor1(Axis[A]).fromArray(Array[Short](-3, 0, 32767)) + shorts.dtype shouldBe DType.Int16 + shorts.toArray shouldBe Array[Short](-3, 0, 32767) + withJaxX64Support: + val longs = Tensor1(Axis[A]).fromArray(Array(-1L, Long.MaxValue)) + longs.dtype shouldBe DType.Int64 + longs.toArray shouldBe Array(-1L, Long.MaxValue) + + it("converts between integer widths"): + Tensor1(Axis[A], VType[Int8]).fromArray(Array(-128, 0, 127)).toArray shouldBe Array[Byte](-128, 0, 127) + Tensor1(Axis[A], VType[Int16]).fromArray(Array[Byte](1, -2)).toArray shouldBe Array[Short](1, -2) + Tensor1(Axis[A], VType[Int32]).fromArray(Array(-5L, 7L)).toArray shouldBe Array(-5, 7) + + it("rejects values out of range of the value type"): + val error = intercept[IllegalArgumentException]: + Tensor1(Axis[A], VType[Int8]).fromArray(Array(1, 200)) + error.getMessage should include("Value 200 at index 1 is out of range for DType int8") + describe("fromFunction"): it("2D: identity matrix from indices"): diff --git a/mdocs/AGENTS.md b/mdocs/AGENTS.md index 919b1b8..ddb646f 100644 --- a/mdocs/AGENTS.md +++ b/mdocs/AGENTS.md @@ -133,6 +133,63 @@ 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 mdoc:fail +// 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 +``` + +```scala mdoc:silent +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 mdoc:fail +// 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]) +``` + +```scala mdoc:crash +// 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]) +``` + +`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 mdoc +val backToSeq = fromSeq1.toSeq // IndexedSeq[Float] +val backToRows = fromSeq2.toSeq // IndexedSeq[IndexedSeq[Float]], the rows along A +val backToList = fromList.toSeq.toList // List[Int] +``` + +```scala mdoc:fail +// 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 +``` + +**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.