Skip to content

[config] Serve unwritten config reads from the module __dict__ - #193160

Closed
anijain2305 wants to merge 23 commits into
gh/anijain2305/1305/basefrom
gh/anijain2305/1305/head
Closed

anijain2305 wants to merge 23 commits into
gh/anijain2305/1305/basefrom
gh/anijain2305/1305/head

Conversation

@anijain2305

@anijain2305 anijain2305 commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Reading torch._inductor.config.foo costs ~1.5us. Almost none of that is the
lookup itself: ConfigModule defines getattr on the class, so every read
first runs normal attribute lookup, which misses and builds an AttributeError,
and only then reaches getattr, which walks the alias / env / user override
/ justknob / mutable-default precedence chain. Compilation reads configs
hundreds of thousands of times per compile, all of it going down that path.

Two changes, both aimed at the case where the answer is just the default:

  • _ConfigEntry.fast_default marks an entry whose read reduces to "user_override
    if set else default" - no alias, env value, justknob, deprecation warning, or
    mutable default that has to be deep-copied. getattr answers those in two
    lookups instead of the full chain.

  • install_config_module parks the default of every fast_default entry in the
    module dict (see Note [config shadow]), so plain attribute lookup finds
    it and getattr never runs. A shadow is only correct while the value is a
    context-independent constant, so any write drops it and that config goes back
    to getattr permanently. Since user_override is a ContextVar, an entry
    that is never written reads as its default in every thread and context.

Invalidation is centralized in _ConfigEntry.set_user_override rather than left
to each caller. An earlier version of this patch dropped the shadow in
setattr only, which silently broke _make_closure_patcher - it writes
user_override directly - and that is how torch.compile(dynamic=True) clears
assume_static_by_default. Reads kept returning the stale default, so the model
compiled with static shapes: 30% "faster" and wrong. Any future direct write to
user_override would reintroduce that, hence the comment on the field.

A config read drops from 1539ns to 99ns. On one model's cold compile with
dynamic=True, total compile time measured as the union of top-level chromium
events:

pair 1: baseline 49.15s changed 47.00s
pair 2: baseline 49.28s changed 47.51s
pair 3: baseline 48.51s changed 47.92s

i.e. 48.98s -> 47.48s, -3.1%, with the change winning every pair.

Test plan:

python test/test_utils_config_module.py
python test/dynamo/test_config.py
python test/inductor/test_config.py
python test/dynamo/test_misc.py
python test/test_dynamic_shapes.py
python test/test_public_bindings.py
python test/test_torch_config_hash_determinism.py

test_utils_config_module and dynamo/test_config pass outright; the rest have
pre-existing failures on this host (aarch64 CPU codegen, missing onnxscript)
and produce failure sets identical to a run with the change stashed.

This PR was authored with the assistance of an AI coding agent.

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Aug 12, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit 8a51c9d with merge base 7438967 (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 commented Aug 12, 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.

anijain2305 added a commit that referenced this pull request Aug 12, 2026
Reading torch._inductor.config.foo costs ~1.5us. Almost none of that is the
lookup itself: ConfigModule defines __getattr__ on the class, so every read
first runs normal attribute lookup, which misses and builds an AttributeError,
and only then reaches __getattr__, which walks the alias / env / user override
/ justknob / mutable-default precedence chain. Compilation reads configs
hundreds of thousands of times per compile, all of it going down that path.

Two changes, both aimed at the case where the answer is just the default:

- _ConfigEntry.fast_default marks an entry whose read reduces to "user_override
  if set else default" - no alias, env value, justknob, deprecation warning, or
  mutable default that has to be deep-copied. __getattr__ answers those in two
  lookups instead of the full chain.

- install_config_module parks the default of every fast_default entry in the
  module __dict__ (see Note [config shadow]), so plain attribute lookup finds
  it and __getattr__ never runs. A shadow is only correct while the value is a
  context-independent constant, so any write drops it and that config goes back
  to __getattr__ permanently. Since user_override is a ContextVar, an entry
  that is never written reads as its default in every thread and context.

Invalidation is centralized in _ConfigEntry.set_user_override rather than left
to each caller. An earlier version of this patch dropped the shadow in
__setattr__ only, which silently broke _make_closure_patcher - it writes
user_override directly - and that is how torch.compile(dynamic=True) clears
assume_static_by_default. Reads kept returning the stale default, so the model
compiled with static shapes: 30% "faster" and wrong. Any future direct write to
user_override would reintroduce that, hence the comment on the field.

A config read drops from 1539ns to 99ns. On a UMA cold compile (fairchem
uma-s-1p2, 1000 atoms, dynamic=True), total compile time measured as the union
of top-level chromium events:

  pair 1:  baseline 49.15s   changed 47.00s
  pair 2:  baseline 49.28s   changed 47.51s
  pair 3:  baseline 48.51s   changed 47.92s

i.e. 48.98s -> 47.48s, -3.1%, with the change winning every pair.

Test plan:

```
python test/test_utils_config_module.py
python test/dynamo/test_config.py
python test/inductor/test_config.py
python test/dynamo/test_misc.py
python test/test_dynamic_shapes.py
python test/test_public_bindings.py
python test/test_torch_config_hash_determinism.py
```

test_utils_config_module and dynamo/test_config pass outright; the rest have
pre-existing failures on this host (aarch64 CPU codegen, missing onnxscript)
and produce failure sets identical to a run with the change stashed.

This PR was authored with the assistance of an AI coding agent.


ghstack-source-id: 7504e3f
Pull-Request: #193160
[ghstack-poisoned]
@anijain2305

Copy link
Copy Markdown
Contributor Author

@claude review this PR - is it possible to still read the stale value if the user sets this config from outside

@claude

claude Bot commented Aug 12, 2026 •

Copy link
Copy Markdown

Claude finished @anijain2305's task in 58m 24s —— View job


Short answer

Yes — two narrow paths remain. Anything that goes through config.foo = x, patch(), load_config(), delattr/mock.patch, or _make_closure_patcher is safe, but the shadow can still go stale if a caller writes entry.user_override.set(...) directly (unenforced convention) or mutates entry.hide/entry.default without calling refresh_fast_default() — and there is already a live example of each in test/test_utils_config_module.py.

Full review

PR Review: #193160

Summary

Adds a fast_default fast path to ConfigModule.__getattr__ and parks defaults of simple entries in the module __dict__ so plain attribute lookup answers most config reads. The optimization is sound and the invalidation point chosen (set_user_override) is the right one, but the invariant is enforced only by convention, fast_default has a second uninvalidated dependency (hide), and no tests were added for either.

Answering the question: remaining stale-read paths

The shadow is dropped globally and permanently on first write, and never re-added. user_override is a ContextVar but module.__dict__ is process-global, so invalidation is strictly more conservative than the reads it guards — cross-thread and cross-context reads are fine. Writes via __setattr__ (torch/utils/_config_module.py:483), patch() (which calls config.__setattr__ explicitly at :1011), load_config (:929, routes to setattr), __delattr__ (:543) and _make_closure_patcher (:1052, :1058) all funnel into set_user_override. Env vars and justknobs are excluded from fast_default entirely. So the designed paths are covered.

What is not covered:

1. Direct entry.user_override.set(...). torch/utils/_config_module.py:361-362 documents the requirement in a comment, but nothing enforces it. test/test_utils_config_module.py:28 already does the raw .set() in tearDown. That instance happens to be benign (it writes _UNSET_SENTINEL, so the stale shadow and the recomputed value are both the default), but it demonstrates that the convention is already not being followed — and this is precisely the class of bug the PR description says produced a silently-wrong 30% "speedup". A comment is weak protection for a failure mode that is invisible at the call site.

Consider making it structurally impossible rather than documented: rename the field to _user_override and expose get_user_override() / set_user_override(), or move the drop into a user_override property setter. Grepping for the old name then finds every offender.

2. fast_default is a cache over seven mutable fields, and only one of them has invalidation wired up. refresh_fast_default() (:423) reads hide, deprecated, alias, justknob, env_value_force, env_value_default and default. Six of those are effectively immutable after __init__, but hide is written at runtime in three places, and the callers must remember to refresh:

  • test/test_utils_config_module.py:100 sets entry.hide = True directly with no refresh. fast_default stays True, so config.e_bool returns a value where pre-PR it raised AttributeError. That is the mock.patch workaround path, so it is not purely hypothetical.
  • test/test_utils_config_module.py:29 sets entry.hide = False with no refresh — benign (loses the optimization only), but same shape.
  • __delattr__ (:543-545) writes hide = True and then refreshes, so between those two statements a concurrent reader takes the fast path on a hidden entry. Narrow, but mock.patch does delattr→setattr and the suite exercises patching from multiple threads (test_patch_context_manager_is_reentrant_across_threads).

Since hide is the only field that actually moves, dropping it from refresh_fast_default and checking it inside the fast branch instead removes it from the invalidation surface completely:

if config.fast_default and not config.hide:

That costs one extra attribute load on the __getattr__ path only — never on the shadow path, which is the hot one — and eliminates all three sites above. Fix this →

3. Env vars set after import are still ignored — pre-existing, unchanged by this PR.

Testing

62 new lines in a module with ~900 lines of dedicated tests, and no test added. The existing test_make_closur_patcher (test/test_utils_config_module.py:507) does happen to cover the regression described in the PR body, which is reassuring, but the new mechanism itself is untested. Missing:

  • The shadow exists after install for a simple entry, and is gone from module.__dict__ after any write.
  • Hidden / deprecated / aliased / env-backed / justknob-backed / mutable-default entries are not shadowed and do not get fast_default.
  • A hidden entry still raises AttributeError (this is the case that regresses under item 2 above).
  • Cross-thread: thread A writes, thread B still reads its own context's value.

The highest-value test is a property test rather than any of the above: for every entry in fake_config_module (and ideally torch._inductor.config), assert that the value returned by getattr(module, name) equals the value the full slow chain would produce. refresh_fast_default is a blocklist by omission — if a future PR adds a new precedence source to __getattr__ and forgets to add it there, fast_default silently starts returning wrong values and nothing fails. A test that compares fast path against slow path for all entries is the only thing that catches that.

Backward Compatibility

dir() on a config module now lists config names. dir() on a module returns its __dict__ keys, and visit() previously deleted every config name from __dict__ (:222, :230), so dir(torch._dynamo.config) returned essentially nothing useful. It now returns all shadowed top-level names. In-tree consumers are fine (test/test_public_bindings.py:493-499 early-returns for non-callables, and _IMMUTABLE_CONFIG_TYPES cannot hold a callable; test/inductor/test_ck_backend.py:100 checks for rocm, a SubConfigProxy, which was already in __dict__). benchmarks/dynamo/runner.py:528 iterates dir(torch._dynamo.config) filtering for bools — it was silently emitting nothing and this PR accidentally fixes it. Worth a line in the description since it is user-visible, and worth confirming it is intended rather than incidental.

Code Quality

owner_dict is a plain dataclass field, so it participates in the generated __repr__ and __eq__. It holds module.__dict__, which contains _config, which contains the entry — so repr(entry) walks the entire module namespace (the dict recursion guard prevents a hang, but the output is enormous and useless), and == between two entries compares whole module dicts. Nothing in-tree reprs a _ConfigEntry today, but debuggers and error messages do it implicitly. Mark it field(repr=False, compare=False). Fix this →

Performance

Nested configs (config.triton.cudagraphs) never get a shadow — install_config_module:278 skips names containing ".", and SubConfigProxy.__getattr__ (:1123) calls __getattr__ explicitly anyway. They do still benefit from the fast_default branch, so this is a partial win, but the 1539ns→99ns figure applies only to top-level reads. Inductor reads nested configs heavily; worth noting in the description so the measured -3.1% isn't read as the ceiling.

Recommendation

Request Changes — on the missing invariant tests. The optimization is well-reasoned and the centralized invalidation point is the right design, but a mechanism whose failure mode is "silently returns a stale value" and which the author already found breaking real code once should not land with its invariants held up only by a comment. Adding the fast-path-vs-slow-path property test plus the hide restructure in item 2 would close both gaps.

· branch `gh/anijain2305/1305/head`

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
anijain2305 added a commit that referenced this pull request Aug 14, 2026
Reading torch._inductor.config.foo costs ~1.5us. Almost none of that is the
lookup itself: ConfigModule defines __getattr__ on the class, so every read
first runs normal attribute lookup, which misses and builds an AttributeError,
and only then reaches __getattr__, which walks the alias / env / user override
/ justknob / mutable-default precedence chain. Compilation reads configs
hundreds of thousands of times per compile, all of it going down that path.

Two changes, both aimed at the case where the answer is just the default:

- _ConfigEntry.fast_default marks an entry whose read reduces to "user_override
  if set else default" - no alias, env value, justknob, deprecation warning, or
  mutable default that has to be deep-copied. __getattr__ answers those in two
  lookups instead of the full chain.

- install_config_module parks the default of every fast_default entry in the
  module __dict__ (see Note [config shadow]), so plain attribute lookup finds
  it and __getattr__ never runs. A shadow is only correct while the value is a
  context-independent constant, so any write drops it and that config goes back
  to __getattr__ permanently. Since user_override is a ContextVar, an entry
  that is never written reads as its default in every thread and context.

Invalidation is centralized in _ConfigEntry.set_user_override rather than left
to each caller. An earlier version of this patch dropped the shadow in
__setattr__ only, which silently broke _make_closure_patcher - it writes
user_override directly - and that is how torch.compile(dynamic=True) clears
assume_static_by_default. Reads kept returning the stale default, so the model
compiled with static shapes: 30% "faster" and wrong. Any future direct write to
user_override would reintroduce that, hence the comment on the field.

A config read drops from 1539ns to 99ns. On one model's cold compile with
dynamic=True, total compile time measured as the union of top-level chromium
events:

  pair 1:  baseline 49.15s   changed 47.00s
  pair 2:  baseline 49.28s   changed 47.51s
  pair 3:  baseline 48.51s   changed 47.92s

i.e. 48.98s -> 47.48s, -3.1%, with the change winning every pair.

Test plan:

```
python test/test_utils_config_module.py
python test/dynamo/test_config.py
python test/inductor/test_config.py
python test/dynamo/test_misc.py
python test/test_dynamic_shapes.py
python test/test_public_bindings.py
python test/test_torch_config_hash_determinism.py
```

test_utils_config_module and dynamo/test_config pass outright; the rest have
pre-existing failures on this host (aarch64 CPU codegen, missing onnxscript)
and produce failure sets identical to a run with the change stashed.

This PR was authored with the assistance of an AI coding agent.

ghstack-source-id: 11c2fb6
Pull-Request: #193160
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@github-actions

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been updated in a while so we're going to go ahead and mark this as Stale.
Feel free to remove the Stale label if you feel this was a mistake.
If you are unable to remove the Stale label please contact a maintainer in order to do so.
If you want the bot to never mark this PR stale again, add the no-stale label.
Stale pull requests will automatically be closed after 30 days of inactivity.

@github-actions github-actions Bot added the Stale label Oct 22, 2026
@github-actions
github-actions Bot deleted the gh/anijain2305/1305/head branch November 24, 2026 01:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant