Skip to content

[Dynamo][cache]Add Isolate_recompile flag for Dynamo cache isolation - #178351

Closed
fxdawnn wants to merge 22 commits into
gh/fxdawnn/50/basefrom
gh/fxdawnn/50/head
Closed

fxdawnn wants to merge 22 commits into
gh/fxdawnn/50/basefrom
gh/fxdawnn/50/head

Conversation

@fxdawnn

@fxdawnn fxdawnn commented Mar 25, 2026 •

Copy link
Copy Markdown
Contributor

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() 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

@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

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
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 @azahed98 @mlazos

@pytorch-bot

pytorch-bot Bot commented Mar 25, 2026 •

Copy link
Copy Markdown

🔗 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 SEVs

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

✅ No Failures

As of commit 5ff95e9 with merge base 3a3756a (image):
💚 Looks good so far! There are no failures yet. 💚

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

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

pytorch-bot Bot commented Mar 25, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

fxdawnn added a commit that referenced this pull request Mar 25, 2026
@fxdawnn
fxdawnn marked this pull request as draft March 25, 2026 00:10
@anijain2305

anijain2305 commented Mar 25, 2026 •

Copy link
Copy Markdown
Contributor

Some notes

  • region_id management - region_id is a counter which is set in the ConvertFrameAssert __init__ method. So for all recompilations of fn.__code__ object, they share the same region_id. This object is referred to as callback in C++. This region_id is also passed to the cached entry during the compilation. At lookup, we get the expected value from the callback and the new value from the cache_entry and compare the two.

  • Where does cache reside? Cache still reside on the fn.__code__ object, so there is still interference. All the recompilations go to the same code object, just that they have additional guard on the region_id.

Comment thread torch/_dynamo/convert_frame.py Outdated
Comment on lines +1824 to +1834
# 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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This will make things quite hard to diagnose on a recompile tbh

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This is right. Would you suggest adding the region_id to the error message?

@anijain2305 anijain2305 Mar 25, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I think we should evaluate the pros and cons of this approach against cloning the code object itself #178347

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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]
fxdawnn added a commit that referenced this pull request Mar 27, 2026
@fxdawnn
fxdawnn marked this pull request as ready for review March 27, 2026 23:35
… 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]
@fxdawnn
fxdawnn requested review from williamwen42 March 30, 2026 19:52
… 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]
fxdawnn added a commit that referenced this pull request Mar 31, 2026
ghstack-source-id: e14bcba
Pull Request resolved: #178351
… 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]
fxdawnn added a commit that referenced this pull request Mar 31, 2026
ghstack-source-id: e8f3492
Pull Request resolved: #178351
… 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]
fxdawnn added a commit that referenced this pull request Mar 31, 2026
ghstack-source-id: f5206b4
Pull Request resolved: #178351
… 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]
@bobrenjc93

Copy link
Copy Markdown
Contributor

@claude

@claude

claude Bot commented Mar 31, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 6m 51s —— View job


PR Review: [Dynamo][cache] Add Isolated_region flag with region_id for cache isolation

  • Read all changed files
  • Review C++ changes (eval_frame, extra_state, cache_entry)
  • Review Python changes (convert_frame, eval_frame, cache_size)
  • Review tests
  • Post review feedback

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 region_id propagation that means C++ cache isolation may not actually work in the non-fullgraph path.

Critical: _region_id not propagated through ConvertFrame to TSS

The non-fullgraph path doesn't properly set the TSS region_id, meaning the C++ per-region cache map won't be used.

Here's the chain:

  1. ConvertFrameAssert.__init__ (convert_frame.py:604-609) assigns self._region_id
  2. But ConvertFrame (convert_frame.py:2151) does not expose _region_id — it stores _isolated_region but not _region_id
  3. CatchErrorsWrapper.__init__ (convert_frame.py:2378) does functools.wraps(callback)(self) which copies ConvertFrame.__dict__ → no _region_id
  4. _TorchDynamoContext.__init__ (eval_frame.py:765) does self._region_id = getattr(callback, "_region_id", -1) — returns -1
  5. So set_eval_frame_region_id() in __enter__/compile_wrapper always sets TSS to -1
  6. C++ get_current_region_id() always returns -1 → all entries go to cache_entry_list, never region_cache_map

In contrast, the fullgraph path (_optimize_assert) passes ConvertFrameAssert directly to CatchErrorsWrapper, so functools.wraps copies _region_id and it works.

Why tests still pass: The tests use separate CompileCounter backends for different regions. Since backend_match() checks pointer/value equality, entries from one counter naturally don't match another. The Python-level _region_compilation_counts and apply_to_code=not self._isolated_region provide functional isolation at the Python level. But the C++ cache bucketing (the core feature) isn't exercised in the non-fullgraph case.

Fix: Add _region_id to ConvertFrame:

# convert_frame.py, ConvertFrame.__init__
self._region_id = self._inner_convert._region_id

Or alternatively, make _TorchDynamoContext reach through:

self._region_id = getattr(getattr(callback, "_inner_convert", None), "_region_id", 
                          getattr(callback, "_region_id", -1))

Test gap: Consider adding a test where two isolated regions use the same backend — this would fail without proper C++ bucketing but isn't currently covered:

def test_isolated_region_same_backend_different_regions(self):
    cnt = torch._dynamo.testing.CompileCounter()
    def f(x): return x.sin()
    opt_a = torch.compile(f, backend=cnt, isolated_region=True)
    opt_b = torch.compile(f, backend=cnt, isolated_region=True)
    opt_a(torch.randn(3))
    opt_b(torch.randn(3))
    # Should compile twice (independent regions), not once (cache hit)
    self.assertEqual(cnt.frame_count, 2)

Additional Issues

1. Global _next_region_id counter is not thread-safe (convert_frame.py:580, 605-607)

_next_region_id = 0
...
global _next_region_id
self._region_id = _next_region_id
_next_region_id += 1

This is a plain Python int with no locking. In multi-threaded compilation scenarios (e.g., torch.compile calls from different threads), two regions could get the same ID. Consider using itertools.count() which is atomic in CPython due to the GIL, or use threading.Lock.

Fix this →

2. _region_compilation_counts keys by id(code) — potential for ID reuse (convert_frame.py:603, 776-778)

self._region_compilation_counts: dict[int, int] = {}
...
self._region_compilation_counts[id(code)] = (
    self._region_compilation_counts.get(id(code), 0) + 1
)

id(code) can be reused after the code object is garbage collected. If a code object is freed and a new one allocated at the same address, the count would be inherited. The PR description acknowledges this design choice ("keyed by id(code) to avoid holding unpicklable code objects"), but a weakref.WeakValueDictionary or similar approach might be safer. In practice this is unlikely to cause issues since Dynamo tends to hold references to code objects, but it's worth noting.

3. Recompile limit check for isolated regions ignores recompile_limit kwarg (convert_frame.py:1836)

elif cache_size.region_num_compilations >= config.recompile_limit:
    exceeded, limit_type = True, "recompile_limit"

This uses config.recompile_limit (the global config), not self._recompile_limit (the per-compile kwarg). If a user passes both isolated_region=True and recompile_limit=N, the kwarg is ignored in favor of the global config. The non-isolated path in exceeds_recompile_limit() also uses config.recompile_limit, so this may be intentional — but it's confusing given the PR adds both features.

Fix this →

4. GuardedCode.region_id is set but never read in C++ (types.py:73)

region_id: int = -1

GuardedCode now carries region_id, and it's set in _compile() at line 1767. However, in C++, create_cache_entry() (extra_state.cpp:313) gets the region_id from get_current_region_id() (TSS), not from the guarded_code Python object. This means GuardedCode.region_id is unused in the cache creation path. If the TSS bug above is fixed, this field is purely informational. If not, it creates a false sense that the region_id is being used.

5. has_any_cache_entries() iterates the entire region map (extra_state.cpp:45-57)

bool ExtraState::has_any_cache_entries() const {
  if (!this->cache_entry_list.empty()) return true;
  if (this->region_cache_map) {
    for (const auto& kv : *this->region_cache_map) {
      if (!kv.second.empty()) return true;
    }
  }
  return false;
}

This is called on every frame evaluation in eval_frame_cpp.cpp:566. While the number of regions is expected to be small, this is O(regions) on every cache hit path. Consider maintaining a separate counter (increment on insert, decrement on invalidation) to make this O(1).

6. Missing FrameExecStrategy scoping for isolated regions (convert_frame.py, eval_frame_cpp.cpp)

The FrameExecStrategy is stored on ExtraState (per code object), not per region. When an isolated region hits the recompile limit, the apply_to_code=not self._isolated_region fix (convert_frame.py:2293) prevents setting the strategy on the code object. But what about the strategy.cur_action == FrameAction::RUN_ONLY check in eval_frame_cpp.cpp:514? If a non-isolated compile on the same code object sets RUN_ONLY, it would affect all isolated regions too. There's no per-region strategy.

Minor Points

  • Test organization: All isolated region tests are in test_recompile_ux.py. This file is becoming large. Consider whether a separate test file (e.g., test_isolated_region.py) would be appropriate.

  • _debug_get_cache_entry_list (extra_state.cpp:336-356) iterates both cache_entry_list and region_cache_map to produce a flat list. This is correct for debugging but loses the region structure. A _debug_get_cache_entry_list_per_region helper might help debugging isolated region issues.

  • PR description mentions recompile_limit kwarg as a change in this PR, but looking at the diff it was already added in a prior stacked PR ([Dynamo][Cache]Add recompile_limit as torch.compile kwarg through plumbing #177936). The description could be clearer about what's new in this specific diff.

Summary

The design is solid — hybrid cache with lazy allocation, TSS for region tracking, shared PGO. The main issue is the _region_id propagation gap in the non-fullgraph path, which means the C++ cache bucketing isn't active for most use cases. The tests pass due to different backends providing natural isolation, masking this issue. Fixing the _region_id propagation and adding a same-backend test would ensure the feature works as designed.


… 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]
fxdawnn added a commit that referenced this pull request Apr 25, 2026
ghstack-source-id: 0cede1e
Pull Request resolved: #178351
… 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]
fxdawnn added a commit that referenced this pull request Apr 25, 2026
ghstack-source-id: da4ea34
Pull Request resolved: #178351
… 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]
fxdawnn added a commit that referenced this pull request Apr 25, 2026
ghstack-source-id: 733b515
Pull Request resolved: #178351

@williamwen42 williamwen42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for addressing all the comments!

@fxdawnn

fxdawnn commented Apr 27, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

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

Copy link
Copy Markdown
Collaborator

Merge started

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

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 8 mandatory check(s) failed. The first few are:

Dig deeper by viewing the failures on hud

Details for Dev Infra team Raised by workflow job

Failing merge rule: Core Maintainers

@fxdawnn

fxdawnn commented Apr 28, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

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

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

@fxdawnn fxdawnn changed the title [Dynamo][cache]Add Isolated_region flag with region_id for cache isolation [Dynamo][cache]Add Isolate_recompile flag with region_id for cache isolation May 2, 2026
@fxdawnn fxdawnn changed the title [Dynamo][cache]Add Isolate_recompile flag with region_id for cache isolation [Dynamo][cache]Add Isolate_recompile flag for Dynamo cache isolation May 2, 2026
@github-actions
github-actions Bot deleted the gh/fxdawnn/50/head branch June 2, 2026 02:28
aperson30 pushed a commit to aperson30/pytorch that referenced this pull request Jun 20, 2026
…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
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…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
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: dynamo release notes: dynamo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants