Skip to content

Commit

Permalink
Fix torch.min and torch.mode (#7513) (#8092)
Browse files Browse the repository at this point in the history
Co-authored-by: Simon Teo <simonteo@google.com>
  • Loading branch information
simonteozw and Simon Teo committed Sep 30, 2024
1 parent d98be5b commit 0f645b2
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
5 changes: 2 additions & 3 deletions experimental/torch_xla2/test/test_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,6 @@
"lu_unpack",
"masked.median",
"max_pool2d_with_indices_backward",
"min",
"mode",
"multinomial",
"mvlgamma",
"nanmedian",
Expand Down Expand Up @@ -243,7 +241,8 @@ def run_export_and_compare(testcase,
# For example: sort( [1, 0, 0]) -> [0, 0, 1]
# the correct index can be [1, 2, 0] or [2, 1, 0]
should_ignore_indexes = {
"topk"
"topk",
"mode"
}


Expand Down
22 changes: 18 additions & 4 deletions experimental/torch_xla2/torch_xla2/ops/jaten.py
Original file line number Diff line number Diff line change
Expand Up @@ -1079,11 +1079,25 @@ def reduce_fn(a, b):


@op(torch.ops.aten.min)
def _aten_min(x, axis=None):
if axis:
return jnp.min(x, axis=axis), jnp.argmin(x, axis=axis).astype(jnp.int64)
def _aten_min(x, dim=None, keepdim=False):
if dim is not None:
return _with_reduction_scalar(jnp.min, x, dim, keepdim), _with_reduction_scalar(jnp.argmin, x, dim, keepdim).astype(jnp.int64)
else:
return jnp.min(x, axis=axis)
return _with_reduction_scalar(jnp.min, x, dim, keepdim)


@op(torch.ops.aten.mode)
def _aten_mode(input, dim=-1, keepdim=False, *, out=None):
if input.ndim == 0: # single number
return input, jnp.array(0)
dim = (input.ndim + dim) % input.ndim # jnp.scipy.stats.mode does not accept -1 as dim
# keepdims must be True for accurate broadcasting
mode, _ = jax.scipy.stats.mode(input, axis=dim, keepdims=True)
mode_broadcast = jnp.broadcast_to(mode, input.shape)
if not keepdim:
mode = mode.squeeze(axis=dim)
indices = jnp.argmax(jnp.equal(mode_broadcast, input), axis=dim, keepdims=keepdim)
return mode, indices


@op(torch.ops.aten.amin)
Expand Down

0 comments on commit 0f645b2

Please sign in to comment.