Skip to content

[inductor][aoti] Use the graph id, not id(self), to make each lazy-autotune JIT first pass unique - #203025

Closed
ezyang wants to merge 2 commits into
pytorch:mainfrom
ezyang:ooo/D128931135
Closed

ezyang wants to merge 2 commits into
pytorch:mainfrom
ezyang:ooo/D128931135

Conversation

@ezyang

@ezyang ezyang commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

GraphLowering._run_jit_variant_for_autotune appends id(self) to the JIT wrapper source so every AOTI lazy-compile first pass builds a fresh wrapper. The JIT wrapper keeps its lazy Triton kernels in function-local statics, and CppWrapperCodeCache caches loaded modules in-process by a hash of the source.

id(self) is not unique over a process lifetime: once a GraphLowering is freed, a later one can get the same id. When the same model is compiled twice in one process (as test_sym_i64_input_codegen does: once through run_and_get_cpp_code, then again in check_model) and the second graph reuses the first graph's id, the JIT source is byte-identical, so the cache hands back the already-loaded module whose kernel statics are already initialized. The lazy kernels never recompile, CudaKernelParamCache (just cleared for these names) is never repopulated, and generate_aoti_kernel_config_header raises:

RuntimeError: When autotune_at_compile_time is False, AOTInductor generates both JIT code and AOT code. They are expected to have exactly the same kernels. However, AOT code contains kernels, ['triton_poi_fused_zeros_like_0', 'triton_poi_fused_ones_1', 'add_kernel_0'], that is not in the JIT code.

Whether the id is reused depends on allocator state, which is why the test fails only on some internal CI runs (first attempt fails, retry passes) and passes in stress runs.

This uses self.post_grad_graph_id instead: every GraphLowering takes it from the module-level _post_grad_graph_counter in __init__, so it never repeats within a process. Across processes a shared on-disk artifact is fine, because a newly loaded module starts with fresh statics.

Clearing the in-process CppWrapperCodeCache entry after the first pass was considered instead; reusing the existing per-graph id is smaller and keeps the existing "fresh wrapper per first pass" design.

Test plan:

python test/inductor/test_aot_inductor.py -k test_sym_i64_input_codegen_cuda

3 passed, 0 failed on A100. The existing test_sym_i64_input_codegen is the regression coverage: it compiles the same model twice in one process. The failure depends on a Python object id being reused, so a passing run cannot prove the fix on its own; the fix removes the dependency on id().

This PR was written by an AI agent (the PT2 oncall's Oncall Operator, revised by @ezyang's agent) and submitted by @ezyang, who authorized it.

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

…une JIT first pass unique

`GraphLowering._run_jit_variant_for_autotune` appends `id(self)` to the JIT wrapper source so every AOTI lazy-compile first pass builds a fresh wrapper. The JIT wrapper keeps its lazy Triton kernels in function-local statics, and `CppWrapperCodeCache` caches loaded modules in-process by a hash of the source.

`id(self)` is not unique over a process lifetime: once a `GraphLowering` is freed, a later one can get the same id. When the same model is compiled twice in one process (as `test_sym_i64_input_codegen` does: once through `run_and_get_cpp_code`, then again in `check_model`) and the second graph reuses the first graph's id, the JIT source is byte-identical, so the cache hands back the already-loaded module whose kernel statics are already initialized. The lazy kernels never recompile, `CudaKernelParamCache` (just cleared for these names) is never repopulated, and `generate_aoti_kernel_config_header` raises:

```
RuntimeError: When autotune_at_compile_time is False, AOTInductor generates both JIT code and AOT code. They are expected to have exactly the same kernels. However, AOT code contains kernels, ['triton_poi_fused_zeros_like_0', 'triton_poi_fused_ones_1', 'add_kernel_0'], that is not in the JIT code.
```

Whether the id is reused depends on allocator state, which is why the test fails only on some internal CI runs (first attempt fails, retry passes) and passes in stress runs.

This uses a module-level `itertools.count()` instead, which never repeats within a process. Across processes a shared on-disk artifact is fine, because a newly loaded module starts with fresh statics.

Clearing the in-process `CppWrapperCodeCache` entry after the first pass was considered instead; a monotonic counter is smaller and keeps the existing "fresh wrapper per first pass" design.

Test plan:

```
python test/inductor/test_aot_inductor.py -k test_sym_i64_input_codegen_cuda
```

3 passed, 0 failed on A100. The existing `test_sym_i64_input_codegen` is the regression coverage: it compiles the same model twice in one process. The failure depends on a Python object id being reused, so a passing run cannot prove the fix on its own; the fix removes the dependency on `id()`.

This PR was written by an AI agent (the PT2 oncall's Oncall Operator) and submitted by @ezyang, who authorized it.
@pytorch-bot

pytorch-bot Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

Please fix all CI failures and trigger merge by commenting "@pytorchbot merge".

✅ AUTOMATED REVIEW - Ready for human review:

The PR replaces `id(self)` with `self.post_grad_graph_id` as the suffix on the
AOTI lazy-autotune JIT wrapper source, so two GraphLowering instances in one
process can't produce byte-identical JIT source that hits CppWrapperCodeCache.
Recommendation: Approve, since no issues were found and nothing blocks merging.

Reviewed commit: d1ad9fc

Review run

🐛 Report a bad review

🔗 Helpful Links

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

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

✅ No Failures

As of commit d1ad9fc with merge base c685ca3 (image):
💚 Looks good so far! There are no failures yet. 💚

🟡 GREEN LIGHT - PR requires human review:

  • Cache key
    • The marker line feeds cpp_source, which CppWrapperCodeCache.load_pybinding hashes as main_code to key the compiled wrapper
    • Swapping id(self) for post_grad_graph_id makes that key repeat across processes, so on-disk JIT wrappers now get reused across runs
  • Triviality
    • Single-cause bugfix needs a test in the diff or no cache-key output; the diff adds no test and the change is the cache key
    • The PR body says the existing test_sym_i64_input_codegen cannot prove the fix, since the failure depends on id() reuse
  • Correctness
    • Looks sound: post_grad_graph_id is next(_post_grad_graph_counter) in GraphLowering.__init__ and nothing resets the counter
    • A human should confirm that cross-process reuse of the lazy-autotune wrapper is intended

reason: not_trivial
Reviewed commit: d1ad9fc

Inference job

🐛 Report a wrong verdict

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

@ezyang
ezyang requested a review from desertfire November 2, 2026 14:21
@pytorchgreenlight pytorchgreenlight Bot added the GL/human GreenLight marked as needing human review label Nov 2, 2026
@ezyang ezyang added autoland mergedog mergedog is watching this PR labels Nov 2, 2026

@ezyang ezyang left a comment

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.

(Posted by GPT-6 Astra, an AI assistant, on behalf of @ezyang.)

One non-blocking follow-up for pre-existing host-wrapper cache churn.

Comment thread torch/_inductor/graph.py Outdated
cpp_source += f"\n// AOTI lazy autotune first pass: {id(self)}\n"
# id(self) is not unique: a later graph can reuse a freed graph's id.
first_pass_id = next(_jit_autotune_first_pass_counter)
cpp_source += f"\n// AOTI lazy autotune first pass: {first_pass_id}\n"

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.

(Posted by GPT-6 Astra, an AI assistant, on behalf of @ezyang.)

Non-blocking, pre-existing performance issue to track in a separate follow-up: this still makes persistent host-wrapper cache identity depend on compilation history. CppPythonBindingsCodeCache.load_pybinding_async passes this text to CppCodeCache.load_async, whose kernel_key hashes the full main_code; that key determines both the on-disk *.main.cpp/shared-library path and the loaded-module identity. Consequently, recompiling identical lazy AOTI graphs in a long-lived process accumulates wrapper binaries and loaded modules, and a warm fresh process misses if earlier lazy AOTI passes shifted the counter. id(self) already had this problem and usually prevented reuse across fresh processes; the counter permits reuse when the pass order matches, but is not a stable per-program key.

Please separate stable compiled-code identity from per-pass lazy state in that follow-up, e.g. an explicit session/state object that owns the pending kernels and initialized handles and ensures CudaKernelParamCache is repopulated for each pass. Merely dropping CppWrapperCodeCache.cache[key] is insufficient: _load_library_inner also reuses sys.modules, and native-library statics need a real state-lifetime solution. Validate identical fresh-process runs, a run with an unrelated lazy AOTI compile first, and repeated compiles in one process against the same cache directory. This finding concerns the temporary host wrapper, not a token leaking into the final AOTI source or individual Triton/autotune keys.

@pytorchbot pytorchbot added the in progress PR is being worked on by the author, until the automated review accepts it label Nov 2, 2026
github-actions[bot]

This comment was marked as outdated.

@ezyang ezyang changed the title [inductor][aoti] Use a counter, not id(self), to make each lazy-autotune JIT first pass unique [inductor][aoti] Use the graph id, not id(self), to make each lazy-autotune JIT first pass unique Nov 2, 2026

@github-actions github-actions Bot left a comment

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.

Automated review of d1ad9fc: nothing blocking; ready for human review.

The PR replaces id(self) with self.post_grad_graph_id as the suffix on the AOTI lazy-autotune JIT wrapper source, so two GraphLowering instances in one process can't produce byte-identical JIT source that hits CppWrapperCodeCache. Recommendation: Approve, since no issues were found and nothing blocks merging.

This review is AI-generated and advisory. Each new automated review replaces the previous one.

@ezyang

ezyang commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

mergedog handoff

Note

This PR is being shepherded by mergedog, an automation tool run by a maintainer. It watches CI and may push fixes; the PR author does not need to act unless a maintainer asks.

All CI is green (or skipped). Ready for human review and @pytorchbot merge.

Current PR head: 0bf94c9598e10473e74a72938a7e51d9c2037aba.
No mergedog-authored commits were pushed during this run.

No LLM was invoked during this run.

@pytorch-bot pytorch-bot Bot added ready for review Automated review passed, ready for a final review by a maintainer. and removed in progress PR is being worked on by the author, until the automated review accepts it labels Nov 2, 2026
@ezyang

ezyang commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

@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

dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 5, 2026
…totune JIT first pass unique (pytorch#203025)

`GraphLowering._run_jit_variant_for_autotune` appends `id(self)` to the JIT wrapper source so every AOTI lazy-compile first pass builds a fresh wrapper. The JIT wrapper keeps its lazy Triton kernels in function-local statics, and `CppWrapperCodeCache` caches loaded modules in-process by a hash of the source.

`id(self)` is not unique over a process lifetime: once a `GraphLowering` is freed, a later one can get the same id. When the same model is compiled twice in one process (as `test_sym_i64_input_codegen` does: once through `run_and_get_cpp_code`, then again in `check_model`) and the second graph reuses the first graph's id, the JIT source is byte-identical, so the cache hands back the already-loaded module whose kernel statics are already initialized. The lazy kernels never recompile, `CudaKernelParamCache` (just cleared for these names) is never repopulated, and `generate_aoti_kernel_config_header` raises:

```
RuntimeError: When autotune_at_compile_time is False, AOTInductor generates both JIT code and AOT code. They are expected to have exactly the same kernels. However, AOT code contains kernels, ['triton_poi_fused_zeros_like_0', 'triton_poi_fused_ones_1', 'add_kernel_0'], that is not in the JIT code.
```

Whether the id is reused depends on allocator state, which is why the test fails only on some internal CI runs (first attempt fails, retry passes) and passes in stress runs.

This uses `self.post_grad_graph_id` instead: every `GraphLowering` takes it from the module-level `_post_grad_graph_counter` in `__init__`, so it never repeats within a process. Across processes a shared on-disk artifact is fine, because a newly loaded module starts with fresh statics.

Clearing the in-process `CppWrapperCodeCache` entry after the first pass was considered instead; reusing the existing per-graph id is smaller and keeps the existing "fresh wrapper per first pass" design.

Test plan:

```
python test/inductor/test_aot_inductor.py -k test_sym_i64_input_codegen_cuda
```

3 passed, 0 failed on A100. The existing `test_sym_i64_input_codegen` is the regression coverage: it compiles the same model twice in one process. The failure depends on a Python object id being reused, so a passing run cannot prove the fix on its own; the fix removes the dependency on `id()`.

This PR was written by an AI agent (the PT2 oncall's Oncall Operator, revised by @ezyang's agent) and submitted by @ezyang, who authorized it.

Pull Request resolved: pytorch#203025
Approved by: https://github.com/desertfire
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 9, 2026
…totune JIT first pass unique (pytorch#203025)

`GraphLowering._run_jit_variant_for_autotune` appends `id(self)` to the JIT wrapper source so every AOTI lazy-compile first pass builds a fresh wrapper. The JIT wrapper keeps its lazy Triton kernels in function-local statics, and `CppWrapperCodeCache` caches loaded modules in-process by a hash of the source.

`id(self)` is not unique over a process lifetime: once a `GraphLowering` is freed, a later one can get the same id. When the same model is compiled twice in one process (as `test_sym_i64_input_codegen` does: once through `run_and_get_cpp_code`, then again in `check_model`) and the second graph reuses the first graph's id, the JIT source is byte-identical, so the cache hands back the already-loaded module whose kernel statics are already initialized. The lazy kernels never recompile, `CudaKernelParamCache` (just cleared for these names) is never repopulated, and `generate_aoti_kernel_config_header` raises:

```
RuntimeError: When autotune_at_compile_time is False, AOTInductor generates both JIT code and AOT code. They are expected to have exactly the same kernels. However, AOT code contains kernels, ['triton_poi_fused_zeros_like_0', 'triton_poi_fused_ones_1', 'add_kernel_0'], that is not in the JIT code.
```

Whether the id is reused depends on allocator state, which is why the test fails only on some internal CI runs (first attempt fails, retry passes) and passes in stress runs.

This uses `self.post_grad_graph_id` instead: every `GraphLowering` takes it from the module-level `_post_grad_graph_counter` in `__init__`, so it never repeats within a process. Across processes a shared on-disk artifact is fine, because a newly loaded module starts with fresh statics.

Clearing the in-process `CppWrapperCodeCache` entry after the first pass was considered instead; reusing the existing per-graph id is smaller and keeps the existing "fresh wrapper per first pass" design.

Test plan:

```
python test/inductor/test_aot_inductor.py -k test_sym_i64_input_codegen_cuda
```

3 passed, 0 failed on A100. The existing `test_sym_i64_input_codegen` is the regression coverage: it compiles the same model twice in one process. The failure depends on a Python object id being reused, so a passing run cannot prove the fix on its own; the fix removes the dependency on `id()`.

This PR was written by an AI agent (the PT2 oncall's Oncall Operator, revised by @ezyang's agent) and submitted by @ezyang, who authorized it.

Pull Request resolved: pytorch#203025
Approved by: https://github.com/desertfire
jeanschmidt added a commit to pytorch/test-infra that referenced this pull request Nov 12, 2026
…r any merge-rule approver (#9417)

🏖️ nmc:

**Impact:** GreenLight's review policy
(`.claude/skills/greenlight-review/SKILL.md`) is rewritten as one linear
decision procedure with broader, generic rules, and GreenLight
eligibility widens to every approver `merge_rules.yaml` names, on any
path. Each of the 12 open GreenLight feedback reports would get the
opposite verdict (LAND). Other PRs are expected to flip to LAND along
the way.

**Risk:** High, by design: it eases review gates. The skill goes live on
merge. The eligibility change goes live in two steps. The record job and
the `@greenlight recheck` path run `greenlight` from test-infra `main`,
so they change on merge. The scheduled scan changes only with the next
greenlight-scan Lambda release. Merge first and release right after. In
between:
- a recheck of an approver's PR outside their merge-rule paths gets a
LAND approval, which the old scan's next pass dismisses;
- PRs the old scan dispatches on a base trymerge refuses end as shadow
verdicts, and Dr. CI shows them as not completed.

Neither loops. The accepted risks are listed under Notes.

## What

### The reports this flips

| Report | PR | What GreenLight objected to | Root cause in the policy |
|---|---|---|---|
| #9098 | pytorch/pytorch#200725 | Flex-attention config pruning on
sm_10x, for a Triton miscompile. Objections: "kernel config selection"
counts as numerics; a new default config; a 5th argument to the
subclassable `InductorChoices` hook; tests miss the pruned autotune
lists | Numerics covered config tuning; "moves a default" and "a caller
outside the diff" were not limited to what users rely on; no class for a
hardware-scoped workaround; tests expected for every branch |
| #9093 | pytorch/pytorch#200126 | `HIDDEN_NAMESPACE_BEGIN` on more
`torch/headeronly` headers: a linkage change, "correct but
consequential", no class fits | The "Correct but consequential" shape;
no class for applying a pattern the checkout already uses (41 headeronly
files used the macro before); linkage treated as API |
| #9140 | pytorch/pytorch#201160 | Docs toctree move: "navigation
markup, not prose"; docs owners may weigh in | Documentation meant prose
only; "a reviewer might ask" sent taste questions to humans |
| #8885 | pytorch/pytorch#198501 | Python 3.10 to 3.11 in periodic, slow
and periodic-strict. Objections: ~30 sites; a coverage shift; job-name
history moves; "confirm it is intended" | Breadth counted sites, not
unchecked sites; "removes coverage" applied to CI that gates no merge;
job names treated as parsed output; intent questions sent to humans |
| #9291 | pytorch/pytorch#202759 | Lowered a perf floor (1.5x to 1.2x)
on non-HIP GPUs: "re-baselined test"; is 1.2x enough? | The test hard
stop covered performance thresholds; the test classes were a closed
list; the "would a reviewer ask" question |
| #9230 | pytorch/pytorch#202224 | Flaky-test fix (warm up, then
reseed): not a skip, xfail or message; first-call RNG coverage | Closed
list; the "would a reviewer ask" question |
| #9259 | pytorch/pytorch#202242 | SM-count skip that also skips some
cases that would fit; "could ask for an occupancy bound" | "Wider than
its guard"; the "would a reviewer ask" question |
| #9359 | pytorch/pytorch#203688 | One new assert in a helper under
`torch/testing/_internal/`: outside `test/`; 17 tests, only 10 run
locally | The test classes stopped at `test/`; "confirm it passes in CI"
sent to a human |
| #9358 | pytorch/pytorch#203742 | Filters cuBLAS-internal profiler
events out of an expected trace: "weakened assertion"; the filter now
applies on every CUDA version | The test hard stop covered checks of
another library's internals; closed list |
| #9329, #9335 | pytorch/pytorch#203292 | Never reviewed: the author is
named only by a path-scoped merge rule (`c10/util/**`) | Eligibility
required one rule naming the author to cover every changed file |
| #9304 | pytorch/pytorch#203025 | One-line bugfix in a JIT-wrapper
cache-key marker with no test in the diff; "confirm cross-process reuse
is intended" | The bugfix class needed a test in the diff, or a change
that leaves nothing lasting (a cache key does); the author's runs did
not count; intent questions sent to humans |

### The broad changes

| # | Change | Flips (report: PR) |
|---|---|---|
| C1 | One linear decision order; only defects send a PR to a human |
Every report needs it: it removes the "would a reviewer ask" question,
its repeat in criterion 8, and "Correct but consequential" |
| C2 | What the PR's text can tell you: reported runs are facts | #9359:
#203688, #9304: #203025, #9098: #200725 |
| C3 | Test code is one class; the only stop is weakening checks of
PyTorch's own results | #9291: #202759, #9230: #202224, #9259: #202242,
#9359: #203688, #9358: #203742 |
| C4 | Bug fixes need evidence, not a new test; platform-scoped
workarounds are included | #9304: #203025, #9098: #200725 |
| C5 | Numerics means changing the math, not choosing a kernel | #9098:
#200725 |
| C6 | The user-facing surface, defined concretely | #9098: #200725,
#9093: #200126, #8885: #198501 |
| C7 | Applying an established pattern is a class | #9093: #200126
(helps #9230, #9358, #9140, #8885) |
| C8 | Documentation includes its structure | #9140: #201160 |
| C9 | CI coverage rules bind merge-gating workflows; hiding failure is
always a stop | #8885: #198501 |
| C10 | Breadth counts unchecked sites, not sites | #8885: #198501 |
| C11 | Merge authorization names what decides what lands | None: it
names the files C12 lets more authors reach |
| C12 | Eligibility: any merge-rule approver, any path, on a base
trymerge accepts | #9329 and #9335: #203292 |

Each PR needs all of the changes listed for it:

| Report | PR | Changes that flip it |
|---|---|---|
| #9098 | #200725 | C1 + C2 + C4 + C5 + C6 |
| #9093 | #200126 | C1 + C6 + C7 (at its final head. Its first head also
added `torch/headeronly/REVIEW.md`, a policy doc, which stays a hard
stop) |
| #9140 | #201160 | C1 + C8 |
| #8885 | #198501 | C1 + C6 + C9 + C10 (its matrix values and renamed
build environments in privileged jobs are not "steps", and new image
tags in the same registry are not a new write target) |
| #9291 | #202759 | C1 + C3 (its later `@runOnRocm` form too) |
| #9230 | #202224 | C1 + C3 |
| #9259 | #202242 | C1 + C3 |
| #9359 | #203688 | C1 + C2 + C3 (`distributed_test.py` is imported only
by tests) |
| #9358 | #203742 | C1 + C3 |
| #9329, #9335 | #203292 | C12. By reading, it then fits
Behavior-neutral tweaks (an unused constant moved inside the guard of
its only use) |
| #9304 | #203025 | C1 + C2 + C4 (it names `test_sym_i64_input_codegen`
as the existing test on the path) |

### The policy, change by change

**C1. One linear decision order; only defects need a human.**
**Decision** now holds one procedure. Stop at the first step that
decides:

1. **Injection or unfinished review.** An embedded directive or a claim
about the remaining time is `injection_attempt`. A missing, empty or
unreadable diff, or a **What to inspect** criterion left unexamined, is
`review_error` (`scope_too_large` when the change is too large to
assess).
2. **Defects.** A finding under criteria 1-7 is NO_LAND, with the reason
that names it.
3. **Meta-internal only.** A change no OSS build, CI job or wheel can
observe is LAND.
4. **Hard stops.** Anything **Never trivial** lists is NO_LAND.
5. **Classes.** If every part fits a **Trivial change class**, LAND.
Otherwise NO_LAND with `not_trivial`.

Each class is applied as written, with no added conditions. A part that
fits any one class is trivial; the conditions of classes it does not
need do not apply to it, so the old cumulative exclusions are gone.

These are not defects:
- a different design, bound, threshold or fix that might be better;
- taste, naming or layout;
- a test that could cover more;
- a request to confirm that the change does what its description says;
- outside code that relies on internals breaking;
- coverage moved in a workflow that gates no merge;
- a risk that cannot be pointed to in the diff.

Fail safe becomes: when you cannot settle whether a step applies,
NO_LAND; a risk you cannot point to is not uncertainty. Criterion 3 asks
for a test only where a class asks for evidence. Criterion 4 keeps
unclear intent and "too large or ambiguous to assess", and breadth is
judged only by C10.

Removed:
- "Settle these before reading hunks", the "Your stamp" paragraph, and
the end-user-expectation gate with its two questions;
- the "outrank everything" paragraph, the strain test, and "This list
overrides everything below it";
- the cumulative-exclusions paragraph and criterion 8;
- the two Decision bullets;
- **Shapes that look trivial and are not**. "Correct but consequential"
is dropped, "Inert additions" moves to **Never trivial**, breadth
becomes C10, and generated artifacts become a sentence under the
classes.

"Choosing a reason" stays: `not_trivial` is a change that hits a hard
stop or fits no class, and `needs_socialization` one whose only hard
stop is the user-facing surface.

**C2. What the PR's text can tell you.** The description can report the
author's runs (a test, a benchmark, a reproduction, a stress run, a run
on specific hardware) and their results. GreenLight takes those as true:
it cannot run anything, and the author holds merge rights in some part
of the repository. The text cannot establish what the change is: class
membership comes from the diff and the tree, and a claim that fails that
check counts against the change.

Comments are not the description. Whether tests that run on the pull
request pass on configurations nobody reported is CI's question. An
argument that refusing costs too much is not evidence. Text the diff
adds (comments, docstrings, docs) is a claim, not evidence; a test in
the diff counts through what its code does. Reported runs are evidence
for a class's conditions; they never clear a defect visible in the diff
or a hard stop the change hits.

**C3. Test changes are one class.** It covers any change confined to
test code: files under `test/`, and files under
`torch/testing/_internal/` that only test code imports. Test runners
(`test/run_test.py`, `conftest.py` files, `tools/testing/`, `run_tests`)
are CI configuration, not test code.

Typical test changes:
- adding tests or checks;
- making a flaky test deterministic by controlling state it does not
check;
- adapting a test to details outside PyTorch's control;
- skipping or limiting a test where it cannot run or where such a detail
makes it fail, even with a conservative guard;
- updating an expected message;
- setting performance or timing thresholds to what the hardware
supports.

The only test hard stop is a check of PyTorch's own results weakened
with no source change behind it: an assertion deleted, skipped where the
test can run (with no detail outside PyTorch's control, such as hardware
size or speed, a driver or toolkit version, or third-party code, behind
the skip, as the checkout or a reported run shows), or its expected
value changed. PyTorch's own results are the values and exception types
its code produces. Message wording, performance, timing and the output
of code outside PyTorch are not.

**C4. Single-cause bugfix.** The PR has one root cause, which the
description or the diff explains, and one fix that reading confirms
removes or avoids it. The fix may take effect only on the hardware,
driver, toolkit or build where the bug shows. It may avoid an outside
cause (a compiler or library bug) instead of removing it, and its
plumbing (an optional parameter, a capability check) is part of it.

Evidence is a test in the diff, an existing test on the path, or a run
the description reports. A fix that changes a cache key, a serialized
artifact, or the files written or deleted needs a test in the diff or an
existing test on the path. Not when the fix changes user-facing behavior
beyond removing the bug, turns an error into a quieter outcome the
documentation did not promise, or keys on a CI or test environment.

**C5. Numerics means changing the math.** That is formulas, precision,
dtypes, numerical tolerances (in code or tests), and an accumulation
order the algorithm specifies. Choosing among kernel configurations,
tile or block sizes, autotuning candidates or backends that implement
the same math is performance tuning, even when it changes rounding.

**C6. The user-facing surface.** One hard stop replaces three earlier
items: the end-user-expectation question, "an expectation a PyTorch user
could reasonably hold", and "Deprecating or removing anything public".
It stops on removing, deprecating or renaming something PyTorch offers
outside code, or changing its signature, a default, a limit or its
documented behavior. It also stops on changing the shape of output
something parses.

What PyTorch offers:
- the public Python API: no underscore in the import path, or listed in
a `docs/source` autodoc entry;
- the C++ extension API: what `docs/cpp` and `docs/source/accelerator`
document, `torch/headeronly`, `torch/csrc/stable`, and libtorch's
exported symbols;
- configuration users set (config modules such as
`torch._inductor.config`, and environment variables);
- formats users save.

Parsed output is output that the repository shows something matches, or
that test-infra, the HUD and Dr. CI read. A job name is parsed only
through the workflow names `merge_rules.yaml` and
`update-viablestrict.yml` list. Everything else is internal: private
modules, internal heuristics and their defaults, extension points under
a private import path, and the linkage of header-only code.

**C7. Established patterns.** A new class: applying a construct the
checkout already uses for the same purpose, the same way, at new sites
of the same kind. Those sites are the same file or module, sibling
workflows, or the code a comment or doc says the construct is for. Lines
the diff adds do not establish a pattern. The reviewer judges
faithfulness, not the pattern's merit.

**C8. Documentation includes its structure.** This covers wording,
examples, headings, toctrees and navigation, cross-links, and page moves
that keep URLs. Not when the code may be the defect, when it adds or
changes a download or install link or command, embeds raw HTML or
script, or adds or removes an autodoc entry. `docs/source/conf.py` and
policy docs stay hard stops.

**C9. CI coverage rules bind merge-gating workflows.** A workflow gates
merges when it runs on every pull request, when
`update-viablestrict.yml`'s `requires` list names it, or when such a
workflow calls it. In other workflows, version bumps, renamed jobs and
images, and added or dropped configurations are their owners' call.

**CI and build configuration** is a class with no exclusions. Everything
that used to exclude a CI change is a hard stop, so no class can reach
it:

- **CI privilege and merge gating**, a new hard stop, covers:
- OIDC roles, `pull_request_target`, and generated workflows or their
generators;
- a step added or edited in a job that holds secrets or an OIDC role, or
in an action or reusable workflow such a job uses, or in a script such a
job runs (test code and PyTorch's own source are not such scripts;
matrix values and reusable-workflow inputs are not steps);
- a change to which bucket, registry, repository, table or branch a
workflow writes to or deletes from;
- a `uses:` outside the `pytorch` org, or a step moved out of the build
container;
  - a test job added to `pull.yml` or `trunk.yml`;
  - coverage removed in a merge-gating workflow.
- **Security**, an existing hard stop, now names secrets, tokens,
permissions, runner trust boundaries, and release or publish plumbing
(the workflows that publish wheels, conda packages, docs and release
tags).
- **Hiding CI failure**, a new hard stop, catches a test or job that
still runs and fails but no longer blocks what it blocked. Examples:
`continue-on-error`, `|| true` on a test step, a name gaining
`unstable`, a workflow dropped from `requires`, or an exit status
ignored in `run_test.py`, a `conftest.py` or `run_tests`.

**Pinned third-party code**, a new hard stop: moving a submodule or a
commit pin of third-party code (such as `ci_commit_pins/`), pointing a
requirement at a commit, branch or URL instead of a released version, or
changing a pinned version of third-party code built into or published
with PyTorch's released artifacts. None of the reports is such a bump.

**C10. Breadth counts unchecked sites.** "Edits at sites you have not
checked" replaces "Breadth disguised as simplicity". A repeated edit is
one change when every site follows one mechanical rule and every site
was checked, by reading them or by searching for what is left of the old
form. The number of sites is not a reason on its own. A change to a
definition other tests are generated from (an OpInfo's or ModuleInfo's
dtypes, devices or samples, the dtypes or devices a device-type test
template is instantiated for, a shared parametrization list) is an edit
at every test that iterates it, suites that do not run on pull requests
included: the reviewer checks that each consumer handles what the change
adds, or the description reports a run that covers them.

**C11. Merge authorization.** One item names `.github/merge_rules.yaml`,
`.github/scripts/trymerge.py`, `.github/scripts/tryrebase.py`,
`.github/scripts/greenlight_*.py`, the modules those scripts import, and
anything else deciding who or what may approve or land a PR. It absorbs
the separate land-time-guard item.

**Re-landing a reverted change**, a new hard stop: the PR, or a commit
it applies again, was reverted from main, and the description does not
say what broke and what in the diff fixes it (which the reviewer
confirms by reading the diff).

**Test gates are traced.** Under criterion 1 (Correctness), for every
class: the reviewer traces what a skip, expected failure or other gate
does with its condition's value, on the platforms it names and on the
others, reading the gate's own implementation where the checkout has it
(for `unittest` or `pytest` gates, the condition's own type settles it).
A gate whose effect differs from what its condition says (wider,
narrower, or a no-op, as with a decorator that acts only on a real
`bool` handed a lazily evaluated object) is a finding.

These last three come from replaying the policy against historical
GreenLight PRs that were later reverted. An OpInfo dtype widening broke
a slow-only suite (pytorch/pytorch#198860). A version of a test-gating
change handed a lazily evaluated value to a skip decorator that only
acts on a real `bool`, so the skip did nothing (pytorch/pytorch#198689).
And the reviewer should not stamp re-lands blind. None of the 12 reports
above is affected.

**Also in the skill:**
- The opening says the author "holds merge rights in some part of the
repository".
- Only three hard stops apply on the path alone: executable docs build
configuration, pytorch's `.claude/` and `.agents/` trees and instruction
files, and merge authorization. Every other hard stop is decided by what
the change does.
- **Meta-internal only** covers code and build files only (never
documentation or instruction files), and never a file one of those three
path items names.
- pytorch's AI-assistant instruction files (`CLAUDE.md`,
`CLAUDE.local.md`, `AGENTS.md`, `.cursorrules`,
`.github/copilot-instructions.md`) join the `.claude/` hard stop, and so
does the `.agents/` tree, where pytorch's skills live.
- Established patterns: a defect at a new site is still a defect.
- The examples drop the "Socialization" topic.
- Unchanged: Type annotations, the mechanical-formatting paragraph,
Output Contract fields and reasons, Message format rules, Time budget,
and the rest of Security.

### C12. Eligibility (greenlight code)

A PR is eligible when a valid rule in pytorch/pytorch's
`.github/merge_rules.yaml` names its author in exact case, and trymerge
accepts its base (`main`, a ghstack PR, or a PR in a GitHub-native stack
on `main`), whatever files it changes. The review decides whether it
needs a human.

- `cohort.assess_rules` no longer reads files. A rule whose patterns
trymerge rejects still qualifies nobody (`MergeRule.valid`).
- The scan applies trymerge's base test from the listing's own fields,
with no extra GitHub request. `authority.Authority` becomes a pure
lookup.
- Dropped on purpose, along with the files read:
  - its failure, rate-limit and undetermined paths;
- the head deferral for a push that raced the files read, and the
deferred `--pr` recheck that came with it;
- the reasons "file listing unavailable" and "no single merge rule
naming this login covers all changed files".
- The `--pr` gate checks the author and the base on the PR it already
fetches.
- At record time, `verdict.has_eligible_author` (renamed from
`has_covering_rule`) makes one fresh read. The verdict is authoritative
only when the head is still the reviewed head, the base is accepted and
a valid rule names the author. Catch-all authors get the head and base
check too.
- A PR over 200 files is now dispatched and gets the workflow's canned
`scope_too_large` NO_LAND.
- `TRUSTED_AUTHORS.md`, `STATUS_LABELS.md`, `README.md`, `CLAUDE.md`,
`CHEATSHEET.md`, the CLI help, the workflows' comments and
`tools/torchci/greenlight_decisions/README.md` are updated.

## Why

The 12 open GreenLight feedback reports are all trivial-in-spirit PRs
that GreenLight sent to a human, or never reviewed. The policy had three
parallel decision procedures: the two triviality questions that "outrank
everything", criterion 8, which repeated them, and the Decision bullets.
Fixing one left the others refusing.

Its rules were also built from per-case exceptions, and the open
follow-up stack (#9127-#9130, #9295-#9298) continues that style: one
kind added to one class per case. By its own replays that stack still
leaves #9098, #9093, #9140 and #8885 refused, and it does not touch
#9359, #9358, #9304 or #9329/#9335.

This PR replaces that with broad rules a person can read, each simple
and linear: no rule carves an exception out of another. Easing gates is
the point. Flipping other PRs to LAND along the way is expected, and the
areas where a mistake is costly stay hard stops: security, CI privilege,
merge authorization, publishing, the reviewer's own instructions, and
hiding CI failure.

Judged by reading the policy against each report; no evals or replays
were run for this.

# Notes

- **Supersedes** #9127, #9128, #9130, #9295, #9296, #9297 and #9298.
Their generic parts are folded in: #9128's API definition, #9130's
reported runs, and #9298's defects-only idea, generalized. #9129
(performance grounding) is not needed for these flips and is left as is.
- **Follow-ups once the greenlight-scan release is live**:
- Dr. CI's GreenLight line
(`torchci/lib/greenlight/greenlightEligibility.ts`, a port of
`assess_rules`) still renders "can't be reviewed due to
`merge_rules.yaml` restrictions" for PRs outside an approver's paths. It
is left unchanged here because the HUD deploys on every push to `main`
and would advertise reviews before the scan runs them.
- Dr. CI's port also shows "waiting for review" for an approver named by
a catch-all rule on any base, so once the release is live a PR on a base
trymerge refuses would show that until the port learns the base test.
- pytorch/pytorch `CONTRIBUTING.md` ("## GreenLight") describes the old
eligibility rule.
- **Accepted risks, stated as what is no longer checked**:
- About 80 logins named only by path-scoped merge rules can now land
anywhere on a LAND: GreenLight's approval satisfies the `*` Greenlight
Review Bot rule. The hard stops still send security, CI privilege, merge
authorization, publishing and release plumbing to a human.
- The reviewed base is not bound at land time for any approver: the
"base not bound" exposure in `TRUSTED_AUTHORS.md` now covers every
approver. Binding the reviewed merge base belongs in pytorch's land-time
guard and is a separate change.
- Kernel-configuration changes, private extension points and header-only
linkage changes land without a human (C5, C6).
- Coverage can drop silently in workflows that gate no merge,
label-triggered ones included (C9).
- Runs the description reports are taken as true (C2), and
platform-scoped fixes often have no pre-merge CI on that platform (C4).
- A pattern with a flaw can be copied to new sites of the same kind
(C7).
  - Dropped conditions:
- C3 drops "production code rejects the skipped case" and "no wider than
its guard";
    - C4 drops "no value shared across configurations that differ";
    - C1 drops the cumulative class exclusions;
    - criterion 4 drops "sprawl across many subsystems";
- #9127's job-name rules and #9296's "still runs on full-size devices"
are not carried over.
- A catch-all author's PR on a base trymerge refuses has GreenLight's
approval dismissed. If it is later retargeted to `main`, it is not
re-reviewed until its fingerprint changes. A retarget between the scan
and the record can leave a review shown as not completed.
- **Pushes run the policy replay**: later pushes to this branch run
`greenlight-policy-replay.yml`, because it touches the skill.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

autoland ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request GL/human GreenLight marked as needing human review Merged mergedog mergedog is watching this PR module: inductor ready for review Automated review passed, ready for a final review by a maintainer. release notes: inductor (aoti)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants