Skip to content

[HOP] Implementation of torch.switch (1/N) - #182902

Closed
bohnstingl wants to merge 2 commits into
pytorch:mainfrom
bohnstingl:switch_p1
Closed

bohnstingl wants to merge 2 commits into
pytorch:mainfrom
bohnstingl:switch_p1

Conversation

@bohnstingl

@bohnstingl bohnstingl commented May 7, 2026 •

Copy link
Copy Markdown
Collaborator

This is the first PR of a series of PRs to add the torch.switch functionality, which shares an equivalent API as the JAX implementation under https://docs.jax.dev/en/latest/_autosummary/jax.lax.switch.html.
In this PR, we add the initial skeleton of switch with the dense implementation only, along with various tests. In follow-up PRs, we will add _inductor support, Autograd, gen_schema, etc.

This PR is related to #175891

cc @gujinghui @PenghuiCheng @XiaobingSuper @jianyuh @jgong5 @mingfeima @sanchitintel @ashokei @jingxu10 @min-jean-cho @yanbing-j @Guobing-Chen @Xia-Weiwen @snadampal @voznesenskym @penguinwu @EikanWang @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98 @lakshayg @ydwu4 @ezyang

@pytorch-bot

pytorch-bot Bot commented May 7, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/182902

Note: Links to docs will display an error until the docs builds have been completed.

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

❌ 2 New Failures, 4 Unrelated Failures

As of commit 00d4c57 with merge base c7a18da (image):

NEW FAILURES - The following jobs have failed:

FLAKY - The following job failed but was likely due to flakiness present on trunk:

BROKEN TRUNK - The following jobs failed but was present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels May 7, 2026
@pytorch-bot

pytorch-bot Bot commented May 7, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@pytorch-bot

pytorch-bot Bot commented May 7, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/inductor
  • ciflow/torchtitan

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

@jansel

jansel commented May 8, 2026

Copy link
Copy Markdown
Contributor

@claude explain those CI failures, check if they are related, and review the changes in this PR

@claude

claude Bot commented May 8, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 4m 59s —— View job


CI Failure Analysis & Code Review

  • Analyze CI failures
  • Determine if failures are related
  • Review PR code changes

CI Failure Analysis

All 13 CI failures are directly caused by this PR and fall into 3 categories:

1. test_correct_module_names (9 failures across multiple configs)

Root cause: torch.switch is not in torch.__all__.

The test checks that any symbol importable from torch that looks public (no leading _, has __module__ = "torch") must either be listed in torch.__all__ or be made private. Since @exposed_in("torch") sets switch.__module__ = "torch", the test expects it in __all__.

Fix: Add "switch" to the __all__ list in torch/__init__.py (between "stack" and "sym_float" to maintain sorted order).

Fix this →

2. test_switch_invalid_index (3 failures in dynamo_wrapped configs)

Root cause: The test expects RuntimeError with message "Expected index to be an int or tensor", but under dynamo_wrapped mode (which wraps everything in torch.compile), the dynamo handler raises UncapturedHigherOrderOpError instead, whose message doesn't match the regex.

The test at line 1505-1508 passes [0, 1] (a Python list) as the index. In eager mode, the _validate_input check catches this and raises RuntimeError. But under dynamo wrapping, the code takes the torch.compiler.is_dynamo_compiling() fast path (line 88-89) which calls switch_op(index, branches, operands) directly. Then the dynamo handler's validation catches the list index and raises UncapturedHigherOrderOpError (via unimplemented()), not a plain RuntimeError.

Fix: Either:

  • Mark this test as an expected failure under dynamo_wrapped (like other tests use @torch._dynamo.config.patch), or
  • Change the assertRaisesRegex to also accept UncapturedHigherOrderOpError (which is a RuntimeError subclass — but the message doesn't match the regex "Expected index to be an int or tensor"). The dynamo error message says "Expected index to be an int or a tensor with a single item". The regex needs to match a substring of the actual error, so a broader regex like "Expected index to be" would work.

Fix this →

3. build-docs-python (1 failure — NEW FAILURE)

Root cause: The docs coverage check found torch.switch as an undocumented public function. The build fails because the undocumented count went from 0 to 1:

torch
-----
Functions:
 * switch

Fix: Either add documentation for torch.switch (create a docs/source/higher_order_ops/switch.md similar to cond.md and while_loop.md), or add "switch" to coverage_ignore_functions in docs/source/conf.py if documentation is planned for a follow-up PR.

Fix this →

Are the failures related?

Yes — all failures stem from the same root cause: torch.switch is exposed as a public API (via @exposed_in("torch") and the import in torch/__init__.py) but the necessary infrastructure for a public API wasn't fully wired up (__all__, docs coverage, and robust error handling under dynamo_wrapped).


Code Review

Overall Assessment

This is a well-structured first PR for the torch.switch HOP. The implementation follows the existing patterns (cond, while_loop) closely, the eager/compiled paths are clearly separated, and the test coverage is thorough. A few issues beyond the CI failures:

Issues

1. Validation ordering in eager path (switch.py:88-135)

When torch.compiler.is_dynamo_compiling() is true (line 88), the function calls switch_op(index, branches, operands) without any validation. The _validate_input function at line 105 is only called for the tensor-index eager path. This means invalid inputs under torch.compile will hit the dynamo handler's validation, which raises UncapturedHigherOrderOpError instead of a user-friendly RuntimeError. This is the root cause of the test_switch_invalid_index failure in dynamo_wrapped.

2. graph_break_registry.json — 132 lines added

The additions to graph_break_registry.json look auto-generated and correct for the graph break types defined in SwitchHigherOrderVariable.

3. _merge_switch_graph_inputs function (higher_order_ops.py:2810-2872)

This function is well-implemented but has a subtle correctness concern: it sorts canonical_order by p.node.name (line 2848). If two branches capture different sets of free variables, the deterministic ordering is important. The approach is sound but worth noting that the placeholder names must be unique across the graph to avoid collisions.

4. switch_op_dense operand check (switch.py:199)

if not all(isinstance(o, (torch.Tensor, int)) for o in operands):

This only checks for torch.Tensor and int, but the _validate_input function (line 127-133) and the docstring mention "possibly nested dict/list/tuple" of tensors. The dense implementation doesn't support nested pytrees as operands, which is inconsistent with the stated API.

5. Autograd impl is a pass-through (switch.py:212-215)

@switch_op.py_autograd_impl
def switch_autograd(index, branches, operands):
    with torch._C._AutoDispatchBelowAutograd():
        return switch_op(index, branches, operands)

This just dispatches below autograd without recording anything for backward. The PR description says autograd is coming in a follow-up, which is fine, but this means torch.switch will silently produce wrong gradients if any branch involves differentiable ops. Consider adding a warning or raising an error if any input requires grad, or at minimum note this limitation in the docstring.

6. Minor: SwitchOpArgsMismatchError (exc.py:263)

This exception is defined but only used in trace_switch (the proxy tracing path). It's fine as-is.

Style / Nits

  • The docstring for switch (lines 48-75) is good and follows PyTorch conventions.
  • The _switch_op_wrapper pattern (line 142) mirrors how cond does it — fine.
  • Test coverage is comprehensive (basic, zero-args, multiple-args, invalid inputs, GPU, functionalization, etc.).

Summary

The implementation is solid and follows existing HOP patterns well. The three CI failures are all fixable with small changes:

  1. Add "switch" to torch.__all__
  2. Fix the test regex for test_switch_invalid_index or skip under dynamo_wrapped
  3. Add docs or suppress the docs coverage check

@bohnstingl

Copy link
Copy Markdown
Collaborator Author

@jansel thank you very much for triggering the claude review! This was really helpful.
I integrated the review findings and also added an initial version of a documentation, see https://github.com/bohnstingl/pytorch/blob/switch_p1/docs/source/higher_order_ops/switch.md.

I'd have one question related to the torch.compile handling. There is currently a bit of an inconsistency between the HOPs in the way how they handle the compilation path. For example, cond and while_loop use

if torch.compiler.is_dynamo_compiling():
        return cond_op(pred, true_fn, false_fn, operands)

...

_hop_compile_and_call(_cond_op_wrapper, (pred, true_fn, false_fn, operands))

while the more recent ones such as map, scan and associative_scan use

_maybe_compile_and_run_fn

I revised switch to also use _maybe_compile_and_run_fn, is this okay with you and shall the others be reworked, or would you prefer any other approach?

Also, could you please add @galv as a reviewer as well?

@jansel
jansel requested a review from galv May 9, 2026 16:07
@jansel

jansel commented May 9, 2026

Copy link
Copy Markdown
Contributor

@zou3519 should be able to answer that HOP question

@jansel

jansel commented May 9, 2026

Copy link
Copy Markdown
Contributor

@claude explain those CI failures, are they related?

@claude

claude Bot commented May 9, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 1m 40s —— View job


CI Failure Analysis

  • Investigate CI failures
  • Determine if failures are related
  • Provide summary

All 5 failures share the same root cause — they are unrelated to this PR's code changes.

Every failed job is a get-label-type / runner-determinator step, and they all fail at the same point with this error:

Get dynamic rollout settings: error: unrecognized arguments: --workflow-name Lint

(The workflow name varies — Lint, inductor, pull — but the error is identical.)

Root Cause: CI workflow / branch skew

The CI workflow YAML (which runs from main) was recently updated to pass a new --workflow-name flag to .github/scripts/runner_determinator.py. However, the runner_determinator.py on this branch doesn't have that argument defined (it was added to main after this branch diverged).

The workflow YAML invokes:

python3 .github/scripts/runner_determinator.py \
  ...
  --workflow-name "${WORKFLOW_NAME}"

But the branch's runner_determinator.py only accepts arguments up to --pr-number — it doesn't recognize --workflow-name, so argparse exits with code 2.

Fix

Rebase or merge from main to pick up the latest runner_determinator.py that includes the --workflow-name argument. No code changes to this PR's actual feature are needed.

Summary

Failure Job Same root cause?
inductor / get-label-type / runner-determinator --workflow-name inductor Yes
inductor / unit-test / get-label-type / runner-determinator --workflow-name inductor Yes
Lint / get-label-type / runner-determinator --workflow-name Lint Yes
pull / before-test / get-label-type / runner-determinator --workflow-name pull Yes
pull / get-label-type / runner-determinator --workflow-name pull Yes

All 5 failures are the same infrastructure issue (CI workflow/branch skew) and are not related to the torch.switch implementation in this PR. A rebase onto current main will resolve them.


View job

@jansel

jansel commented May 9, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Successfully rebased switch_p1 onto refs/remotes/origin/viable/strict, please pull locally before adding more changes (for example, via git checkout switch_p1 && git pull --rebase)

@bohnstingl

Copy link
Copy Markdown
Collaborator Author

@jansel bad merge?

@jansel

jansel commented May 10, 2026

Copy link
Copy Markdown
Contributor

@bohnstingl yeah I think you raced with the bot, please update it again

@liangel-02 liangel-02 added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label May 11, 2026
@bohnstingl

Copy link
Copy Markdown
Collaborator Author

@jansel I merged in the latest main. Could you please take another look?

@ezyang
ezyang self-requested a review May 14, 2026 04:15
Comment thread torch/_higher_order_ops/switch.py Resolved
Comment thread torch/_higher_order_ops/switch.py Resolved
Comment thread test/functorch/test_control_flow.py Resolved
@bohnstingl

Copy link
Copy Markdown
Collaborator Author

@jansel I pulled in the latest main and the tests again seem to be unrelated failures. Is there a chance that this gets merged without all the tests passing?

@bohnstingl
bohnstingl requested a review from jansel June 22, 2026 09:21
@zou3519

zou3519 commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

@claude review these changes

@claude

claude Bot commented Jun 23, 2026 •

Copy link
Copy Markdown

Claude finished @zou3519's task in 12m 54s —— View job


Code Review: torch.switch (1/N)

I read through switch.py, the dynamo handler (higher_order_ops.py), _merge_graph_inputs, the registry, and the test suite. This PR is in good shape — the major blockers raised earlier in review (registry corruption, the N-branch int-leaf merge crash, the requires_grad/docstring contradiction) have all been addressed, and test coverage is excellent. Below are the remaining observations, none of which I consider blocking for a 1/N skeleton PR.

Confirmed-resolved (from prior review threads)

  • Registry: GB0312/GB0340 are restored to their torch.cond entries; the switch gb_types now own dedicated IDs. The phantom GB2796 and folded-in cond duplicates are gone. ✅
  • N-branch int merge: _merge_output (switch.py:252-275) now handles the all-None and all-int cases N-ary (single unbacked symint over min/max), with a regression test at test_switch_three_branches_divergent_int_leaves. ✅
  • Docstring vs. autograd: the docstring (switch.py:79-82) now correctly states autograd is a no-op redispatch, matching switch_autograd. ✅

Observations / nits (non-blocking)

1. Eager vs. compiled operand-type divergence is real but matches cond. _validate_input (switch.py:112-114) rejects any non-Tensor operand leaf in eager, while switch_op_dense (switch.py:201) and the dynamo gate accept ints/SymInts. So switch(idx, branches, (x, 5)) raises in eager but is accepted under compile. As you noted, this exactly mirrors cond (lifted int/SymInt args), so keeping it consistent is the right call — just flagging it remains a latent footgun shared with cond.

2. Known mixed int/SymInt merge gap. _merge_output handles all int and all None, but a branch set mixing concrete int and SymInt leaves still falls through to cond._merge_output and will assert. You've already agreed to track this for the cond/switch follow-up — noting it here for completeness. Same applies to the bool-leaf case aorenste flagged at switch.py:262.

3. trace_switch non-tensor closure leak (minor). trace_switch (switch.py:166) calls reenter_make_fx(branch)(*operands) directly on the user branches. The dynamo path lifts closed-over tensors into the operand signature, but a raw make_fx-only path (no dynamo) relies on reenter_make_fx to lift them. The test_switch_with_tensor_closure test confirms this works for the make_fx(foo) path, so this is fine — just worth keeping the test as a guard since the lifting is implicit.

4. Docstring operand type. The docstring (switch.py:72-73) says operands are "possibly nested dict/list/tuple of torch.Tensor", and the entry point now tree_flattens them — consistent with the dynamo flattening. Good. One small thing: the Restrictions block (switch.py:75-82) still implies branches must return "the same output structure (shape, dtype, etc.)" but the implementation also permits constant int/None leaves and clamps/merges divergent ints. Consider a one-line note that constant int/None leaves are allowed, to match validate_subgraph_output_types behavior. Low priority.

5. switch_op_dense mode assertion. switch.py:205-207 raises AssertionError("Mode should never be enabled for CPU/CUDA key"). This matches the cond pattern, fine. The int(index.item()) if ... else int(index) cleanup (switch.py:208) from the earlier review is applied. ✅

Tests

Coverage is comprehensive: basic/zero/multi-arg, invalid index, empty/single branch, output-shape divergence, GPU, functionalization + input-mutation rejection, tensor closures, None/int/float leaves, mismatched arity/structure, constant-index specialization, nn.Module branches, heterogeneous lifted args, pytree operands, and graph-shape golden checks. This is well beyond what I'd expect for a skeleton PR.

Summary

The implementation faithfully generalizes cond to N branches, reuses cond's merge/stride machinery rather than duplicating it, and the API intentionally matches jax.lax.switch semantics (clamping, same-output-structure). The deferred pieces (autograd, vmap, gen_schema, inductor lowering) are clearly scoped to follow-up PRs and the autograd stub's limitation is documented. The remaining items above are nits or already-tracked follow-ups — nothing I'd block on. With jansel's and ydwu4's approvals already in, this looks ready pending the recurring (unrelated) torchtitan/inductor CI flakes clearing.

@jansel

jansel commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Rebase failed due to Command git -C /home/runner/work/pytorch/pytorch rebase refs/remotes/origin/viable/strict pull/182902/head returned non-zero exit code 1

Rebasing (1/27)
Rebasing (2/27)
Rebasing (3/27)
Rebasing (4/27)
Rebasing (5/27)
Rebasing (6/27)
Rebasing (7/27)
Auto-merging docs/source/torch.md
CONFLICT (content): Merge conflict in docs/source/torch.md
error: could not apply 8011f67343a... Added switch documentation to index
hint: Resolve all conflicts manually, mark them as resolved with
hint: "git add/rm <conflicted_files>", then run "git rebase --continue".
hint: You can instead skip this commit: run "git rebase --skip".
hint: To abort and get back to the state before "git rebase", run "git rebase --abort".
hint: Disable this message with "git config set advice.mergeConflict false"
Could not apply 8011f67343a... # Added switch documentation to index

Raised by https://github.com/pytorch/pytorch/actions/runs/28014068819

@bohnstingl

Copy link
Copy Markdown
Collaborator Author

@jansel I rebased onto refs/remotes/origin/viable/strict and force-pushed, but the CI failures still remain. How an we proceed here?

@aorenste

Copy link
Copy Markdown
Contributor

DrCI says it's clean so this should work:
@pytorchbot merge

If not then we can do it with "-i" to ignore the unrelated errors.

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Jun 23, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: trunk / linux-jammy-cuda13.0-py3.10-gcc11 / test-osdc (default, 4, 5, mt-l-x86aavx2-29-113-l4)

Details for Dev Infra team Raised by workflow job

@bohnstingl

bohnstingl commented Jun 23, 2026 •

Copy link
Copy Markdown
Collaborator Author

@aorenste I added a test skip statement for switch, similar to scan, while_loop and other HOPs. However, the number of CI fails seems to got worse... The fails though seem to be unrelated? Can you take a look again?

@ydwu4

ydwu4 commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot merge -i

gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
This is the first PR of a series of PRs to add the `torch.switch` functionality, which shares an equivalent API as the JAX implementation under https://docs.jax.dev/en/latest/_autosummary/jax.lax.switch.html.
In this PR, we add the initial skeleton of switch with the dense implementation only, along with various tests. In follow-up PRs, we will add _inductor support, Autograd, gen_schema, etc.

This PR is related to pytorch#175891

Pull Request resolved: pytorch#182902
Approved by: https://github.com/aorenste, https://github.com/ydwu4
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
This is the first PR of a series of PRs to add the `torch.switch` functionality, which shares an equivalent API as the JAX implementation under https://docs.jax.dev/en/latest/_autosummary/jax.lax.switch.html.
In this PR, we add the initial skeleton of switch with the dense implementation only, along with various tests. In follow-up PRs, we will add _inductor support, Autograd, gen_schema, etc.

This PR is related to pytorch#175891

Pull Request resolved: pytorch#182902
Approved by: https://github.com/aorenste, https://github.com/ydwu4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: dynamo module: mkldnn Related to Intel IDEEP or oneDNN (a.k.a. mkldnn) integration open source release notes: dynamo triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[RFC] torch.switch

10 participants