From 7ee89eab028c29ac3e8d8ca0f7630774bc6f373b Mon Sep 17 00:00:00 2001 From: Marcel Luethi Date: Tue, 17 Nov 2026 11:07:21 +0100 Subject: [PATCH] Use toPythonCopy instead of toPythonProxy in stack and concatenate stack and concatenate passed their tensors as toPythonProxy. A proxy is a lazy view of the Scala Seq. Every len() call and every element read goes back to the JVM through ScalaPy's JNI bridge. toPythonCopy builds a real Python list in a single conversion. Jax reads it and never has to call back into the JVM. --- .../main/scala/dimwit/tensor/tensorops/StructuralOps.scala | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core/src/main/scala/dimwit/tensor/tensorops/StructuralOps.scala b/core/src/main/scala/dimwit/tensor/tensorops/StructuralOps.scala index 60aaced..88dfdc0 100644 --- a/core/src/main/scala/dimwit/tensor/tensorops/StructuralOps.scala +++ b/core/src/main/scala/dimwit/tensor/tensorops/StructuralOps.scala @@ -162,7 +162,7 @@ private[dimwit] object StructuralOps: newAxis: Axis[L] ): Tensor[L *: T, V] = require(tensors.nonEmpty, "Cannot stack an empty sequence of tensors") - val jaxValuesSeq = tensors.map(_.jaxValue).toPythonProxy + val jaxValuesSeq = tensors.map(_.jaxValue).toPythonCopy val stackedJaxValue = Jax.jnp.stack(jaxValuesSeq, axis = 0) Tensor(stackedJaxValue) @@ -185,7 +185,7 @@ private[dimwit] object StructuralOps: ): Tensor[inserter.Out, V] = require(tensors.nonEmpty, "Cannot stack an empty sequence of tensors") val axisIdx = axisIndex.index + 1 // we are inserting after the given axis, so shift by 1 - val jaxValuesSeq = tensors.map(_.jaxValue).toPythonProxy + val jaxValuesSeq = tensors.map(_.jaxValue).toPythonCopy val stackedJaxValue = Jax.jnp.stack(jaxValuesSeq, axis = axisIdx) val names = summon[Labels[T]].names val newNames = names.take(axisIdx) ++ Seq(newLabel.name) ++ names.drop(axisIdx) @@ -209,7 +209,7 @@ private[dimwit] object StructuralOps: ): Tensor[T, V] = require(tensors.nonEmpty, "Cannot concatenate an empty sequence of tensors") val axisIdx = axisIndex.index - val jaxValuesSeq = tensors.map(_.jaxValue).toPythonProxy + val jaxValuesSeq = tensors.map(_.jaxValue).toPythonCopy val concatenatedJaxValue = Jax.jnp.concatenate(jaxValuesSeq, axis = axisIdx) Tensor(concatenatedJaxValue)