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
12 changes: 10 additions & 2 deletions emlx/lib/emlx/backend.ex
Original file line number Diff line number Diff line change
Expand Up @@ -2164,11 +2164,19 @@ defmodule EMLX.Backend do
|> to_nx(out)
end

# mx::allclose takes abs(b) in the type of b, which overflows at the smallest signed integer.
# Two integer tensors go to the default function, which widens them first.
@impl true
def block(%Nx.Block.AllClose{atol: atol, rtol: rtol, equal_nan: equal_nan}, out, [a, b], _fun) do
def block(
%Nx.Block.AllClose{atol: atol, rtol: rtol, equal_nan: equal_nan},
out,
[%T{type: {kind_a, _}} = a, %T{type: {kind_b, _}} = b],
_fun
)
when kind_a not in [:s, :u] or kind_b not in [:s, :u] do
a
|> from_nx()
|> EMLX.allclose(from_nx(b), atol || 1.0e-4, rtol || 1.0e-8, equal_nan == true)
|> EMLX.allclose(from_nx(b), rtol, atol, equal_nan == true)
|> to_nx(out)
end

Expand Down
9 changes: 9 additions & 0 deletions emlx/test/emlx/native/expr_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -2828,6 +2828,15 @@ defmodule EMLX.Native.ExprTest do
assert Nx.to_number(native) == 1
end

test "all_close: rtol scales with b and atol does not, eager and compiled" do
# |a - b| = 0.005 is within rtol * |b| = 0.01, but not within atol = 1.0e-8.
a = Nx.tensor([1000.0], type: :f32, backend: EMLX.Backend)
b = Nx.tensor([1000.005], type: :f32, backend: EMLX.Backend)

assert Nx.to_number(Nx.all_close(a, b)) == 1
assert Nx.to_number(Nx.Defn.jit(&all_close_defn/2, compiler: EMLX).(a, b)) == 1
end

test "all_close: not-close tensors vs EMLX.Backend" do
a = Nx.tensor([1.0, 2.0, 3.0], type: :f32, backend: EMLX.Backend)
b = Nx.tensor([1.0, 2.0, 4.0], type: :f32, backend: EMLX.Backend)
Expand Down
Loading