Skip to content

[Relax][FRONTEND][Pytorch] Add support for searchsorted - #20760

Open
Netra-Srinivasan-McW wants to merge 5 commits into
apache:mainfrom
Netra-Srinivasan-McW:searchsorted-support
Open

Netra-Srinivasan-McW wants to merge 5 commits into
apache:mainfrom
Netra-Srinivasan-McW:searchsorted-support

Conversation

@Netra-Srinivasan-McW

@Netra-Srinivasan-McW Netra-Srinivasan-McW commented Oct 16, 2026 •

Copy link
Copy Markdown

This PR adds support for the searchsorted operator in TVM Relax, which is used in transformer models such as Perplexity AI's pplx-embed-v2-late-9b.

The following requirements have been covered:

  • C0: Check whether the operator can be decomposed into existing Relax operators.
  • C1: Introduce legalization rules to enable compilation on CPU.
  • C2: Ensure the operator compiles on CUDA.

Tests have been added to validate the operator's behavior and compilation across the supported targets, covering both static and dynamic shapes.

Closes #20739

@Netra-Srinivasan-McW

Copy link
Copy Markdown
Author

@tqchen @tlopex Could you review this PR and provide your feedback. Thanks.

@Netra-Srinivasan-McW

Copy link
Copy Markdown
Author

Hi @mshr-h, @yzhliu, @tqchen, @tlopex,
Could you please take a look at this PR when you get a chance. Thanks.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Missing searchsorted rank and batch-shape validation allows incompatible inputs to reach CPU code that reads beyond the sequence buffer.

5 open issues
What changed in this PR

Adds PyTorch searchsorted support to TVM Relax, addressing the unsupported operator reported in #20739 for models such as pplx-embed-v2-late-9b.

Changes:

  • Introduces the Relax operator, attributes, type inference, and Python/script APIs.
  • Adds FX and exported-program conversion, CPU legalization, and GPU dispatch.
  • Adds structural and CPU numerical tests covering search options and dynamic batch shapes.
File Description
tests/​python/​relax/​test_frontend_from_fx.py Adds structural FX import coverage.
tests/​python/​relax/​test_frontend_from_exported_program.py Adds structural and numerical tests, including dynamic shapes.
src/​relax/​op/​tensor/​search.h Declares the C++ operator constructor.
src/​relax/​op/​tensor/​search.cc Registers the operator, attributes, and type inference.
python/​tvm/​relax/​transform/​legalize_ops/​search.py Adds CPU legalization through TOPI.
python/​tvm/​relax/​script/​ir_builder/​op.py Exposes R.searchsorted in Relax scripts.
python/​tvm/​relax/​op/​search.py Adds the public Python wrapper and documentation.
python/​tvm/​relax/​op/​__init__.py Exports the new operator.
python/​tvm/​relax/​frontend/​torch/​fx_translator.py Registers FX conversion.
python/​tvm/​relax/​frontend/​torch/​exported_program_translator.py Registers tensor and scalar overloads.
python/​tvm/​relax/​frontend/​torch/​base_fx_graph_translator.py Translates operands, scalar constants, and search options.
python/​tvm/​relax/​backend/​dispatch_sort_scan.py Selects CPU or GPU TOPI implementations.
include/​tvm/​relax/​op/​search.h Defines output-dtype and insertion-side attributes.

Review effort: Max

Comment thread src/relax/op/tensor/search.cc Resolved
@Netra-Srinivasan-McW

Copy link
Copy Markdown
Author

Hi @mshr-h, @yzhliu, @tqchen, @tlopex,

I have updated the PR to address all the review changes:

  • Rank & Batch Validation: Updated InferTypeSearchSorted in search.cc to reject rank-0 sequences and enforce batch/outer-dimension equality via sym::Analyzer for N>1, preventing TOPI out-of-bounds reads.
  • GPU Dispatch & Tests: Corrected operand ordering (sorted_sequence, values) and explicitly passed target to topi.gpu.searchsorted in dispatch_sort_scan.py to eliminate reliance on ambient target contexts. Added CPU/CUDA structural dispatch and N-D symbolic compilation tests in test_backend_dispatch_sort_scan.py.
  • FX Operand Resolution: Resolved node.kwargs via _retrieve_args() with input/values/self fallback in base_fx_graph_translator.py, validated side ("left"/"right").
  • Scalar Promotion & Regressions: Promoted integer sequences alongside float scalars via relax.op.astype to avoid index truncation; added Python-scalar numerical tests in test_frontend_from_exported_program.py.

Could you please take a look into the changes made when you get a chance? Thanks!

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Missing GPU target forwarding breaks CUDA compilation of relax.bucketize, while scalar-promotion and NaN-handling errors produce results inconsistent with PyTorch.

4 open issues
5 resolved since last review

Review effort: Max

@Netra-Srinivasan-McW

Copy link
Copy Markdown
Author

Hi @mshr-h, @yzhliu, @tqchen, @tlopex,

I have updated the PR to address all the review changes:

  • GPU Bucketize Target Forwarding: Restored conditional target forwarding **({"target": tgt} if self.is_gpu_target(tgt) else {}) in dispatch_sort_scan.py to prevent CUDA compilation failures.
  • PyTorch Default Dtype Promotion: Honored torch.get_default_dtype() instead of hardcoding float32 during scalar promotion in base_fx_graph_translator.py.
  • NaN Query Semantics & Regressions: Corrected TOPI's shared binary_search to match PyTorch/NumPy semantics for NaN queries (mapping to sequence length) and added numerical regression tests covering both right=False and right=True.
  • GPU CI Marker: Added @pytest.mark.gpu and device_enabled(target) check to test_dispatch_searchsorted_cuda_symbolic in test_backend_dispatch_sort_scan.py.

Could you take a look into the changes when you get a chance? Thanks!

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

values = call.args[1]
right = call.attrs.right
out_dtype = "int32" if call.attrs.out_int32 else "int64"
return bb.call_te(topi.searchsorted, sorted_sequence, values, right, out_dtype)
Comment thread src/relax/op/tensor/search.cc Outdated
static_cast<int>(values_shape->values.size()) == sorted_sequence_info->ndim) {
sym::Analyzer analyzer;
for (int i = 0; i + 1 < sorted_sequence_info->ndim; ++i) {
if (analyzer->CanProve(sequence_shape->values[i] != values_shape->values[i])) {


@pytest.mark.parametrize("right", [False, True])
def test_searchsorted_nan_numerical(right):

def _searchsorted(self, node: fx.Node) -> relax.Var:
args = self.retrieve_args(node)
kwargs = self._retrieve_args(node.kwargs)
import torch

dtype = self._convert_data_type(torch.get_default_dtype())
sorted_sequence = self.block_builder.emit(relax.op.astype(sorted_sequence, dtype))

dtype = self._convert_data_type(torch.get_default_dtype())
sorted_sequence = self.block_builder.emit(relax.op.astype(sorted_sequence, dtype))
values = relax.const(values, dtype)
Comment on lines +2138 to +2140
return self.block_builder.emit(
relax.op.searchsorted(sorted_sequence, values, out_int32=out_int32, right=right)
)

Type InferTypeSearchSorted(const CallObj* call_node) {
const Call call = ffi::GetRef<Call>(call_node);
ffi::Array<TensorType> input_ty = GetInputTensorType(call);
Comment thread src/relax/op/tensor/search.cc Outdated
Comment on lines +186 to +190
const auto* data_shape = values_info->shape.as<ShapeExprObj>();
if (data_shape) {
return TensorType(ShapeExpr(data_shape->values), out_dtype, values_info->vdevice);
}
return TensorType(out_dtype, values_info->ndim, values_info->vdevice);
@Netra-Srinivasan-McW

Copy link
Copy Markdown
Author

Hi @mshr-h, @yzhliu, @tqchen, @tlopex,

I have updated the PR to address all the review comments:

  • GPU Legalization: Updated relax.searchsorted legalization to dispatch to topi.gpu.searchsorted for GPU targets.
  • Type Inference & Shape Validation: Added RequiresTensorInputNormalization, preserved values shape with InferBinaryArithOpOutVDevice for target inference, and required provably equal outer dimensions (!CanProveEqual) across inference and GPU lowering with symbolic shape tests.
  • PyTorch Frontend Edge Cases: Rejected non-None out arguments, promoted bool boundaries for integer and primitive scalar queries, materialized primitive scalar queries as rank-zero tensors, and applied PyTorch rank-aware dtype promotion for tensor queries (including 0-D tensors), with regression tests for each case.
  • LLVM Test Guard: Added a has_llvm() skip guard to test_searchsorted_nan_numerical.

Could you take a look into the changes when you get a chance? Thanks!

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] Unsupported function type searchsorted.Tensor

2 participants