Skip to content

[Relax][PyTorch] Add torch.cond support to ExportedProgram frontend#18904

Draft
mshr-h wants to merge 2 commits intoapache:mainfrom
mshr-h:torch-cond
Draft

[Relax][PyTorch] Add torch.cond support to ExportedProgram frontend#18904
mshr-h wants to merge 2 commits intoapache:mainfrom
mshr-h:torch-cond

Conversation

@mshr-h
Copy link
Contributor

@mshr-h mshr-h commented Mar 14, 2026

Add support for importing torch.ops.higher_order.cond from PyTorch ExportedProgram into Relax IR. This enables torch.cond-based conditional logic to be represented as relax.If with branch functions.

Key changes:

  • Add 'cond' entry to ExportedProgramImporter.convert_map
  • Add _has_cond_op() to detect cond in FX graphs
  • Add _import_branch_subgraph() to translate branch GraphModules into separate Relax functions with fresh symbolic vars
  • Add _cond() converter that emits relax.If
  • Skip DataflowBlock when graph contains cond (use BindingBlock)
  • Add gt/lt to symbolic comparison operators
  • Add 4 tests with structural equality: basic, shape predicate, tuple output, nested cond

Add support for importing torch.ops.higher_order.cond from PyTorch
ExportedProgram into Relax IR. This enables torch.cond-based conditional
logic to be represented as relax.If with branch functions.

Key changes:
- Add 'cond' entry to ExportedProgramImporter.convert_map
- Add _has_cond_op() to detect cond in FX graphs
- Add _import_branch_subgraph() to translate branch GraphModules
  into separate Relax functions with fresh symbolic vars
- Add _cond() converter that emits relax.If
- Skip DataflowBlock when graph contains cond (use BindingBlock)
- Add gt/lt to symbolic comparison operators
- Add 4 tests with structural equality: basic, shape predicate,
  tuple output, nested cond

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the PyTorch ExportedProgram frontend for Relax by introducing comprehensive support for torch.cond. This enables the seamless translation of conditional control flow from PyTorch FX graphs into Relax's relax.If construct, allowing for more complex and dynamic model structures to be compiled. The changes involve new conversion logic, careful handling of branch subgraphs as distinct Relax functions, and adaptive block building based on the presence of conditional operations, thereby expanding the range of PyTorch models that can be effectively imported and optimized by Relax.

Highlights

  • Torch.cond Support: Added an entry for 'cond' to the ExportedProgramImporter's conversion map.
  • Conditional Operation Detection: Implemented a static method _has_cond_op() to detect the presence of torch.ops.higher_order.cond in FX graphs.
  • Branch Subgraph Translation: Introduced _import_branch_subgraph() to translate GraphModule branches into separate Relax functions, ensuring fresh symbolic variables for parameters.
  • Relax.If Conversion: Developed the _cond() converter to emit relax.If expressions from torch.ops.higher_order.cond nodes.
  • DataflowBlock Handling: Modified the translation process to skip DataflowBlock and use BindingBlock when the graph contains torch.cond, as relax.If cannot appear within a dataflow region.
  • Symbolic Comparison Operators: Added gt (greater than) and lt (less than) to the symbolic comparison operators.
  • New Test Cases: Included four new tests to verify structural equality for basic, shape predicate, tuple output, and nested torch.cond scenarios.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • python/tvm/relax/frontend/torch/exported_program_translator.py
    • Imported contextlib for managing block builder contexts.
    • Implemented _has_cond_op to detect torch.ops.higher_order.cond in FX graphs.
    • Added _translate_fx_graph to encapsulate FX graph translation logic, which is now reused for main and branch graphs.
    • Introduced _import_branch_subgraph to convert GraphModule branches into distinct Relax functions, managing parameter struct info and symbolic variables.
    • Developed _cond converter to transform torch.ops.higher_order.cond nodes into relax.If expressions, handling both static and dynamic predicates.
    • Extended create_convert_map to register cond, gt, and lt operations.
    • Modified from_exported_program to dynamically choose between DataflowBlock and BindingBlock based on the presence of torch.cond to accommodate relax.If constraints.
  • tests/python/relax/test_frontend_from_exported_program.py
    • Added test_cond_basic to verify basic torch.cond functionality with runtime predicates.
    • Included test_cond_shape_predicate to test torch.cond with shape-derived predicates and dynamic shapes.
    • Added test_cond_tuple_output to ensure correct handling of torch.cond when branches return tuples.
    • Introduced test_cond_nested to validate the translation of nested torch.cond structures.
Activity
  • No human activity has occurred on this pull request yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request adds valuable support for torch.cond to the ExportedProgram frontend, enabling the translation of conditional logic into relax.If expressions. The implementation is well-structured, correctly handling branch subgraphs as separate Relax functions and disabling dataflow blocks when necessary. The new tests are comprehensive, covering basic usage, dynamic shapes, tuple outputs, and nested conditionals. I have a couple of suggestions to enhance robustness and code clarity.

Comment on lines +1289 to +1292
if not hasattr(self, "_branch_cache"):
self._branch_cache: dict[int, tvm.ir.GlobalVar] = {}
if not hasattr(self, "_branch_counter"):
self._branch_counter: int = 0
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

These attributes (_branch_cache and _branch_counter) are specific to cond handling and are being lazily initialized here. It would be cleaner to initialize them in the __init__ method of the ExportedProgramImporter class. This would make the state of the importer more explicit and is a more conventional way to handle instance attributes.

@mshr-h
Copy link
Contributor Author

mshr-h commented Mar 14, 2026

E2E example on LLVM target:

torch_cond_example.py
"""End-to-end example: torch.cond → TVM Relax import → build → run."""

import numpy as np
import torch
from torch.export import export

import tvm
import tvm.testing
from tvm import relax
from tvm.relax.frontend.torch import from_exported_program


class CondBasic(torch.nn.Module):
    def forward(self, x):
        def true_fn(x):
            return x.cos()

        def false_fn(x):
            return x.sin()

        return torch.cond(x.sum() > 0, true_fn, false_fn, (x,))


class CondTuple(torch.nn.Module):
    def forward(self, x):
        def true_fn(x):
            return x + 1.0, x * 2.0

        def false_fn(x):
            return x - 1.0, x * 3.0

        return torch.cond(x.sum() > 0, true_fn, false_fn, (x,))


class CondNested(torch.nn.Module):
    def forward(self, x):
        def outer_true(x):
            def inner_true(x):
                return x + 10.0

            def inner_false(x):
                return x + 20.0

            return torch.cond(x[0] > 0, inner_true, inner_false, (x,))

        def outer_false(x):
            return x - 1.0

        return torch.cond(x.sum() > 0, outer_true, outer_false, (x,))


# ---------------------------------------------------------------------------
# Helper: export → import → build → run, then compare with PyTorch
# ---------------------------------------------------------------------------
def run_and_compare(model, example_args, *, name, rtol=1e-5, atol=1e-5):
    model.eval()
    print(f"\n{'=' * 60}")
    print(f"  {name}")
    print(f"{'=' * 60}")

    # --- PyTorch reference ---
    with torch.no_grad():
        pt_out = model(*example_args)

    # --- Export → Relax ---
    ep = export(model, args=example_args)
    mod = from_exported_program(ep)

    # --- Build & run ---
    target = tvm.target.Target("llvm")
    ex = relax.build(mod, target)
    vm = relax.VirtualMachine(ex, tvm.cpu())
    tvm_args = [tvm.runtime.tensor(a.numpy()) for a in example_args]
    tvm_out = vm["main"](*tvm_args)

    # --- Compare ---
    def to_numpy(v):
        if isinstance(v, torch.Tensor):
            return v.numpy()
        return v

    if isinstance(pt_out, tuple):
        for i, (p, t) in enumerate(zip(pt_out, tvm_out)):
            tvm.testing.assert_allclose(to_numpy(p), t.numpy(), rtol=rtol, atol=atol)
            print(f"  output[{i}] ✓  (max diff: {np.max(np.abs(to_numpy(p) - t.numpy())):.2e})")
    else:
        pt_np = to_numpy(pt_out)
        tvm_np = tvm_out.numpy() if hasattr(tvm_out, "numpy") else tvm_out[0].numpy()
        tvm.testing.assert_allclose(pt_np, tvm_np, rtol=rtol, atol=atol)
        print(f"  output ✓  (max diff: {np.max(np.abs(pt_np - tvm_np)):.2e})")


if __name__ == "__main__":
    # positive sum  → true branch (cos)
    run_and_compare(CondBasic(), (torch.tensor([1.0, 2.0, 3.0]),), name="cond_basic (positive)")
    # negative sum  → false branch (sin)
    run_and_compare(CondBasic(), (torch.tensor([-1.0, -2.0, -3.0]),), name="cond_basic (negative)")

    run_and_compare(CondTuple(), (torch.tensor([1.0, 2.0]),), name="cond_tuple")

    run_and_compare(CondNested(), (torch.tensor([1.0, 2.0, 3.0]),), name="cond_nested")

    print(f"\n{'=' * 60}")
    print("  All torch.cond e2e tests passed!")
    print(f"{'=' * 60}")

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.

1 participant