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
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,7 @@ private[dimwit] object Tensor2Extensions:
def toArray: Array[Array[X]] =
require(!t.isTracer, "Cannot convert a JAX Tracer to an array.")
given scala.reflect.ClassTag[X] = ev.classTag
ev.readFlat(t.jaxValue).grouped(t.shape.dimensions(1)).toArray
val rows = t.shape.dimensions(0)
val columns = t.shape.dimensions(1)
val values = ev.readFlat(t.jaxValue)
Array.tabulate(rows)(row => values.slice(row * columns, (row + 1) * columns))
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,6 @@ private[dimwit] object Tensor3Extensions:
def toArray: Array[Array[Array[X]]] =
require(!t.isTracer, "Cannot convert a JAX Tracer to an array.")
given scala.reflect.ClassTag[X] = ev.classTag
val d1 = t.shape.dimensions(1); val d2 = t.shape.dimensions(2)
ev.readFlat(t.jaxValue).grouped(d1 * d2).map(_.grouped(d2).toArray).toArray
val d0 = t.shape.dimensions(0); val d1 = t.shape.dimensions(1); val d2 = t.shape.dimensions(2)
val values = ev.readFlat(t.jaxValue)
Array.tabulate(d0, d1)((i, j) => values.slice((i * d1 + j) * d2, (i * d1 + j + 1) * d2))
10 changes: 10 additions & 0 deletions core/src/test/scala/dimwit/tensor/ToArraySuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ class ToArraySuite extends DimwitTest:
val t = Tensor2(Axis[A], Axis[B]).fromArray(data)
t.toArray shouldBe data

it("axes of extent 0"):
Tensor(Shape2(Axis[A] -> 2, Axis[B] -> 0)).fill(0.0f).toArray shouldBe Array(Array.empty[Float], Array.empty[Float])
Tensor(Shape2(Axis[A] -> 0, Axis[B] -> 3)).fill(0.0f).toArray shouldBe empty

describe("Tensor3.toArray"):
it("Float32 roundtrip"):
val data = Array(
Expand All @@ -39,6 +43,12 @@ class ToArraySuite extends DimwitTest:
)
t.toArray shouldBe data

it("axes of extent 0"):
val emptyRow = Array.empty[Float]
Tensor(Shape3(Axis[A] -> 2, Axis[B] -> 3, Axis[C] -> 0)).fill(0.0f).toArray shouldBe Array.fill(2, 3)(emptyRow)
Tensor(Shape3(Axis[A] -> 2, Axis[B] -> 0, Axis[C] -> 4)).fill(0.0f).toArray shouldBe Array.fill(2)(Array.empty[Array[Float]])
Tensor(Shape3(Axis[A] -> 0, Axis[B] -> 3, Axis[C] -> 4)).fill(0.0f).toArray shouldBe empty

describe("toArray with filled tensors"):
it("fill value is reflected in array"):
val t = Tensor(Shape2(Axis[A] -> 3, Axis[B] -> 2)).fill(7.0f)
Expand Down
Loading