Skip to content

[inductor] AOTI cpp wrapper: support invoke_subgraph (#194703) - #194703

Closed
zoranzhao wants to merge 1 commit into
pytorch:mainfrom
zoranzhao:export-D115659603
Closed

zoranzhao wants to merge 1 commit into
pytorch:mainfrom
zoranzhao:export-D115659603

Conversation

@zoranzhao

@zoranzhao zoranzhao commented Aug 25, 2026 •

Copy link
Copy Markdown
Member

Summary:

CppWrapperCpu.codegen_invoke_subgraph was a bare raise NotImplementedError, so any
torch.compiler.nested_compile_region under AOTInductor died at codegen:

torch._inductor.exc.InductorError: NotImplementedError:
    codegen invoke_subgraph is not implemented for cpp wrapper
  cpp_wrapper_cpu.py:2813

Two parts.

1. Implement CppWrapperCpu.codegen_invoke_subgraph. The class already has a complete
subgraph-inlining implementation, codegen_subgraph, used by cond/switch/while_loop;
invoke_subgraph was the only HOP left raising. Declare one owning RAIIAtenTensorHandle
per output -- the same shape as codegen_switch, because in ABI-compatible mode
ir.MultiOutput is not codegened -- and delegate. A non-tensor region output raises
explicitly rather than emitting C++ that will not compile.

The region body is emitted inside its own C++ block. The region has its own Scheduler,
which re-emits per-device state -- notably <stream_t> stream0; from
write_get_raw_stream -- and in the parent's scope that is a redefinition
(error: redefinition of 'stream0'). The outputs are declared outside the block so
codegen_subgraph_suffix can still assign into them, and _preserve_device_guard_state
keeps the region's device-guard bookkeeping from leaking out.

2. Fix a cross-graph index bug in wrapper-IR memory planning that (1) exposes.
AllocateLine/FreeIfNotReusedLine record
scheduler_node_index = V.graph.scheduler.nodes.index(...), but an inlined subgraph emits
its lines into the parent's line list while V.graph is the subgraph. Pairing a parent
free with a region allocation then compares indices into two different node lists:

ValueError: Start index must be less than or equal to end index
  segmented_tree.py:234, via should_reuse_buffer -> peak_between

Record the scheduler alongside the index and refuse reuse across schedulers. This is a
latent pre-existing bug for cond/while_loop too -- inlining is what makes it reachable --
but it is only reproducible once (1) lands.

Per-region Inductor config under the cpp wrapper is the next diff in the stack.

Note: caffe2/... and xplat/caffe2/... are separate synced copies; both are edited.

Test Plan:
test_lite_regional_compile_invoke_subgraph was skipped under config.cpp_wrapper with
the very message this diff deletes; the skip is removed.

New test_invoke_subgraph_nested_region in test_aot_inductor.py -- a full AOTI round trip
through check_model: compile, package, dlopen, run and compare against eager. That is
what a generated-C++ assertion cannot cover.

buck2 test @//mode/opt fbcode//caffe2/test/inductor:test_aot_inductor \
  -- --regex "invoke_subgraph"
=> Pass 4. Fail 0. Skip 1.

buck2 test @//mode/opt-amd-gpu fbcode//caffe2/test/inductor:test_inductor \
  -- --regex "regional|lite_"
=> Pass 8. Fail 0. Skip 3.

cpp wrapper coverage for the other subgraph HOPs. test_control_flow.py had none: every
case ran only under the default python wrapper, even though cond/while_loop/scan/map/switch
all reach CppWrapperCpu.codegen_subgraph and part (2) above touches every inlined
subgraph. This diff adds a _CppWrapperMixin that re-runs a suite with
config.cpp_wrapper=True, and turns it on for the four suites that pass:
CondTestsCppWrapper, AssociativeScanTestsCppWrapper, MapTestsCppWrapper,
SwitchTestsCppWrapper.

buck2 test @//mode/opt fbcode//caffe2/test/inductor:control_flow -- --regex "CppWrapper"
=> Pass 122. Fail 0. Skip 6.

buck2 test @//mode/opt fbcode//caffe2/test/inductor:control_flow
=> Pass 799. Fail 0. Skip 104.

(799 = the suite's previous 677 plus these 122; no existing case changed.)

Not everything could be turned on, and the reasons are pre-existing rather than caused by
this diff. Measured under TORCHINDUCTOR_CPP_WRAPPER=1 on the parent commit and again on
this one -- identical both times, Pass 341 / Fail 337:

  • ScanTests (264 cases) and WhileLoopTests (69) still fail. Pinning that many names
    would rot on the next parametrization, so those two suites are left off with the
    reasons recorded in the file.
  • CondTests needed only four exclusions, listed in _CPP_WRAPPER_XFAIL
    (test_cond_unbacked_symint_inner*).
    Two distinct causes, each worth its own diff:
  • error: redefinition of 'true_graph_0_bufN' -- a branch subgraph declares its buffers
    in the parent's C++ scope, so two branches reusing a name collide. Same class of bug as
    the region stream0 collision fixed above, but for buffers rather than per-device
    state.
  • NotImplementedError: NYI cpp wrapper for while_loop_stack_output.

Authored with an AI assistant.

Reviewed By: desertfire

Differential Revision: D115659603

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo

@pytorch-bot

pytorch-bot Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (1 Unrelated Failure)

As of commit 2558ce6 with merge base 3196064 (image):

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

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

@meta-codesync

meta-codesync Bot commented Aug 25, 2026

Copy link
Copy Markdown

@zoranzhao has exported this pull request. If you are a Meta employee, you can view the originating Diff in D115659603.

@meta-codesync meta-codesync Bot changed the title [inductor] AOTI cpp wrapper: support invoke_subgraph [inductor] AOTI cpp wrapper: support invoke_subgraph (#194703) Aug 28, 2026
zoranzhao added a commit to zoranzhao/pytorch that referenced this pull request Aug 28, 2026
Summary:

`CppWrapperCpu.codegen_invoke_subgraph` was a bare `raise NotImplementedError`, so any
`torch.compiler.nested_compile_region` under AOTInductor died at codegen:

```
torch._inductor.exc.InductorError: NotImplementedError:
    codegen invoke_subgraph is not implemented for cpp wrapper
  cpp_wrapper_cpu.py:2813
```

Two parts.

**1. Implement `CppWrapperCpu.codegen_invoke_subgraph`.** The class already has a complete
subgraph-inlining implementation, `codegen_subgraph`, used by cond/switch/while_loop;
invoke_subgraph was the only HOP left raising. Declare one owning `RAIIAtenTensorHandle`
per output -- the same shape as `codegen_switch`, because in ABI-compatible mode
`ir.MultiOutput` is not codegened -- and delegate. A non-tensor region output raises
explicitly rather than emitting C++ that will not compile.

The region body is emitted inside its own C++ block. The region has its own `Scheduler`,
which re-emits per-device state -- notably `<stream_t> stream0;` from
`write_get_raw_stream` -- and in the parent's scope that is a redefinition
(`error: redefinition of 'stream0'`). The outputs are declared *outside* the block so
`codegen_subgraph_suffix` can still assign into them, and `_preserve_device_guard_state`
keeps the region's device-guard bookkeeping from leaking out.

**2. Fix a cross-graph index bug in wrapper-IR memory planning** that (1) exposes.
`AllocateLine`/`FreeIfNotReusedLine` record
`scheduler_node_index = V.graph.scheduler.nodes.index(...)`, but an inlined subgraph emits
its lines into the *parent's* line list while `V.graph` is the *subgraph*. Pairing a parent
free with a region allocation then compares indices into two different node lists:

```
ValueError: Start index must be less than or equal to end index
  segmented_tree.py:234, via should_reuse_buffer -> peak_between
```

Record the scheduler alongside the index and refuse reuse across schedulers. This is a
latent pre-existing bug for cond/while_loop too -- inlining is what makes it reachable --
but it is only reproducible once (1) lands.

Per-region Inductor config under the cpp wrapper is the next diff in the stack.

Note: `caffe2/...` and `xplat/caffe2/...` are separate synced copies; both are edited.

Test Plan:
`test_lite_regional_compile_invoke_subgraph` was skipped under `config.cpp_wrapper` with
the very message this diff deletes; the skip is removed.

New `test_invoke_subgraph_nested_region` in test_aot_inductor.py -- a full AOTI round trip
through `check_model`: compile, package, dlopen, run and compare against eager. That is
what a generated-C++ assertion cannot cover.

```
buck2 test @//mode/opt fbcode//caffe2/test/inductor:test_aot_inductor \
  -- --regex "invoke_subgraph"
=> Pass 4. Fail 0. Skip 1.

buck2 test @//mode/opt-amd-gpu fbcode//caffe2/test/inductor:test_inductor \
  -- --regex "regional|lite_"
=> Pass 8. Fail 0. Skip 3.
```

**cpp wrapper coverage for the other subgraph HOPs.** `test_control_flow.py` had none: every
case ran only under the default python wrapper, even though cond/while_loop/scan/map/switch
all reach `CppWrapperCpu.codegen_subgraph` and part (2) above touches every inlined
subgraph. This diff adds a `_CppWrapperMixin` that re-runs a suite with
`config.cpp_wrapper=True`, and turns it on for the four suites that pass:
`CondTestsCppWrapper`, `AssociativeScanTestsCppWrapper`, `MapTestsCppWrapper`,
`SwitchTestsCppWrapper`.

```
buck2 test @//mode/opt fbcode//caffe2/test/inductor:control_flow -- --regex "CppWrapper"
=> Pass 122. Fail 0. Skip 6.

buck2 test @//mode/opt fbcode//caffe2/test/inductor:control_flow
=> Pass 799. Fail 0. Skip 104.
```
(799 = the suite's previous 677 plus these 122; no existing case changed.)

Not everything could be turned on, and the reasons are pre-existing rather than caused by
this diff. Measured under `TORCHINDUCTOR_CPP_WRAPPER=1` on the parent commit and again on
this one -- identical both times, Pass 341 / Fail 337:
  - `ScanTests` (264 cases) and `WhileLoopTests` (69) still fail. Pinning that many names
    would rot on the next parametrization, so those two suites are left off with the
    reasons recorded in the file.
  - `CondTests` needed only four exclusions, listed in `_CPP_WRAPPER_XFAIL`
    (`test_cond_unbacked_symint_inner*`).
Two distinct causes, each worth its own diff:
  - `error: redefinition of 'true_graph_0_bufN'` -- a branch subgraph declares its buffers
    in the parent's C++ scope, so two branches reusing a name collide. Same class of bug as
    the region `stream0` collision fixed above, but for buffers rather than per-device
    state.
  - `NotImplementedError: NYI cpp wrapper for while_loop_stack_output`.

Authored with an AI assistant.

Differential Revision: D115659603
zoranzhao added a commit to zoranzhao/pytorch that referenced this pull request Aug 28, 2026
Summary:

`CppWrapperCpu.codegen_invoke_subgraph` was a bare `raise NotImplementedError`, so any
`torch.compiler.nested_compile_region` under AOTInductor died at codegen:

```
torch._inductor.exc.InductorError: NotImplementedError:
    codegen invoke_subgraph is not implemented for cpp wrapper
  cpp_wrapper_cpu.py:2813
```

Two parts.

**1. Implement `CppWrapperCpu.codegen_invoke_subgraph`.** The class already has a complete
subgraph-inlining implementation, `codegen_subgraph`, used by cond/switch/while_loop;
invoke_subgraph was the only HOP left raising. Declare one owning `RAIIAtenTensorHandle`
per output -- the same shape as `codegen_switch`, because in ABI-compatible mode
`ir.MultiOutput` is not codegened -- and delegate. A non-tensor region output raises
explicitly rather than emitting C++ that will not compile.

The region body is emitted inside its own C++ block. The region has its own `Scheduler`,
which re-emits per-device state -- notably `<stream_t> stream0;` from
`write_get_raw_stream` -- and in the parent's scope that is a redefinition
(`error: redefinition of 'stream0'`). The outputs are declared *outside* the block so
`codegen_subgraph_suffix` can still assign into them, and `_preserve_device_guard_state`
keeps the region's device-guard bookkeeping from leaking out.

**2. Fix a cross-graph index bug in wrapper-IR memory planning** that (1) exposes.
`AllocateLine`/`FreeIfNotReusedLine` record
`scheduler_node_index = V.graph.scheduler.nodes.index(...)`, but an inlined subgraph emits
its lines into the *parent's* line list while `V.graph` is the *subgraph*. Pairing a parent
free with a region allocation then compares indices into two different node lists:

```
ValueError: Start index must be less than or equal to end index
  segmented_tree.py:234, via should_reuse_buffer -> peak_between
```

Record the scheduler alongside the index and refuse reuse across schedulers. This is a
latent pre-existing bug for cond/while_loop too -- inlining is what makes it reachable --
but it is only reproducible once (1) lands.

Per-region Inductor config under the cpp wrapper is the next diff in the stack.

Note: `caffe2/...` and `xplat/caffe2/...` are separate synced copies; both are edited.

Test Plan:
`test_lite_regional_compile_invoke_subgraph` was skipped under `config.cpp_wrapper` with
the very message this diff deletes; the skip is removed.

New `test_invoke_subgraph_nested_region` in test_aot_inductor.py -- a full AOTI round trip
through `check_model`: compile, package, dlopen, run and compare against eager. That is
what a generated-C++ assertion cannot cover.

```
buck2 test @//mode/opt fbcode//caffe2/test/inductor:test_aot_inductor \
  -- --regex "invoke_subgraph"
=> Pass 4. Fail 0. Skip 1.

buck2 test @//mode/opt-amd-gpu fbcode//caffe2/test/inductor:test_inductor \
  -- --regex "regional|lite_"
=> Pass 8. Fail 0. Skip 3.
```

**cpp wrapper coverage for the other subgraph HOPs.** `test_control_flow.py` had none: every
case ran only under the default python wrapper, even though cond/while_loop/scan/map/switch
all reach `CppWrapperCpu.codegen_subgraph` and part (2) above touches every inlined
subgraph. This diff adds a `_CppWrapperMixin` that re-runs a suite with
`config.cpp_wrapper=True`, and turns it on for the four suites that pass:
`CondTestsCppWrapper`, `AssociativeScanTestsCppWrapper`, `MapTestsCppWrapper`,
`SwitchTestsCppWrapper`.

```
buck2 test @//mode/opt fbcode//caffe2/test/inductor:control_flow -- --regex "CppWrapper"
=> Pass 122. Fail 0. Skip 6.

buck2 test @//mode/opt fbcode//caffe2/test/inductor:control_flow
=> Pass 799. Fail 0. Skip 104.
```
(799 = the suite's previous 677 plus these 122; no existing case changed.)

Not everything could be turned on, and the reasons are pre-existing rather than caused by
this diff. Measured under `TORCHINDUCTOR_CPP_WRAPPER=1` on the parent commit and again on
this one -- identical both times, Pass 341 / Fail 337:
  - `ScanTests` (264 cases) and `WhileLoopTests` (69) still fail. Pinning that many names
    would rot on the next parametrization, so those two suites are left off with the
    reasons recorded in the file.
  - `CondTests` needed only four exclusions, listed in `_CPP_WRAPPER_XFAIL`
    (`test_cond_unbacked_symint_inner*`).
Two distinct causes, each worth its own diff:
  - `error: redefinition of 'true_graph_0_bufN'` -- a branch subgraph declares its buffers
    in the parent's C++ scope, so two branches reusing a name collide. Same class of bug as
    the region `stream0` collision fixed above, but for buffers rather than per-device
    state.
  - `NotImplementedError: NYI cpp wrapper for while_loop_stack_output`.

Authored with an AI assistant.

Differential Revision: D115659603
zoranzhao added a commit to zoranzhao/pytorch that referenced this pull request Aug 28, 2026
Summary:

`CppWrapperCpu.codegen_invoke_subgraph` was a bare `raise NotImplementedError`, so any
`torch.compiler.nested_compile_region` under AOTInductor died at codegen:

```
torch._inductor.exc.InductorError: NotImplementedError:
    codegen invoke_subgraph is not implemented for cpp wrapper
  cpp_wrapper_cpu.py:2813
```

Two parts.

**1. Implement `CppWrapperCpu.codegen_invoke_subgraph`.** The class already has a complete
subgraph-inlining implementation, `codegen_subgraph`, used by cond/switch/while_loop;
invoke_subgraph was the only HOP left raising. Declare one owning `RAIIAtenTensorHandle`
per output -- the same shape as `codegen_switch`, because in ABI-compatible mode
`ir.MultiOutput` is not codegened -- and delegate. A non-tensor region output raises
explicitly rather than emitting C++ that will not compile.

The region body is emitted inside its own C++ block. The region has its own `Scheduler`,
which re-emits per-device state -- notably `<stream_t> stream0;` from
`write_get_raw_stream` -- and in the parent's scope that is a redefinition
(`error: redefinition of 'stream0'`). The outputs are declared *outside* the block so
`codegen_subgraph_suffix` can still assign into them, and `_preserve_device_guard_state`
keeps the region's device-guard bookkeeping from leaking out.

**2. Fix a cross-graph index bug in wrapper-IR memory planning** that (1) exposes.
`AllocateLine`/`FreeIfNotReusedLine` record
`scheduler_node_index = V.graph.scheduler.nodes.index(...)`, but an inlined subgraph emits
its lines into the *parent's* line list while `V.graph` is the *subgraph*. Pairing a parent
free with a region allocation then compares indices into two different node lists:

```
ValueError: Start index must be less than or equal to end index
  segmented_tree.py:234, via should_reuse_buffer -> peak_between
```

Record the scheduler alongside the index and refuse reuse across schedulers. This is a
latent pre-existing bug for cond/while_loop too -- inlining is what makes it reachable --
but it is only reproducible once (1) lands.

Per-region Inductor config under the cpp wrapper is the next diff in the stack.

Note: `caffe2/...` and `xplat/caffe2/...` are separate synced copies; both are edited.

Test Plan:
`test_lite_regional_compile_invoke_subgraph` was skipped under `config.cpp_wrapper` with
the very message this diff deletes; the skip is removed.

New `test_invoke_subgraph_nested_region` in test_aot_inductor.py -- a full AOTI round trip
through `check_model`: compile, package, dlopen, run and compare against eager. That is
what a generated-C++ assertion cannot cover.

```
buck2 test @//mode/opt fbcode//caffe2/test/inductor:test_aot_inductor \
  -- --regex "invoke_subgraph"
=> Pass 4. Fail 0. Skip 1.

buck2 test @//mode/opt-amd-gpu fbcode//caffe2/test/inductor:test_inductor \
  -- --regex "regional|lite_"
=> Pass 8. Fail 0. Skip 3.
```

**cpp wrapper coverage for the other subgraph HOPs.** `test_control_flow.py` had none: every
case ran only under the default python wrapper, even though cond/while_loop/scan/map/switch
all reach `CppWrapperCpu.codegen_subgraph` and part (2) above touches every inlined
subgraph. This diff adds a `_CppWrapperMixin` that re-runs a suite with
`config.cpp_wrapper=True`, and turns it on for the four suites that pass:
`CondTestsCppWrapper`, `AssociativeScanTestsCppWrapper`, `MapTestsCppWrapper`,
`SwitchTestsCppWrapper`.

```
buck2 test @//mode/opt fbcode//caffe2/test/inductor:control_flow -- --regex "CppWrapper"
=> Pass 122. Fail 0. Skip 6.

buck2 test @//mode/opt fbcode//caffe2/test/inductor:control_flow
=> Pass 799. Fail 0. Skip 104.
```
(799 = the suite's previous 677 plus these 122; no existing case changed.)

Not everything could be turned on, and the reasons are pre-existing rather than caused by
this diff. Measured under `TORCHINDUCTOR_CPP_WRAPPER=1` on the parent commit and again on
this one -- identical both times, Pass 341 / Fail 337:
  - `ScanTests` (264 cases) and `WhileLoopTests` (69) still fail. Pinning that many names
    would rot on the next parametrization, so those two suites are left off with the
    reasons recorded in the file.
  - `CondTests` needed only four exclusions, listed in `_CPP_WRAPPER_XFAIL`
    (`test_cond_unbacked_symint_inner*`).
Two distinct causes, each worth its own diff:
  - `error: redefinition of 'true_graph_0_bufN'` -- a branch subgraph declares its buffers
    in the parent's C++ scope, so two branches reusing a name collide. Same class of bug as
    the region `stream0` collision fixed above, but for buffers rather than per-device
    state.
  - `NotImplementedError: NYI cpp wrapper for while_loop_stack_output`.

Authored with an AI assistant.

Differential Revision: D115659603
@zoranzhao
zoranzhao requested a review from desertfire August 31, 2026 16:50
@desertfire

Copy link
Copy Markdown
Contributor

@claude review this pr

@claude

claude Bot commented Aug 31, 2026 •

Copy link
Copy Markdown

Claude finished @desertfire's task in 27m 45s —— View job


The codegen_invoke_subgraph implementation and the cross-scheduler reuse guard both look correct, but the new test infrastructure has issues that should be fixed before landing (a skip masquerading as an xfail, a device-name mismatch that breaks on XPU, and a test that can silently stop covering the feature it was added for).

Full review

PR Review: #194703

Summary

Implements CppWrapperCpu.codegen_invoke_subgraph (previously a bare raise NotImplementedError) by inlining the region via the existing codegen_subgraph, and adds a scheduler-identity guard in AllocateLine.should_reuse_buffer so a parent free is never paired with a subgraph allocation. Core implementation reads correctly; the problems are in the tests and in comments that document the diff rather than the code.


Testing

1. _CPP_WRAPPER_XFAIL is named "xfail" but implemented as a skip — test/inductor/test_control_flow.py:2745-2749

if self._testMethodName in _CPP_WRAPPER_XFAIL:
    raise unittest.SkipTest("not yet supported by the cpp wrapper")

These are deterministic assertion/codegen failures (per the PR body: unbacked SymInts not bound correctly in the inlined C++), not crashes, hangs, or flakes. A skip silently disables the test forever — once inner-unbacked-SymInt binding is fixed, nobody will notice these four cases are still off, and the coverage this PR is explicitly adding is lost. Use unittest.expectedFailure (e.g. decorate the inherited methods on each subclass, or setattr the expectedFailure wrapper), which flips to a hard failure the moment it starts passing. At minimum the constant name must not claim XFAIL while the code does SkipTest.

Fix this →

2. Hardcoded _device_cuda will not match on XPU/MTIA — test/inductor/test_control_flow.py:2726-2730

The suites parametrize with @parametrize("device", ["cpu", GPU_TYPE]) (e.g. line 589), and GPU_TYPE is get_gpu_type() — cuda, xpu, or mtia depending on the runner. The literal test_cond_unbacked_symint_inner_device_cuda entries will never match ..._device_xpu, so on an XPU runner those cases run and fail instead of being excluded. Build the names from GPU_TYPE:

_CPP_WRAPPER_XFAIL = frozenset(
    f"test_cond_unbacked_symint_inner{suffix}_device_{dev}"
    for suffix in ("", "_to_outer")
    for dev in ("cpu", GPU_TYPE)
)

Fix this →

3. test_invoke_subgraph_nested_region can silently stop testing what it was added for — test/inductor/test_aot_inductor.py:366-386

The test relies entirely on inline_single_use_invoke_subgraph=False to keep the region from being inlined away before it reaches codegen_invoke_subgraph. If that config is renamed, defaulted differently, or the inlining decision moves, the test keeps passing while exercising none of the new code. Since this is the only end-to-end coverage of the feature, pin it: assert the region actually reached the cpp wrapper (run_and_get_cpp_code + a FileCheck on the emitted // subgraph: marker or the pre-declared RAIIAtenTensorHandle).

Separately, the model calls gn exactly once — the single-use case, which is the weakest possible shape for a feature whose whole purpose is emitting one region and reusing it. Two call sites would exercise region reuse and are precisely the shape that trips the redefinition of 'true_graph_0_bufN' buffer-name collision the PR body documents as unfixed. Worth adding, or worth stating in the test why one call is sufficient.

Fix this →


Code Quality

4. The wrapper.py guard treats the symptom; the root cause is a missing subgraph bracket — torch/_inductor/codegen/wrapper.py:1155-1162

The reason a parent FreeIfNotReusedLine can pair with a region AllocateLine at all is that PythonWrapperCodegen.codegen_invoke_subgraph calls codegen_subgraph_by_inlining (line 5075) with no EnterSubgraphLine/ExitSubgraphLine around it, unlike codegen_switch (lines 5102/5108) and codegen_while_loop (lines 5183/5187, 5197/5201). memory_plan_reuse only pushes a fresh MemoryPlanningState and swaps estimate_peak on EnterSubgraphLine (lines 2881-2890), so without the bracket the region's lines land in the parent's pool and are scored against the parent's segmented tree.

The guard is a defensible choice — adding the bracket would call code.do_indent() (line 580) with no enclosing Python block statement, producing mis-indented output — but none of that reasoning is in the code. The comment explains that the indices are incomparable, not why invoke_subgraph alone lacks the bracket that its two sibling HOPs have, which is exactly what a future reader will need. State it, and leave a TODO for the structural fix; otherwise the next person hits this and adds a second symptom-level guard.

Consequence worth noting in the comment too: cond/while_loop get a real per-subgraph reuse pool, whereas invoke_subgraph regions now get reuse disabled across the boundary — a small, permanent peak-memory regression for regions relative to the other HOPs.

Fix this →

5. Comments narrate the diff instead of the code — several places

CLAUDE.md asks for minimal comments that supply non-obvious global context, and specifically not references to the current change. Three spots read as changelog:

  • torch/_inductor/codegen/cpp_wrapper_cpu.py:2943-2951 — nine lines to justify one {/} pair. The load-bearing fact is one sentence: the region's own Scheduler re-emits stream0, which would redefine the parent's. The rest ("the same way codegen_switch / codegen_while_loop emit their branch bodies", "The outputs are declared above, outside the block") restates adjacent code.
  • test/inductor/test_torchinductor.py:17815-17817 — "No longer skipped under cpp_wrapper: CppWrapperCpu.codegen_invoke_subgraph inlines the region..." describes this PR and will be stale as soon as the implementation changes. The removed skipIf is visible in git log; drop the comment and keep the original one-liner.
  • test/inductor/test_control_flow.py:2734-2744 — eleven lines recording measured pass/fail counts (69 and 264 of their cases) and verbatim compiler error strings. Those numbers go stale on the next parametrization change, which is the same rot the comment itself warns about. This content already lives in the PR description, which is where it belongs; one line naming the two suites and one line per blocking reason is enough.

Fix this →


Recommendation

Request Changes — the codegen and the reuse guard look right, and the ArrayRef allow_stack_allocation = False override is real coverage (it runs under AOTInductorTestABICompatibleCpuWithStackAllocation, which is copied unconditionally). Blocking items are all in the tests: #1 (skip where an xfail is required) and #2 (device-name mismatch that breaks the exclusion list on non-CUDA GPU runners) are correctness bugs in the new test infra, and #3 leaves the feature's only end-to-end test able to pass without exercising the feature. #4 and #5 are comment/documentation fixes and are cheap.

Two things I did not flag, for the record, since they look like plausible objections:

  • Missing if V.graph.is_dual_wrapper_mode split. codegen_switch/codegen_while_loop need it because only one branch runs at runtime while the JIT pass must visit all of them. A region has exactly one body that always executes, so emitting it identically to both buffers is correct, and AOTInductorTestDualWrapper copies the new test so the path is covered.
  • Missing instantiate_parametrized_tests on the four new subclasses. Not needed: the existing calls at lines 2714-2719 expand the parent classes in place, so the subclasses inherit already-concrete methods and _testMethodName sees the expanded names.
| Branch: `export-D115659603`

zoranzhao added a commit to zoranzhao/pytorch that referenced this pull request Sep 1, 2026
Summary:

`CppWrapperCpu.codegen_invoke_subgraph` was a bare `raise NotImplementedError`, so any
`torch.compiler.nested_compile_region` under AOTInductor died at codegen:

```
torch._inductor.exc.InductorError: NotImplementedError:
    codegen invoke_subgraph is not implemented for cpp wrapper
  cpp_wrapper_cpu.py:2813
```

Two parts.

**1. Implement `CppWrapperCpu.codegen_invoke_subgraph`.** The class already has a complete
subgraph-inlining implementation, `codegen_subgraph`, used by cond/switch/while_loop;
invoke_subgraph was the only HOP left raising. Declare one owning `RAIIAtenTensorHandle`
per output -- the same shape as `codegen_switch`, because in ABI-compatible mode
`ir.MultiOutput` is not codegened -- and delegate. A non-tensor region output raises
explicitly rather than emitting C++ that will not compile.

The region body is emitted inside its own C++ block. The region has its own `Scheduler`,
which re-emits per-device state -- notably `<stream_t> stream0;` from
`write_get_raw_stream` -- and in the parent's scope that is a redefinition
(`error: redefinition of 'stream0'`). The outputs are declared *outside* the block so
`codegen_subgraph_suffix` can still assign into them, and `_preserve_device_guard_state`
keeps the region's device-guard bookkeeping from leaking out.

**2. Fix a cross-graph index bug in wrapper-IR memory planning** that (1) exposes.
`AllocateLine`/`FreeIfNotReusedLine` record
`scheduler_node_index = V.graph.scheduler.nodes.index(...)`, but an inlined subgraph emits
its lines into the *parent's* line list while `V.graph` is the *subgraph*. Pairing a parent
free with a region allocation then compares indices into two different node lists:

```
ValueError: Start index must be less than or equal to end index
  segmented_tree.py:234, via should_reuse_buffer -> peak_between
```

Record the scheduler alongside the index and refuse reuse across schedulers. This is a
latent pre-existing bug for cond/while_loop too -- inlining is what makes it reachable --
but it is only reproducible once (1) lands.

Per-region Inductor config under the cpp wrapper is the next diff in the stack.

Note: `caffe2/...` and `xplat/caffe2/...` are separate synced copies; both are edited.

Test Plan:
`test_lite_regional_compile_invoke_subgraph` was skipped under `config.cpp_wrapper` with
the very message this diff deletes; the skip is removed.

New `test_invoke_subgraph_nested_region` in test_aot_inductor.py -- a full AOTI round trip
through `check_model`: compile, package, dlopen, run and compare against eager. That is
what a generated-C++ assertion cannot cover.

```
buck2 test @//mode/opt fbcode//caffe2/test/inductor:test_aot_inductor \
  -- --regex "invoke_subgraph"
=> Pass 4. Fail 0. Skip 1.

buck2 test @//mode/opt-amd-gpu fbcode//caffe2/test/inductor:test_inductor \
  -- --regex "regional|lite_"
=> Pass 8. Fail 0. Skip 3.
```

**cpp wrapper coverage for the other subgraph HOPs.** `test_control_flow.py` had none: every
case ran only under the default python wrapper, even though cond/while_loop/scan/map/switch
all reach `CppWrapperCpu.codegen_subgraph` and part (2) above touches every inlined
subgraph. This diff adds a `_CppWrapperMixin` that re-runs a suite with
`config.cpp_wrapper=True`, and turns it on for the four suites that pass:
`CondTestsCppWrapper`, `AssociativeScanTestsCppWrapper`, `MapTestsCppWrapper`,
`SwitchTestsCppWrapper`.

```
buck2 test @//mode/opt fbcode//caffe2/test/inductor:control_flow -- --regex "CppWrapper"
=> Pass 122. Fail 0. Skip 6.

buck2 test @//mode/opt fbcode//caffe2/test/inductor:control_flow
=> Pass 799. Fail 0. Skip 104.
```
(799 = the suite's previous 677 plus these 122; no existing case changed.)

Not everything could be turned on, and the reasons are pre-existing rather than caused by
this diff. Measured under `TORCHINDUCTOR_CPP_WRAPPER=1` on the parent commit and again on
this one -- identical both times, Pass 341 / Fail 337:
  - `ScanTests` (264 cases) and `WhileLoopTests` (69) still fail. Pinning that many names
    would rot on the next parametrization, so those two suites are left off with the
    reasons recorded in the file.
  - `CondTests` needed only four exclusions, listed in `_CPP_WRAPPER_XFAIL`
    (`test_cond_unbacked_symint_inner*`).
Two distinct causes, each worth its own diff:
  - `error: redefinition of 'true_graph_0_bufN'` -- a branch subgraph declares its buffers
    in the parent's C++ scope, so two branches reusing a name collide. Same class of bug as
    the region `stream0` collision fixed above, but for buffers rather than per-device
    state.
  - `NotImplementedError: NYI cpp wrapper for while_loop_stack_output`.

Authored with an AI assistant.

Differential Revision: D115659603
@desertfire

Copy link
Copy Markdown
Contributor

Claude's review about the tests are valid. Please address before landing.

zoranzhao added a commit to zoranzhao/pytorch that referenced this pull request Sep 1, 2026
Summary:

`CppWrapperCpu.codegen_invoke_subgraph` was a bare `raise NotImplementedError`, so any
`torch.compiler.nested_compile_region` under AOTInductor died at codegen:

```
torch._inductor.exc.InductorError: NotImplementedError:
    codegen invoke_subgraph is not implemented for cpp wrapper
  cpp_wrapper_cpu.py:2813
```

Two parts.

**1. Implement `CppWrapperCpu.codegen_invoke_subgraph`.** The class already has a complete
subgraph-inlining implementation, `codegen_subgraph`, used by cond/switch/while_loop;
invoke_subgraph was the only HOP left raising. Declare one owning `RAIIAtenTensorHandle`
per output -- the same shape as `codegen_switch`, because in ABI-compatible mode
`ir.MultiOutput` is not codegened -- and delegate. A non-tensor region output raises
explicitly rather than emitting C++ that will not compile.

The region body is emitted inside its own C++ block. The region has its own `Scheduler`,
which re-emits per-device state -- notably `<stream_t> stream0;` from
`write_get_raw_stream` -- and in the parent's scope that is a redefinition
(`error: redefinition of 'stream0'`). The outputs are declared *outside* the block so
`codegen_subgraph_suffix` can still assign into them, and `_preserve_device_guard_state`
keeps the region's device-guard bookkeeping from leaking out.

**2. Fix a cross-graph index bug in wrapper-IR memory planning** that (1) exposes.
`AllocateLine`/`FreeIfNotReusedLine` record
`scheduler_node_index = V.graph.scheduler.nodes.index(...)`, but an inlined subgraph emits
its lines into the *parent's* line list while `V.graph` is the *subgraph*. Pairing a parent
free with a region allocation then compares indices into two different node lists:

```
ValueError: Start index must be less than or equal to end index
  segmented_tree.py:234, via should_reuse_buffer -> peak_between
```

Record the scheduler alongside the index and refuse reuse across schedulers. This is a
latent pre-existing bug for cond/while_loop too -- inlining is what makes it reachable --
but it is only reproducible once (1) lands.

Per-region Inductor config under the cpp wrapper is the next diff in the stack.

Note: `caffe2/...` and `xplat/caffe2/...` are separate synced copies; both are edited.

Test Plan:
`test_lite_regional_compile_invoke_subgraph` was skipped under `config.cpp_wrapper` with
the very message this diff deletes; the skip is removed.

New `test_invoke_subgraph_nested_region` in test_aot_inductor.py -- a full AOTI round trip
through `check_model`: compile, package, dlopen, run and compare against eager. That is
what a generated-C++ assertion cannot cover.

```
buck2 test @//mode/opt fbcode//caffe2/test/inductor:test_aot_inductor \
  -- --regex "invoke_subgraph"
=> Pass 4. Fail 0. Skip 1.

buck2 test @//mode/opt-amd-gpu fbcode//caffe2/test/inductor:test_inductor \
  -- --regex "regional|lite_"
=> Pass 8. Fail 0. Skip 3.
```

**cpp wrapper coverage for the other subgraph HOPs.** `test_control_flow.py` had none: every
case ran only under the default python wrapper, even though cond/while_loop/scan/map/switch
all reach `CppWrapperCpu.codegen_subgraph` and part (2) above touches every inlined
subgraph. This diff adds a `_CppWrapperMixin` that re-runs a suite with
`config.cpp_wrapper=True`, and turns it on for the four suites that pass:
`CondTestsCppWrapper`, `AssociativeScanTestsCppWrapper`, `MapTestsCppWrapper`,
`SwitchTestsCppWrapper`.

```
buck2 test @//mode/opt fbcode//caffe2/test/inductor:control_flow -- --regex "CppWrapper"
=> Pass 122. Fail 0. Skip 6.

buck2 test @//mode/opt fbcode//caffe2/test/inductor:control_flow
=> Pass 799. Fail 0. Skip 104.
```
(799 = the suite's previous 677 plus these 122; no existing case changed.)

Not everything could be turned on, and the reasons are pre-existing rather than caused by
this diff. Measured under `TORCHINDUCTOR_CPP_WRAPPER=1` on the parent commit and again on
this one -- identical both times, Pass 341 / Fail 337:
  - `ScanTests` (264 cases) and `WhileLoopTests` (69) still fail. Pinning that many names
    would rot on the next parametrization, so those two suites are left off with the
    reasons recorded in the file.
  - `CondTests` needed only four exclusions, listed in `_CPP_WRAPPER_XFAIL`
    (`test_cond_unbacked_symint_inner*`).
Two distinct causes, each worth its own diff:
  - `error: redefinition of 'true_graph_0_bufN'` -- a branch subgraph declares its buffers
    in the parent's C++ scope, so two branches reusing a name collide. Same class of bug as
    the region `stream0` collision fixed above, but for buffers rather than per-device
    state.
  - `NotImplementedError: NYI cpp wrapper for while_loop_stack_output`.

Authored with an AI assistant.

Reviewed By: desertfire

Differential Revision: D115659603
zoranzhao added a commit to zoranzhao/pytorch that referenced this pull request Sep 1, 2026
Summary:

`CppWrapperCpu.codegen_invoke_subgraph` was a bare `raise NotImplementedError`, so any
`torch.compiler.nested_compile_region` under AOTInductor died at codegen:

```
torch._inductor.exc.InductorError: NotImplementedError:
    codegen invoke_subgraph is not implemented for cpp wrapper
  cpp_wrapper_cpu.py:2813
```

Two parts.

**1. Implement `CppWrapperCpu.codegen_invoke_subgraph`.** The class already has a complete
subgraph-inlining implementation, `codegen_subgraph`, used by cond/switch/while_loop;
invoke_subgraph was the only HOP left raising. Declare one owning `RAIIAtenTensorHandle`
per output -- the same shape as `codegen_switch`, because in ABI-compatible mode
`ir.MultiOutput` is not codegened -- and delegate. A non-tensor region output raises
explicitly rather than emitting C++ that will not compile.

The region body is emitted inside its own C++ block. The region has its own `Scheduler`,
which re-emits per-device state -- notably `<stream_t> stream0;` from
`write_get_raw_stream` -- and in the parent's scope that is a redefinition
(`error: redefinition of 'stream0'`). The outputs are declared *outside* the block so
`codegen_subgraph_suffix` can still assign into them, and `_preserve_device_guard_state`
keeps the region's device-guard bookkeeping from leaking out.

**2. Fix a cross-graph index bug in wrapper-IR memory planning** that (1) exposes.
`AllocateLine`/`FreeIfNotReusedLine` record
`scheduler_node_index = V.graph.scheduler.nodes.index(...)`, but an inlined subgraph emits
its lines into the *parent's* line list while `V.graph` is the *subgraph*. Pairing a parent
free with a region allocation then compares indices into two different node lists:

```
ValueError: Start index must be less than or equal to end index
  segmented_tree.py:234, via should_reuse_buffer -> peak_between
```

Record the scheduler alongside the index and refuse reuse across schedulers. This is a
latent pre-existing bug for cond/while_loop too -- inlining is what makes it reachable --
but it is only reproducible once (1) lands.

Per-region Inductor config under the cpp wrapper is the next diff in the stack.

Note: `caffe2/...` and `xplat/caffe2/...` are separate synced copies; both are edited.

Test Plan:
`test_lite_regional_compile_invoke_subgraph` was skipped under `config.cpp_wrapper` with
the very message this diff deletes; the skip is removed.

New `test_invoke_subgraph_nested_region` in test_aot_inductor.py -- a full AOTI round trip
through `check_model`: compile, package, dlopen, run and compare against eager. That is
what a generated-C++ assertion cannot cover.

```
buck2 test @//mode/opt fbcode//caffe2/test/inductor:test_aot_inductor \
  -- --regex "invoke_subgraph"
=> Pass 4. Fail 0. Skip 1.

buck2 test @//mode/opt-amd-gpu fbcode//caffe2/test/inductor:test_inductor \
  -- --regex "regional|lite_"
=> Pass 8. Fail 0. Skip 3.
```

**cpp wrapper coverage for the other subgraph HOPs.** `test_control_flow.py` had none: every
case ran only under the default python wrapper, even though cond/while_loop/scan/map/switch
all reach `CppWrapperCpu.codegen_subgraph` and part (2) above touches every inlined
subgraph. This diff adds a `_CppWrapperMixin` that re-runs a suite with
`config.cpp_wrapper=True`, and turns it on for the four suites that pass:
`CondTestsCppWrapper`, `AssociativeScanTestsCppWrapper`, `MapTestsCppWrapper`,
`SwitchTestsCppWrapper`.

```
buck2 test @//mode/opt fbcode//caffe2/test/inductor:control_flow -- --regex "CppWrapper"
=> Pass 122. Fail 0. Skip 6.

buck2 test @//mode/opt fbcode//caffe2/test/inductor:control_flow
=> Pass 799. Fail 0. Skip 104.
```
(799 = the suite's previous 677 plus these 122; no existing case changed.)

Not everything could be turned on, and the reasons are pre-existing rather than caused by
this diff. Measured under `TORCHINDUCTOR_CPP_WRAPPER=1` on the parent commit and again on
this one -- identical both times, Pass 341 / Fail 337:
  - `ScanTests` (264 cases) and `WhileLoopTests` (69) still fail. Pinning that many names
    would rot on the next parametrization, so those two suites are left off with the
    reasons recorded in the file.
  - `CondTests` needed only four exclusions, listed in `_CPP_WRAPPER_XFAIL`
    (`test_cond_unbacked_symint_inner*`).
Two distinct causes, each worth its own diff:
  - `error: redefinition of 'true_graph_0_bufN'` -- a branch subgraph declares its buffers
    in the parent's C++ scope, so two branches reusing a name collide. Same class of bug as
    the region `stream0` collision fixed above, but for buffers rather than per-device
    state.
  - `NotImplementedError: NYI cpp wrapper for while_loop_stack_output`.

Authored with an AI assistant.

Reviewed By: desertfire

Differential Revision: D115659603
zoranzhao added a commit to zoranzhao/pytorch that referenced this pull request Sep 1, 2026
Summary:

`CppWrapperCpu.codegen_invoke_subgraph` was a bare `raise NotImplementedError`, so any
`torch.compiler.nested_compile_region` under AOTInductor died at codegen:

```
torch._inductor.exc.InductorError: NotImplementedError:
    codegen invoke_subgraph is not implemented for cpp wrapper
  cpp_wrapper_cpu.py:2813
```

Two parts.

**1. Implement `CppWrapperCpu.codegen_invoke_subgraph`.** The class already has a complete
subgraph-inlining implementation, `codegen_subgraph`, used by cond/switch/while_loop;
invoke_subgraph was the only HOP left raising. Declare one owning `RAIIAtenTensorHandle`
per output -- the same shape as `codegen_switch`, because in ABI-compatible mode
`ir.MultiOutput` is not codegened -- and delegate. A non-tensor region output raises
explicitly rather than emitting C++ that will not compile.

The region body is emitted inside its own C++ block. The region has its own `Scheduler`,
which re-emits per-device state -- notably `<stream_t> stream0;` from
`write_get_raw_stream` -- and in the parent's scope that is a redefinition
(`error: redefinition of 'stream0'`). The outputs are declared *outside* the block so
`codegen_subgraph_suffix` can still assign into them, and `_preserve_device_guard_state`
keeps the region's device-guard bookkeeping from leaking out.

**2. Fix a cross-graph index bug in wrapper-IR memory planning** that (1) exposes.
`AllocateLine`/`FreeIfNotReusedLine` record
`scheduler_node_index = V.graph.scheduler.nodes.index(...)`, but an inlined subgraph emits
its lines into the *parent's* line list while `V.graph` is the *subgraph*. Pairing a parent
free with a region allocation then compares indices into two different node lists:

```
ValueError: Start index must be less than or equal to end index
  segmented_tree.py:234, via should_reuse_buffer -> peak_between
```

Record the scheduler alongside the index and refuse reuse across schedulers. This is a
latent pre-existing bug for cond/while_loop too -- inlining is what makes it reachable --
but it is only reproducible once (1) lands.

Per-region Inductor config under the cpp wrapper is the next diff in the stack.

Note: `caffe2/...` and `xplat/caffe2/...` are separate synced copies; both are edited.

Test Plan:
`test_lite_regional_compile_invoke_subgraph` was skipped under `config.cpp_wrapper` with
the very message this diff deletes; the skip is removed.

New `test_invoke_subgraph_nested_region` in test_aot_inductor.py -- a full AOTI round trip
through `check_model`: compile, package, dlopen, run and compare against eager. That is
what a generated-C++ assertion cannot cover.

```
buck2 test @//mode/opt fbcode//caffe2/test/inductor:test_aot_inductor \
  -- --regex "invoke_subgraph"
=> Pass 4. Fail 0. Skip 1.

buck2 test @//mode/opt-amd-gpu fbcode//caffe2/test/inductor:test_inductor \
  -- --regex "regional|lite_"
=> Pass 8. Fail 0. Skip 3.
```

**cpp wrapper coverage for the other subgraph HOPs.** `test_control_flow.py` had none: every
case ran only under the default python wrapper, even though cond/while_loop/scan/map/switch
all reach `CppWrapperCpu.codegen_subgraph` and part (2) above touches every inlined
subgraph. This diff adds a `_CppWrapperMixin` that re-runs a suite with
`config.cpp_wrapper=True`, and turns it on for the four suites that pass:
`CondTestsCppWrapper`, `AssociativeScanTestsCppWrapper`, `MapTestsCppWrapper`,
`SwitchTestsCppWrapper`.

```
buck2 test @//mode/opt fbcode//caffe2/test/inductor:control_flow -- --regex "CppWrapper"
=> Pass 122. Fail 0. Skip 6.

buck2 test @//mode/opt fbcode//caffe2/test/inductor:control_flow
=> Pass 799. Fail 0. Skip 104.
```
(799 = the suite's previous 677 plus these 122; no existing case changed.)

Not everything could be turned on, and the reasons are pre-existing rather than caused by
this diff. Measured under `TORCHINDUCTOR_CPP_WRAPPER=1` on the parent commit and again on
this one -- identical both times, Pass 341 / Fail 337:
  - `ScanTests` (264 cases) and `WhileLoopTests` (69) still fail. Pinning that many names
    would rot on the next parametrization, so those two suites are left off with the
    reasons recorded in the file.
  - `CondTests` needed only four exclusions, listed in `_CPP_WRAPPER_XFAIL`
    (`test_cond_unbacked_symint_inner*`).
Two distinct causes, each worth its own diff:
  - `error: redefinition of 'true_graph_0_bufN'` -- a branch subgraph declares its buffers
    in the parent's C++ scope, so two branches reusing a name collide. Same class of bug as
    the region `stream0` collision fixed above, but for buffers rather than per-device
    state.
  - `NotImplementedError: NYI cpp wrapper for while_loop_stack_output`.

Authored with an AI assistant.

Reviewed By: desertfire

Differential Revision: D115659603
@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Sep 1, 2026
Summary:

`CppWrapperCpu.codegen_invoke_subgraph` was a bare `raise NotImplementedError`, so any
`torch.compiler.nested_compile_region` under AOTInductor died at codegen:

```
torch._inductor.exc.InductorError: NotImplementedError:
    codegen invoke_subgraph is not implemented for cpp wrapper
  cpp_wrapper_cpu.py:2813
```

Two parts.

**1. Implement `CppWrapperCpu.codegen_invoke_subgraph`.** The class already has a complete
subgraph-inlining implementation, `codegen_subgraph`, used by cond/switch/while_loop;
invoke_subgraph was the only HOP left raising. Declare one owning `RAIIAtenTensorHandle`
per output -- the same shape as `codegen_switch`, because in ABI-compatible mode
`ir.MultiOutput` is not codegened -- and delegate. A non-tensor region output raises
explicitly rather than emitting C++ that will not compile.

The region body is emitted inside its own C++ block. The region has its own `Scheduler`,
which re-emits per-device state -- notably `<stream_t> stream0;` from
`write_get_raw_stream` -- and in the parent's scope that is a redefinition
(`error: redefinition of 'stream0'`). The outputs are declared *outside* the block so
`codegen_subgraph_suffix` can still assign into them, and `_preserve_device_guard_state`
keeps the region's device-guard bookkeeping from leaking out.

**2. Fix a cross-graph index bug in wrapper-IR memory planning** that (1) exposes.
`AllocateLine`/`FreeIfNotReusedLine` record
`scheduler_node_index = V.graph.scheduler.nodes.index(...)`, but an inlined subgraph emits
its lines into the *parent's* line list while `V.graph` is the *subgraph*. Pairing a parent
free with a region allocation then compares indices into two different node lists:

```
ValueError: Start index must be less than or equal to end index
  segmented_tree.py:234, via should_reuse_buffer -> peak_between
```

Record the scheduler alongside the index and refuse reuse across schedulers. This is a
latent pre-existing bug for cond/while_loop too -- inlining is what makes it reachable --
but it is only reproducible once (1) lands.

Per-region Inductor config under the cpp wrapper is the next diff in the stack.

Note: `caffe2/...` and `xplat/caffe2/...` are separate synced copies; both are edited.

Test Plan:
`test_lite_regional_compile_invoke_subgraph` was skipped under `config.cpp_wrapper` with
the very message this diff deletes; the skip is removed.

New `test_invoke_subgraph_nested_region` in test_aot_inductor.py -- a full AOTI round trip
through `check_model`: compile, package, dlopen, run and compare against eager. That is
what a generated-C++ assertion cannot cover.

```
buck2 test @//mode/opt fbcode//caffe2/test/inductor:test_aot_inductor \
  -- --regex "invoke_subgraph"
=> Pass 4. Fail 0. Skip 1.

buck2 test @//mode/opt-amd-gpu fbcode//caffe2/test/inductor:test_inductor \
  -- --regex "regional|lite_"
=> Pass 8. Fail 0. Skip 3.
```

**cpp wrapper coverage for the other subgraph HOPs.** `test_control_flow.py` had none: every
case ran only under the default python wrapper, even though cond/while_loop/scan/map/switch
all reach `CppWrapperCpu.codegen_subgraph` and part (2) above touches every inlined
subgraph. This diff adds a `_CppWrapperMixin` that re-runs a suite with
`config.cpp_wrapper=True`, and turns it on for the four suites that pass:
`CondTestsCppWrapper`, `AssociativeScanTestsCppWrapper`, `MapTestsCppWrapper`,
`SwitchTestsCppWrapper`.

```
buck2 test @//mode/opt fbcode//caffe2/test/inductor:control_flow -- --regex "CppWrapper"
=> Pass 122. Fail 0. Skip 6.

buck2 test @//mode/opt fbcode//caffe2/test/inductor:control_flow
=> Pass 799. Fail 0. Skip 104.
```
(799 = the suite's previous 677 plus these 122; no existing case changed.)

Not everything could be turned on, and the reasons are pre-existing rather than caused by
this diff. Measured under `TORCHINDUCTOR_CPP_WRAPPER=1` on the parent commit and again on
this one -- identical both times, Pass 341 / Fail 337:
  - `ScanTests` (264 cases) and `WhileLoopTests` (69) still fail. Pinning that many names
    would rot on the next parametrization, so those two suites are left off with the
    reasons recorded in the file.
  - `CondTests` needed only four exclusions, listed in `_CPP_WRAPPER_XFAIL`
    (`test_cond_unbacked_symint_inner*`).
Two distinct causes, each worth its own diff:
  - `error: redefinition of 'true_graph_0_bufN'` -- a branch subgraph declares its buffers
    in the parent's C++ scope, so two branches reusing a name collide. Same class of bug as
    the region `stream0` collision fixed above, but for buffers rather than per-device
    state.
  - `NotImplementedError: NYI cpp wrapper for while_loop_stack_output`.

Authored with an AI assistant.

Reviewed By: desertfire

Differential Revision: D115659603
zoranzhao added a commit to zoranzhao/pytorch that referenced this pull request Sep 2, 2026
Summary:

`CppWrapperCpu.codegen_invoke_subgraph` was a bare `raise NotImplementedError`, so any
`torch.compiler.nested_compile_region` under AOTInductor died at codegen:

```
torch._inductor.exc.InductorError: NotImplementedError:
    codegen invoke_subgraph is not implemented for cpp wrapper
  cpp_wrapper_cpu.py:2813
```

Two parts.

**1. Implement `CppWrapperCpu.codegen_invoke_subgraph`.** The class already has a complete
subgraph-inlining implementation, `codegen_subgraph`, used by cond/switch/while_loop;
invoke_subgraph was the only HOP left raising. Declare one owning `RAIIAtenTensorHandle`
per output -- the same shape as `codegen_switch`, because in ABI-compatible mode
`ir.MultiOutput` is not codegened -- and delegate. A non-tensor region output raises
explicitly rather than emitting C++ that will not compile.

The region body is emitted inside its own C++ block. The region has its own `Scheduler`,
which re-emits per-device state -- notably `<stream_t> stream0;` from
`write_get_raw_stream` -- and in the parent's scope that is a redefinition
(`error: redefinition of 'stream0'`). The outputs are declared *outside* the block so
`codegen_subgraph_suffix` can still assign into them, and `_preserve_device_guard_state`
keeps the region's device-guard bookkeeping from leaking out.

**2. Fix a cross-graph index bug in wrapper-IR memory planning** that (1) exposes.
`AllocateLine`/`FreeIfNotReusedLine` record
`scheduler_node_index = V.graph.scheduler.nodes.index(...)`, but an inlined subgraph emits
its lines into the *parent's* line list while `V.graph` is the *subgraph*. Pairing a parent
free with a region allocation then compares indices into two different node lists:

```
ValueError: Start index must be less than or equal to end index
  segmented_tree.py:234, via should_reuse_buffer -> peak_between
```

Record the scheduler alongside the index and refuse reuse across schedulers. This is a
latent pre-existing bug for cond/while_loop too -- inlining is what makes it reachable --
but it is only reproducible once (1) lands.

Per-region Inductor config under the cpp wrapper is the next diff in the stack.

Note: `caffe2/...` and `xplat/caffe2/...` are separate synced copies; both are edited.

Test Plan:
`test_lite_regional_compile_invoke_subgraph` was skipped under `config.cpp_wrapper` with
the very message this diff deletes; the skip is removed.

New `test_invoke_subgraph_nested_region` in test_aot_inductor.py -- a full AOTI round trip
through `check_model`: compile, package, dlopen, run and compare against eager. That is
what a generated-C++ assertion cannot cover.

```
buck2 test @//mode/opt fbcode//caffe2/test/inductor:test_aot_inductor \
  -- --regex "invoke_subgraph"
=> Pass 4. Fail 0. Skip 1.

buck2 test @//mode/opt-amd-gpu fbcode//caffe2/test/inductor:test_inductor \
  -- --regex "regional|lite_"
=> Pass 8. Fail 0. Skip 3.
```

**cpp wrapper coverage for the other subgraph HOPs.** `test_control_flow.py` had none: every
case ran only under the default python wrapper, even though cond/while_loop/scan/map/switch
all reach `CppWrapperCpu.codegen_subgraph` and part (2) above touches every inlined
subgraph. This diff adds a `_CppWrapperMixin` that re-runs a suite with
`config.cpp_wrapper=True`, and turns it on for the four suites that pass:
`CondTestsCppWrapper`, `AssociativeScanTestsCppWrapper`, `MapTestsCppWrapper`,
`SwitchTestsCppWrapper`.

```
buck2 test @//mode/opt fbcode//caffe2/test/inductor:control_flow -- --regex "CppWrapper"
=> Pass 122. Fail 0. Skip 6.

buck2 test @//mode/opt fbcode//caffe2/test/inductor:control_flow
=> Pass 799. Fail 0. Skip 104.
```
(799 = the suite's previous 677 plus these 122; no existing case changed.)

Not everything could be turned on, and the reasons are pre-existing rather than caused by
this diff. Measured under `TORCHINDUCTOR_CPP_WRAPPER=1` on the parent commit and again on
this one -- identical both times, Pass 341 / Fail 337:
  - `ScanTests` (264 cases) and `WhileLoopTests` (69) still fail. Pinning that many names
    would rot on the next parametrization, so those two suites are left off with the
    reasons recorded in the file.
  - `CondTests` needed only four exclusions, listed in `_CPP_WRAPPER_XFAIL`
    (`test_cond_unbacked_symint_inner*`).
Two distinct causes, each worth its own diff:
  - `error: redefinition of 'true_graph_0_bufN'` -- a branch subgraph declares its buffers
    in the parent's C++ scope, so two branches reusing a name collide. Same class of bug as
    the region `stream0` collision fixed above, but for buffers rather than per-device
    state.
  - `NotImplementedError: NYI cpp wrapper for while_loop_stack_output`.

Authored with an AI assistant.

Reviewed By: desertfire

Differential Revision: D115659603
@meta-codesync

meta-codesync Bot commented Sep 2, 2026

Copy link
Copy Markdown

@pytorchbot merge

(Initiating merge automatically since Phabricator Diff has merged)

@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: torchtitan-test / torchtitan-x-pytorch-test / test (torchtitan_models_integration, 1, 1, mt-l-x86aavx2-189-704-a10g-8)

Details for Dev Infra team Raised by workflow job

@huydhn

huydhn commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot merge

@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

Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…pytorch#194703)

Summary:

`CppWrapperCpu.codegen_invoke_subgraph` was a bare `raise NotImplementedError`, so any
`torch.compiler.nested_compile_region` under AOTInductor died at codegen:

```
torch._inductor.exc.InductorError: NotImplementedError:
    codegen invoke_subgraph is not implemented for cpp wrapper
  cpp_wrapper_cpu.py:2813
```

Two parts.

**1. Implement `CppWrapperCpu.codegen_invoke_subgraph`.** The class already has a complete
subgraph-inlining implementation, `codegen_subgraph`, used by cond/switch/while_loop;
invoke_subgraph was the only HOP left raising. Declare one owning `RAIIAtenTensorHandle`
per output -- the same shape as `codegen_switch`, because in ABI-compatible mode
`ir.MultiOutput` is not codegened -- and delegate. A non-tensor region output raises
explicitly rather than emitting C++ that will not compile.

The region body is emitted inside its own C++ block. The region has its own `Scheduler`,
which re-emits per-device state -- notably `<stream_t> stream0;` from
`write_get_raw_stream` -- and in the parent's scope that is a redefinition
(`error: redefinition of 'stream0'`). The outputs are declared *outside* the block so
`codegen_subgraph_suffix` can still assign into them, and `_preserve_device_guard_state`
keeps the region's device-guard bookkeeping from leaking out.

**2. Fix a cross-graph index bug in wrapper-IR memory planning** that (1) exposes.
`AllocateLine`/`FreeIfNotReusedLine` record
`scheduler_node_index = V.graph.scheduler.nodes.index(...)`, but an inlined subgraph emits
its lines into the *parent's* line list while `V.graph` is the *subgraph*. Pairing a parent
free with a region allocation then compares indices into two different node lists:

```
ValueError: Start index must be less than or equal to end index
  segmented_tree.py:234, via should_reuse_buffer -> peak_between
```

Record the scheduler alongside the index and refuse reuse across schedulers. This is a
latent pre-existing bug for cond/while_loop too -- inlining is what makes it reachable --
but it is only reproducible once (1) lands.

Per-region Inductor config under the cpp wrapper is the next diff in the stack.

Note: `caffe2/...` and `xplat/caffe2/...` are separate synced copies; both are edited.

Test Plan:
`test_lite_regional_compile_invoke_subgraph` was skipped under `config.cpp_wrapper` with
the very message this diff deletes; the skip is removed.

New `test_invoke_subgraph_nested_region` in test_aot_inductor.py -- a full AOTI round trip
through `check_model`: compile, package, dlopen, run and compare against eager. That is
what a generated-C++ assertion cannot cover.

```
buck2 test @//mode/opt fbcode//caffe2/test/inductor:test_aot_inductor \
  -- --regex "invoke_subgraph"
=> Pass 4. Fail 0. Skip 1.

buck2 test @//mode/opt-amd-gpu fbcode//caffe2/test/inductor:test_inductor \
  -- --regex "regional|lite_"
=> Pass 8. Fail 0. Skip 3.
```

**cpp wrapper coverage for the other subgraph HOPs.** `test_control_flow.py` had none: every
case ran only under the default python wrapper, even though cond/while_loop/scan/map/switch
all reach `CppWrapperCpu.codegen_subgraph` and part (2) above touches every inlined
subgraph. This diff adds a `_CppWrapperMixin` that re-runs a suite with
`config.cpp_wrapper=True`, and turns it on for the four suites that pass:
`CondTestsCppWrapper`, `AssociativeScanTestsCppWrapper`, `MapTestsCppWrapper`,
`SwitchTestsCppWrapper`.

```
buck2 test @//mode/opt fbcode//caffe2/test/inductor:control_flow -- --regex "CppWrapper"
=> Pass 122. Fail 0. Skip 6.

buck2 test @//mode/opt fbcode//caffe2/test/inductor:control_flow
=> Pass 799. Fail 0. Skip 104.
```
(799 = the suite's previous 677 plus these 122; no existing case changed.)

Not everything could be turned on, and the reasons are pre-existing rather than caused by
this diff. Measured under `TORCHINDUCTOR_CPP_WRAPPER=1` on the parent commit and again on
this one -- identical both times, Pass 341 / Fail 337:
  - `ScanTests` (264 cases) and `WhileLoopTests` (69) still fail. Pinning that many names
    would rot on the next parametrization, so those two suites are left off with the
    reasons recorded in the file.
  - `CondTests` needed only four exclusions, listed in `_CPP_WRAPPER_XFAIL`
    (`test_cond_unbacked_symint_inner*`).
Two distinct causes, each worth its own diff:
  - `error: redefinition of 'true_graph_0_bufN'` -- a branch subgraph declares its buffers
    in the parent's C++ scope, so two branches reusing a name collide. Same class of bug as
    the region `stream0` collision fixed above, but for buffers rather than per-device
    state.
  - `NotImplementedError: NYI cpp wrapper for while_loop_stack_output`.

Authored with an AI assistant.

Reviewed By: desertfire

Differential Revision: D115659603

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants