[Relax][PyTorch] Add torch.cond support to ExportedProgram frontend#18904
[Relax][PyTorch] Add torch.cond support to ExportedProgram frontend#18904mshr-h wants to merge 2 commits intoapache:mainfrom
Conversation
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>
Summary of ChangesHello, 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 Highlights
🧠 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
Activity
Using Gemini Code AssistThe 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
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 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
|
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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.
|
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}") |
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: