Skip to content

[AOTI] Support AOTI lazy autotune with dual-wrapper - #184735

Closed
desertfire wants to merge 13 commits into
gh/desertfire/732/basefrom
gh/desertfire/732/head
Closed

desertfire wants to merge 13 commits into
gh/desertfire/732/basefrom
gh/desertfire/732/head

Conversation

@desertfire

@desertfire desertfire commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Switch the AOTI lazy-autotune path to emit separate JIT and AOTI C++ wrapper bodies in one codegen pass. The JIT body is compiled and run with real inputs to populate lazy Triton kernel metadata, then the generated AOTI source includes the captured kernel config for packaging.

Add test_aot_inductor variant that runs with triton.autotune_at_compile_time=False so this path is exercised. torch.cond and torch.while_loop are not yet wired up for the dual-wrapper path and are skipped in this variant; a follow-up commit adds support for them.

Example generated code:
JIT wrapper code
AOT wrapper code

Authored with Codex.

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

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented May 21, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 1 New Failure, 1 Unrelated Failure

As of commit f28a6b1 with merge base dc833a2 (image):

NEW FAILURE - The following job has failed:

BROKEN TRUNK - The following job failed but were 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.

[ghstack-poisoned]
@desertfire

Copy link
Copy Markdown
Contributor Author

@claude review this PR

@claude

claude Bot commented May 21, 2026 •

Copy link
Copy Markdown

Claude finished @desertfire's task in 2m 30s —— View job


Reviewing PR #184735

  • Gather context and read PR diff
  • Review test changes
  • Review core implementation changes
  • Post review feedback

Review Summary

This is a well-structured PR that replaces the old two-pass AOTI codegen (compile → run → reset → recompile) with a single-pass dual-wrapper approach using DualIndentedBuffer. The architecture is sound: one codegen pass emits both a JIT body (for autotuning) and an AOTI body (for packaging) side-by-side, avoiding the expensive metrics/state reset and full second codegen pass.


Architecture Feedback

Strengths:

  • The DualIndentedBuffer abstraction is clean — it keeps the writeline_jit/writeline_aot routing transparent and avoids invasive changes to existing codegen methods.
  • The is_dual_wrapper_mode property at graph.py:1013 correctly guards the new path behind aot_mode and not autotune_at_compile_time and has_triton_device.
  • Good separation: the JIT variant is compiled/run purely to populate CudaKernelParamCache, and the AOTI variant consumes those results through a generated config header.

Issues & Suggestions

1. _aot_output is set as a dynamic attribute with no declaration (medium)

self._aot_output in cpp_wrapper_cpu.py:1576 is assigned inside _generate_end_aoti but never declared on the class. Accessing it later in graph.py:2594 uses # type: ignore[attr-defined]. Consider declaring it in __init__ (e.g., self._aot_output: str | None = None) for discoverability and to avoid silent AttributeError if _generate_end_aoti isn't called in the expected order.

2. Assertion without clear error recovery in generate_aoti_kernel_config_header (low)

At cpp_wrapper_gpu.py:82:

assert params is not None, (
    f"CudaKernelParamCache not populated for {kernel_name} "
    "after first-pass execution"
)

This is fine for a development assert, but since this runs after the JIT variant has already been compiled and executed, if the kernel fails to autotune (e.g., due to OOM or a runtime error), the assertion will fire with no additional diagnostic context. Consider catching and wrapping with the actual error from the JIT execution if possible.

3. stream_ variable scoping in _generate_lazy_launch (low)

At cpp_wrapper_gpu.py:575, common_launch_args references stream_ which is a parameter of the wrapper function for both JIT and AOTI sides. This works correctly because _write_wrapper_signature adds stream_ to both sides' parameter lists. Just noting this dependency is correct but non-obvious.

4. The generate_before_suffix logic could be simplified (nit)

At cpp_wrapper_cpu.py:1545-1555:

if V.graph.aot_mode:
    if V.graph.is_dual_wrapper_mode:
        result.writeline("} // inductor_entry_impl")
    else:
        entry = "_const_run_impl" if V.graph.is_const_graph else "run_impl"
        result.writeline(f"}} // {self.aoti_model_class_name}::{entry}")
else:
    result.writeline("} // inductor_entry_impl")

The first and third branches emit the same string. Could be:

if V.graph.aot_mode and not V.graph.is_dual_wrapper_mode:
    entry = "_const_run_impl" if V.graph.is_const_graph else "run_impl"
    result.writeline(f"}} // {self.aoti_model_class_name}::{entry}")
else:
    result.writeline("} // inductor_entry_impl")

5. config_dict default values for block sizes (low)

At cpp_wrapper_gpu.py:117-120:

xblocks = [config_dict.get("XBLOCK", 128)]
yblocks = [config_dict.get("YBLOCK", 1)]

These defaults (128, 1, 1, 1) are duplicated from the runtime. If those defaults ever change in triton_heuristics.py, this header generation would emit stale values. Consider referencing a shared constant or documenting why these defaults are safe here.

6. Unused import removal of metrics from graph.py (nit)

The diff removes from . import config, ir, metrics → from . import config, ir. This is correct since the old two-pass path that called metrics.reset() is gone. Just confirming there's no other reference.

7. Test skip pattern repetition (nit)

The 6 autotune_at_compile_time is False skip blocks in test_aot_inductor.py are identical. Consider extracting a decorator:

def requires_autotune_at_compile_time(fn):
    @functools.wraps(fn)
    def wrapper(self, *args, **kwargs):
        if config.triton.autotune_at_compile_time is False:
            raise unittest.SkipTest("requires autotune_at_compile_time=True")
        return fn(self, *args, **kwargs)
    return wrapper

8. pyrefly: ignore annotations (nit)

At cpp_wrapper_cpu.py:3591 and 3594:

writer = (
    writer if writer is not None else self
)  # pyrefly: ignore [bad-assignment]

These were added to suppress type checker warnings for the existing code pattern. This is fine, but worth a follow-up to properly type the writer parameter.


Security & Correctness

  • The unsafe_alloc_void_ptrs_from_tensors / alloc_tensors_by_stealing_from_void_ptrs usage in _run_jit_variant_for_autotune (graph.py:2678-2685) correctly handles tensor lifetime — del real_inputs, input_tensors before the output steal ensures no double-free.
  • The cache invalidation at graph.py:2631 (CudaKernelParamCache.cache.pop(name, None)) correctly forces re-autotuning for each compilation.
  • The config.patch("aot_inductor.link_libtorch", True) at graph.py:2646 correctly scopes the libtorch dependency to the temporary JIT wrapper only.

Overall

This is a solid architectural improvement. The dual-wrapper approach eliminates the expensive second codegen pass and makes the lazy-autotune path more maintainable. The test coverage via AOTInductorTestDualWrapper with the known skip list for torch.cond/while_loop is appropriate for landing this incrementally. The main actionable suggestion is declaring _aot_output on the class to avoid a latent AttributeError risk.

[ghstack-poisoned]
@desertfire

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented May 22, 2026 •

Copy link
Copy Markdown

Claude finished @desertfire's task in 3m 40s —— View job


Reviewing PR #184735

  • Gather context and read PR diff
  • Review core implementation changes (graph.py, cpp_wrapper_cpu.py, cpp_wrapper_gpu.py)
  • Review wrapper.py and runtime changes
  • Review test changes
  • Post review feedback

Review Summary

This PR replaces the old two-pass AOTI codegen (compile → run → reset → recompile) with a single-pass dual-wrapper architecture using DualIndentedBuffer. One codegen pass emits both a JIT body (for autotuning with real inputs) and an AOTI body (for packaging with captured kernel config). The architecture is clean and well-thought-out.

Since the last review, notable improvements include:

  • Proper _aot_output field declaration in __init__ (addressing the prior review's top feedback)
  • Better error wrapping in _run_jit_variant_for_autotune with from exc
  • The requires_autotune_at_compile_time decorator is now implemented (prior review suggestion)
  • Shared constants (TRITON_DEFAULT_BLOCK_SIZES, etc.) in hints.py to avoid default value duplication (prior review suggestion)
  • The generate_before_suffix simplification suggested previously

Issues

1. Missing spaces in error messages (bug)

All three RuntimeError messages in this PR have implicit string concatenation without a separating space:

graph.py:2593-2594:

"When autotune_at_compile_time is False, AOTInductor generates"
"both JIT code and AOT code. The JIT code failed to run."

This produces: ...generates**both** JIT code... (no space between "generates" and "both").

Same at graph.py:2603-2604 and cpp_wrapper_gpu.py:89-92 (the latter also has missing space before "that is not").

Fix this →

2. generate_before_suffix writes misleading close-brace comment in dual-wrapper-mode (low)

cpp_wrapper_cpu.py:1546-1553:

def generate_before_suffix(self, result):
    if V.graph.aot_mode:
        entry = "_const_run_impl" if V.graph.is_const_graph else "run_impl"
        result.writeline(f"}} // {self.aoti_model_class_name}::{entry}")
    else:
        result.writeline("} // inductor_entry_impl")

The comment says "In dual-wrapper-mode result is the JIT side", yet when aot_mode=True (which is always true in dual-wrapper-mode), it writes } // AOTInductorModel::run_impl to the JIT output. The JIT function is inductor_entry_impl. This is cosmetic (just a C++ comment on the closing brace) but misleading for anyone reading the generated code. Should be:

if V.graph.aot_mode and not V.graph.is_dual_wrapper_mode:
    entry = "_const_run_impl" if V.graph.is_const_graph else "run_impl"
    result.writeline(f"}} // {self.aoti_model_class_name}::{entry}")
else:
    result.writeline("} // inductor_entry_impl")

3. DualWrapperCodeLine.codegen receives a plain IndentedBuffer as code (correctness question)

cpp_wrapper_cpu.py:54-63:

@dataclasses.dataclass
class DualWrapperCodeLine(WrapperLine):
    jit_code: IndentedBuffer
    aot_code: IndentedBuffer

    def codegen(self, code: IndentedBuffer) -> None:
        code.splice_jit(self.jit_code)
        code.splice_aot(self.aot_code)

This is used at line 2951: self.writeline(DualWrapperCodeLine(jit_code, aot_code)). The self.writeline dispatches to self.wrapper_call.writeline(line) which for a DualIndentedBuffer calls codegen on the line with... actually, looking at the DualIndentedBuffer.writeline, it writes the line object to both buffers. Then when the buffer is getvalue'd/spliced, it calls codegen(code) where code is one side. But splice_jit / splice_aot on a plain IndentedBuffer — splice_jit writes (since IndentedBuffer.splice_jit falls through to splice) and splice_aot is a no-op. So when the JIT buffer codegen's this line, it gets jit_code; when the AOT buffer codegen's it, it gets aot_code. This is clever but relies on the no-op behavior of IndentedBuffer.splice_aot. Worth a brief inline comment on the codegen method explaining why this works.


Observations (non-blocking)

4. _write_jit_entry_point_signature is always called regardless of mode

cpp_wrapper_cpu.py:901-903:

if V.graph.aot_mode:
    self._write_aoti_entry_point_signature()
self._write_jit_entry_point_signature()

In pure JIT mode (aot_mode=False), self.prefix is a plain IndentedBuffer, so splice_jit inside _write_jit_entry_point_signature calls through to splice — this works correctly. In pure AOTI mode (aot_mode=True, not dual-wrapper), self.prefix is an AotOnlyBuffer, so splice_jit is a no-op — also correct. And in dual-wrapper mode, splice_jit writes to the JIT side only. This is well-designed but the correctness depends entirely on the buffer type dispatch; a brief comment would help future readers.

5. runtime_bin_path usage is correct but subtle

triton_lazy_compile.py:179,259: The change to use runtime_bin_path (pre-multi-arch path) for the JIT TritonKernelCompileResult while generate_aoti_kernel_config_header uses the rewritten cubin_path for AOTI is correct — the JIT needs the actual binary that exists on disk now, while AOTI references the fatbin that'll be compiled into the package later.

6. _generate_lazy_scratch uses device_idx_ directly

cpp_wrapper_gpu.py:534:

    {device_ptr_type} {var} = allocate_scratch_tensor<{device_ptr_type}>(
        {var}_numel, {dtype_str}, {device_type}, device_idx_, {var}_tensor);

This references device_idx_ which is a parameter in the wrapper function signature (from _write_wrapper_signature). In dual mode, both JIT and AOTI pass their device index as device_idx_ to the wrapper function, so this shared code is correct. The JIT caller passes the concrete index, the AOTI caller passes this->device_idx_.

7. The DualIndentedBuffer.splice override semantics are subtle

utils.py:1757-1773: When splice is called on a DualIndentedBuffer with a DualIndentedBuffer argument, the JIT side gets the JIT content and the AOT side gets the AOT content. When called with a plain IndentedBuffer, both sides get the same content. This is correct but the dual-dispatch behavior could trip up future contributors — the existing comment ("Splice into each buffer independently") helps, but the asymmetry of aot_other fallback logic is worth noting.


Security & Correctness

  • The tensor lifetime management in _run_jit_variant_for_autotune (graph.py:2694) is correct: del real_inputs, input_tensors before using output handles prevents double-free.
  • Cache invalidation at graph.py:2644 (CudaKernelParamCache.cache.pop(name, None)) correctly forces re-autotuning.
  • The config.patch("aot_inductor.link_libtorch", True) at graph.py:2659 correctly scopes libtorch to the temporary JIT wrapper only.
  • The DebugAutotuner fallback to inductor_meta.get("kernel_name") (triton_heuristics.py:2799-2803) correctly handles the case where the autotuner isn't module-bound in the AOTI lazy compile path.

Overall

Solid improvement over the previous review iteration. The missing spaces in error messages (issue #1) are the only actual bug. The close-brace comment mismatch (issue #2) is cosmetic but worth fixing. The rest is well-structured.


[ghstack-poisoned]
[ghstack-poisoned]
@desertfire

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented May 27, 2026 •

Copy link
Copy Markdown

Claude finished @desertfire's task in 2m 32s —— View job


Reviewing PR #184735

  • Gather context and read PR diff
  • Review core implementation changes (graph.py, cpp_wrapper_cpu.py, cpp_wrapper_gpu.py)
  • Review wrapper.py, utils.py, and runtime changes
  • Review test changes
  • Post review feedback

Review Summary

This is the third review of this PR. The architecture remains solid — a single codegen pass using DualIndentedBuffer to emit both JIT (for autotuning) and AOTI (for packaging) C++ sources simultaneously, replacing the expensive two-pass approach. Since the last review, the code is more polished: _aot_output is declared in __init__, the requires_autotune_at_compile_time decorator is in place, shared constants for block sizes are in hints.py, and the generate_before_suffix simplification is applied.


Issues

1. Missing spaces in error messages (bug — still present from last review)

cpp_wrapper_gpu.py:89-92:

raise RuntimeError(
    "When autotune_at_compile_time is False, AOTInductor generates"
    "both JIT code and AOT code. They are expected to have exactly"
    f"the same kernels. However, AOT code contains kernels, {kernel_names},"
    "that is not in the JIT code."
)

Implicit string concatenation produces ...generates**both**..., ...exactly**the**..., and ...kernels,**that**... (missing leading space on each continuation line). The messages at graph.py:2594 were fixed since last review but this one in cpp_wrapper_gpu.py is still broken.

Fix this →

2. EnterDeviceContextManagerLine emits stream_guard only to AOTI but not in non-dual pure-AOTI mode (correctness concern)

wrapper.py:581-586:

if self.last_seen_device_guard_index is None:
    code.writeline_aot(
        f"{V.graph.device_ops.cpp_aoti_stream_guard()} stream_guard(stream, this->device_idx_);"
    )
    code.writeline_jit(
        f"{V.graph.device_ops.cpp_aoti_device_guard()} device_guard({self.device_idx});"
    )

In pure-AOTI mode (no dual-wrapper), code is an AotOnlyBuffer where writeline_aot delegates to writeline — this is correct. In dual-wrapper mode, code is a DualIndentedBuffer — also correct. In pure JIT (IndentedBuffer), writeline_aot is a no-op and writeline_jit writes — correct. So all three modes work.

However, there's a subtle behavior change from the old code: previously, in pure JIT mode (not V.graph.aot_mode), the first device context emitted a device_guard(...) and subsequent ones emitted device_guard.set_index(...). Now the else branch (line 593) unconditionally does writeline_jit(f"device_guard.set_index(...)") without the if not V.graph.aot_mode guard. In pure-AOTI mode, writeline_jit is a no-op on AotOnlyBuffer, so there's no harm. But the old code only ran device_guard.set_index when not V.graph.aot_mode — the assertion was the only behavior in AOTI. Now the assertion fires for AOTI, and then writeline_jit emits a line that gets dropped. This is functionally correct but worth noting the assertion still guards AOTI single-device semantics.

3. _write_input_preamble const_graph case emits JIT input stealing without AOTI counterpart (review question)

cpp_wrapper_cpu.py:908-924:

def _write_input_preamble(self):
    jit_num_args = len(V.graph.graph_inputs) + len(V.graph.constants)
    if not V.graph.is_const_graph:
        aoti_num_args = len(V.graph.graph_inputs)
        self.prefix.splice_aot(...)
    # release GIL ...
    self.prefix.splice_jit("py::gil_scoped_release_simple release;")
    self.prefix.splice_jit(
        f"auto inputs = steal_from_raw_handles_to_raii_handles(input_handles, {jit_num_args});"
    )

For a const_graph, the AOTI side skips steal_from_raw_handles_to_raii_handles (no input_handles param for _const_run_impl), but the JIT side always emits it. This is correct because the JIT entry point receives constants as appended input handles — the comment confirms this. Good.

4. generate_before_suffix doesn't close const_graph in dual-wrapper JIT mode (potential issue)

cpp_wrapper_cpu.py:1549-1556:

def generate_before_suffix(self, result):
    if V.graph.aot_mode and not V.graph.is_dual_wrapper_mode:
        entry = "_const_run_impl" if V.graph.is_const_graph else "run_impl"
        result.writeline(f"}} // {self.aoti_model_class_name}::{entry}")
    else:
        result.writeline("} // inductor_entry_impl")

For a const_graph in dual-wrapper-mode, this emits } // inductor_entry_impl to result (the JIT side). But the AOTI close brace is in _generate_end_aoti at line 1572: aot_result.writeline(f"}} // {self.aoti_model_class_name}::{entry}"). This is correct — the JIT const graph has its own inductor_entry_impl wrapper, and the AOTI const graph's _const_run_impl is closed separately. The logic is sound.

5. Potential issue with aot_call_args using "stream" while JIT uses stream{device_idx} (correctness observation)

cpp_wrapper_gpu.py:1580-1581:

jit_call_args = [*call_args, jit_device_idx, stream]
aot_call_args = [*call_args, aoti_device_idx, "stream"]

Here stream is the return value of write_get_raw_stream(device.index, graph_name), which in dual-wrapper-mode returns f"stream{device_idx}" (line 1112-1117). So jit_call_args uses stream0 (correct for the JIT side). The aot_call_args hardcodes "stream" which is the run_impl parameter name. This is correct since write_get_raw_stream in pure-AOTI returns "stream" and in dual-wrapper returns the JIT variable name — the AOTI side needs the function parameter which is just stream.

6. Fallback kernel dual-wrapper code captures into DualIndentedBuffer but wraps in DualWrapperCodeLine (subtle correctness)

cpp_wrapper_cpu.py:2926-2954:

jit_code = DualIndentedBuffer(initial_indent=self.wrapper_call._indent)
with (
    self._target_buf("wrapper_call", jit_code),
    self.set_writeline(jit_code, jit_code.writeline_jit),
):
    self._generate_fallback_kernel_jit(...)

aot_code = DualIndentedBuffer(initial_indent=self.wrapper_call._indent)
with (
    self._target_buf("wrapper_call", aot_code),
    self.set_writeline(aot_code, aot_code.writeline_aot),
):
    self.generate_fallback_kernel_with_runtime_lookup_aot(...)

self.writeline(DualWrapperCodeLine(jit_code, aot_code))

The DualWrapperCodeLine.codegen method calls code.splice_jit(self.jit_code) and code.splice_aot(self.aot_code). When jit_code is a DualIndentedBuffer, splice_jit (which on DualIndentedBuffer calls IndentedBuffer.splice(self, other_code)) will splice the JIT side of jit_code (the IndentedBuffer base). Since set_writeline redirects to writeline_jit, the JIT content goes to the base IndentedBuffer part. Similarly, aot_code with writeline_aot routes content to .aot. Then splice_aot(self.aot_code) on a DualIndentedBuffer will call self.aot.splice(aot_code.aot). This is correct.

However, there's an interesting asymmetry: jit_code is itself a DualIndentedBuffer, so when splice_jit is called on a DualIndentedBuffer target, it calls IndentedBuffer.splice(self, jit_code). Since jit_code is a DualIndentedBuffer, this splices the JIT side (base buffer) — correct. But if any method inside _generate_fallback_kernel_jit calls writeline (not writeline_jit), that writes to both sides of jit_code. Since set_writeline overrides the writeline dispatch to writeline_jit, this should be fine. This is complex but correct.


Non-blocking observations

7. _python_source_literal handles """ but not r"""

graph.py:2618-2624:

if '"""' in source:
    return f"{name} = {source!r}\n"
return f'{name} = (\nr"""\n{source}"""\n)\n'

If the source contains """ (triple quotes), it falls back to repr(). This is fine since C++ code rarely contains literal """. But if it ever does contain \ sequences that repr would escape, the repr'd string would differ from the original. Since this is only used for logging/repro scripts, not for actual compilation, this is non-blocking.

8. stream_ vs stream naming in generated code

In _generate_lazy_launch, the shared kernel call uses stream_ (the wrapper function's parameter, line 597). In the non-lazy Triton call path (generate_kernel_call), the AOTI side uses "stream" (the run_impl parameter, line 1581). These are different variables in the generated C++ — stream_ is the lazy wrapper's parameter while stream is run_impl's. The lazy wrappers are self-contained functions that receive stream_ as an arg, while the main call site passes stream (AOTI) or stream0 (JIT) to those wrappers. This is correct but the naming inconsistency between stream_ (lazy wrapper param) and stream (run_impl param) could confuse future contributors.

9. The not V.graph.is_const_graph guard removed from generate_before_suffix

The old code had:

if not V.graph.is_const_graph:
    if V.graph.aot_mode: ...
    else: ...

The new code always enters generate_before_suffix for const_graphs too. In dual-wrapper-mode, const_graphs hit the else branch and emit } // inductor_entry_impl. This is now needed because the JIT const graph wrapper does have an inductor_entry_impl to close. The AOTI const graph's _const_run_impl close is handled in _generate_end_aoti. This is a behavioral change from the old code where const_graphs skipped generate_before_suffix entirely — worth verifying this doesn't emit a spurious close-brace in pure-AOTI const_graph mode (it shouldn't, since V.graph.aot_mode and not V.graph.is_dual_wrapper_mode is true there, and the correct entry name _const_run_impl is used).


Overall

The PR is in good shape. The only actionable bug is the missing spaces in the error message at cpp_wrapper_gpu.py:89-92 (issue #1). The architecture is well-designed, buffer type dispatch is correct across all three modes, and tensor lifetime management is safe. The DualWrapperCodeLine pattern for fallback kernels is complex but correctly leverages the splice dispatch semantics.


[ghstack-poisoned]
[ghstack-poisoned]
@desertfire
desertfire requested a review from yushangdi May 28, 2026 13:37
@@ -561,7 +582,7 @@ def write_prefix(self):
"""
)
if V.graph.aot_mode:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

do we still need the if V.graph.aot_mode: check with writeline_aot?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

You are right to question. No, we don't need it.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

should we remove the check?

[ghstack-poisoned]
[ghstack-poisoned]
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #184736

[ghstack-poisoned]
[ghstack-poisoned]
@desertfire desertfire added the ciflow/trunk Trigger trunk jobs on your pull request label Jun 9, 2026
[ghstack-poisoned]
[ghstack-poisoned]
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #184736

pytorchmergebot pushed a commit that referenced this pull request Jun 10, 2026
…184736)

Emit cond and while_loop as DualWrapperCodeLine entries so the dual-wrapper codegen can route the predicate-guarded body to the AOTI side while running the JIT first pass through both branches (cond) or both subgraphs once (while_loop) for lazy autotune. Introduce _preserve_codegen_state and _preserve_device_guard_state so wrapper bookkeeping is restored between the JIT and AOTI passes over the same subgraphs.

Update test_cond_with_replace_view_ops to use aoti_compile_and_package, and drop the cond/while_loop skips from AOTInductorTestDualWrapper now that the dual-wrapper path supports them.

Authored with Codex.

Pull Request resolved: #184736
Approved by: https://github.com/yushangdi
ghstack dependencies: #184735
jemitche1 pushed a commit to jemitche1/pytorch that referenced this pull request Jun 13, 2026
Switch the AOTI lazy-autotune path to emit separate JIT and AOTI C++ wrapper bodies in one codegen pass. The JIT body is compiled and run with real inputs to populate lazy Triton kernel metadata, then the generated AOTI source includes the captured kernel config for packaging.

Add test_aot_inductor variant that runs with triton.autotune_at_compile_time=False so this path is exercised. torch.cond and torch.while_loop are not yet wired up for the dual-wrapper path and are skipped in this variant; a follow-up commit adds support for them.

Example generated code:
[JIT wrapper code](https://gist.github.com/desertfire/c699cb01ea1b1c53c94761cf94c101bd)
[AOT wrapper code](https://gist.github.com/desertfire/b565adb51eb3d9438501a84301ac6ca3)

Authored with Codex.

Pull Request resolved: pytorch#184735
Approved by: https://github.com/yushangdi
jemitche1 pushed a commit to jemitche1/pytorch that referenced this pull request Jun 13, 2026
…ytorch#184736)

Emit cond and while_loop as DualWrapperCodeLine entries so the dual-wrapper codegen can route the predicate-guarded body to the AOTI side while running the JIT first pass through both branches (cond) or both subgraphs once (while_loop) for lazy autotune. Introduce _preserve_codegen_state and _preserve_device_guard_state so wrapper bookkeeping is restored between the JIT and AOTI passes over the same subgraphs.

Update test_cond_with_replace_view_ops to use aoti_compile_and_package, and drop the cond/while_loop skips from AOTInductorTestDualWrapper now that the dual-wrapper path supports them.

Authored with Codex.

Pull Request resolved: pytorch#184736
Approved by: https://github.com/yushangdi
ghstack dependencies: pytorch#184735
pytorchmergebot pushed a commit that referenced this pull request Jun 16, 2026
)

# Motivation
#184735 introduces AOTI lazy autotuning with the dual-wrapper mechanism, which uncovered some new XPU test failures in CI.

# Additonal Context
Fix #187124
Fix #187123
Fix #187035
Fix #187035
Fix #187036
Fix #187125
Fix #187121

This needs to be cherry-picked to the release branch.

Pull Request resolved: #187137
Approved by: https://github.com/EikanWang, https://github.com/atalman
ghstack dependencies: #181233
atalman pushed a commit that referenced this pull request Jun 16, 2026
)

[xpu][fix] Include kernel_compile_result.h in aoti xpu.h header (#187137)

# Motivation
#184735 introduces AOTI lazy autotuning with the dual-wrapper mechanism, which uncovered some new XPU test failures in CI.

# Additonal Context
Fix #187124
Fix #187123
Fix #187035
Fix #187035
Fix #187036
Fix #187125
Fix #187121

This needs to be cherry-picked to the release branch.

Pull Request resolved: #187137
Approved by: https://github.com/EikanWang, https://github.com/atalman
ghstack dependencies: #181233

(cherry picked from commit 6ec77b0)

Co-authored-by: Yu, Guangye <[email protected]>
@github-actions
github-actions Bot deleted the gh/desertfire/732/head branch July 11, 2026 02:24
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
Switch the AOTI lazy-autotune path to emit separate JIT and AOTI C++ wrapper bodies in one codegen pass. The JIT body is compiled and run with real inputs to populate lazy Triton kernel metadata, then the generated AOTI source includes the captured kernel config for packaging.

Add test_aot_inductor variant that runs with triton.autotune_at_compile_time=False so this path is exercised. torch.cond and torch.while_loop are not yet wired up for the dual-wrapper path and are skipped in this variant; a follow-up commit adds support for them.

Example generated code:
[JIT wrapper code](https://gist.github.com/desertfire/c699cb01ea1b1c53c94761cf94c101bd)
[AOT wrapper code](https://gist.github.com/desertfire/b565adb51eb3d9438501a84301ac6ca3)

Authored with Codex.

Pull Request resolved: pytorch#184735
Approved by: https://github.com/yushangdi
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…ytorch#184736)

Emit cond and while_loop as DualWrapperCodeLine entries so the dual-wrapper codegen can route the predicate-guarded body to the AOTI side while running the JIT first pass through both branches (cond) or both subgraphs once (while_loop) for lazy autotune. Introduce _preserve_codegen_state and _preserve_device_guard_state so wrapper bookkeeping is restored between the JIT and AOTI passes over the same subgraphs.

Update test_cond_with_replace_view_ops to use aoti_compile_and_package, and drop the cond/while_loop skips from AOTInductorTestDualWrapper now that the dual-wrapper path supports them.

Authored with Codex.

Pull Request resolved: pytorch#184736
Approved by: https://github.com/yushangdi
ghstack dependencies: pytorch#184735
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…rch#187137)

# Motivation
pytorch#184735 introduces AOTI lazy autotuning with the dual-wrapper mechanism, which uncovered some new XPU test failures in CI.

# Additonal Context
Fix pytorch#187124
Fix pytorch#187123
Fix pytorch#187035
Fix pytorch#187035
Fix pytorch#187036
Fix pytorch#187125
Fix pytorch#187121

This needs to be cherry-picked to the release branch.

Pull Request resolved: pytorch#187137
Approved by: https://github.com/EikanWang, https://github.com/atalman
ghstack dependencies: pytorch#181233
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
Switch the AOTI lazy-autotune path to emit separate JIT and AOTI C++ wrapper bodies in one codegen pass. The JIT body is compiled and run with real inputs to populate lazy Triton kernel metadata, then the generated AOTI source includes the captured kernel config for packaging.

Add test_aot_inductor variant that runs with triton.autotune_at_compile_time=False so this path is exercised. torch.cond and torch.while_loop are not yet wired up for the dual-wrapper path and are skipped in this variant; a follow-up commit adds support for them.

Example generated code:
[JIT wrapper code](https://gist.github.com/desertfire/c699cb01ea1b1c53c94761cf94c101bd)
[AOT wrapper code](https://gist.github.com/desertfire/b565adb51eb3d9438501a84301ac6ca3)

Authored with Codex.

Pull Request resolved: pytorch#184735
Approved by: https://github.com/yushangdi
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…ytorch#184736)

Emit cond and while_loop as DualWrapperCodeLine entries so the dual-wrapper codegen can route the predicate-guarded body to the AOTI side while running the JIT first pass through both branches (cond) or both subgraphs once (while_loop) for lazy autotune. Introduce _preserve_codegen_state and _preserve_device_guard_state so wrapper bookkeeping is restored between the JIT and AOTI passes over the same subgraphs.

Update test_cond_with_replace_view_ops to use aoti_compile_and_package, and drop the cond/while_loop skips from AOTInductorTestDualWrapper now that the dual-wrapper path supports them.

Authored with Codex.

Pull Request resolved: pytorch#184736
Approved by: https://github.com/yushangdi
ghstack dependencies: pytorch#184735
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…rch#187137)

# Motivation
pytorch#184735 introduces AOTI lazy autotuning with the dual-wrapper mechanism, which uncovered some new XPU test failures in CI.

# Additonal Context
Fix pytorch#187124
Fix pytorch#187123
Fix pytorch#187035
Fix pytorch#187035
Fix pytorch#187036
Fix pytorch#187125
Fix pytorch#187121

This needs to be cherry-picked to the release branch.

Pull Request resolved: pytorch#187137
Approved by: https://github.com/EikanWang, https://github.com/atalman
ghstack dependencies: pytorch#181233
pytorchmergebot pushed a commit that referenced this pull request Aug 5, 2026
…0637)

## Summary

Skip the CUDA-specific stream event codegen (`_aoti_aux_stream_cache` helpers) in the AOTI `cpp_wrapper` for XPU devices. SYCL in-order queues handle events implicitly, making the generated CUDA stream cache code unnecessary and incompatible.

## Root Cause

PR [#182971](#182971) (Jul 8, 2026) added `codegen_stream_info_prologue()` to `cpp_wrapper_gpu.py`, which emits `_aoti_aux_stream_cache.ensure(...)` — a CUDA-specific stream cache helper. When a model uses `torch.Event()`, the AOTI compiler detects `num_strams > 1` and enters this codegen path, generating code that references CUDA-only symbols.

For the XPU backend, these CUDA stream helpers are not needed because:
- SYCL in-order queues handle event synchronization implicitly
- The generated code causes compilation/link errors on XPU

This affected the `AOTInductorTestDualWrapper` test class specifically because it uses `autotune_at_compile_time=False` (lazy Triton compile), which triggers the dual-wrapper codegen path that exercises the multi-stream codegen.

## Timeline

| Date | Event |
|------|-------|
| Jun 10 | `AOTInductorTestDualWrapper` added (PR #184735) — running fine |
| **Jul 8** | **User-streams support added (PR #182971) — introduced CUDA stream codegen** |
| Jul 9 | Auto-disabler detected test failure, created issues #189327 and #189326 |
| Jul 15 | PR #189980 submitted with barrier chaining fix in Copy.cpp |
| Jul 17 | Reviewer rejected barrier fix as unnecessary overhead |
| Jul 21 | **This PR** — correct root cause identified |

## Notes on PR #189980

The earlier PR #189980 attempted to fix this by capturing the `sycl::event` from `q.memcpy()` and chaining it with `ext_oneapi_submit_barrier({copy_event})` in `Copy.cpp`. That approach was rejected by the reviewer ([comment](intel/torch-xpu-ops#4349 (comment))) as adding unnecessary overhead, and has since been determined to be unrelated to the actual root cause. The DMA engine event tracking gap described there is a separate PVC driver-level issue that does not reproduce on the tested hardware configuration (driver 1.6.33578+15, all D2H non_blocking copy tests pass without the barrier workaround).

## Test Plan

- `test_copy_non_blocking_is_pinned_xpu` on both `AOTInductorTestDualWrapper` and `AOTInductorTestABICompatibleGpu`
- Full XPU CI suite

Fixes #189327
Fixes #189326

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants