Repository navigation
[aot_compile] Decide a module dispatch call's shared binding at the second scanned result - #197133
bobrenjc93 wants to merge 1 commit into
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/197133
Note: Links to docs will display an error until the docs builds have been completed. ✅ You can merge normally! (4 Unrelated Failures)As of commit 9c8c36c with merge base 45882d3 ( GREEN LIGHT - PR approved to be merged without human review:
reason: UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:
CRCR (non-blocking) - The following CRCR downstream CI jobs failed but are non-blocking:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
…econd scanned result A follow-up to #197071, which landed as first reviewed; this commit carries what its review asked for and changes no behaviour: every call is served by the same result or refused with the same error, and pays the number of binds #197071 set. Against the landed code it restructures `AOTCompiledModel.__call__` so the first result is bound and checked ahead of the scan and the shared-binding verdict is asked exactly once, after that result has refused the call and only when there is a second result; it names `_binding_key`'s return type `_BindingKey`; it shortens the `_binding_verdict` field comment to the invariants and says the field is a hint, not a lock; it states above the scan the read-only `f_locals` contract the sharing rests on; and it hardens the tests: both interleaving tests bound every wait, record what the decider raised and assert it was started, the binds-once test asserts which result served and which one bound, the first-result test stops reading the private field and gains a one-result half, the tensor-default forward is built per test rather than as a module global, and the setup four tests repeated is one helper. Review order: `_BindingKey` and `_binding_key`, then the `_binding_verdict` field comment, then `__call__` down to the re-check, then the tests. `_binding_key` returned `tuple[object, ...]`, which says nothing about what a key holds. `_BindingKey` spells its three members out -- parameters as name, kind and default id, `co_freevars`, cell ids -- so the identity-sensitive parts are visible in the signature; the body is unchanged, `tuple([...])` over list comprehensions included (FAQ below). The field comment argued against a two-field design in eleven lines. It now states the invariants in six -- the contents are weak references so a dropped result is not kept alive, one store publishes contents and verdict together so a reader never sees one list's contents beside another's verdict, the default is the verdict over no results -- and adds the one thing the landed comment left unsaid: the field is a hint, not a lock. Two threads deciding at once each publish a pair and the last writer wins, so a reader can find a pair about a list other than the one it holds, decide again and publish again, at a `_binding_key` per result and never at a wrong binding, since a call binds from the verdict it decided or from a pair whose contents are the results it holds. The two-field rebuttal stays in #197071's message. In the landed `__call__` the scan tests `bound and shared is None` on every iteration, and a single-result model runs that test for a served call and a refused one alike. Now `results[0]` is peeled out of the loop: bound and checked as at a single-result model and served on a match; only when it refuses does `__call__` ask `_binds_alike` once, gated on `len(results) > 1`, and scan the rest, reusing the first binding or binding each result on its own. So a call `[0]` serves pays nothing for the sharing, a single-result model never consults the verdict whether it serves or refuses, and the scan tests no per-result branch about the verdict. `test_module_dispatch_decides_a_shared_binding_past_the_first_result` pins that on a two-result model -- a call `[0]` serves never calls `_binds_alike`, the next call, which `[0]` refuses, calls it once -- and, new here, on a one-result model, where neither a served nor a refused call calls it. Every binding, shared or not, is still appended once per result, so the re-check zips `results` with `bound` as before, and the opt-out stage below it is untouched. This is a restructure, not a speedup: measured on the machine #197071's figures come from, the landed `__call__` and this one exec'd from source into subclasses over the same results and timed in alternation, best of 9, min of two rounds, a match at `[1]` of two costs 17.5us against 17.9us, a match at `[3]` of four 20.5us against 20.7us, and a no-match call that raises 23.5us against 23.3us at two results and 27.8us against 27.5us at four, all within noise; the per-iteration test the review pointed at costs tens of nanoseconds. A match at `[0]` of one result, which now runs the statements the code before #197071 ran in their order, costs 15.1us against 14.6us for that code. Handing one dict to N guard trees is sound only because `check()` reads the mapping it is given and never writes it, and the comment above the scan now says so: a future leaf guard that stored into `f_locals` would make `[1]` check a dict `[0]` had changed, and that would surface as a wrong graph served, not as a crash. Today `torch/csrc/dynamo/guards.cpp` has no `PyDict_SetItem`, `PyDict_DelItem` or `PyObject_SetItem` call at all, so `RootGuardManager::check_nopybind_template` cannot store into the mapping it is passed, and the relational guard state that could carry one tree's view into the next (`NO_TENSOR_ALIASING`, `OBJECT_ALIASING`, the symbolic shape guard's `_args_seen`) is reset on entry and on every one of its four exits, the early no-tensor-aliasing refusal included. The tests change as follows. `test_module_dispatch_binds_a_call_once_for_results_sharing_a_signature` asserted `len(binds) == 1`, which a model that compiled fewer results than the four it asked for would also satisfy; it now asserts four results, that `[3]`'s `fn` served the call (`patch.object(..., wraps=)`) and that `binds == [results[0]]`. The first-result test asserted `combined._binding_verdict == ((), False)`, hardcoding the private tuple; the mock on `_binds_alike` carries the laziness claim, so the assertion is gone and the one-result half is added. Both interleaving tests waited without bound: the decider now parks for at most 10s and the test waits at most 10s for it to park, so a decider that never reaches its parking point fails the test in seconds and no `join` can hang; the decider is a `RecordedThread`, which keeps what its target raised so the test fails on it after the join instead of `threading` printing it to stderr; and the old-contents test asserts the decider was started before joining it, since only the patched `_binds_alike` starts it and a dispatch that stopped consulting the verdict would still raise the error the test expects. `TensorDefaultModule` held its `mask=torch.ones(3)` default as a module global shared across the file; `make_masked_forward()` builds the forward per test on a bare `torch.nn.Module`. The two shared-binding round-trip tests keep their `assertFalse(loaded._binds_alike(...))`, now commented as pinning the accepted limitation -- each blob unpickles through its own `AOTCompileUnpickler`, so equal defaults and cells come back as distinct objects -- that a load sharing one memo across the blobs is free to flip. `compile_mode_defaults` is the two `mode`-default results four tests built by hand. > **FAQ: Can two threads deciding at once leave the cache re-deciding on every > call?** Only while the list is being edited under them: two deciders over > the same contents publish the same pair, and a pair about other contents is > found stale by the next call, which decides once more and publishes. Each > such decision costs a `_binding_key` per result, about 1.0us, and none of > them can produce a wrong binding, since a call binds from the verdict it > decided or from a pair whose contents are the results it holds. A lock would > put an acquire on every call `[0]` refuses to spare a re-decision that only a > concurrent edit of `compiled_results` can cause. > **FAQ: Why does `_binding_key` still build `tuple([...])` over list > comprehensions rather than `tuple(...)` over generators?** Because it is > faster: measured on the same artifact, best of 9 over 200000 calls, run > twice, the shipped form costs 0.99us per key and the generator form 1.33us; > for these sizes the list a comprehension builds is cheaper than a generator > frame. The key is computed once per result on every re-decision, which is > the cost the cache exists to bound, so the idiomatic form was not taken. Test Plan: ``` python test/dynamo/test_aot_compile.py -k test_module_dispatch_decides_a_shared_binding_past_the_first_result python test/dynamo/test_aot_compile.py -k test_module_dispatch_binds_a_call_once_for_results_sharing_a_signature python test/dynamo/test_aot_compile.py -k test_module_dispatch_never_pairs_new_contents_with_a_stale_verdict python test/dynamo/test_aot_compile.py -k test_module_dispatch_never_pairs_old_contents_with_a_new_verdict python test/dynamo/test_aot_compile.py -k test_module_dispatch_shares_a_binding_past_a_tensor_default python test/dynamo/test_aot_compile.py -k test_module_dispatch_shares_a_binding_across_closure_cells python test/dynamo/test_aot_compile.py -k test_module_dispatch python test/dynamo/test_aot_compile.py lintrunner --take RUFF,PYFMT torch/_dynamo/aot_compile.py test/dynamo/test_aot_compile.py ``` This commit adds no test; the full file runs 205 tests and passes (6 skipped), as at the parent, and `-k test_module_dispatch` runs 19. Behaviour is unchanged, so all 19 also pass with the landed `torch/_dynamo/aot_compile.py` under this commit's test file; what the tests pin is the shape, by mutation, each run against the 19 and each failing only the tests named: dropping the `len(results) > 1` gate fails the first-result test through its one-result half with `Expected '_binds_alike' to not have been called. Called 1 times`, and deciding ahead of the first result fails it the same way through the two-result half; never consulting `_binds_alike` fails the binds-once test with `The length of the sequences mismatch: 4 != 1`, the first-result test with `Called 0 times` and the old-contents test at its started-decider assertion with `unexpectedly None`, where the landed test died on `cannot join thread before it is started`. The mutation controls in #197071's message concern code this commit does not change and were not re-run. Lint is clean. Authored with the assistance of Claude Code. Co-Authored-By: Claude Fable 5.1 <[email protected]> ghstack-source-id: cd50e86 Pull-Request: #197133
|
Claude finished @bobrenjc93's task in 28m 21s —— View job A no-op restructure that I verified case-by-case as behavior-preserving; the only things I'd change are one comment that dropped its load-bearing atomicity rationale and two ignored-timeout/lost-traceback spots in the reworked thread tests. Full reviewPR Review: #197133SummaryRestructures Thread Safety
Testing
Code Quality
RecommendationApprove — behavior is unchanged and I could not find an input that separates the two Note: I could not execute the test plan — this checkout has no built torch ( |
|
@pytorchbot merge -i |
Merge startedYour change will be merged while ignoring the following 2 checks: inductor / unit-test / inductor-cpu-test / test (inductor_aoti_fallback, 1, 2, mt-l-x86iamx-8-64, unstable), inductor / unit-test / inductor-cpu-test / test (inductor_aoti_fallback, 2, 2, mt-l-x86iamx-8-64, unstable) Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
Stack from ghstack (oldest at bottom):
Summary. This is the follow-up #197071's review asked for, and it changes no
behaviour: every call is served by the same result or refused with the same
error, and pays the number of binds #197071 set. The landed dispatch loop tested
bound and shared is Noneon every iteration, so even a single-result model rana per-result branch about the shared-binding verdict on every call. The first
result is now bound and checked ahead of the loop, exactly as a single-result
model always was, and only when it refuses the call does
__call__ask_binds_alikeonce, gated on there being a second result, before scanning therest. Around that,
_binding_key's return type gets a name that spells out itsthree identity-sensitive members, the
_binding_verdictcomment shrinks to theinvariants and says the field is a hint rather than a lock, and the scan states
the read-only
f_localscontract that sharing one dict across N guard treesrests on. The tests are hardened rather than added to: bounded waits and a
recorded exception in both interleaving tests, an assertion of which result
served and which one bound in the binds-once test, a one-result half for the
first-result test, and one helper for the setup four tests repeated.
Review order:
_BindingKeyand_binding_key, then the_binding_verdictfield comment, then
__call__down to the re-check, then the tests.__call__: peel the first result out of the loopSo a call
[0]serves pays nothing for the sharing, a single-result modelnever consults the verdict whether it serves or refuses, and the scan tests no
per-result branch about the verdict.
test_module_dispatch_decides_a_shared_binding_past_the_first_resultpinsthat on a two-result model (a call
[0]serves never calls_binds_alike; thenext call, which
[0]refuses, calls it once) and, new here, on a one-resultmodel, where neither a served nor a refused call calls it:
Every binding, shared or not, is still appended once per result, so the
re-check zips
resultswithboundas before, and the opt-out stage below itis untouched. This is a restructure, not a speedup: measured on the machine
#197071's figures come from, the landed
__call__and this one exec'd fromsource into subclasses over the same results and timed in alternation, best of
9, min of two rounds:
[1]of two[3]of four[0]of one resultAll within noise; the per-iteration test the review pointed at costs tens of
nanoseconds. The one-result row now runs the statements the code before
#197071 ran, in their order.
Why one dict can serve N guard trees
Handing one
f_localsto N guard trees is sound only becausecheck()readsthe mapping it is given and never writes it, and the comment above the scan now
says so: a future leaf guard that stored into
f_localswould make[1]checka dict
[0]had changed, and that would surface as a wrong graph served, notas a crash. Today
torch/csrc/dynamo/guards.cpphas noPyDict_SetItem,PyDict_DelItemorPyObject_SetItemcall at all, soRootGuardManager::check_nopybind_templatecannot store into the mapping itis passed, and the relational guard state that could carry one tree's view
into the next (
NO_TENSOR_ALIASING,OBJECT_ALIASING, the symbolic shapeguard's
_args_seen) is reset on entry and on every one of its four exits, theearly no-tensor-aliasing refusal included.
_BindingKeynames what a key holdstuple[object, ...]says nothing about what a key holds._BindingKeyspellsits three members out so the identity-sensitive parts are visible in the
signature; the body is unchanged,
tuple([...])over list comprehensionsincluded (FAQ below).
The field comment: invariants, and "a hint, not a lock"
The field comment argued against a two-field design in eleven lines. It now
states the invariants in six: the contents are weak references so a dropped
result is not kept alive, one store publishes contents and verdict together so
a reader never sees one list's contents beside another's verdict, and the
default is the verdict over no results. It adds the one thing the landed
comment left unsaid: the field is a hint, not a lock.
The two-field rebuttal stays in #197071's message.
The tests, hardened
test_module_dispatch_binds_a_call_once_for_results_sharing_a_signatureasserted
len(binds) == 1, which a model that compiled fewer results thanthe four it asked for would also satisfy. It now asserts four results, that
[3]'sfnserved the call (patch.object(..., wraps=)), andbinds == [results[0]].The first-result test asserted
combined._binding_verdict == ((), False),hardcoding the private tuple; the mock on
_binds_alikecarries thelaziness claim, so the assertion is gone and the one-result half above is
added.
Both interleaving tests waited without bound. The decider now parks for at
most 10s and the test waits at most 10s for it to park, so a decider that
never reaches its parking point fails the test in seconds and no
joincanhang. The decider is a
RecordedThread, which keeps what its target raisedso the test fails on it after the join instead of
threadingprinting it tostderr. The old-contents test asserts the decider was started before joining
it, since only the patched
_binds_alikestarts it and a dispatch thatstopped consulting the verdict would still raise the error the test expects:
TensorDefaultModuleheld itsmask=torch.ones(3)default as a moduleglobal shared across the file;
make_masked_forward()builds the forwardper test on a bare
torch.nn.Module.The two shared-binding round-trip tests keep their
assertFalse(loaded._binds_alike(...)), now commented as pinning theaccepted limitation (each blob unpickles through its own
AOTCompileUnpickler, so equal defaults and cells come back as distinctobjects) that a load sharing one memo across the blobs is free to flip.
compile_mode_defaultsis the twomode-default results four tests builtby hand.
Test Plan:
This commit adds no test; the full file runs 205 tests and passes (6 skipped),
as at the parent, and
-k test_module_dispatchruns 19. Behaviour isunchanged, so all 19 also pass with the landed
torch/_dynamo/aot_compile.pyunder this commit's test file; what the tests pin is the shape, by mutation,
each run against the 19 and each failing only the tests named: dropping the
len(results) > 1gate fails the first-result test through its one-resulthalf with
Expected '_binds_alike' to not have been called. Called 1 times,and deciding ahead of the first result fails it the same way through the
two-result half; never consulting
_binds_alikefails the binds-once testwith
The length of the sequences mismatch: 4 != 1, the first-result testwith
Called 0 timesand the old-contents test at its started-deciderassertion with
unexpectedly None, where the landed test died oncannot join thread before it is started. The mutation controls in #197071's messageconcern code this commit does not change and were not re-run. Lint is clean.
Authored with the assistance of Claude Code.
Co-Authored-By: Claude Fable 5.1 [email protected]
🤖 Generated with Claude Code
cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98