Skip to content
Open
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
18 changes: 18 additions & 0 deletions lib/ortex/backend.ex
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,24 @@ defmodule Ortex.Backend do
%{out | data: %B{ref: Ortex.Native.concatenate(tensor_refs, type, axis)}}
end

# stack/3 is a backend callback since Nx 0.8; older Nx stacks with reshape and concatenate.
@impl {:stack, 3} in Nx.Backend.behaviour_info(:callbacks)
def stack(out, tensors, axis) do
# Give each tensor a new axis of size 1 at `axis`, then join them along it.
tensors =
Enum.map(tensors, fn %T{shape: shape, names: names} = t ->
new_axis = %{
t
| shape: Tuple.insert_at(shape, axis, 1),
names: List.insert_at(names, axis, nil)
}

reshape(new_axis, t)
end)

concatenate(out, tensors, axis)
end

if Application.compile_env(:ortex, :add_backend_on_inspect, true) do
defp maybe_add_signature(result, %T{data: %B{ref: _mat_ref}}) do
Inspect.Algebra.concat([
Expand Down
30 changes: 30 additions & 0 deletions test/shape/stack_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
defmodule Ortex.TestStack do
use ExUnit.Case

defp to_ortex(tensor), do: Nx.backend_transfer(tensor, Ortex.Backend)

test "stack 1d tensors" do
t1 = Nx.tensor([1, 2, 3])
t2 = Nx.tensor([4, 5, 6])

stacked = Nx.stack([to_ortex(t1), to_ortex(t2)]) |> Nx.backend_transfer()
assert stacked == Nx.stack([t1, t2])
end

test "stack 2d tensors on each axis" do
t1 = Nx.iota({2, 3}, type: :f32)
t2 = Nx.iota({2, 3}, type: :f32) |> Nx.add(10)

for axis <- 0..2 do
stacked = Nx.stack([to_ortex(t1), to_ortex(t2)], axis: axis) |> Nx.backend_transfer()
assert stacked == Nx.stack([t1, t2], axis: axis)
end
end

test "stack three tensors" do
tensors = for i <- 1..3, do: Nx.iota({2, 2}, type: :s64) |> Nx.multiply(i)

stacked = tensors |> Enum.map(&to_ortex/1) |> Nx.stack(axis: 1) |> Nx.backend_transfer()
assert stacked == Nx.stack(tensors, axis: 1)
end
end
Loading