Repository navigation
Conversation
PR Status: Approved 🚀Please fix all CI failures and trigger merge by commenting "@pytorchbot merge". ✅ AUTOMATED REVIEW - OUTDATED (earlier commit) - Ready for human review:
Findings (11): Reviewed commit: 🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/201766
Note: Links to docs will display an error until the docs builds have been completed. ✅ No FailuresAs of commit bb168a6 with merge base 836c141 ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
Pull Request resolved: #201766 TunableOp keys a tuned solution on an exact shape signature, but models lowered with dynamic shapes rarely see the traced shape at runtime, so lookups miss and fall back to the untuned default. The existing answer is to borrow a neighbouring shape's solution at runtime. That borrow is an unvalidated guess made in the serving path, and when it goes wrong the failure modes are a hang or an uncatchable GPU fault. This lays the C++ groundwork for making the same decision at compile time instead, where it can be proven by benchmark and where a fault is containable. Execution then only ever needs an exact match. `Lookup` gains a nearest-larger fallback: when there is no exact entry, reuse the tuned solution identical except in exactly one free dim (M, N or batch count), rounded up to the smallest tuned value at least as large as the request. K, transpose, dtype suffix and the layout-independent leading dims must match. It is gated on `IsNearestMatchEnabled() && !IsTuningEnabled()`, so a tuning pass always tunes the real shape rather than short-circuiting to a neighbour. The borrowed result is deliberately not memoized. The caller is expected to benchmark it against the default and persist the winner with `RecordBorrowed`, which makes the shape an ordinary exact hit from then on. Memoizing would make a second lookup in the same process look like an exact hit and silently bypass that comparison. `RecordBorrowed` exists because the normal write path is gated on tuning being enabled, so nothing would reach the results file during a reuse pass. It mirrors the existing `RecordUntuned` feature and routes through `Add`, so entries stream out through the same realtime-append path. A borrowed entry is written as an ordinary result, so the file cannot distinguish it from a tuned one; the donor is visible only in the `LookupNearest` log at verbosity 3. Recording borrows in the untuned log, so a later pass knows which shapes still want real tuning, is left to follow-up work. A recorded `Default` (the default kernel beat the borrow) is an ordinary exact hit and is never revisited, including by a later tuning pass. That keeps the reuse pass idempotent: the comparison is made once and the verdict stands. It does mean a `Default` recorded here is final, since tuning only runs when the lookup returns Null -- tuning such a shape properly means tuning from a results file that does not carry the reuse pass's entries. Relaxing this is not a one-line change to the lookup predicate. `Add` returns early when the key already exists, `AddImpl` uses `try_emplace`, and `ReadFile` uses `emplace`, so a re-tuned result would be discarded in memory and on disk alike -- the shape would be re-tuned on every compile and never persist. Making a `Default` revisable means making the write path overwrite and the results file rewritten rather than appended, which is a larger change than it appears. A tuned solution can still be rejected for the actual shape at runtime, so a FAIL now falls back to the default rather than surfacing an error. That failure is deliberately not cached: unlike a borrow, a tuned entry that fails is a real defect and should stay visible rather than be masked after the first call. The two new flags are runtime-settable members rather than env-only statics, because a lowering job needs nearest match on at compile time and off at runtime within the same process. The env vars remain as force-off overrides. ghstack-source-id: 454857408 @exported-using-ghexport Differential Revision: [D116493593](https://our.internmc.facebook.com/intern/diff/D116493593/)
Pull Request resolved: #201766 TunableOp keys a tuned solution on an exact shape signature, but models lowered with dynamic shapes rarely see the traced shape at runtime, so lookups miss and fall back to the untuned default. The existing answer is to borrow a neighbouring shape's solution at runtime. That borrow is an unvalidated guess made in the serving path, and when it goes wrong the failure modes are a hang or an uncatchable GPU fault. This lays the C++ groundwork for making the same decision at compile time instead, where it can be proven by benchmark and where a fault is containable. Execution then only ever needs an exact match. A new TuningResultsManager::LookupNearest API offers a nearest-larger fallback: when there is no exact entry, it returns the tuned solution identical except in exactly one free dim (M, N or batch count), rounded up to the smallest tuned value at least as large as the request. K, transpose, dtype suffix and the layout-independent leading dims must match. It is gated on `IsNearestMatchEnabled() && !IsTuningEnabled()`, so a tuning pass always tunes the real shape rather than short-circuiting to a neighbour. `Lookup` itself is unchanged; the borrow is consulted explicitly by the caller -- the reuse-mode validation in D116493590 -- never by TunableOp dispatch, so an unvalidated borrow is structurally impossible on the serving path. The borrowed result is deliberately not memoized. The caller is expected to benchmark it against the default and persist the winner with `RecordBorrowed`, which makes the shape an ordinary exact hit from then on. Memoizing would make a second lookup in the same process look like an exact hit and silently bypass that comparison. `RecordBorrowed` exists because the normal write path is gated on tuning being enabled, so nothing would reach the results file during a reuse pass. It mirrors the existing `RecordUntuned` feature and routes through `Add`, so entries stream out through the same realtime-append path. A borrowed entry is written as an ordinary result, so the file cannot distinguish it from a tuned one; the donor is visible only in the `LookupNearest` log at verbosity 3. Recording borrows in the untuned log, so a later pass knows which shapes still want real tuning, is left to follow-up work. A recorded `Default` (the default kernel beat the borrow) is an ordinary exact hit and is never revisited, including by a later tuning pass. That keeps the reuse pass idempotent: the comparison is made once and the verdict stands. It does mean a `Default` recorded here is final, since tuning only runs when the lookup returns Null -- tuning such a shape properly means tuning from a results file that does not carry the reuse pass's entries. Relaxing this is not a one-line change to the lookup predicate. `Add` returns early when the key already exists, `AddImpl` uses `try_emplace`, and `ReadFile` uses `emplace`, so a re-tuned result would be discarded in memory and on disk alike -- the shape would be re-tuned on every compile and never persist. Making a `Default` revisable means making the write path overwrite and the results file rewritten rather than appended, which is a larger change than it appears. A tuned solution that fails at runtime returns a non-OK status from Call(); every caller -- gemm, bgemm, gemm-and-bias and scaled gemm -- already reads that as "use my own non-tunable path", so the failure surfaces as a caller-side fallback to default, not an error. This diff adds only a TUNABLE_LOG1 line at that site. That failure is deliberately not cached: unlike a borrow, a tuned entry that fails is a real defect and should stay visible rather than be masked after the first call. The two new flags are runtime-settable members rather than env-only statics, because a lowering job needs nearest match on at compile time and off at runtime within the same process. The env vars remain as force-off overrides. ghstack-source-id: 455668746 @exported-using-ghexport Differential Revision: [D116493593](https://our.internmc.facebook.com/intern/diff/D116493593/)
Withdrawn: the automated review of 78701cb found nothing blocking.
…ted (pytorch#202455) ✴️ iz2: Two prompt fixes to Stage B of the hardened PR review. In both cases a real blocking review was rejected by `extract_verdict.py` and nothing was posted. Part of pytorch/test-infra#9260. 1. **Needs Discussion with a blocker.** Stage A can recommend Needs Discussion while naming a defect that must be fixed. Stage B mapped Needs Discussion to `ready_for_human_review` and the defect to `major`, and the sanitizer refuses that combination. This happened on pytorch#202251 and pytorch#201766. Now such a defect is `major` and the verdict is `changes_requested`; open questions, requests for data or discussion, and unreviewed files are not such defects. The summary keeps the Recommendation and says when a defect overrode it. 2. **Findings on files with no anchorable line.** `/tmp/pr-files.txt` lists deletions, pure renames, mode-only changes and binary files, but their diffs show no added or context line, so a finding on one is discarded and a change request left with none is rejected (pytorch#201671). The prompt now names these and points Stage B at a changed line instead. This does not fix PRs whose every file is such a file, since they have no anchorable line at all. A separate change to the sanitizer covers that case. Test plan: `python3 -m unittest test_workflow_contract` in `scripts/pr_review` (174 pass). Two new tests pin both rules and fail on the old prompt. Pull Request resolved: pytorch#202455 Approved by: https://github.com/huydhn
Withdrawn: the automated review of e9114a5 found nothing blocking.
…ted (pytorch#202455) ✴️ iz2: Two prompt fixes to Stage B of the hardened PR review. In both cases a real blocking review was rejected by `extract_verdict.py` and nothing was posted. Part of pytorch/test-infra#9260. 1. **Needs Discussion with a blocker.** Stage A can recommend Needs Discussion while naming a defect that must be fixed. Stage B mapped Needs Discussion to `ready_for_human_review` and the defect to `major`, and the sanitizer refuses that combination. This happened on pytorch#202251 and pytorch#201766. Now such a defect is `major` and the verdict is `changes_requested`; open questions, requests for data or discussion, and unreviewed files are not such defects. The summary keeps the Recommendation and says when a defect overrode it. 2. **Findings on files with no anchorable line.** `/tmp/pr-files.txt` lists deletions, pure renames, mode-only changes and binary files, but their diffs show no added or context line, so a finding on one is discarded and a change request left with none is rejected (pytorch#201671). The prompt now names these and points Stage B at a changed line instead. This does not fix PRs whose every file is such a file, since they have no anchorable line at all. A separate change to the sanitizer covers that case. Test plan: `python3 -m unittest test_workflow_contract` in `scripts/pr_review` (174 pass). Two new tests pin both rules and fail on the old prompt. Pull Request resolved: pytorch#202455 Approved by: https://github.com/huydhn
There was a problem hiding this comment.
Automated review of 50483ae: nothing blocking; ready for human review.
The PR adds TuningResultsManager::LookupNearest and RecordBorrowed, two reuse-pass policy flags (each with an env kill switch and private Python bindings), and moves the leading-dimension rules into a header-only GemmLdRules.h. Recommendation: Approve. This is a re-review: the earlier blocking findings are resolved or answered, and every remaining point is non-blocking.
⚪ 11 non-blocking findings
(non-blocking) The kill-switch wording doesn't match the code. Tunable.cpp:55-56 says the switches are "read once at startup fixed before main()", but they are function-local statics set on first call. Setting os.environ[...] = "0" from Python therefore works before the first query and is silently ignored after it. Also, torch/cuda/tunable.py:319-321 and 341-343 say LookupNearest / RecordBorrowed act "whenever it is called, regardless of this value", but both return early when the env switch is 0 (Tunable.cpp:210, 368). Suggested wording: "regardless of the policy flag; the env kill switch applies to both".
pytorch/aten/tools/run_tests.sh
Line 55 in 50483ae
(non-blocking) The comment says ROCm builds the binary as hip_tunable_nearest_test and points at aten/src/ATen/test/CMakeLists.txt. That file only renames the hipified source. caffe2/CMakeLists.txt:2252 (REGEX REPLACE "^hip_" "cuda_") names the ROCm binary cuda_tunable_nearest_test, so the hip_ loop entry never runs.
pytorch/aten/tools/run_tests.sh
Line 63 in 50483ae
(non-blocking) The direct --gtest_filter='EnvKillSwitch' run exits 0 when the test hits GTEST_SKIP or the filter matches nothing. It is the only C++ coverage of the kill switches inside LookupNearest and RecordBorrowed, so it can silently become a no-op. Fix: check the output for one passed test, or use --gtest_fail_if_no_test_selected.
(non-blocking) NearestMatchRejectsBatchedAgainstNonBatched (lines 238-246) still passes if the q.has_b != c.has_b check (GemmLdRules.h:189) is deleted. Batched vs plain is still rejected as a round-down (cv=0 < qv=2), and plain vs batched is still rejected because no dim differs. A pair that would catch it: plain NN_8_512_256_ld_8_256_8 vs batched NN_16_512_256_B_1_ld_16_256_16.
(non-blocking) NearestMatchRejectsKMismatch (lines 262-268): the candidate's ldb (128) differs from the query's (256), so LdsCompatibleWhenMVaries rejects it whether or not the q.k != c.k check exists. Use NN_64_512_128_ld_64_256_64 instead.
(non-blocking) NearestMatchRejectsTransposeAndSuffixMismatch (lines 273-274), transpose half: the NT_...ld_256... candidate has a padded lda, so the lda rule rejects it without the transab comparison. Use NT_64_512_256_ld_64_256_64 instead.
(non-blocking) ParseRejectsMalformed, "missing ld token" case: the string has 7 tokens, so the t.size() < 8 guard rejects it before the "ld" check is reached. Use an 8-token string with a wrong marker, e.g. NN_1024_512_256_x_1024_256_1024.
(non-blocking) Conjugate-transpose tests (lines 74-89): neither case exercises "the case a bare 't'/'T' check misses"; the direct UsesMForLda('C') asserts at lines 41-42 are what catch it. A 'C' case with an lda that is tight in M on both sides, e.g. q{32,64,32} vs c{64,64,64}, would back the comment.
(non-blocking) TieBreakIsDeterministic still relies on one hash-iteration order.
(non-blocking) RecordBorrowedPersistsTheBorrowersMeasurement still tests a property that belongs to the caller.
(non-blocking) LookupNearest (lines 224-235) copies every (signature, ResultEntry) pair for the op while holding lock_, and Lookup takes the same lock on every GEMM dispatch. The copy includes Default entries and * wildcard keys, which are thrown away right after (lines 249, 253); filtering them out before copying is cheap. The parsing cost the comment at 220-223 avoids is the std::vector<std::string> that SplitUnderscore (GemmLdRules.h:103-116) allocates per candidate. Splitting into string_view tokens (c10::split, or the allocation-free tokenising matches_wildcard_pattern already does) would make the scan cheap enough to filter in place; c10::split drops a trailing empty token and returns [] for empty input, so ParseGemmShape would need small adjustments.
This review is AI-generated and advisory. Each new automated review replaces the previous one. Report a bad review
Stack from ghstack (oldest at bottom):
TunableOp keys a tuned solution on an exact shape signature, but models lowered
with dynamic shapes rarely see the traced shape at runtime, so lookups miss and
fall back to the untuned default.
The existing answer is to borrow a neighbouring shape's solution at runtime. That
borrow is an unvalidated guess made in the serving path, and when it goes wrong
the failure modes are a hang or an uncatchable GPU fault. This lays the C++
groundwork for making the same decision at compile time instead, where it can be
proven by benchmark and where a fault is containable. Execution then only ever
needs an exact match.
Lookupitself is unchanged. The fallback is a separateTuningResultsManager::LookupNearest: when there is no exact entry, it returnsthe tuned solution identical except in exactly one free dim (M, N or batch
count), rounded up to the smallest tuned value at least as large as the request.
K, transpose, dtype suffix and the layout-independent leading dims must match.
It is consulted explicitly by the caller -- the reuse-mode validation in
#201769 -- never by TunableOp dispatch, so an unvalidated borrow is
structurally impossible on the serving path.
LookupNearestandRecordBorrowedconsult no flags of their own. TunableOpdispatch resolves shapes through
Lookupand never reaches either of them, socalling one is itself the opt-in and the reuse pass is the only caller. The
pass decides whether borrowing applies -- including never borrowing during a
tuning pass, which it enforces by only reaching these entry points on its
non-tuning path.
The borrowed result is deliberately not memoized. The caller is expected to
benchmark it against the default and persist the winner with
RecordBorrowed,which makes the shape an ordinary exact hit from then on. Memoizing would make a
second lookup in the same process look like an exact hit and silently bypass that
comparison.
RecordBorrowedexists becauseAdd's write path only fires during tuning, sonothing would reach the results file during a reuse pass, and nothing bulk-writes
results_at process exit. It mirrors the existingRecordUntunedfeature. Itshares a private
AddAndMaybePersistwithAdd, which takes aforce_persistargument only
RecordBorrowedsets.Add's own rule -- write during tuningunless the run is merely collecting untuned shapes -- is left exactly as it was
before this diff, deliberately:
Addis on every GEMM's path on every thread, soa reuse-pass decision must not change what any other caller writes. A borrowed
entry is written as an ordinary result, so the file cannot distinguish it from a
tuned one; the donor is visible only in the
LookupNearestlog at verbosity 3.Recording borrows in the untuned log, so a later pass knows which shapes still
want real tuning, is left to follow-up work.
A recorded
Default(the default kernel beat the borrow) is an ordinary exact hitand is never revisited, including by a later tuning pass. That keeps the reuse pass
idempotent: the comparison is made once and the verdict stands. It does mean a
Defaultrecorded here is final, since tuning only runs when the lookup returnsNull -- tuning such a shape properly means tuning from a results file that does not
carry the reuse pass's entries.
Relaxing this is not a one-line change to the lookup predicate.
Addreturnsearly when the key already exists,
AddImplusestry_emplace, andReadFileuses
emplace, so a re-tuned result would be discarded in memory and on diskalike -- the shape would be re-tuned on every compile and never persist. Making
a
Defaultrevisable means making the write path overwrite and the results filerewritten rather than appended, which is a larger change than it appears.
EnableNearestMatchandEnableRecordBorrowedare reuse-pass policy. The passreads them to decide whether to borrow and whether to persist what it decided;
neither the manager nor TunableOp dispatch consults them. They are
runtime-settable members rather than env-only statics because a lowering job
needs nearest match on at compile time and off at runtime within the same
process. The env vars remain as force-off overrides. Like the Python helpers that
set them, they are deliberately absent from the README: this is an internal
compile-time mechanism, and documenting it would commit us to a supported
contract.
@exported-using-ghexport
Differential Revision: D116493593
Differential Revision: D116493593