Repository navigation
Conversation
…ation [ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/178351
Note: Links to docs will display an error until the docs builds have been completed. ❗ 1 Active SEVsThere are 1 currently active SEVs. If your PR is affected, please view them below: ✅ No FailuresAs of commit 5ff95e9 with merge base 3a3756a ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
This PR needs a
|
|
Some notes
|
| # With isolated_region, use per-region compilation count instead | ||
| # of global num_cache_entries. The C++ region_id isolates cache | ||
| # lookup; this isolates the limit check. | ||
| if cache_size.will_compilation_exceed_accumulated_limit(): | ||
| exceeded, limit_type = True, "accumulated_recompile_limit" | ||
| elif cache_size.region_num_compilations >= config.recompile_limit: | ||
| exceeded, limit_type = True, "recompile_limit" | ||
| else: | ||
| exceeded, limit_type = False, "" | ||
| else: | ||
| exceeded, limit_type = exceeds_recompile_limit(cache_size, compile_id) |
There was a problem hiding this comment.
This will make things quite hard to diagnose on a recompile tbh
There was a problem hiding this comment.
This is right. Would you suggest adding the region_id to the error message?
There was a problem hiding this comment.
I think we should evaluate the pros and cons of this approach against cloning the code object itself #178347
There was a problem hiding this comment.
For this approach, we should provide some way of identifying the region (perhaps id is not informative enough)
… cache isolation"
## Summary
Cache entries in Dynamo are stored per code object. When multiple `torch.compile()` calls
target the same function, their cache entries are interleaved on the same linked list. This
causes cross-region interference: one region's compilations affect another region's cache
lookup, recompile limit checks, and `FrameExecStrategy`.
`torch.compile(f, isolated_cache=True)` gives each compile region its own isolated cache:
1. **C++ `region_id`** — each `CacheEntry` is tagged with a region_id. `lookup()` filters
entries by region_id, so each region only sees its own entries.
2. **Python `_region_compilation_counts`** — tracks per-region, per-code-object compilation
counts. Uses `max` across all code objects in the region (including resume functions from
graph breaks) so that once any code object hits the limit, all compilation in the region
stops.
Regions without `isolated_cache` (region_id = -1) use the shared cache as before.
## Visualization
```
ExtraState (per code object)
└── cache_entry_list
├── CacheEntry { guards, code, backend, region_id=0 } ← from opt_f
├── CacheEntry { guards, code, backend, region_id=0 } ← from opt_f
├── CacheEntry { guards, code, backend, region_id=1 } ← from opt_g
└── CacheEntry { guards, code, backend, region_id=-1 } ← no region set
```
```
def test_region_id_cache_entries_visual(self):
cnt1 = torch._dynamo.testing.CompileCounter()
cnt2 = torch._dynamo.testing.CompileCounter()
def f(x):
return x.sin()
opt_f = torch.compile(f, backend=cnt1, isolated_cache=True)
opt_g = torch.compile(f, backend=cnt2, isolated_cache=True)
opt_f(torch.randn(3))
opt_f(torch.randn(3, dtype=torch.float64))
opt_g(torch.randn(4))
# Print cache entries showing region_id
entries = torch._dynamo.eval_frame._debug_get_cache_entry_list(f)
for i, entry in enumerate(entries):
print(f"CacheEntry[{i}]: region_id={entry.region_id}, compile_id={entry.compile_id}")
```
This would output something like:
CacheEntry[0]: region_id=0, compile_id=0/0 ← from opt_f
CacheEntry[1]: region_id=0, compile_id=0/1 ← from opt_f
CacheEntry[2]: region_id=1, compile_id=0/2 ← from opt_g
## Use cases
### Static vs dynamic on same function
```python
magic_static = torch.compile(magic, dynamic=False, isolated_cache=True)
magic_dynamic = torch.compile(magic, dynamic=True, isolated_cache=True)
# Each has its own cache — static entries don't interfere with dynamic entries
```
### Shared PGO
With `isolated_cache`, PGO (`frame_state`) is still shared across regions on the same
code object. Region B benefits from region A's shape observations — faster convergence
to dynamic shapes without redundant compilations.
## Changes
**C++:**
- `cache_entry.h/cpp`: `region_id` field on `CacheEntry`, `get_region_id()` helper
- `extra_state.h/cpp`: `lookup()` filters by `region_id`
- `eval_frame_cpp.cpp`: Extracts `region_id` from callback and passes to `lookup()`
- `init.cpp`: Exposes `region_id` via pybind
**Python:**
- `torch/__init__.py`: `isolated_cache: bool = False` kwarg on `torch.compile()`
- `torch/_dynamo/eval_frame.py`: Threads `isolated_cache` through `_optimize` / `optimize_assert`
- `torch/_dynamo/convert_frame.py`: `_isolated_cache`, `_region_id`, `_region_compilation_counts`
on `ConvertFrameAssert`. Global limit override and `apply_to_code` fix in error handler.
- `torch/_dynamo/cache_size.py`: `isolated_cache` and `region_num_compilations` fields
- `torch/_dynamo/types.py`: `region_id` on `GuardedCode`
- `torch/_dynamo/resume_execution.py`: `get_all_resume_code_objects` helper
## Test Plan
- `test_isolated_cache_same_function_different_regions` — two regions on same function, independent caches
- `test_isolated_cache_factory_pattern` — factory pattern with `fail_on_recompile_limit_hit=True`
- `test_isolated_cache_static_and_dynamic` — static vs dynamic on same function
- `test_isolated_cache_fullgraph_raises` — fullgraph contract honored
- `test_isolated_cache_two_models_independent` — two model compiles don't interfere
- `test_isolated_cache_mark_dynamic_vs_static` — mark_static and mark_dynamic coexist
- `test_isolated_cache_auto_dynamic_shared_pgo` — PGO sharing across isolated regions
- `test_isolated_cache_explicit_dispatch_static_vs_dynamic` — explicit dispatch without exclusion guards
- `test_global_recompile_limit_resume_function` — documents existing per-code-object behavior
cc voznesenskym penguinwu EikanWang jgong5 Guobing-Chen XiaobingSuper zhuhaozhe blzheng wenzhe-nrv jiayisunx kadeng chauhang amjames Lucaskabela jataylo mlazos
[ghstack-poisoned]
… cache isolation"
## Summary
Cache entries in Dynamo are stored per code object. When multiple `torch.compile()` calls
target the same function, their cache entries are interleaved on the same linked list. This
causes cross-region interference: one region's compilations affect another region's cache
lookup, recompile limit checks, and `FrameExecStrategy`.
`torch.compile(f, isolated_cache=True)` gives each compile region its own isolated cache:
1. **C++ `region_id`** — each `CacheEntry` is tagged with a region_id. `lookup()` filters
entries by region_id, so each region only sees its own entries.
2. **Python `_region_compilation_counts`** — tracks per-region, per-code-object compilation
counts. Uses `max` across all code objects in the region (including resume functions from
graph breaks) so that once any code object hits the limit, all compilation in the region
stops.
Regions without `isolated_cache` (region_id = -1) use the shared cache as before.
## Visualization
```
ExtraState (per code object)
└── cache_entry_list
├── CacheEntry { guards, code, backend, region_id=0 } ← from opt_f
├── CacheEntry { guards, code, backend, region_id=0 } ← from opt_f
├── CacheEntry { guards, code, backend, region_id=1 } ← from opt_g
└── CacheEntry { guards, code, backend, region_id=-1 } ← no region set
```
```
def test_region_id_cache_entries_visual(self):
cnt1 = torch._dynamo.testing.CompileCounter()
cnt2 = torch._dynamo.testing.CompileCounter()
def f(x):
return x.sin()
opt_f = torch.compile(f, backend=cnt1, isolated_cache=True)
opt_g = torch.compile(f, backend=cnt2, isolated_cache=True)
opt_f(torch.randn(3))
opt_f(torch.randn(3, dtype=torch.float64))
opt_g(torch.randn(4))
# Print cache entries showing region_id
entries = torch._dynamo.eval_frame._debug_get_cache_entry_list(f)
for i, entry in enumerate(entries):
print(f"CacheEntry[{i}]: region_id={entry.region_id}, compile_id={entry.compile_id}")
```
This would output something like:
CacheEntry[0]: region_id=0, compile_id=0/0 ← from opt_f
CacheEntry[1]: region_id=0, compile_id=0/1 ← from opt_f
CacheEntry[2]: region_id=1, compile_id=0/2 ← from opt_g
## Use cases
### Static vs dynamic on same function
```python
magic_static = torch.compile(magic, dynamic=False, isolated_cache=True)
magic_dynamic = torch.compile(magic, dynamic=True, isolated_cache=True)
# Each has its own cache — static entries don't interfere with dynamic entries
```
### Shared PGO
With `isolated_cache`, PGO (`frame_state`) is still shared across regions on the same
code object. Region B benefits from region A's shape observations — faster convergence
to dynamic shapes without redundant compilations.
## Changes
**C++:**
- `cache_entry.h/cpp`: `region_id` field on `CacheEntry`, `get_region_id()` helper
- `extra_state.h/cpp`: `lookup()` filters by `region_id`
- `eval_frame_cpp.cpp`: Extracts `region_id` from callback and passes to `lookup()`
- `init.cpp`: Exposes `region_id` via pybind
**Python:**
- `torch/__init__.py`: `isolated_cache: bool = False` kwarg on `torch.compile()`
- `torch/_dynamo/eval_frame.py`: Threads `isolated_cache` through `_optimize` / `optimize_assert`
- `torch/_dynamo/convert_frame.py`: `_isolated_cache`, `_region_id`, `_region_compilation_counts`
on `ConvertFrameAssert`. Global limit override and `apply_to_code` fix in error handler.
- `torch/_dynamo/cache_size.py`: `isolated_cache` and `region_num_compilations` fields
- `torch/_dynamo/types.py`: `region_id` on `GuardedCode`
- `torch/_dynamo/resume_execution.py`: `get_all_resume_code_objects` helper
## Test Plan
- `test_isolated_cache_same_function_different_regions` — two regions on same function, independent caches
- `test_isolated_cache_factory_pattern` — factory pattern with `fail_on_recompile_limit_hit=True`
- `test_isolated_cache_static_and_dynamic` — static vs dynamic on same function
- `test_isolated_cache_fullgraph_raises` — fullgraph contract honored
- `test_isolated_cache_two_models_independent` — two model compiles don't interfere
- `test_isolated_cache_mark_dynamic_vs_static` — mark_static and mark_dynamic coexist
- `test_isolated_cache_auto_dynamic_shared_pgo` — PGO sharing across isolated regions
- `test_isolated_cache_explicit_dispatch_static_vs_dynamic` — explicit dispatch without exclusion guards
- `test_global_recompile_limit_resume_function` — documents existing per-code-object behavior
cc voznesenskym penguinwu EikanWang jgong5 Guobing-Chen XiaobingSuper zhuhaozhe blzheng wenzhe-nrv jiayisunx kadeng chauhang amjames Lucaskabela jataylo mlazos
[ghstack-poisoned]
… cache isolation"
## Summary
Cache entries in Dynamo are stored per code object. When multiple `torch.compile()` calls
target the same function, their cache entries are interleaved on the same linked list. This
causes cross-region interference: one region's compilations affect another region's cache
lookup, recompile limit checks, and `FrameExecStrategy`.
`torch.compile(f, isolated_cache=True)` gives each compile region its own isolated cache:
1. **C++ `region_id`** — each `CacheEntry` is tagged with a region_id. `lookup()` filters
entries by region_id, so each region only sees its own entries.
2. **Python `_region_compilation_counts`** — tracks per-region, per-code-object compilation
counts. Uses `max` across all code objects in the region (including resume functions from
graph breaks) so that once any code object hits the limit, all compilation in the region
stops.
Regions without `isolated_cache` (region_id = -1) use the shared cache as before.
## Visualization
```
ExtraState (per code object)
└── cache_entry_list
├── CacheEntry { guards, code, backend, region_id=0 } ← from opt_f
├── CacheEntry { guards, code, backend, region_id=0 } ← from opt_f
├── CacheEntry { guards, code, backend, region_id=1 } ← from opt_g
└── CacheEntry { guards, code, backend, region_id=-1 } ← no region set
```
```
def test_region_id_cache_entries_visual(self):
cnt1 = torch._dynamo.testing.CompileCounter()
cnt2 = torch._dynamo.testing.CompileCounter()
def f(x):
return x.sin()
opt_f = torch.compile(f, backend=cnt1, isolated_cache=True)
opt_g = torch.compile(f, backend=cnt2, isolated_cache=True)
opt_f(torch.randn(3))
opt_f(torch.randn(3, dtype=torch.float64))
opt_g(torch.randn(4))
# Print cache entries showing region_id
entries = torch._dynamo.eval_frame._debug_get_cache_entry_list(f)
for i, entry in enumerate(entries):
print(f"CacheEntry[{i}]: region_id={entry.region_id}, compile_id={entry.compile_id}")
```
This would output something like:
CacheEntry[0]: region_id=0, compile_id=0/0 ← from opt_f
CacheEntry[1]: region_id=0, compile_id=0/1 ← from opt_f
CacheEntry[2]: region_id=1, compile_id=0/2 ← from opt_g
## Use cases
### Factory pattern
Multiple `torch.compile()` wrappers around the same inner function:
```python
cache
def factory(key):
torch.compile(fullgraph=True, isolated_cache=True)
def frontend(x, n):
return core(x) + n
return frontend
factory("foo")(torch.ones(3), 3) # compiles
factory("bar")(torch.ones(4), 3) # compiles (separate region)
factory("baz")(torch.ones(5), 3) # compiles (separate region)
```
### Static vs dynamic on same function
```python
magic_static = torch.compile(magic, dynamic=False, isolated_cache=True)
magic_dynamic = torch.compile(magic, dynamic=True, isolated_cache=True)
# Each has its own cache — static entries don't interfere with dynamic entries
```
### Shared PGO
With `isolated_cache`, PGO (`frame_state`) is still shared across regions on the same
code object. Region B benefits from region A's shape observations — faster convergence
to dynamic shapes without redundant compilations.
## Changes
**C++:**
- `cache_entry.h/cpp`: `region_id` field on `CacheEntry`, `get_region_id()` helper
- `extra_state.h/cpp`: `lookup()` filters by `region_id`
- `eval_frame_cpp.cpp`: Extracts `region_id` from callback and passes to `lookup()`
- `init.cpp`: Exposes `region_id` via pybind
**Python:**
- `torch/__init__.py`: `isolated_cache: bool = False` kwarg on `torch.compile()`
- `torch/_dynamo/eval_frame.py`: Threads `isolated_cache` through `_optimize` / `optimize_assert`
- `torch/_dynamo/convert_frame.py`: `_isolated_cache`, `_region_id`, `_region_compilation_counts`
on `ConvertFrameAssert`. Global limit override and `apply_to_code` fix in error handler.
- `torch/_dynamo/cache_size.py`: `isolated_cache` and `region_num_compilations` fields
- `torch/_dynamo/types.py`: `region_id` on `GuardedCode`
- `torch/_dynamo/resume_execution.py`: `get_all_resume_code_objects` helper
## Test Plan
- `test_isolated_cache_same_function_different_regions` — two regions on same function, independent caches
- `test_isolated_cache_factory_pattern` — factory pattern with `fail_on_recompile_limit_hit=True`
- `test_isolated_cache_static_and_dynamic` — static vs dynamic on same function
- `test_isolated_cache_fullgraph_raises` — fullgraph contract honored
- `test_isolated_cache_two_models_independent` — two model compiles don't interfere
- `test_isolated_cache_mark_dynamic_vs_static` — mark_static and mark_dynamic coexist
- `test_isolated_cache_auto_dynamic_shared_pgo` — PGO sharing across isolated regions
- `test_isolated_cache_explicit_dispatch_static_vs_dynamic` — explicit dispatch without exclusion guards
- `test_global_recompile_limit_resume_function` — documents existing per-code-object behavior
cc voznesenskym penguinwu EikanWang jgong5 Guobing-Chen XiaobingSuper zhuhaozhe blzheng wenzhe-nrv jiayisunx kadeng chauhang amjames Lucaskabela jataylo mlazos
[ghstack-poisoned]
… cache isolation"
## Summary
Cache entries in Dynamo are stored per code object. When multiple `torch.compile()` calls
target the same function, their cache entries are interleaved on the same linked list. This
causes cross-region interference: one region's compilations affect another region's cache
lookup, recompile limit checks, and `FrameExecStrategy`.
`torch.compile(f, isolated_cache=True)` gives each compile region its own isolated cache:
1. **C++ `region_id`** — each `CacheEntry` is tagged with a region_id. `lookup()` filters
entries by region_id, so each region only sees its own entries.
2. **Python `_region_compilation_counts`** — tracks per-region, per-code-object compilation
counts. Uses `max` across all code objects in the region (including resume functions from
graph breaks) so that once any code object hits the limit, all compilation in the region
stops.
Regions without `isolated_cache` (region_id = -1) use the shared cache as before.
## Visualization
```
ExtraState (per code object)
└── cache_entry_list
├── CacheEntry { guards, code, backend, region_id=0 } ← from opt_f
├── CacheEntry { guards, code, backend, region_id=0 } ← from opt_f
├── CacheEntry { guards, code, backend, region_id=1 } ← from opt_g
└── CacheEntry { guards, code, backend, region_id=-1 } ← no region set
```
```
def test_region_id_cache_entries_visual(self):
cnt1 = torch._dynamo.testing.CompileCounter()
cnt2 = torch._dynamo.testing.CompileCounter()
def f(x):
return x.sin()
opt_f = torch.compile(f, backend=cnt1, isolated_cache=True)
opt_g = torch.compile(f, backend=cnt2, isolated_cache=True)
opt_f(torch.randn(3))
opt_f(torch.randn(3, dtype=torch.float64))
opt_g(torch.randn(4))
# Print cache entries showing region_id
entries = torch._dynamo.eval_frame._debug_get_cache_entry_list(f)
for i, entry in enumerate(entries):
print(f"CacheEntry[{i}]: region_id={entry.region_id}, compile_id={entry.compile_id}")
```
This would output something like:
CacheEntry[0]: region_id=0, compile_id=0/0 ← from opt_f
CacheEntry[1]: region_id=0, compile_id=0/1 ← from opt_f
CacheEntry[2]: region_id=1, compile_id=0/2 ← from opt_g
## Use cases
### Factory pattern
Multiple `torch.compile()` wrappers around the same inner function:
```python
cache
def factory(key):
torch.compile(fullgraph=True, isolated_cache=True)
def frontend(x, n):
return core(x) + n
return frontend
factory("foo")(torch.ones(3), 3) # compiles
factory("bar")(torch.ones(4), 3) # compiles (separate region)
factory("baz")(torch.ones(5), 3) # compiles (separate region)
```
### Static vs dynamic on same function
```python
magic_static = torch.compile(magic, dynamic=False, isolated_cache=True)
magic_dynamic = torch.compile(magic, dynamic=True, isolated_cache=True)
# Each has its own cache — static entries don't interfere with dynamic entries
```
### Shared PGO
With `isolated_cache`, PGO (`frame_state`) is still shared across regions on the same
code object. Region B benefits from region A's shape observations — faster convergence
to dynamic shapes without redundant compilations.
## Changes
**C++:**
- `cache_entry.h/cpp`: `region_id` field on `CacheEntry`, `get_region_id()` helper
- `extra_state.h/cpp`: `lookup()` filters by `region_id`
- `eval_frame_cpp.cpp`: Extracts `region_id` from callback and passes to `lookup()`
- `init.cpp`: Exposes `region_id` via pybind
**Python:**
- `torch/__init__.py`: `isolated_cache: bool = False` kwarg on `torch.compile()`
- `torch/_dynamo/eval_frame.py`: Threads `isolated_cache` through `_optimize` / `optimize_assert`
- `torch/_dynamo/convert_frame.py`: `_isolated_cache`, `_region_id`, `_region_compilation_counts`
on `ConvertFrameAssert`. Global limit override and `apply_to_code` fix in error handler.
- `torch/_dynamo/cache_size.py`: `isolated_cache` and `region_num_compilations` fields
- `torch/_dynamo/types.py`: `region_id` on `GuardedCode`
- `torch/_dynamo/resume_execution.py`: `get_all_resume_code_objects` helper
## Test Plan
- `test_isolated_cache_same_function_different_regions` — two regions on same function, independent caches
- `test_isolated_cache_factory_pattern` — factory pattern with `fail_on_recompile_limit_hit=True`
- `test_isolated_cache_static_and_dynamic` — static vs dynamic on same function
- `test_isolated_cache_fullgraph_raises` — fullgraph contract honored
- `test_isolated_cache_two_models_independent` — two model compiles don't interfere
- `test_isolated_cache_mark_dynamic_vs_static` — mark_static and mark_dynamic coexist
- `test_isolated_cache_auto_dynamic_shared_pgo` — PGO sharing across isolated regions
- `test_isolated_cache_explicit_dispatch_static_vs_dynamic` — explicit dispatch without exclusion guards
- `test_global_recompile_limit_resume_function` — documents existing per-code-object behavior
cc voznesenskym penguinwu EikanWang jgong5 Guobing-Chen XiaobingSuper zhuhaozhe blzheng wenzhe-nrv jiayisunx kadeng chauhang amjames Lucaskabela jataylo mlazos
[ghstack-poisoned]
… cache isolation"
## Summary
Cache entries in Dynamo are stored per code object. When multiple `torch.compile()` calls
target the same function, their cache entries are interleaved on the same linked list. This
causes cross-region interference: one region's compilations affect another region's cache
lookup, recompile limit checks, and `FrameExecStrategy`.
`torch.compile(f, isolated_cache=True)` gives each compile region its own isolated cache:
1. **C++ `region_id`** — each `CacheEntry` is tagged with a region_id. `lookup()` filters
entries by region_id, so each region only sees its own entries.
2. **Python `_region_compilation_counts`** — tracks per-region, per-code-object compilation
counts. Uses `max` across all code objects in the region (including resume functions from
graph breaks) so that once any code object hits the limit, all compilation in the region
stops.
Regions without `isolated_cache` (region_id = -1) use the shared cache as before.
## Visualization
```
ExtraState (per code object)
└── cache_entry_list
├── CacheEntry { guards, code, backend, region_id=0 } ← from opt_f
├── CacheEntry { guards, code, backend, region_id=0 } ← from opt_f
├── CacheEntry { guards, code, backend, region_id=1 } ← from opt_g
└── CacheEntry { guards, code, backend, region_id=-1 } ← no region set
```
```
def test_region_id_cache_entries_visual(self):
cnt1 = torch._dynamo.testing.CompileCounter()
cnt2 = torch._dynamo.testing.CompileCounter()
def f(x):
return x.sin()
opt_f = torch.compile(f, backend=cnt1, isolated_cache=True)
opt_g = torch.compile(f, backend=cnt2, isolated_cache=True)
opt_f(torch.randn(3))
opt_f(torch.randn(3, dtype=torch.float64))
opt_g(torch.randn(4))
# Print cache entries showing region_id
entries = torch._dynamo.eval_frame._debug_get_cache_entry_list(f)
for i, entry in enumerate(entries):
print(f"CacheEntry[{i}]: region_id={entry.region_id}, compile_id={entry.compile_id}")
```
This would output something like:
CacheEntry[0]: region_id=0, compile_id=0/0 ← from opt_f
CacheEntry[1]: region_id=0, compile_id=0/1 ← from opt_f
CacheEntry[2]: region_id=1, compile_id=0/2 ← from opt_g
## Use cases
### Factory pattern
Multiple `torch.compile()` wrappers around the same inner function:
```python
cache
def factory(key):
torch.compile(fullgraph=True, isolated_cache=True)
def frontend(x, n):
return core(x) + n
return frontend
factory("foo")(torch.ones(3), 3) # compiles
factory("bar")(torch.ones(4), 3) # compiles (separate region)
factory("baz")(torch.ones(5), 3) # compiles (separate region)
```
### Static vs dynamic on same function
```python
magic_static = torch.compile(magic, dynamic=False, isolated_cache=True)
magic_dynamic = torch.compile(magic, dynamic=True, isolated_cache=True)
# Each has its own cache — static entries don't interfere with dynamic entries
```
### Shared PGO
With `isolated_cache`, PGO (`frame_state`) is still shared across regions on the same
code object. Region B benefits from region A's shape observations — faster convergence
to dynamic shapes without redundant compilations.
## Changes
**C++:**
- `cache_entry.h/cpp`: `region_id` field on `CacheEntry`, `get_region_id()` helper
- `extra_state.h/cpp`: `lookup()` filters by `region_id`
- `eval_frame_cpp.cpp`: Extracts `region_id` from callback and passes to `lookup()`
- `init.cpp`: Exposes `region_id` via pybind
**Python:**
- `torch/__init__.py`: `isolated_cache: bool = False` kwarg on `torch.compile()`
- `torch/_dynamo/eval_frame.py`: Threads `isolated_cache` through `_optimize` / `optimize_assert`
- `torch/_dynamo/convert_frame.py`: `_isolated_cache`, `_region_id`, `_region_compilation_counts`
on `ConvertFrameAssert`. Global limit override and `apply_to_code` fix in error handler.
- `torch/_dynamo/cache_size.py`: `isolated_cache` and `region_num_compilations` fields
- `torch/_dynamo/types.py`: `region_id` on `GuardedCode`
- `torch/_dynamo/resume_execution.py`: `get_all_resume_code_objects` helper
## Test Plan
- `test_isolated_cache_same_function_different_regions` — two regions on same function, independent caches
- `test_isolated_cache_factory_pattern` — factory pattern with `fail_on_recompile_limit_hit=True`
- `test_isolated_cache_static_and_dynamic` — static vs dynamic on same function
- `test_isolated_cache_fullgraph_raises` — fullgraph contract honored
- `test_isolated_cache_two_models_independent` — two model compiles don't interfere
- `test_isolated_cache_mark_dynamic_vs_static` — mark_static and mark_dynamic coexist
- `test_isolated_cache_auto_dynamic_shared_pgo` — PGO sharing across isolated regions
- `test_isolated_cache_explicit_dispatch_static_vs_dynamic` — explicit dispatch without exclusion guards
- `test_global_recompile_limit_resume_function` — documents existing per-code-object behavior
cc voznesenskym penguinwu EikanWang jgong5 Guobing-Chen XiaobingSuper zhuhaozhe blzheng wenzhe-nrv jiayisunx kadeng chauhang amjames Lucaskabela jataylo mlazos
[ghstack-poisoned]
… cache isolation"
## Summary
Cache entries in Dynamo are stored per code object. When multiple `torch.compile()` calls
target the same function, their cache entries are interleaved on the same linked list. This
causes cross-region interference: one region's compilations affect another region's cache
lookup, recompile limit checks, and `FrameExecStrategy`.
`torch.compile(f, isolated_cache=True)` gives each compile region its own isolated cache:
1. **C++ `region_id`** — each `CacheEntry` is tagged with a region_id. `lookup()` filters
entries by region_id, so each region only sees its own entries.
2. **Python `_region_compilation_counts`** — tracks per-region, per-code-object compilation
counts. Uses `max` across all code objects in the region (including resume functions from
graph breaks) so that once any code object hits the limit, all compilation in the region
stops.
Regions without `isolated_cache` (region_id = -1) use the shared cache as before.
## Visualization
```
ExtraState (per code object)
└── cache_entry_list
├── CacheEntry { guards, code, backend, region_id=0 } ← from opt_f
├── CacheEntry { guards, code, backend, region_id=0 } ← from opt_f
├── CacheEntry { guards, code, backend, region_id=1 } ← from opt_g
└── CacheEntry { guards, code, backend, region_id=-1 } ← no region set
```
```
def test_region_id_cache_entries_visual(self):
cnt1 = torch._dynamo.testing.CompileCounter()
cnt2 = torch._dynamo.testing.CompileCounter()
def f(x):
return x.sin()
opt_f = torch.compile(f, backend=cnt1, isolated_cache=True)
opt_g = torch.compile(f, backend=cnt2, isolated_cache=True)
opt_f(torch.randn(3))
opt_f(torch.randn(3, dtype=torch.float64))
opt_g(torch.randn(4))
# Print cache entries showing region_id
entries = torch._dynamo.eval_frame._debug_get_cache_entry_list(f)
for i, entry in enumerate(entries):
print(f"CacheEntry[{i}]: region_id={entry.region_id}, compile_id={entry.compile_id}")
```
This would output something like:
CacheEntry[0]: region_id=0, compile_id=0/0 ← from opt_f
CacheEntry[1]: region_id=0, compile_id=0/1 ← from opt_f
CacheEntry[2]: region_id=1, compile_id=0/2 ← from opt_g
## Use cases
### Factory pattern
Multiple `torch.compile()` wrappers around the same inner function:
```python
cache
def factory(key):
torch.compile(fullgraph=True, isolated_cache=True)
def frontend(x, n):
return core(x) + n
return frontend
factory("foo")(torch.ones(3), 3) # compiles
factory("bar")(torch.ones(4), 3) # compiles (separate region)
factory("baz")(torch.ones(5), 3) # compiles (separate region)
```
### Static vs dynamic on same function
```python
magic_static = torch.compile(magic, dynamic=False, isolated_cache=True)
magic_dynamic = torch.compile(magic, dynamic=True, isolated_cache=True)
# Each has its own cache — static entries don't interfere with dynamic entries
```
### Shared PGO
With `isolated_cache`, PGO (`frame_state`) is still shared across regions on the same
code object. Region B benefits from region A's shape observations — faster convergence
to dynamic shapes without redundant compilations.
## Changes
**C++:**
- `cache_entry.h/cpp`: `region_id` field on `CacheEntry`, `get_region_id()` helper
- `extra_state.h/cpp`: `lookup()` filters by `region_id`
- `eval_frame_cpp.cpp`: Extracts `region_id` from callback and passes to `lookup()`
- `init.cpp`: Exposes `region_id` via pybind
**Python:**
- `torch/__init__.py`: `isolated_cache: bool = False` kwarg on `torch.compile()`
- `torch/_dynamo/eval_frame.py`: Threads `isolated_cache` through `_optimize` / `optimize_assert`
- `torch/_dynamo/convert_frame.py`: `_isolated_cache`, `_region_id`, `_region_compilation_counts`
on `ConvertFrameAssert`. Global limit override and `apply_to_code` fix in error handler.
- `torch/_dynamo/cache_size.py`: `isolated_cache` and `region_num_compilations` fields
- `torch/_dynamo/types.py`: `region_id` on `GuardedCode`
- `torch/_dynamo/resume_execution.py`: `get_all_resume_code_objects` helper
## Test Plan
- `test_isolated_cache_same_function_different_regions` — two regions on same function, independent caches
- `test_isolated_cache_factory_pattern` — factory pattern with `fail_on_recompile_limit_hit=True`
- `test_isolated_cache_static_and_dynamic` — static vs dynamic on same function
- `test_isolated_cache_fullgraph_raises` — fullgraph contract honored
- `test_isolated_cache_two_models_independent` — two model compiles don't interfere
- `test_isolated_cache_mark_dynamic_vs_static` — mark_static and mark_dynamic coexist
- `test_isolated_cache_auto_dynamic_shared_pgo` — PGO sharing across isolated regions
- `test_isolated_cache_explicit_dispatch_static_vs_dynamic` — explicit dispatch without exclusion guards
- `test_global_recompile_limit_resume_function` — documents existing per-code-object behavior
cc voznesenskym penguinwu EikanWang jgong5 Guobing-Chen XiaobingSuper zhuhaozhe blzheng wenzhe-nrv jiayisunx kadeng chauhang amjames Lucaskabela jataylo mlazos
[ghstack-poisoned]
|
Claude finished @bobrenjc93's task in 6m 51s —— View job PR Review: [Dynamo][cache] Add Isolated_region flag with region_id for cache isolation
Overall this is an ambitious feature with a well-thought-out design. The hybrid cache structure (flat list + lazily-allocated per-region map) is a good approach for zero-overhead in the common case. The test coverage is extensive. However, I found a significant issue with Critical:
|
… cache isolation"
## TL;DR
``torch.compile(f, isolated_region=True)`` — each compile call gets its own cache bucket so they don't interfere. Zero overhead when not used.
## Summary
Cache entries in Dynamo are stored per code object. When multiple `torch.compile()` calls
target the same function, their cache entries are interleaved on the same linked list. This
causes cross-region interference: one region's compilations affect another region's cache
lookup, recompile limit checks, and `FrameExecStrategy`.
`torch.compile(f, isolated_region=True)` gives each compile region its own isolated cache:
1. **Thread-local `region_id`** — set/restored from Python around each `torch.compile`
invocation via TSS (thread-specific storage). `get_current_region_id()` is a single TSS
read (~5ns), replacing the previous per-frame Python attribute chain walk (~200-300ns
for 4-6 `PyObject_GetAttr` calls).
2. **Hybrid per-region cache map** — the default `cache_entry_list` is kept for non-isolated
compilations (region_id == -1). A lazily-allocated `unordered_map<int64_t, list<CacheEntry>>`
is created only when the first isolated region is used. When `isolated_region=False`
(the default), the map is never allocated — zero time overhead, only 16 bytes of storage
(8 for the null `unique_ptr` per `ExtraState` + 8 for `_owner_list` per `CacheEntry`).
3. **Python `_region_compilation_counts`** — tracks per-region, per-code-object compilation
counts (keyed by `id(code)` to avoid holding unpicklable code objects). Uses `max()` across
all code objects in the region (including resume functions from graph breaks) so that once
any single code object hits the limit, the region stops compiling that code object. We use
`max()` rather than `sum()` because the recompile limit targets runaway recompilation on
individual code objects; a region with 1 parent + 1 resume compilation should not be
penalized as 2. This runs only on cache misses (compilation path), not on cache hits.
4. **`recompile_limit` kwarg** — `torch.compile(f, recompile_limit=N)` sets a per-region
recompile limit independent of `config.recompile_limit`.
Regions without `isolated_region` (region_id == -1) use the shared cache as before.
## Visualization
When `isolated_region=False` (default), all entries go into `cache_entry_list`:
```
ExtraState (per code object)
├── cache_entry_list
│ ├── CacheEntry { guards, code, backend }
│ └── CacheEntry { guards, code, backend }
└── region_cache_map = null (never allocated)
```
When `isolated_region=True`, isolated entries go into the lazily-allocated map:
```
ExtraState (per code object)
├── cache_entry_list ← non-isolated entries (region -1)
│ └── CacheEntry { guards, code, backend }
└── region_cache_map
├── [region 0] → list<CacheEntry> ← from opt_f
│ ├── CacheEntry { guards, code, backend }
│ └── CacheEntry { guards, code, backend }
└── [region 1] → list<CacheEntry> ← from opt_g
└── CacheEntry { guards, code, backend }
```
Each region's list is independent — `CacheEntry::next()` traverses only within the
per-region list via `_owner_list`, so `compute_cache_size` and recompile limits naturally
scope per-region without additional filtering.
Isolated regions also fall back to `cache_entry_list` (non-isolated entries) during lookup,
so non-isolated compilations with matching backends remain visible.
## Use cases
### Factory pattern
Multiple `torch.compile()` wrappers around the same inner function:
```python
cache
def factory(key):
torch.compile(fullgraph=True, isolated_region=True)
def frontend(x, n):
return core(x) + n
return frontend
factory("foo")(torch.ones(3), 3) # compiles
factory("bar")(torch.ones(4), 3) # compiles (separate region)
factory("baz")(torch.ones(5), 3) # compiles (separate region)
```
### Static vs dynamic on same function
```python
magic_static = torch.compile(magic, dynamic=False, isolated_region=True)
magic_dynamic = torch.compile(magic, dynamic=True, isolated_region=True)
# Each has its own cache — static entries don't interfere with dynamic entries
```
### Shared PGO
With `isolated_region`, PGO (`frame_state`) is still shared across regions on the same
code object. Region B benefits from region A's shape observations — faster convergence
to dynamic shapes without redundant compilations.
## Changes
**C++:**
- `eval_frame.c/h`: Thread-local `region_id` via TSS (`eval_frame_region_id_key`),
`get_current_region_id()`, `set_eval_frame_region_id_py()`
- `extra_state.h/cpp`: Hybrid `cache_entry_list` + lazily-allocated `region_cache_map`.
`lookup()` walks `cache_entry_list` for region -1, map bucket for region >= 0 with
fallback to `cache_entry_list`. `get_or_create_region_list()`, `has_any_cache_entries()`,
`extract_cache_entry(extra, region_id)`
- `cache_entry.h/cpp`: `_owner_list` pointer for per-region `next()`, `move_to_front()`,
`move_to_back()`. `get_region_id()` callback chain walk removed (replaced by thread-local)
- `eval_frame_cpp.cpp`: `get_current_region_id()` replaces `get_region_id(callback)`,
`extract_cache_entry(extra, region_id)`, `has_any_cache_entries()`
- `init.cpp`: `region_id` pybind removed (no longer a field on `CacheEntry`)
**Python:**
- `torch/__init__.py`: `isolated_region: bool = False`, `recompile_limit: int | None = None`
kwargs on `torch.compile()`
- `torch/_dynamo/eval_frame.py`: `set_eval_frame_region_id` import, save/restore in
`_TorchDynamoContext.__enter__/__exit__` and `compile_wrapper`
- `torch/_dynamo/convert_frame.py`: `_isolated_region`, `_region_id`,
`_region_compilation_counts` on `ConvertFrameAssert`. Region limit check and
`apply_to_code=False` in error handler for isolated regions.
- `torch/_dynamo/cache_size.py`: `isolated_region` and `region_num_compilations` fields
on `CacheSizeRelevantForFrame`
- `torch/_dynamo/types.py`: `region_id` on `GuardedCode`
- `torch/_C/_dynamo/eval_frame.pyi`: Stub for `set_eval_frame_region_id`
**Pointer stability invariant**: `CacheEntry::_owner_list` holds raw pointers to
`std::list` values inside `region_cache_map`. The C++ standard guarantees that
`unordered_map` insert/rehash does not invalidate pointers or references to elements,
so these pointers remain valid. However, erasing a region from the map would invalidate
all `_owner_list` pointers for that region's entries. Regions must NOT be erased for the
lifetime of the `ExtraState`.
## Test Plan
`RecompileLimitKwargTests`:
- `test_recompile_limit_basic` — basic per-region recompile limit
- `test_recompile_limit_none_uses_global` — None falls back to global config
- `test_recompile_limit_stricter_than_global` — kwarg can be stricter than global
- `test_recompile_limit_fullgraph_raises` — fullgraph contract honored with kwarg
- `test_recompile_limit_resume_function_auto_dynamic` — resume functions respect limit
`IsolatedRegionTests`:
- `test_isolated_region_basic` — basic isolation with recompile limit
- `test_isolated_region_same_function_different_regions` — two wrappers, independent caches
- `test_isolated_region_factory_pattern` — factory creating multiple wrappers
- `test_isolated_region_static_and_dynamic` — static vs dynamic on same function
- `test_isolated_region_fullgraph_raises` — recompile limit raises with fullgraph
- `test_isolated_region_two_models_independent` — two models, independent recompilation
- `test_global_recompile_limit_resume_function` — resume function limit behavior
- `test_isolated_region_mark_dynamic_vs_static` — mark_dynamic vs mark_static
- `test_isolated_region_auto_dynamic_shared_pgo` — PGO shared across regions
- `test_isolated_region_explicit_dispatch` — explicit dispatch between regions
- `test_isolated_region_runtime_dispatch` — runtime dispatch pattern
- `test_per_region_cache_counts` — total entries across regions sum correctly
- `test_region_b_lookup_skips_region_a` — independent region lookups
- `test_per_region_recompile_limit` — limit enforced per-region
- `test_non_isolated_entries_visible_to_isolated` — global fallback with same backend
- `test_isolated_region_lru_independent` — LRU within one region doesn't affect another
- `test_isolated_region_reset` — reset clears all regions
- `test_isolated_region_resume_function` — resume functions inherit region_id
cc voznesenskym penguinwu EikanWang jgong5 Guobing-Chen XiaobingSuper zhuhaozhe blzheng wenzhe-nrv jiayisunx kadeng chauhang amjames Lucaskabela jataylo mlazos
[ghstack-poisoned]
… cache isolation"
## TL;DR
`torch.compile(f, isolate_recompiles=True)` — each compile call gets its own cache bucket so they don't interfere. Zero overhead when not used.
## Summary
Cache entries in Dynamo are stored per code object. When multiple `torch.compile()` calls
target the same function, their cache entries share one linked list. This causes
cross-compile interference: one compile call's compilations affect another's cache lookup,
recompile limit checks, and `FrameExecStrategy`.
`torch.compile(f, isolate_recompiles=True)` gives each compile call its own isolated cache:
1. **Global `isolate_recompiles_id`** — set/restored from Python around each
`torch.compile` invocation. `get_current_isolate_recompiles_id()` is a single global
read.
2. **Per-compile cache map** — `ExtraState` stores an
`unordered_map<int64_t, list<CacheEntry>> cache_entry_map`. Non-isolated compiles use
key -1, isolated compiles get unique ids >= 0. Each `CacheEntry` stores its
`_isolate_recompiles_id`, used by `move_to_front`/`move_to_back`/`invalidate` to locate
the correct list via map lookup.
3. **`recompile_limit` kwarg** — `torch.compile(f, recompile_limit=N)` sets a per-compile
recompile limit independent of `config.recompile_limit`.
Isolated compiles also fall back read-only to the default bucket (key -1) during lookup,
so non-isolated compilations with matching backends remain visible. This is BC friendly.
New entries are always written to the isolated bucket only.
## Before (single flat list per code object)
```
ExtraState (per code object)
│
└── cache_entry_list: std::list<CacheEntry> ← one shared list
│
├── CacheEntry { guards, code, backend_A }
│ _owner_list ──► &cache_entry_list
│ next() ──► CacheEntry below
│
├── CacheEntry { guards, code, backend_B }
│ _owner_list ──► &cache_entry_list
│ next() ──► CacheEntry below
│
└── CacheEntry { guards, code, backend_A }
_owner_list ──► &cache_entry_list
next() ──► None
Problems:
- All torch.compile() calls share one list
- Recompile limit counted across ALL entries
- opt_a's entries interfere with opt_b's lookup
- Python walks list via .next (linked-list traversal)
```
## After (per-compile cache map)
```
torch.compile(f, isolate_recompiles=True)
│
▼
┌─────────────────────────────────────┐
│ ConvertFrameAssert │
│ _isolate_recompiles_id = N │ ◄── allocated once, shared with clones
│ _clone_with_backend ─────────────┼──── preserves same id
└──────────────┬──────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ _TorchDynamoContext (eval_frame.py)│
│ sets global id before fn call │ ◄── save/restore around fn(*args)
│ restores previous id after │
└──────────────┬──────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ C++ eval_frame │
│ id = get_current_isolate_ │
│ recompiles_id() │
│ lookup(extra, ..., id, ...) │
└──────────────┬──────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ ExtraState (per code object) │
│ │
│ cache_entry_map: unordered_map<int64_t, list<CacheEntry>> │
│ ┌─────┬───────────────────────────────────────────┐ │
│ │ -1 │ CacheEntry ↔ CacheEntry ↔ CacheEntry │ non- │
│ │ │ (_isolate_recompiles_id = -1) │ iso. │
│ ├─────┼───────────────────────────────────────────┤ │
│ │ 0 │ CacheEntry ↔ CacheEntry │ opt_a │
│ │ │ (_isolate_recompiles_id = 0) │ │
│ ├─────┼───────────────────────────────────────────┤ │
│ │ 1 │ CacheEntry │ opt_b │
│ │ │ (_isolate_recompiles_id = 1) │ │
│ └─────┴───────────────────────────────────────────┘ │
│ │
│ Lookup: cache_entry_map[id], fallback to [-1] if id >= 0 │
│ Recompile limit: counted per bucket │
│ LRU: move_to_front via map[entry._isolate_recompiles_id] │
│ PGO (frame_state): shared across all buckets │
│ Python iteration: _get_cache_entries_for_region(code, id) │
└─────────────────────────────────────────────────────────────┘
Key changes from before:
- _owner_list pointer removed from CacheEntry
- .next() removed — Python gets full list via C++ API
- _isolate_recompiles_id on CacheEntry for map lookups
- Each bucket is still a std::list<CacheEntry> (LRU ordered)
- Isolated compiles fall back read-only to [-1] (BC friendly)
```
## Use cases
### Factory pattern
```python
cache
def factory(key):
torch.compile(fullgraph=True, isolate_recompiles=True)
def frontend(x, n):
return core(x) + n
return frontend
factory("foo")(torch.ones(3), 3) # compiles in bucket 0
factory("bar")(torch.ones(4), 3) # compiles in bucket 1
factory("baz")(torch.ones(5), 3) # compiles in bucket 2
```
### Static vs dynamic on same function
```python
opt_static = torch.compile(f, dynamic=False, isolate_recompiles=True)
opt_dynamic = torch.compile(f, dynamic=True, isolate_recompiles=True)
# Each has its own cache — static entries don't interfere with dynamic entries
# Each exhausts its recompile_limit independently
```
### Shared PGO
With `isolate_recompiles`, PGO (`frame_state`) is still shared across compiles on the
same code object. Compile B benefits from compile A's shape observations.
## Changes
**C++:**
- `eval_frame.c/h`: Thread-local `isolate_recompiles_id`,
`get_current_isolate_recompiles_id()`, `set_eval_frame_isolate_recompiles_id_py()`.
- `extra_state.h/cpp`:
- `unordered_map<int64_t, list<CacheEntry>> cache_entry_map` — per-region cache buckets.
- `unordered_map<int64_t, FrameExecStrategy> region_strategy_map` — per-region
`RUN_ONLY` persistence after limit hit.
- `lookup()` searches own bucket, falls back read-only to bucket -1 for isolated compiles.
- `extra_state_get_region_exec_strategy(extra, id)`: for isolated regions with no map
entry, inherits global `SKIP` (deliberate `skip_code` / `skip` / FX plumbing
decisions) but **not** global `RUN_ONLY` (avoids non-isolated limit-hit bleeding into
new regions). Single strategy read drives both SKIP short-circuit and RUN_ONLY check
in `eval_frame_cpp.cpp`.
- `extract_cache_entry(extra, id)`: searches own bucket first, then default.
- `_get_cache_entries_for_region(code, id)`: returns entries for a specific bucket in
LRU order.
- `_debug_get_cache_entry_list`: sorted by `isolate_recompiles_id` for deterministic
iteration.
- `move_to_front` / `move_to_back` / `invalidate` locate the correct list via
`_isolate_recompiles_id`.
- `cache_entry.h/cpp`: `_isolate_recompiles_id` field on CacheEntry. Removed `_owner_list`
pointer and `.next` property — callers iterate per-bucket lists instead.
- `init.cpp`: `_get_cache_entries_for_region` binding, `isolate_recompiles_id` readonly
property on CacheEntry.
**Python:**
- `torch/__init__.py`: `isolate_recompiles: bool = False`, `recompile_limit: int | None = None`
kwargs on `torch.compile()`. Docstring documents BC-friendly default-bucket fallback,
per-region vs accumulated limit semantics, and the SKIP-inherit / RUN_ONLY-isolate
asymmetry.
- `torch/_dynamo/eval_frame.py`:
- Id minted in `_optimize` / `_optimize_assert`, passed as a kwarg through
`_optimize_catch_errors` → `OptimizeContext` → `_TorchDynamoContext.__init__` →
closed over by `compile_wrapper`.
- `compile_wrapper` sets/restores TLS id around `fn(*args, **kwargs)`. Ctx-manager
`__enter__`/`__exit__` do **not** set TLS id — `raise_on_ctx_manager_usage=True`
by default makes that path unreachable.
- `_get_cache_entries_for_region()` Python wrapper with LRU-order / bucket semantics
docstring.
- `torch/_dynamo/convert_frame.py`:
- `ConvertFrameAssert`, `ConvertFrame`, their factories, and `_clone_with_backend`
no longer carry `_isolate_recompiles` / `_isolate_recompiles_id` attributes. Id
flows via TLS, read in `ConvertFrameAssert.__call__`.
- Recompile-reason logging: `cache_entries` (filtered per-region) used for
`compute_cache_size` and `build_guards`; `cache_entries_for_reasons` = region ∪
default for isolated calls, passed to `get_and_maybe_log_recompilation_reasons` so
default-bucket guard failures aren't dropped from the log.
- `torch/_dynamo/cache_size.py`: `compute_cache_size` takes a filtered list (per-region);
`total_cache_entries_all_regions` is used only for the accumulated-limit safety cap.
- `torch/_dynamo/guards.py`: `get_and_maybe_log_recompilation_reasons` and
`update_diff_guard_managers_for_existing_cache_entries` take lists instead of walking
`.next`. `CheckFunctionManager` accepts `cache_entries` list.
## Test Plan
`IsolateRecompilesTests` (full list below; grouped by scenario):
**Basic isolation**
- `test_isolate_recompiles_basic`
- `test_isolate_recompiles_same_function_different_regions`
- `test_isolate_recompiles_factory_pattern`
- `test_isolate_recompiles_same_backend_different_regions`
- `test_isolate_recompiles_string_backends` (parametrized over eager/aot_eager/inductor)
**Static vs dynamic**
- `test_isolate_recompiles_static_and_dynamic`
- `test_isolate_recompiles_mark_dynamic_vs_static`
- `test_isolate_recompiles_auto_dynamic_shared_pgo`
- `test_isolate_recompiles_same_backend_different_dynamic_independent_limits`
**Recompile limits**
- `test_isolate_recompiles_fullgraph_raises`
- `test_isolate_recompiles_accumulated_limit`
- `test_isolate_recompiles_accumulated_limit_hard_fail`
**RUN_ONLY per-region persistence**
- `test_isolate_recompiles_limit_does_not_skip_other_regions`
- `test_isolate_recompiles_region_run_only_persists`
**Default strategy × region: SKIP inherited, RUN_ONLY not**
- `test_isolate_recompiles_inherits_default_skip`
- `test_isolate_recompiles_ignores_default_run_only`
**Cache internals**
- `test_isolate_recompiles_insertion_order_per_region`
- `test_isolate_recompiles_lru_move_to_front`
- `test_non_isolated_entries_visible_to_isolated` (BC-friendly fallback)
- `test_isolate_recompiles_reasons_include_default_bucket` (reason-logging across buckets)
- `test_non_isolated_reasons_unchanged` (id=-1 regression)
- `test_reasons_include_all_default_entries` (multi-entry default bucket reason coverage)
- `test_reset_clears_region_strategy` (reset clears `region_strategy_map`)
- `test_non_isolated_compiles_share_cache`
- `test_no_isolate_recompiles_shared_cache`
- `test_different_backends_shared_cache_without_isolate`
- `test_different_backends_independent_with_isolate`
**Lifecycle**
- `test_isolate_recompiles_reset`
- `test_isolate_recompiles_resume_function`
- `test_isolate_recompiles_gc_wrapper`
**Debug / introspection**
- `test_debug_get_cache_entry_list_deterministic_order`
```bash
python test/dynamo/test_recompile_ux.py IsolateRecompilesTests
python test/dynamo/test_recompile_ux.py RecompileUxTests
python test/dynamo/test_recompile_ux.py RecompileLimitKwargTests
```
cc voznesenskym penguinwu EikanWang jgong5 Guobing-Chen XiaobingSuper zhuhaozhe blzheng wenzhe-nrv jiayisunx kadeng chauhang amjames Lucaskabela jataylo mlazos
[ghstack-poisoned]
… cache isolation"
## TL;DR
`torch.compile(f, isolate_recompiles=True)` — each compile call gets its own cache bucket so they don't interfere. Zero overhead when not used.
## Summary
Cache entries in Dynamo are stored per code object. When multiple `torch.compile()` calls
target the same function, their cache entries share one linked list. This causes
cross-compile interference: one compile call's compilations affect another's cache lookup,
recompile limit checks, and `FrameExecStrategy`.
`torch.compile(f, isolate_recompiles=True)` gives each compile call its own isolated cache:
1. **Global `isolate_recompiles_id`** — set/restored from Python around each
`torch.compile` invocation. `get_current_isolate_recompiles_id()` is a single global
read.
2. **Per-compile cache map** — `ExtraState` stores an
`unordered_map<int64_t, list<CacheEntry>> cache_entry_map`. Non-isolated compiles use
key -1, isolated compiles get unique ids >= 0. Each `CacheEntry` stores its
`_isolate_recompiles_id`, used by `move_to_front`/`move_to_back`/`invalidate` to locate
the correct list via map lookup.
3. **`recompile_limit` kwarg** — `torch.compile(f, recompile_limit=N)` sets a per-compile
recompile limit independent of `config.recompile_limit`.
Isolated compiles also fall back read-only to the default bucket (key -1) during lookup,
so non-isolated compilations with matching backends remain visible. This is BC friendly.
New entries are always written to the isolated bucket only.
## Before (single flat list per code object)
```
ExtraState (per code object)
│
└── cache_entry_list: std::list<CacheEntry> ← one shared list
│
├── CacheEntry { guards, code, backend_A }
│ _owner_list ──► &cache_entry_list
│ next() ──► CacheEntry below
│
├── CacheEntry { guards, code, backend_B }
│ _owner_list ──► &cache_entry_list
│ next() ──► CacheEntry below
│
└── CacheEntry { guards, code, backend_A }
_owner_list ──► &cache_entry_list
next() ──► None
Problems:
- All torch.compile() calls share one list
- Recompile limit counted across ALL entries
- opt_a's entries interfere with opt_b's lookup
- Python walks list via .next (linked-list traversal)
```
## After (per-compile cache map)
```
torch.compile(f, isolate_recompiles=True)
│
▼
┌─────────────────────────────────────┐
│ ConvertFrameAssert │
│ _isolate_recompiles_id = N │ ◄── allocated once, shared with clones
│ _clone_with_backend ─────────────┼──── preserves same id
└──────────────┬──────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ _TorchDynamoContext (eval_frame.py)│
│ sets global id before fn call │ ◄── save/restore around fn(*args)
│ restores previous id after │
└──────────────┬──────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ C++ eval_frame │
│ id = get_current_isolate_ │
│ recompiles_id() │
│ lookup(extra, ..., id, ...) │
└──────────────┬──────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ ExtraState (per code object) │
│ │
│ cache_entry_map: unordered_map<int64_t, list<CacheEntry>> │
│ ┌─────┬───────────────────────────────────────────┐ │
│ │ -1 │ CacheEntry ↔ CacheEntry ↔ CacheEntry │ non- │
│ │ │ (_isolate_recompiles_id = -1) │ iso. │
│ ├─────┼───────────────────────────────────────────┤ │
│ │ 0 │ CacheEntry ↔ CacheEntry │ opt_a │
│ │ │ (_isolate_recompiles_id = 0) │ │
│ ├─────┼───────────────────────────────────────────┤ │
│ │ 1 │ CacheEntry │ opt_b │
│ │ │ (_isolate_recompiles_id = 1) │ │
│ └─────┴───────────────────────────────────────────┘ │
│ │
│ Lookup: cache_entry_map[id], fallback to [-1] if id >= 0 │
│ Recompile limit: counted per bucket │
│ LRU: move_to_front via map[entry._isolate_recompiles_id] │
│ PGO (frame_state): shared across all buckets │
│ Python iteration: _get_cache_entries_for_region(code, id) │
└─────────────────────────────────────────────────────────────┘
Key changes from before:
- _owner_list pointer removed from CacheEntry
- .next() removed — Python gets full list via C++ API
- _isolate_recompiles_id on CacheEntry for map lookups
- Each bucket is still a std::list<CacheEntry> (LRU ordered)
- Isolated compiles fall back read-only to [-1] (BC friendly)
```
## Use cases
### Factory pattern
```python
cache
def factory(key):
torch.compile(fullgraph=True, isolate_recompiles=True)
def frontend(x, n):
return core(x) + n
return frontend
factory("foo")(torch.ones(3), 3) # compiles in bucket 0
factory("bar")(torch.ones(4), 3) # compiles in bucket 1
factory("baz")(torch.ones(5), 3) # compiles in bucket 2
```
### Static vs dynamic on same function
```python
opt_static = torch.compile(f, dynamic=False, isolate_recompiles=True)
opt_dynamic = torch.compile(f, dynamic=True, isolate_recompiles=True)
# Each has its own cache — static entries don't interfere with dynamic entries
# Each exhausts its recompile_limit independently
```
### Shared PGO
With `isolate_recompiles`, PGO (`frame_state`) is still shared across compiles on the
same code object. Compile B benefits from compile A's shape observations.
## Changes
**C++:**
- `eval_frame.c/h`: Thread-local `isolate_recompiles_id`,
`get_current_isolate_recompiles_id()`, `set_eval_frame_isolate_recompiles_id_py()`.
- `extra_state.h/cpp`:
- `unordered_map<int64_t, list<CacheEntry>> cache_entry_map` — per-region cache buckets.
- `unordered_map<int64_t, FrameExecStrategy> region_strategy_map` — per-region
`RUN_ONLY` persistence after limit hit.
- `lookup()` searches own bucket, falls back read-only to bucket -1 for isolated compiles.
- `extra_state_get_region_exec_strategy(extra, id)`: for isolated regions with no map
entry, inherits global `SKIP` (deliberate `skip_code` / `skip` / FX plumbing
decisions) but **not** global `RUN_ONLY` (avoids non-isolated limit-hit bleeding into
new regions). Single strategy read drives both SKIP short-circuit and RUN_ONLY check
in `eval_frame_cpp.cpp`.
- `extract_cache_entry(extra, id)`: searches own bucket first, then default.
- `_get_cache_entries_for_region(code, id)`: returns entries for a specific bucket in
LRU order.
- `_debug_get_cache_entry_list`: sorted by `isolate_recompiles_id` for deterministic
iteration.
- `move_to_front` / `move_to_back` / `invalidate` locate the correct list via
`_isolate_recompiles_id`.
- `cache_entry.h/cpp`: `_isolate_recompiles_id` field on CacheEntry. Removed `_owner_list`
pointer and `.next` property — callers iterate per-bucket lists instead.
- `init.cpp`: `_get_cache_entries_for_region` binding, `isolate_recompiles_id` readonly
property on CacheEntry.
**Python:**
- `torch/__init__.py`: `isolate_recompiles: bool = False`, `recompile_limit: int | None = None`
kwargs on `torch.compile()`. Docstring documents BC-friendly default-bucket fallback,
per-region vs accumulated limit semantics, and the SKIP-inherit / RUN_ONLY-isolate
asymmetry.
- `torch/_dynamo/eval_frame.py`:
- Id minted in `_optimize` / `_optimize_assert`, passed as a kwarg through
`_optimize_catch_errors` → `OptimizeContext` → `_TorchDynamoContext.__init__` →
closed over by `compile_wrapper`.
- `compile_wrapper` sets/restores TLS id around `fn(*args, **kwargs)`. Ctx-manager
`__enter__`/`__exit__` do **not** set TLS id — `raise_on_ctx_manager_usage=True`
by default makes that path unreachable.
- `_get_cache_entries_for_region()` Python wrapper with LRU-order / bucket semantics
docstring.
- `torch/_dynamo/convert_frame.py`:
- `ConvertFrameAssert`, `ConvertFrame`, their factories, and `_clone_with_backend`
no longer carry `_isolate_recompiles` / `_isolate_recompiles_id` attributes. Id
flows via TLS, read in `ConvertFrameAssert.__call__`.
- Recompile-reason logging: `cache_entries` (filtered per-region) used for
`compute_cache_size` and `build_guards`; `cache_entries_for_reasons` = region ∪
default for isolated calls, passed to `get_and_maybe_log_recompilation_reasons` so
default-bucket guard failures aren't dropped from the log.
- `torch/_dynamo/cache_size.py`: `compute_cache_size` takes a filtered list (per-region);
`total_cache_entries_all_regions` is used only for the accumulated-limit safety cap.
- `torch/_dynamo/guards.py`: `get_and_maybe_log_recompilation_reasons` and
`update_diff_guard_managers_for_existing_cache_entries` take lists instead of walking
`.next`. `CheckFunctionManager` accepts `cache_entries` list.
## Test Plan
`IsolateRecompilesTests` (full list below; grouped by scenario):
**Basic isolation**
- `test_isolate_recompiles_basic`
- `test_isolate_recompiles_same_function_different_regions`
- `test_isolate_recompiles_factory_pattern`
- `test_isolate_recompiles_same_backend_different_regions`
- `test_isolate_recompiles_string_backends` (parametrized over eager/aot_eager/inductor)
**Static vs dynamic**
- `test_isolate_recompiles_static_and_dynamic`
- `test_isolate_recompiles_mark_dynamic_vs_static`
- `test_isolate_recompiles_auto_dynamic_shared_pgo`
- `test_isolate_recompiles_same_backend_different_dynamic_independent_limits`
**Recompile limits**
- `test_isolate_recompiles_fullgraph_raises`
- `test_isolate_recompiles_accumulated_limit`
- `test_isolate_recompiles_accumulated_limit_hard_fail`
**RUN_ONLY per-region persistence**
- `test_isolate_recompiles_limit_does_not_skip_other_regions`
- `test_isolate_recompiles_region_run_only_persists`
**Default strategy × region: SKIP inherited, RUN_ONLY not**
- `test_isolate_recompiles_inherits_default_skip`
- `test_isolate_recompiles_ignores_default_run_only`
**Cache internals**
- `test_isolate_recompiles_insertion_order_per_region`
- `test_isolate_recompiles_lru_move_to_front`
- `test_non_isolated_entries_visible_to_isolated` (BC-friendly fallback)
- `test_isolate_recompiles_reasons_include_default_bucket` (reason-logging across buckets)
- `test_non_isolated_reasons_unchanged` (id=-1 regression)
- `test_reasons_include_all_default_entries` (multi-entry default bucket reason coverage)
- `test_reset_clears_region_strategy` (reset clears `region_strategy_map`)
- `test_non_isolated_compiles_share_cache`
- `test_no_isolate_recompiles_shared_cache`
- `test_different_backends_shared_cache_without_isolate`
- `test_different_backends_independent_with_isolate`
**Lifecycle**
- `test_isolate_recompiles_reset`
- `test_isolate_recompiles_resume_function`
- `test_isolate_recompiles_gc_wrapper`
**Debug / introspection**
- `test_debug_get_cache_entry_list_deterministic_order`
```bash
python test/dynamo/test_recompile_ux.py IsolateRecompilesTests
python test/dynamo/test_recompile_ux.py RecompileUxTests
python test/dynamo/test_recompile_ux.py RecompileLimitKwargTests
```
cc voznesenskym penguinwu EikanWang jgong5 Guobing-Chen XiaobingSuper zhuhaozhe blzheng wenzhe-nrv jiayisunx kadeng chauhang amjames Lucaskabela jataylo mlazos
[ghstack-poisoned]
… cache isolation"
## TL;DR
`torch.compile(f, isolate_recompiles=True)` — each compile call gets its own cache bucket so they don't interfere. Zero overhead when not used.
## Summary
Cache entries in Dynamo are stored per code object. When multiple `torch.compile()` calls
target the same function, their cache entries share one linked list. This causes
cross-compile interference: one compile call's compilations affect another's cache lookup,
recompile limit checks, and `FrameExecStrategy`.
`torch.compile(f, isolate_recompiles=True)` gives each compile call its own isolated cache:
1. **Global `isolate_recompiles_id`** — set/restored from Python around each
`torch.compile` invocation. `get_current_isolate_recompiles_id()` is a single global
read.
2. **Per-compile cache map** — `ExtraState` stores an
`unordered_map<int64_t, list<CacheEntry>> cache_entry_map`. Non-isolated compiles use
key -1, isolated compiles get unique ids >= 0. Each `CacheEntry` stores its
`_isolate_recompiles_id`, used by `move_to_front`/`move_to_back`/`invalidate` to locate
the correct list via map lookup.
3. **`recompile_limit` kwarg** — `torch.compile(f, recompile_limit=N)` sets a per-compile
recompile limit independent of `config.recompile_limit`.
Isolated compiles also fall back read-only to the default bucket (key -1) during lookup,
so non-isolated compilations with matching backends remain visible. This is BC friendly.
New entries are always written to the isolated bucket only.
## Before (single flat list per code object)
```
ExtraState (per code object)
│
└── cache_entry_list: std::list<CacheEntry> ← one shared list
│
├── CacheEntry { guards, code, backend_A }
│ _owner_list ──► &cache_entry_list
│ next() ──► CacheEntry below
│
├── CacheEntry { guards, code, backend_B }
│ _owner_list ──► &cache_entry_list
│ next() ──► CacheEntry below
│
└── CacheEntry { guards, code, backend_A }
_owner_list ──► &cache_entry_list
next() ──► None
Problems:
- All torch.compile() calls share one list
- Recompile limit counted across ALL entries
- opt_a's entries interfere with opt_b's lookup
- Python walks list via .next (linked-list traversal)
```
## After (per-compile cache map)
```
torch.compile(f, isolate_recompiles=True)
│
▼
┌─────────────────────────────────────┐
│ ConvertFrameAssert │
│ _isolate_recompiles_id = N │ ◄── allocated once, shared with clones
│ _clone_with_backend ─────────────┼──── preserves same id
└──────────────┬──────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ _TorchDynamoContext (eval_frame.py)│
│ sets global id before fn call │ ◄── save/restore around fn(*args)
│ restores previous id after │
└──────────────┬──────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ C++ eval_frame │
│ id = get_current_isolate_ │
│ recompiles_id() │
│ lookup(extra, ..., id, ...) │
└──────────────┬──────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ ExtraState (per code object) │
│ │
│ cache_entry_map: unordered_map<int64_t, list<CacheEntry>> │
│ ┌─────┬───────────────────────────────────────────┐ │
│ │ -1 │ CacheEntry ↔ CacheEntry ↔ CacheEntry │ non- │
│ │ │ (_isolate_recompiles_id = -1) │ iso. │
│ ├─────┼───────────────────────────────────────────┤ │
│ │ 0 │ CacheEntry ↔ CacheEntry │ opt_a │
│ │ │ (_isolate_recompiles_id = 0) │ │
│ ├─────┼───────────────────────────────────────────┤ │
│ │ 1 │ CacheEntry │ opt_b │
│ │ │ (_isolate_recompiles_id = 1) │ │
│ └─────┴───────────────────────────────────────────┘ │
│ │
│ Lookup: cache_entry_map[id], fallback to [-1] if id >= 0 │
│ Recompile limit: counted per bucket │
│ LRU: move_to_front via map[entry._isolate_recompiles_id] │
│ PGO (frame_state): shared across all buckets │
│ Python iteration: _get_cache_entries_for_region(code, id) │
└─────────────────────────────────────────────────────────────┘
Key changes from before:
- _owner_list pointer removed from CacheEntry
- .next() removed — Python gets full list via C++ API
- _isolate_recompiles_id on CacheEntry for map lookups
- Each bucket is still a std::list<CacheEntry> (LRU ordered)
- Isolated compiles fall back read-only to [-1] (BC friendly)
```
## Use cases
### Factory pattern
```python
cache
def factory(key):
torch.compile(fullgraph=True, isolate_recompiles=True)
def frontend(x, n):
return core(x) + n
return frontend
factory("foo")(torch.ones(3), 3) # compiles in bucket 0
factory("bar")(torch.ones(4), 3) # compiles in bucket 1
factory("baz")(torch.ones(5), 3) # compiles in bucket 2
```
### Static vs dynamic on same function
```python
opt_static = torch.compile(f, dynamic=False, isolate_recompiles=True)
opt_dynamic = torch.compile(f, dynamic=True, isolate_recompiles=True)
# Each has its own cache — static entries don't interfere with dynamic entries
# Each exhausts its recompile_limit independently
```
### Shared PGO
With `isolate_recompiles`, PGO (`frame_state`) is still shared across compiles on the
same code object. Compile B benefits from compile A's shape observations.
## Changes
**C++:**
- `eval_frame.c/h`: Thread-local `isolate_recompiles_id`,
`get_current_isolate_recompiles_id()`, `set_eval_frame_isolate_recompiles_id_py()`.
- `extra_state.h/cpp`:
- `unordered_map<int64_t, list<CacheEntry>> cache_entry_map` — per-region cache buckets.
- `unordered_map<int64_t, FrameExecStrategy> region_strategy_map` — per-region
`RUN_ONLY` persistence after limit hit.
- `lookup()` searches own bucket, falls back read-only to bucket -1 for isolated compiles.
- `extra_state_get_region_exec_strategy(extra, id)`: for isolated regions with no map
entry, inherits global `SKIP` (deliberate `skip_code` / `skip` / FX plumbing
decisions) but **not** global `RUN_ONLY` (avoids non-isolated limit-hit bleeding into
new regions). Single strategy read drives both SKIP short-circuit and RUN_ONLY check
in `eval_frame_cpp.cpp`.
- `extract_cache_entry(extra, id)`: searches own bucket first, then default.
- `_get_cache_entries_for_region(code, id)`: returns entries for a specific bucket in
LRU order.
- `_debug_get_cache_entry_list`: sorted by `isolate_recompiles_id` for deterministic
iteration.
- `move_to_front` / `move_to_back` / `invalidate` locate the correct list via
`_isolate_recompiles_id`.
- `cache_entry.h/cpp`: `_isolate_recompiles_id` field on CacheEntry. Removed `_owner_list`
pointer and `.next` property — callers iterate per-bucket lists instead.
- `init.cpp`: `_get_cache_entries_for_region` binding, `isolate_recompiles_id` readonly
property on CacheEntry.
**Python:**
- `torch/__init__.py`: `isolate_recompiles: bool = False`, `recompile_limit: int | None = None`
kwargs on `torch.compile()`. Docstring documents BC-friendly default-bucket fallback,
per-region vs accumulated limit semantics, and the SKIP-inherit / RUN_ONLY-isolate
asymmetry.
- `torch/_dynamo/eval_frame.py`:
- Id minted in `_optimize` / `_optimize_assert`, passed as a kwarg through
`_optimize_catch_errors` → `OptimizeContext` → `_TorchDynamoContext.__init__` →
closed over by `compile_wrapper`.
- `compile_wrapper` sets/restores TLS id around `fn(*args, **kwargs)`. Ctx-manager
`__enter__`/`__exit__` do **not** set TLS id — `raise_on_ctx_manager_usage=True`
by default makes that path unreachable.
- `_get_cache_entries_for_region()` Python wrapper with LRU-order / bucket semantics
docstring.
- `torch/_dynamo/convert_frame.py`:
- `ConvertFrameAssert`, `ConvertFrame`, their factories, and `_clone_with_backend`
no longer carry `_isolate_recompiles` / `_isolate_recompiles_id` attributes. Id
flows via TLS, read in `ConvertFrameAssert.__call__`.
- Recompile-reason logging: `cache_entries` (filtered per-region) used for
`compute_cache_size` and `build_guards`; `cache_entries_for_reasons` = region ∪
default for isolated calls, passed to `get_and_maybe_log_recompilation_reasons` so
default-bucket guard failures aren't dropped from the log.
- `torch/_dynamo/cache_size.py`: `compute_cache_size` takes a filtered list (per-region);
`total_cache_entries_all_regions` is used only for the accumulated-limit safety cap.
- `torch/_dynamo/guards.py`: `get_and_maybe_log_recompilation_reasons` and
`update_diff_guard_managers_for_existing_cache_entries` take lists instead of walking
`.next`. `CheckFunctionManager` accepts `cache_entries` list.
## Test Plan
`IsolateRecompilesTests` (full list below; grouped by scenario):
**Basic isolation**
- `test_isolate_recompiles_basic`
- `test_isolate_recompiles_same_function_different_regions`
- `test_isolate_recompiles_factory_pattern`
- `test_isolate_recompiles_same_backend_different_regions`
- `test_isolate_recompiles_string_backends` (parametrized over eager/aot_eager/inductor)
**Static vs dynamic**
- `test_isolate_recompiles_static_and_dynamic`
- `test_isolate_recompiles_mark_dynamic_vs_static`
- `test_isolate_recompiles_auto_dynamic_shared_pgo`
- `test_isolate_recompiles_same_backend_different_dynamic_independent_limits`
**Recompile limits**
- `test_isolate_recompiles_fullgraph_raises`
- `test_isolate_recompiles_accumulated_limit`
- `test_isolate_recompiles_accumulated_limit_hard_fail`
**RUN_ONLY per-region persistence**
- `test_isolate_recompiles_limit_does_not_skip_other_regions`
- `test_isolate_recompiles_region_run_only_persists`
**Default strategy × region: SKIP inherited, RUN_ONLY not**
- `test_isolate_recompiles_inherits_default_skip`
- `test_isolate_recompiles_ignores_default_run_only`
**Cache internals**
- `test_isolate_recompiles_insertion_order_per_region`
- `test_isolate_recompiles_lru_move_to_front`
- `test_non_isolated_entries_visible_to_isolated` (BC-friendly fallback)
- `test_isolate_recompiles_reasons_include_default_bucket` (reason-logging across buckets)
- `test_non_isolated_reasons_unchanged` (id=-1 regression)
- `test_reasons_include_all_default_entries` (multi-entry default bucket reason coverage)
- `test_reset_clears_region_strategy` (reset clears `region_strategy_map`)
- `test_non_isolated_compiles_share_cache`
- `test_no_isolate_recompiles_shared_cache`
- `test_different_backends_shared_cache_without_isolate`
- `test_different_backends_independent_with_isolate`
**Lifecycle**
- `test_isolate_recompiles_reset`
- `test_isolate_recompiles_resume_function`
- `test_isolate_recompiles_gc_wrapper`
**Debug / introspection**
- `test_debug_get_cache_entry_list_deterministic_order`
```bash
python test/dynamo/test_recompile_ux.py IsolateRecompilesTests
python test/dynamo/test_recompile_ux.py RecompileUxTests
python test/dynamo/test_recompile_ux.py RecompileLimitKwargTests
```
cc voznesenskym penguinwu EikanWang jgong5 Guobing-Chen XiaobingSuper zhuhaozhe blzheng wenzhe-nrv jiayisunx kadeng chauhang amjames Lucaskabela jataylo mlazos
[ghstack-poisoned]
williamwen42
left a comment
There was a problem hiding this comment.
Thanks for addressing all the comments!
|
@pytorchbot merge |
Merge startedYour 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 |
Merge failedReason: 8 mandatory check(s) failed. The first few are:
Dig deeper by viewing the failures on hud |
|
@pytorchbot merge |
Merge startedYour 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 |
…ation (pytorch#178351) ## TL;DR `torch.compile(f, isolate_recompiles=True)` — each compile call gets its own cache bucket so they don't interfere. Zero overhead when not used. ## Summary Cache entries in Dynamo are stored per code object. When multiple `torch.compile()` calls target the same function, their cache entries share one linked list. This causes cross-compile interference: one compile call's compilations affect another's cache lookup, recompile limit checks, and `FrameExecStrategy`. `torch.compile(f, isolate_recompiles=True)` gives each compile call its own isolated cache: 1. **Global `isolate_recompiles_id`** — set/restored from Python around each `torch.compile` invocation. `get_current_isolate_recompiles_id()` is a single global read. 2. **Per-compile cache map** — `ExtraState` stores an `unordered_map<int64_t, list<CacheEntry>> cache_entry_map`. Non-isolated compiles use key -1, isolated compiles get unique ids >= 0. Each `CacheEntry` stores its `_isolate_recompiles_id`, used by `move_to_front`/`move_to_back`/`invalidate` to locate the correct list via map lookup. 3. **`recompile_limit` kwarg** — `torch.compile(f, recompile_limit=N)` sets a per-compile recompile limit independent of `config.recompile_limit`. Isolated compiles also fall back read-only to the default bucket (key -1) during lookup, so non-isolated compilations with matching backends remain visible. This is BC friendly. New entries are always written to the isolated bucket only. ## Before (single flat list per code object) ``` ExtraState (per code object) │ └── cache_entry_list: std::list<CacheEntry> ← one shared list │ ├── CacheEntry { guards, code, backend_A } │ _owner_list ──► &cache_entry_list │ next() ──► CacheEntry below │ ├── CacheEntry { guards, code, backend_B } │ _owner_list ──► &cache_entry_list │ next() ──► CacheEntry below │ └── CacheEntry { guards, code, backend_A } _owner_list ──► &cache_entry_list next() ──► None Problems: - All torch.compile() calls share one list - Recompile limit counted across ALL entries - opt_a's entries interfere with opt_b's lookup - Python walks list via .next (linked-list traversal) ``` ## After (per-compile cache map) ``` torch.compile(f, isolate_recompiles=True) │ ▼ ┌─────────────────────────────────────┐ │ ConvertFrameAssert │ │ _isolate_recompiles_id = N │ ◄── allocated once, shared with clones │ _clone_with_backend ─────────────┼──── preserves same id └──────────────┬──────────────────────┘ │ ▼ ┌─────────────────────────────────────┐ │ _TorchDynamoContext (eval_frame.py)│ │ sets global id before fn call │ ◄── save/restore around fn(*args) │ restores previous id after │ └──────────────┬──────────────────────┘ │ ▼ ┌─────────────────────────────────────┐ │ C++ eval_frame │ │ id = get_current_isolate_ │ │ recompiles_id() │ │ lookup(extra, ..., id, ...) │ └──────────────┬──────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────┐ │ ExtraState (per code object) │ │ │ │ cache_entry_map: unordered_map<int64_t, list<CacheEntry>> │ │ ┌─────┬───────────────────────────────────────────┐ │ │ │ -1 │ CacheEntry ↔ CacheEntry ↔ CacheEntry │ non- │ │ │ │ (_isolate_recompiles_id = -1) │ iso. │ │ ├─────┼───────────────────────────────────────────┤ │ │ │ 0 │ CacheEntry ↔ CacheEntry │ opt_a │ │ │ │ (_isolate_recompiles_id = 0) │ │ │ ├─────┼───────────────────────────────────────────┤ │ │ │ 1 │ CacheEntry │ opt_b │ │ │ │ (_isolate_recompiles_id = 1) │ │ │ └─────┴───────────────────────────────────────────┘ │ │ │ │ Lookup: cache_entry_map[id], fallback to [-1] if id >= 0 │ │ Recompile limit: counted per bucket │ │ LRU: move_to_front via map[entry._isolate_recompiles_id] │ │ PGO (frame_state): shared across all buckets │ │ Python iteration: _get_cache_entries_for_region(code, id) │ └─────────────────────────────────────────────────────────────┘ Key changes from before: - _owner_list pointer removed from CacheEntry - .next() removed — Python gets full list via C++ API - _isolate_recompiles_id on CacheEntry for map lookups - Each bucket is still a std::list<CacheEntry> (LRU ordered) - Isolated compiles fall back read-only to [-1] (BC friendly) ``` ## Use cases ### Factory pattern ```python @cache def factory(key): @torch.compile(fullgraph=True, isolate_recompiles=True) def frontend(x, n): return core(x) + n return frontend factory("foo")(torch.ones(3), 3) # compiles in bucket 0 factory("bar")(torch.ones(4), 3) # compiles in bucket 1 factory("baz")(torch.ones(5), 3) # compiles in bucket 2 ``` ### Static vs dynamic on same function ```python opt_static = torch.compile(f, dynamic=False, isolate_recompiles=True) opt_dynamic = torch.compile(f, dynamic=True, isolate_recompiles=True) # Each has its own cache — static entries don't interfere with dynamic entries # Each exhausts its recompile_limit independently ``` ### Shared PGO With `isolate_recompiles`, PGO (`frame_state`) is still shared across compiles on the same code object. Compile B benefits from compile A's shape observations. ## Changes **C++:** - `eval_frame.c/h`: Thread-local `isolate_recompiles_id`, `get_current_isolate_recompiles_id()`, `set_eval_frame_isolate_recompiles_id_py()`. - `extra_state.h/cpp`: - `unordered_map<int64_t, list<CacheEntry>> cache_entry_map` — per-region cache buckets. - `unordered_map<int64_t, FrameExecStrategy> region_strategy_map` — per-region `RUN_ONLY` persistence after limit hit. - `lookup()` searches own bucket, falls back read-only to bucket -1 for isolated compiles. - `extra_state_get_region_exec_strategy(extra, id)`: for isolated regions with no map entry, inherits global `SKIP` (deliberate `skip_code` / `@skip` / FX plumbing decisions) but **not** global `RUN_ONLY` (avoids non-isolated limit-hit bleeding into new regions). Single strategy read drives both SKIP short-circuit and RUN_ONLY check in `eval_frame_cpp.cpp`. - `extract_cache_entry(extra, id)`: searches own bucket first, then default. - `_get_cache_entries_for_region(code, id)`: returns entries for a specific bucket in LRU order. - `_debug_get_cache_entry_list`: sorted by `isolate_recompiles_id` for deterministic iteration. - `move_to_front` / `move_to_back` / `invalidate` locate the correct list via `_isolate_recompiles_id`. - `cache_entry.h/cpp`: `_isolate_recompiles_id` field on CacheEntry. Removed `_owner_list` pointer and `.next` property — callers iterate per-bucket lists instead. - `init.cpp`: `_get_cache_entries_for_region` binding, `isolate_recompiles_id` readonly property on CacheEntry. **Python:** - `torch/__init__.py`: `isolate_recompiles: bool = False`, `recompile_limit: int | None = None` kwargs on `torch.compile()`. Docstring documents BC-friendly default-bucket fallback, per-region vs accumulated limit semantics, and the SKIP-inherit / RUN_ONLY-isolate asymmetry. - `torch/_dynamo/eval_frame.py`: - Id minted in `_optimize` / `_optimize_assert`, passed as a kwarg through `_optimize_catch_errors` → `OptimizeContext` → `_TorchDynamoContext.__init__` → closed over by `compile_wrapper`. - `compile_wrapper` sets/restores TLS id around `fn(*args, **kwargs)`. Ctx-manager `__enter__`/`__exit__` do **not** set TLS id — `raise_on_ctx_manager_usage=True` by default makes that path unreachable. - `_get_cache_entries_for_region()` Python wrapper with LRU-order / bucket semantics docstring. - `torch/_dynamo/convert_frame.py`: - `ConvertFrameAssert`, `ConvertFrame`, their factories, and `_clone_with_backend` no longer carry `_isolate_recompiles` / `_isolate_recompiles_id` attributes. Id flows via TLS, read in `ConvertFrameAssert.__call__`. - Recompile-reason logging: `cache_entries` (filtered per-region) used for `compute_cache_size` and `build_guards`; `cache_entries_for_reasons` = region ∪ default for isolated calls, passed to `get_and_maybe_log_recompilation_reasons` so default-bucket guard failures aren't dropped from the log. - `torch/_dynamo/cache_size.py`: `compute_cache_size` takes a filtered list (per-region); `total_cache_entries_all_regions` is used only for the accumulated-limit safety cap. - `torch/_dynamo/guards.py`: `get_and_maybe_log_recompilation_reasons` and `update_diff_guard_managers_for_existing_cache_entries` take lists instead of walking `.next`. `CheckFunctionManager` accepts `cache_entries` list. ## Test Plan `IsolateRecompilesTests` (full list below; grouped by scenario): **Basic isolation** - `test_isolate_recompiles_basic` - `test_isolate_recompiles_same_function_different_regions` - `test_isolate_recompiles_factory_pattern` - `test_isolate_recompiles_same_backend_different_regions` - `test_isolate_recompiles_string_backends` (parametrized over eager/aot_eager/inductor) **Static vs dynamic** - `test_isolate_recompiles_static_and_dynamic` - `test_isolate_recompiles_mark_dynamic_vs_static` - `test_isolate_recompiles_auto_dynamic_shared_pgo` - `test_isolate_recompiles_same_backend_different_dynamic_independent_limits` **Recompile limits** - `test_isolate_recompiles_fullgraph_raises` - `test_isolate_recompiles_accumulated_limit` - `test_isolate_recompiles_accumulated_limit_hard_fail` **RUN_ONLY per-region persistence** - `test_isolate_recompiles_limit_does_not_skip_other_regions` - `test_isolate_recompiles_region_run_only_persists` **Default strategy × region: SKIP inherited, RUN_ONLY not** - `test_isolate_recompiles_inherits_default_skip` - `test_isolate_recompiles_ignores_default_run_only` **Cache internals** - `test_isolate_recompiles_insertion_order_per_region` - `test_isolate_recompiles_lru_move_to_front` - `test_non_isolated_entries_visible_to_isolated` (BC-friendly fallback) - `test_isolate_recompiles_reasons_include_default_bucket` (reason-logging across buckets) - `test_non_isolated_reasons_unchanged` (id=-1 regression) - `test_reasons_include_all_default_entries` (multi-entry default bucket reason coverage) - `test_reset_clears_region_strategy` (reset clears `region_strategy_map`) - `test_non_isolated_compiles_share_cache` - `test_no_isolate_recompiles_shared_cache` - `test_different_backends_shared_cache_without_isolate` - `test_different_backends_independent_with_isolate` **Lifecycle** - `test_isolate_recompiles_reset` - `test_isolate_recompiles_resume_function` - `test_isolate_recompiles_gc_wrapper` **Debug / introspection** - `test_debug_get_cache_entry_list_deterministic_order` ```bash python test/dynamo/test_recompile_ux.py IsolateRecompilesTests python test/dynamo/test_recompile_ux.py RecompileUxTests python test/dynamo/test_recompile_ux.py RecompileLimitKwargTests ``` Pull Request resolved: pytorch#178351 Approved by: https://github.com/williamwen42 ghstack dependencies: pytorch#177936
…ation (pytorch#178351) ## TL;DR `torch.compile(f, isolate_recompiles=True)` — each compile call gets its own cache bucket so they don't interfere. Zero overhead when not used. ## Summary Cache entries in Dynamo are stored per code object. When multiple `torch.compile()` calls target the same function, their cache entries share one linked list. This causes cross-compile interference: one compile call's compilations affect another's cache lookup, recompile limit checks, and `FrameExecStrategy`. `torch.compile(f, isolate_recompiles=True)` gives each compile call its own isolated cache: 1. **Global `isolate_recompiles_id`** — set/restored from Python around each `torch.compile` invocation. `get_current_isolate_recompiles_id()` is a single global read. 2. **Per-compile cache map** — `ExtraState` stores an `unordered_map<int64_t, list<CacheEntry>> cache_entry_map`. Non-isolated compiles use key -1, isolated compiles get unique ids >= 0. Each `CacheEntry` stores its `_isolate_recompiles_id`, used by `move_to_front`/`move_to_back`/`invalidate` to locate the correct list via map lookup. 3. **`recompile_limit` kwarg** — `torch.compile(f, recompile_limit=N)` sets a per-compile recompile limit independent of `config.recompile_limit`. Isolated compiles also fall back read-only to the default bucket (key -1) during lookup, so non-isolated compilations with matching backends remain visible. This is BC friendly. New entries are always written to the isolated bucket only. ## Before (single flat list per code object) ``` ExtraState (per code object) │ └── cache_entry_list: std::list<CacheEntry> ← one shared list │ ├── CacheEntry { guards, code, backend_A } │ _owner_list ──► &cache_entry_list │ next() ──► CacheEntry below │ ├── CacheEntry { guards, code, backend_B } │ _owner_list ──► &cache_entry_list │ next() ──► CacheEntry below │ └── CacheEntry { guards, code, backend_A } _owner_list ──► &cache_entry_list next() ──► None Problems: - All torch.compile() calls share one list - Recompile limit counted across ALL entries - opt_a's entries interfere with opt_b's lookup - Python walks list via .next (linked-list traversal) ``` ## After (per-compile cache map) ``` torch.compile(f, isolate_recompiles=True) │ ▼ ┌─────────────────────────────────────┐ │ ConvertFrameAssert │ │ _isolate_recompiles_id = N │ ◄── allocated once, shared with clones │ _clone_with_backend ─────────────┼──── preserves same id └──────────────┬──────────────────────┘ │ ▼ ┌─────────────────────────────────────┐ │ _TorchDynamoContext (eval_frame.py)│ │ sets global id before fn call │ ◄── save/restore around fn(*args) │ restores previous id after │ └──────────────┬──────────────────────┘ │ ▼ ┌─────────────────────────────────────┐ │ C++ eval_frame │ │ id = get_current_isolate_ │ │ recompiles_id() │ │ lookup(extra, ..., id, ...) │ └──────────────┬──────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────┐ │ ExtraState (per code object) │ │ │ │ cache_entry_map: unordered_map<int64_t, list<CacheEntry>> │ │ ┌─────┬───────────────────────────────────────────┐ │ │ │ -1 │ CacheEntry ↔ CacheEntry ↔ CacheEntry │ non- │ │ │ │ (_isolate_recompiles_id = -1) │ iso. │ │ ├─────┼───────────────────────────────────────────┤ │ │ │ 0 │ CacheEntry ↔ CacheEntry │ opt_a │ │ │ │ (_isolate_recompiles_id = 0) │ │ │ ├─────┼───────────────────────────────────────────┤ │ │ │ 1 │ CacheEntry │ opt_b │ │ │ │ (_isolate_recompiles_id = 1) │ │ │ └─────┴───────────────────────────────────────────┘ │ │ │ │ Lookup: cache_entry_map[id], fallback to [-1] if id >= 0 │ │ Recompile limit: counted per bucket │ │ LRU: move_to_front via map[entry._isolate_recompiles_id] │ │ PGO (frame_state): shared across all buckets │ │ Python iteration: _get_cache_entries_for_region(code, id) │ └─────────────────────────────────────────────────────────────┘ Key changes from before: - _owner_list pointer removed from CacheEntry - .next() removed — Python gets full list via C++ API - _isolate_recompiles_id on CacheEntry for map lookups - Each bucket is still a std::list<CacheEntry> (LRU ordered) - Isolated compiles fall back read-only to [-1] (BC friendly) ``` ## Use cases ### Factory pattern ```python @cache def factory(key): @torch.compile(fullgraph=True, isolate_recompiles=True) def frontend(x, n): return core(x) + n return frontend factory("foo")(torch.ones(3), 3) # compiles in bucket 0 factory("bar")(torch.ones(4), 3) # compiles in bucket 1 factory("baz")(torch.ones(5), 3) # compiles in bucket 2 ``` ### Static vs dynamic on same function ```python opt_static = torch.compile(f, dynamic=False, isolate_recompiles=True) opt_dynamic = torch.compile(f, dynamic=True, isolate_recompiles=True) # Each has its own cache — static entries don't interfere with dynamic entries # Each exhausts its recompile_limit independently ``` ### Shared PGO With `isolate_recompiles`, PGO (`frame_state`) is still shared across compiles on the same code object. Compile B benefits from compile A's shape observations. ## Changes **C++:** - `eval_frame.c/h`: Thread-local `isolate_recompiles_id`, `get_current_isolate_recompiles_id()`, `set_eval_frame_isolate_recompiles_id_py()`. - `extra_state.h/cpp`: - `unordered_map<int64_t, list<CacheEntry>> cache_entry_map` — per-region cache buckets. - `unordered_map<int64_t, FrameExecStrategy> region_strategy_map` — per-region `RUN_ONLY` persistence after limit hit. - `lookup()` searches own bucket, falls back read-only to bucket -1 for isolated compiles. - `extra_state_get_region_exec_strategy(extra, id)`: for isolated regions with no map entry, inherits global `SKIP` (deliberate `skip_code` / `@skip` / FX plumbing decisions) but **not** global `RUN_ONLY` (avoids non-isolated limit-hit bleeding into new regions). Single strategy read drives both SKIP short-circuit and RUN_ONLY check in `eval_frame_cpp.cpp`. - `extract_cache_entry(extra, id)`: searches own bucket first, then default. - `_get_cache_entries_for_region(code, id)`: returns entries for a specific bucket in LRU order. - `_debug_get_cache_entry_list`: sorted by `isolate_recompiles_id` for deterministic iteration. - `move_to_front` / `move_to_back` / `invalidate` locate the correct list via `_isolate_recompiles_id`. - `cache_entry.h/cpp`: `_isolate_recompiles_id` field on CacheEntry. Removed `_owner_list` pointer and `.next` property — callers iterate per-bucket lists instead. - `init.cpp`: `_get_cache_entries_for_region` binding, `isolate_recompiles_id` readonly property on CacheEntry. **Python:** - `torch/__init__.py`: `isolate_recompiles: bool = False`, `recompile_limit: int | None = None` kwargs on `torch.compile()`. Docstring documents BC-friendly default-bucket fallback, per-region vs accumulated limit semantics, and the SKIP-inherit / RUN_ONLY-isolate asymmetry. - `torch/_dynamo/eval_frame.py`: - Id minted in `_optimize` / `_optimize_assert`, passed as a kwarg through `_optimize_catch_errors` → `OptimizeContext` → `_TorchDynamoContext.__init__` → closed over by `compile_wrapper`. - `compile_wrapper` sets/restores TLS id around `fn(*args, **kwargs)`. Ctx-manager `__enter__`/`__exit__` do **not** set TLS id — `raise_on_ctx_manager_usage=True` by default makes that path unreachable. - `_get_cache_entries_for_region()` Python wrapper with LRU-order / bucket semantics docstring. - `torch/_dynamo/convert_frame.py`: - `ConvertFrameAssert`, `ConvertFrame`, their factories, and `_clone_with_backend` no longer carry `_isolate_recompiles` / `_isolate_recompiles_id` attributes. Id flows via TLS, read in `ConvertFrameAssert.__call__`. - Recompile-reason logging: `cache_entries` (filtered per-region) used for `compute_cache_size` and `build_guards`; `cache_entries_for_reasons` = region ∪ default for isolated calls, passed to `get_and_maybe_log_recompilation_reasons` so default-bucket guard failures aren't dropped from the log. - `torch/_dynamo/cache_size.py`: `compute_cache_size` takes a filtered list (per-region); `total_cache_entries_all_regions` is used only for the accumulated-limit safety cap. - `torch/_dynamo/guards.py`: `get_and_maybe_log_recompilation_reasons` and `update_diff_guard_managers_for_existing_cache_entries` take lists instead of walking `.next`. `CheckFunctionManager` accepts `cache_entries` list. ## Test Plan `IsolateRecompilesTests` (full list below; grouped by scenario): **Basic isolation** - `test_isolate_recompiles_basic` - `test_isolate_recompiles_same_function_different_regions` - `test_isolate_recompiles_factory_pattern` - `test_isolate_recompiles_same_backend_different_regions` - `test_isolate_recompiles_string_backends` (parametrized over eager/aot_eager/inductor) **Static vs dynamic** - `test_isolate_recompiles_static_and_dynamic` - `test_isolate_recompiles_mark_dynamic_vs_static` - `test_isolate_recompiles_auto_dynamic_shared_pgo` - `test_isolate_recompiles_same_backend_different_dynamic_independent_limits` **Recompile limits** - `test_isolate_recompiles_fullgraph_raises` - `test_isolate_recompiles_accumulated_limit` - `test_isolate_recompiles_accumulated_limit_hard_fail` **RUN_ONLY per-region persistence** - `test_isolate_recompiles_limit_does_not_skip_other_regions` - `test_isolate_recompiles_region_run_only_persists` **Default strategy × region: SKIP inherited, RUN_ONLY not** - `test_isolate_recompiles_inherits_default_skip` - `test_isolate_recompiles_ignores_default_run_only` **Cache internals** - `test_isolate_recompiles_insertion_order_per_region` - `test_isolate_recompiles_lru_move_to_front` - `test_non_isolated_entries_visible_to_isolated` (BC-friendly fallback) - `test_isolate_recompiles_reasons_include_default_bucket` (reason-logging across buckets) - `test_non_isolated_reasons_unchanged` (id=-1 regression) - `test_reasons_include_all_default_entries` (multi-entry default bucket reason coverage) - `test_reset_clears_region_strategy` (reset clears `region_strategy_map`) - `test_non_isolated_compiles_share_cache` - `test_no_isolate_recompiles_shared_cache` - `test_different_backends_shared_cache_without_isolate` - `test_different_backends_independent_with_isolate` **Lifecycle** - `test_isolate_recompiles_reset` - `test_isolate_recompiles_resume_function` - `test_isolate_recompiles_gc_wrapper` **Debug / introspection** - `test_debug_get_cache_entry_list_deterministic_order` ```bash python test/dynamo/test_recompile_ux.py IsolateRecompilesTests python test/dynamo/test_recompile_ux.py RecompileUxTests python test/dynamo/test_recompile_ux.py RecompileLimitKwargTests ``` Pull Request resolved: pytorch#178351 Approved by: https://github.com/williamwen42 ghstack dependencies: pytorch#177936
…ation (pytorch#178351) ## TL;DR `torch.compile(f, isolate_recompiles=True)` — each compile call gets its own cache bucket so they don't interfere. Zero overhead when not used. ## Summary Cache entries in Dynamo are stored per code object. When multiple `torch.compile()` calls target the same function, their cache entries share one linked list. This causes cross-compile interference: one compile call's compilations affect another's cache lookup, recompile limit checks, and `FrameExecStrategy`. `torch.compile(f, isolate_recompiles=True)` gives each compile call its own isolated cache: 1. **Global `isolate_recompiles_id`** — set/restored from Python around each `torch.compile` invocation. `get_current_isolate_recompiles_id()` is a single global read. 2. **Per-compile cache map** — `ExtraState` stores an `unordered_map<int64_t, list<CacheEntry>> cache_entry_map`. Non-isolated compiles use key -1, isolated compiles get unique ids >= 0. Each `CacheEntry` stores its `_isolate_recompiles_id`, used by `move_to_front`/`move_to_back`/`invalidate` to locate the correct list via map lookup. 3. **`recompile_limit` kwarg** — `torch.compile(f, recompile_limit=N)` sets a per-compile recompile limit independent of `config.recompile_limit`. Isolated compiles also fall back read-only to the default bucket (key -1) during lookup, so non-isolated compilations with matching backends remain visible. This is BC friendly. New entries are always written to the isolated bucket only. ## Before (single flat list per code object) ``` ExtraState (per code object) │ └── cache_entry_list: std::list<CacheEntry> ← one shared list │ ├── CacheEntry { guards, code, backend_A } │ _owner_list ──► &cache_entry_list │ next() ──► CacheEntry below │ ├── CacheEntry { guards, code, backend_B } │ _owner_list ──► &cache_entry_list │ next() ──► CacheEntry below │ └── CacheEntry { guards, code, backend_A } _owner_list ──► &cache_entry_list next() ──► None Problems: - All torch.compile() calls share one list - Recompile limit counted across ALL entries - opt_a's entries interfere with opt_b's lookup - Python walks list via .next (linked-list traversal) ``` ## After (per-compile cache map) ``` torch.compile(f, isolate_recompiles=True) │ ▼ ┌─────────────────────────────────────┐ │ ConvertFrameAssert │ │ _isolate_recompiles_id = N │ ◄── allocated once, shared with clones │ _clone_with_backend ─────────────┼──── preserves same id └──────────────┬──────────────────────┘ │ ▼ ┌─────────────────────────────────────┐ │ _TorchDynamoContext (eval_frame.py)│ │ sets global id before fn call │ ◄── save/restore around fn(*args) │ restores previous id after │ └──────────────┬──────────────────────┘ │ ▼ ┌─────────────────────────────────────┐ │ C++ eval_frame │ │ id = get_current_isolate_ │ │ recompiles_id() │ │ lookup(extra, ..., id, ...) │ └──────────────┬──────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────┐ │ ExtraState (per code object) │ │ │ │ cache_entry_map: unordered_map<int64_t, list<CacheEntry>> │ │ ┌─────┬───────────────────────────────────────────┐ │ │ │ -1 │ CacheEntry ↔ CacheEntry ↔ CacheEntry │ non- │ │ │ │ (_isolate_recompiles_id = -1) │ iso. │ │ ├─────┼───────────────────────────────────────────┤ │ │ │ 0 │ CacheEntry ↔ CacheEntry │ opt_a │ │ │ │ (_isolate_recompiles_id = 0) │ │ │ ├─────┼───────────────────────────────────────────┤ │ │ │ 1 │ CacheEntry │ opt_b │ │ │ │ (_isolate_recompiles_id = 1) │ │ │ └─────┴───────────────────────────────────────────┘ │ │ │ │ Lookup: cache_entry_map[id], fallback to [-1] if id >= 0 │ │ Recompile limit: counted per bucket │ │ LRU: move_to_front via map[entry._isolate_recompiles_id] │ │ PGO (frame_state): shared across all buckets │ │ Python iteration: _get_cache_entries_for_region(code, id) │ └─────────────────────────────────────────────────────────────┘ Key changes from before: - _owner_list pointer removed from CacheEntry - .next() removed — Python gets full list via C++ API - _isolate_recompiles_id on CacheEntry for map lookups - Each bucket is still a std::list<CacheEntry> (LRU ordered) - Isolated compiles fall back read-only to [-1] (BC friendly) ``` ## Use cases ### Factory pattern ```python @cache def factory(key): @torch.compile(fullgraph=True, isolate_recompiles=True) def frontend(x, n): return core(x) + n return frontend factory("foo")(torch.ones(3), 3) # compiles in bucket 0 factory("bar")(torch.ones(4), 3) # compiles in bucket 1 factory("baz")(torch.ones(5), 3) # compiles in bucket 2 ``` ### Static vs dynamic on same function ```python opt_static = torch.compile(f, dynamic=False, isolate_recompiles=True) opt_dynamic = torch.compile(f, dynamic=True, isolate_recompiles=True) # Each has its own cache — static entries don't interfere with dynamic entries # Each exhausts its recompile_limit independently ``` ### Shared PGO With `isolate_recompiles`, PGO (`frame_state`) is still shared across compiles on the same code object. Compile B benefits from compile A's shape observations. ## Changes **C++:** - `eval_frame.c/h`: Thread-local `isolate_recompiles_id`, `get_current_isolate_recompiles_id()`, `set_eval_frame_isolate_recompiles_id_py()`. - `extra_state.h/cpp`: - `unordered_map<int64_t, list<CacheEntry>> cache_entry_map` — per-region cache buckets. - `unordered_map<int64_t, FrameExecStrategy> region_strategy_map` — per-region `RUN_ONLY` persistence after limit hit. - `lookup()` searches own bucket, falls back read-only to bucket -1 for isolated compiles. - `extra_state_get_region_exec_strategy(extra, id)`: for isolated regions with no map entry, inherits global `SKIP` (deliberate `skip_code` / `@skip` / FX plumbing decisions) but **not** global `RUN_ONLY` (avoids non-isolated limit-hit bleeding into new regions). Single strategy read drives both SKIP short-circuit and RUN_ONLY check in `eval_frame_cpp.cpp`. - `extract_cache_entry(extra, id)`: searches own bucket first, then default. - `_get_cache_entries_for_region(code, id)`: returns entries for a specific bucket in LRU order. - `_debug_get_cache_entry_list`: sorted by `isolate_recompiles_id` for deterministic iteration. - `move_to_front` / `move_to_back` / `invalidate` locate the correct list via `_isolate_recompiles_id`. - `cache_entry.h/cpp`: `_isolate_recompiles_id` field on CacheEntry. Removed `_owner_list` pointer and `.next` property — callers iterate per-bucket lists instead. - `init.cpp`: `_get_cache_entries_for_region` binding, `isolate_recompiles_id` readonly property on CacheEntry. **Python:** - `torch/__init__.py`: `isolate_recompiles: bool = False`, `recompile_limit: int | None = None` kwargs on `torch.compile()`. Docstring documents BC-friendly default-bucket fallback, per-region vs accumulated limit semantics, and the SKIP-inherit / RUN_ONLY-isolate asymmetry. - `torch/_dynamo/eval_frame.py`: - Id minted in `_optimize` / `_optimize_assert`, passed as a kwarg through `_optimize_catch_errors` → `OptimizeContext` → `_TorchDynamoContext.__init__` → closed over by `compile_wrapper`. - `compile_wrapper` sets/restores TLS id around `fn(*args, **kwargs)`. Ctx-manager `__enter__`/`__exit__` do **not** set TLS id — `raise_on_ctx_manager_usage=True` by default makes that path unreachable. - `_get_cache_entries_for_region()` Python wrapper with LRU-order / bucket semantics docstring. - `torch/_dynamo/convert_frame.py`: - `ConvertFrameAssert`, `ConvertFrame`, their factories, and `_clone_with_backend` no longer carry `_isolate_recompiles` / `_isolate_recompiles_id` attributes. Id flows via TLS, read in `ConvertFrameAssert.__call__`. - Recompile-reason logging: `cache_entries` (filtered per-region) used for `compute_cache_size` and `build_guards`; `cache_entries_for_reasons` = region ∪ default for isolated calls, passed to `get_and_maybe_log_recompilation_reasons` so default-bucket guard failures aren't dropped from the log. - `torch/_dynamo/cache_size.py`: `compute_cache_size` takes a filtered list (per-region); `total_cache_entries_all_regions` is used only for the accumulated-limit safety cap. - `torch/_dynamo/guards.py`: `get_and_maybe_log_recompilation_reasons` and `update_diff_guard_managers_for_existing_cache_entries` take lists instead of walking `.next`. `CheckFunctionManager` accepts `cache_entries` list. ## Test Plan `IsolateRecompilesTests` (full list below; grouped by scenario): **Basic isolation** - `test_isolate_recompiles_basic` - `test_isolate_recompiles_same_function_different_regions` - `test_isolate_recompiles_factory_pattern` - `test_isolate_recompiles_same_backend_different_regions` - `test_isolate_recompiles_string_backends` (parametrized over eager/aot_eager/inductor) **Static vs dynamic** - `test_isolate_recompiles_static_and_dynamic` - `test_isolate_recompiles_mark_dynamic_vs_static` - `test_isolate_recompiles_auto_dynamic_shared_pgo` - `test_isolate_recompiles_same_backend_different_dynamic_independent_limits` **Recompile limits** - `test_isolate_recompiles_fullgraph_raises` - `test_isolate_recompiles_accumulated_limit` - `test_isolate_recompiles_accumulated_limit_hard_fail` **RUN_ONLY per-region persistence** - `test_isolate_recompiles_limit_does_not_skip_other_regions` - `test_isolate_recompiles_region_run_only_persists` **Default strategy × region: SKIP inherited, RUN_ONLY not** - `test_isolate_recompiles_inherits_default_skip` - `test_isolate_recompiles_ignores_default_run_only` **Cache internals** - `test_isolate_recompiles_insertion_order_per_region` - `test_isolate_recompiles_lru_move_to_front` - `test_non_isolated_entries_visible_to_isolated` (BC-friendly fallback) - `test_isolate_recompiles_reasons_include_default_bucket` (reason-logging across buckets) - `test_non_isolated_reasons_unchanged` (id=-1 regression) - `test_reasons_include_all_default_entries` (multi-entry default bucket reason coverage) - `test_reset_clears_region_strategy` (reset clears `region_strategy_map`) - `test_non_isolated_compiles_share_cache` - `test_no_isolate_recompiles_shared_cache` - `test_different_backends_shared_cache_without_isolate` - `test_different_backends_independent_with_isolate` **Lifecycle** - `test_isolate_recompiles_reset` - `test_isolate_recompiles_resume_function` - `test_isolate_recompiles_gc_wrapper` **Debug / introspection** - `test_debug_get_cache_entry_list_deterministic_order` ```bash python test/dynamo/test_recompile_ux.py IsolateRecompilesTests python test/dynamo/test_recompile_ux.py RecompileUxTests python test/dynamo/test_recompile_ux.py RecompileLimitKwargTests ``` Pull Request resolved: pytorch#178351 Approved by: https://github.com/williamwen42 ghstack dependencies: pytorch#177936
Stack from ghstack (oldest at bottom):
TL;DR
torch.compile(f, isolate_recompiles=True)— each compile call gets its own cache bucket so they don't interfere. Zero overhead when not used.Summary
Cache entries in Dynamo are stored per code object. When multiple
torch.compile()callstarget the same function, their cache entries share one linked list. This causes
cross-compile interference: one compile call's compilations affect another's cache lookup,
recompile limit checks, and
FrameExecStrategy.torch.compile(f, isolate_recompiles=True)gives each compile call its own isolated cache:isolate_recompiles_id— set/restored from Python around eachtorch.compileinvocation.get_current_isolate_recompiles_id()is a single globalread.
ExtraStatestores anunordered_map<int64_t, list<CacheEntry>> cache_entry_map. Non-isolated compiles usekey -1, isolated compiles get unique ids >= 0. Each
CacheEntrystores its_isolate_recompiles_id, used bymove_to_front/move_to_back/invalidateto locatethe correct list via map lookup.
recompile_limitkwarg —torch.compile(f, recompile_limit=N)sets a per-compilerecompile limit independent of
config.recompile_limit.Isolated compiles also fall back read-only to the default bucket (key -1) during lookup,
so non-isolated compilations with matching backends remain visible. This is BC friendly.
New entries are always written to the isolated bucket only.
Before (single flat list per code object)
After (per-compile cache map)
Use cases
Factory pattern
Static vs dynamic on same function
Shared PGO
With
isolate_recompiles, PGO (frame_state) is still shared across compiles on thesame code object. Compile B benefits from compile A's shape observations.
Changes
C++:
eval_frame.c/h: Thread-localisolate_recompiles_id,get_current_isolate_recompiles_id(),set_eval_frame_isolate_recompiles_id_py().extra_state.h/cpp:unordered_map<int64_t, list<CacheEntry>> cache_entry_map— per-region cache buckets.unordered_map<int64_t, FrameExecStrategy> region_strategy_map— per-regionRUN_ONLYpersistence after limit hit.lookup()searches own bucket, falls back read-only to bucket -1 for isolated compiles.extra_state_get_region_exec_strategy(extra, id): for isolated regions with no mapentry, inherits global
SKIP(deliberateskip_code/@skip/ FX plumbingdecisions) but not global
RUN_ONLY(avoids non-isolated limit-hit bleeding intonew regions). Single strategy read drives both SKIP short-circuit and RUN_ONLY check
in
eval_frame_cpp.cpp.extract_cache_entry(extra, id): searches own bucket first, then default._get_cache_entries_for_region(code, id): returns entries for a specific bucket inLRU order.
_debug_get_cache_entry_list: sorted byisolate_recompiles_idfor deterministiciteration.
move_to_front/move_to_back/invalidatelocate the correct list via_isolate_recompiles_id.cache_entry.h/cpp:_isolate_recompiles_idfield on CacheEntry. Removed_owner_listpointer and
.nextproperty — callers iterate per-bucket lists instead.init.cpp:_get_cache_entries_for_regionbinding,isolate_recompiles_idreadonlyproperty on CacheEntry.
Python:
torch/__init__.py:isolate_recompiles: bool = False,recompile_limit: int | None = Nonekwargs on
torch.compile(). Docstring documents BC-friendly default-bucket fallback,per-region vs accumulated limit semantics, and the SKIP-inherit / RUN_ONLY-isolate
asymmetry.
torch/_dynamo/eval_frame.py:_optimize/_optimize_assert, passed as a kwarg through_optimize_catch_errors→OptimizeContext→_TorchDynamoContext.__init__→closed over by
compile_wrapper.compile_wrappersets/restores TLS id aroundfn(*args, **kwargs). Ctx-manager__enter__/__exit__do not set TLS id —raise_on_ctx_manager_usage=Trueby default makes that path unreachable.
_get_cache_entries_for_region()Python wrapper with LRU-order / bucket semanticsdocstring.
torch/_dynamo/convert_frame.py:ConvertFrameAssert,ConvertFrame, their factories, and_clone_with_backendno longer carry
_isolate_recompiles/_isolate_recompiles_idattributes. Idflows via TLS, read in
ConvertFrameAssert.__call__.cache_entries(filtered per-region) used forcompute_cache_sizeandbuild_guards;cache_entries_for_reasons= region ∪default for isolated calls, passed to
get_and_maybe_log_recompilation_reasonssodefault-bucket guard failures aren't dropped from the log.
torch/_dynamo/cache_size.py:compute_cache_sizetakes a filtered list (per-region);total_cache_entries_all_regionsis used only for the accumulated-limit safety cap.torch/_dynamo/guards.py:get_and_maybe_log_recompilation_reasonsandupdate_diff_guard_managers_for_existing_cache_entriestake lists instead of walking.next.CheckFunctionManageracceptscache_entrieslist.Test Plan
IsolateRecompilesTests(full list below; grouped by scenario):Basic isolation
test_isolate_recompiles_basictest_isolate_recompiles_same_function_different_regionstest_isolate_recompiles_factory_patterntest_isolate_recompiles_same_backend_different_regionstest_isolate_recompiles_string_backends(parametrized over eager/aot_eager/inductor)Static vs dynamic
test_isolate_recompiles_static_and_dynamictest_isolate_recompiles_mark_dynamic_vs_statictest_isolate_recompiles_auto_dynamic_shared_pgotest_isolate_recompiles_same_backend_different_dynamic_independent_limitsRecompile limits
test_isolate_recompiles_fullgraph_raisestest_isolate_recompiles_accumulated_limittest_isolate_recompiles_accumulated_limit_hard_failRUN_ONLY per-region persistence
test_isolate_recompiles_limit_does_not_skip_other_regionstest_isolate_recompiles_region_run_only_persistsDefault strategy × region: SKIP inherited, RUN_ONLY not
test_isolate_recompiles_inherits_default_skiptest_isolate_recompiles_ignores_default_run_onlyCache internals
test_isolate_recompiles_insertion_order_per_regiontest_isolate_recompiles_lru_move_to_fronttest_non_isolated_entries_visible_to_isolated(BC-friendly fallback)test_isolate_recompiles_reasons_include_default_bucket(reason-logging across buckets)test_non_isolated_reasons_unchanged(id=-1 regression)test_reasons_include_all_default_entries(multi-entry default bucket reason coverage)test_reset_clears_region_strategy(reset clearsregion_strategy_map)test_non_isolated_compiles_share_cachetest_no_isolate_recompiles_shared_cachetest_different_backends_shared_cache_without_isolatetest_different_backends_independent_with_isolateLifecycle
test_isolate_recompiles_resettest_isolate_recompiles_resume_functiontest_isolate_recompiles_gc_wrapperDebug / introspection
test_debug_get_cache_entry_list_deterministic_ordercc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @Lucaskabela @jataylo @azahed98 @mlazos