Skip to content

[Fix][Relax][Frontend][Torch] Promote mixed-dtype branches in torch.where - #21130

Open
GoyalIshaan wants to merge 1 commit into
apache:mainfrom
GoyalIshaan:fix/torch-where-mixed-dtype
Open

GoyalIshaan wants to merge 1 commit into
apache:mainfrom
GoyalIshaan:fix/torch-where-mixed-dtype

Conversation

@GoyalIshaan

Copy link
Copy Markdown

Fixes #20940.

BaseFXGraphImporter._where previously passed x and y straight to relax.op.where without dtype promotion. Non-bool mismatches (e.g., int64/float32) failed in InferTypeWhere, bool/float32 slipped past type inference and failed later in tvm.compile, and ops decomposed into aten.where.self (like mixed-dtype torch.select_scatter) hit the same error.

To fix this, _where now promotes mismatched TensorType branches before emitting relax.op.where (leaving condition unchanged and taking the fast path when dtypes already match). When both ranks are known (ndim >= 0), it computes the target dtype via torch.result_type on zero-allocation "meta" tensors (() for 0-D, (1,) for N-D) so 0-D vs N-D cases match PyTorch's rank-aware promotion rules (e.g., 1-D float32 + 0-D float64 stays float32), falling back to torch.promote_types if either rank is unknown, and casts any mismatched branch with relax.op.astype. Because from_exported_program and from_fx share _where, both importers are covered without touching _binary_op.

Testing

Added LLVM/CPU execution tests in test_frontend_from_exported_program.py (6 dtype pairs in both branch orders including bool/float32 and uint8/int8, 0-D vs 1-D rank-aware cases, and mixed-dtype select_scatter) and structural IR tests in test_frontend_from_fx.py.

pytest tests/python/relax/test_frontend_from_exported_program.py \
       tests/python/relax/test_frontend_from_fx.py \
       -k "test_where or test_binary_dtype_promotion" -v
# 29 passed

pre-commit run --files \
  python/tvm/relax/frontend/torch/base_fx_graph_translator.py \
  tests/python/relax/test_frontend_from_exported_program.py \
  tests/python/relax/test_frontend_from_fx.py
# All checks passed

…here

Fixes apache#20940.

Promote mismatched TensorType branches in BaseFXGraphImporter._where
using PyTorch's rank-aware torch.result_type on zero-allocation meta
tensors (falling back to torch.promote_types when rank is unknown)
before emitting relax.op.where, leaving condition unchanged.

Adds LLVM/CPU tests in test_frontend_from_exported_program.py for
mixed-dtype branch pairs in both orders, 0-D vs 1-D rank-aware cases,
and mixed-dtype select_scatter, plus FX structural tests in
test_frontend_from_fx.py.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug][Relax] torch.where with branches of different dtypes fails in from_exported_program

1 participant