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
36 changes: 36 additions & 0 deletions Tensors/src/main/scala/com/thoughtworks/compute/Tensors.scala
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,42 @@ trait Tensors extends OpenCL {
}

sealed trait Tensor { thisTensor =>

override def toString: String = {
enqueue
.intransitiveFlatMap { pendingBuffer =>
pendingBuffer.toHostBuffer.intransitiveMap { floatBuffer =>
val floatArray = Array.ofDim[Float](floatBuffer.capacity())
floatBuffer.asReadOnlyBuffer().get(floatArray)
floatArray
}
}
.run
.map { floatArray =>
def toFastring(shape: Seq[Int], floatArray: Seq[Float]): Fastring = {
shape match {
case headSize +: tailShape =>
val length = floatArray.length
if (tailShape.isEmpty) {
if (headSize == length) {
fast"[${floatArray.mkFastring(",")}]"
} else {
throw new IllegalArgumentException
}
} else {
val groupSize = length / headSize
def groups = for (i <- (0 until headSize).view) yield {
toFastring(tailShape, floatArray.view(i * groupSize, (i + 1) * groupSize))
}
fast"[${groups.mkFastring(",")}]"
}
}
}

toFastring(shape.view, floatArray).toString
}.blockingAwait
}

def broadcast(newShape: Array[Int]): Tensor = {
val newLength = newShape.length
val length = shape.length
Expand Down
14 changes: 14 additions & 0 deletions Tensors/src/test/scala/com/thoughtworks/compute/TensorsSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,20 @@ class TensorsSpec extends AsyncFreeSpec with Matchers {
val element = 42.0f
val padding = 99.0f
val translated = tensors.Tensor.fill(element, shape, padding = padding).translate(Array(1, 2, -3))
translated.toString should be(
"[" +
"[" +
"[99.0,99.0,99.0,99.0,99.0]," +
"[99.0,99.0,99.0,99.0,99.0]," +
"[99.0,99.0,99.0,99.0,99.0]" +
"]," +
"[" +
"[99.0,99.0,99.0,99.0,99.0]," +
"[99.0,99.0,99.0,99.0,99.0]," +
"[42.0,42.0,99.0,99.0,99.0]" +
"]" +
"]")

for {
pendingBuffer <- translated.enqueue
floatBuffer <- pendingBuffer.toHostBuffer
Expand Down