Repository navigation
fix(projection_kernel): derive the default rank tolerance from the compute dtype - #1829
Merged
jlarson4 merged 4 commits intoSep 28, 2026
Conversation
The default relative rank tolerance is floored at the storage dtype's epsilon. For bfloat16 storage that floor is about 7.8e-3, which is far above the singular-value ratios that separate a full-rank head from a numerically rank-deficient one. A full-rank head whose spectrum decays gradually therefore collapses to a much smaller measured rank, and a caller requesting the full width fails with "requested rank N exceeds measured rank M". Add a fixture that builds a full-rank matrix with a geometric singular-value spectrum, plus a single-head bridge that injects it as W_Q. Cover the collapse at both half-precision storage dtypes, confirm a structurally rank-deficient half-precision matrix is still detected, and pin the float32 path as unchanged so the tests distinguish half-precision storage from genuinely deficient data. These tests fail against the current default and pass once the tolerance is derived from the compute dtype.
…mpute dtype The default relative rank tolerance was floored at the storage dtype's epsilon. For bfloat16 storage that floor is about 7.8e-3, which is far above the singular-value ratios that separate a full-rank head from a numerically rank-deficient one. A full-rank head whose spectrum decays gradually therefore collapsed to a much smaller measured rank, and a caller requesting the full width failed with "requested rank N exceeds measured rank M". The SVD already promotes float16 and bfloat16 inputs to float32, so the measured singular values carry float32 precision regardless of how the checkpoint was stored. Flooring the tolerance at the storage epsilon discarded that precision and made the rank decision depend on the storage dtype rather than on the numerics actually computed. Derive the default from the compute dtype instead, and drop the storage-dtype helper that existed only to feed the old floor. An explicit rtol still takes precedence. One existing deficiency fixture relied on the loose floor to register a near-degenerate direction; it now uses an exactly dependent column so it tests structural deficiency rather than quantization noise.
…rance The guide still documented the default relative rank tolerance as `max(max(matrix.shape) * compute_eps, storage_eps)`, which no longer matches the implementation. Rewrite both passages to describe the compute-dtype default and say why it is derived from the dtype the SVD runs in rather than the storage dtype: half-precision inputs are promoted to float32, so a storage-dtype floor would discard the precision of the singular values actually computed and collapse the measured rank of a full-rank half-precision head. Also note that an explicit rtol still takes precedence, and that half-precision checkpoints no longer need a manual override.
…2-small Add an integration case that loads gpt2-small with bfloat16 weights and runs the default O -> Q call without an explicit rtol. gpt2-small is dense MHA with no GQA grouping, so this isolates the storage dtype effect from the head-cardinality effect. The discriminating assertion is the effective tolerance: it must sit below the bfloat16 epsilon, which is what the storage-dtype floor violated. The measured ranks are additionally pinned against the float32 run, and the scores are checked for finiteness and the documented bounds. Exact score equality across dtypes is deliberately not asserted. gpt2-small's worst-conditioned head sits near 40, below the reciprocal of the bfloat16 epsilon, so its measured ranks survive even the storage-dtype floor. The rank and bound checks therefore guard the end-to-end contract rather than reproducing the collapse; a head whose spectrum decays past that reciprocal is covered by the synthetic unit cases.
koriyoshi2041
left a comment
Contributor
There was a problem hiding this comment.
Validated this at 4a07d535. The focused projection-kernel unit file passes 84/84. On the test-only predecessor e1711dfe, the same file fails the four new low-precision contract cases, including the bfloat16 wrapper case measuring rank 45 instead of 64; restoring the fix returns the suite to green.
I also checked that explicit rtol remains authoritative and that the structural-deficiency negative control is exact rather than tolerance-dependent. The hosted compatibility, coverage, type, format, docstring, benchmark, and applicable notebook checks are green. I did not find a blocking issue in the scoped compute-dtype tolerance change.
1 task done
Collaborator
|
Looks good @janmenjayap! Approved, merging now |
1 task done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
orthonormal_subspaceand itsTransformerBridgewrapper derived the default rank tolerance (rtol) from the storage dtype's epsilon. On half-precision inputs this floors the tolerance far above the singular-value ratios that separate a full-rank attention head from a rank-deficient one, so genuinely full-rank heads were reported as low rank.This PR derives the default from the compute dtype instead. The SVD already promotes half-precision inputs to
float32, so the old floor was discarding precision the computation actually had.Part of #1784. Does not close it — the same-role pairing work and the
top_pairstensor top-k are separate PRs under the same issue.The bug
_validate_rtolfell back totorch.finfo(storage_dtype).epswhen no explicitrtolwas supplied:finfo(dtype).epsfloat32float16bfloat16Rank is determined by counting singular values above
rtol * sigma_max. Withrtol = 7.81e-3, every singular value below 0.78% of the largest is treated as zero. Real attention heads routinely have spectra that decay past that ratio while remaining structurally full rank, so the measured rank collapses.Observed on Qwen2.5-0.5B in
bfloat16:The failure is dtype-dependent, which is why it surfaced only on half-precision models and not on the
float32paths the module was developed against.Reproduction
tests/unit/tools/test_projection_kernel.pygains two fixtures:decaying_spectrum_matrix— a full-rank matrix with geometric singular-value decay, tuned so its spectrum crosses thebfloat16floor but not thefloat32one.single_head_bridge— injects that matrix asW_Qthrough a minimal bridge.Against the unfixed module, 4 of the new tests fail:
The suite is red on the reproduction commit by design; the fix commit turns it green.
The fix
The default is now:
where
compute_dtypeis the dtype the SVD actually runs in (float32for half-precision inputs). Themax(shape)factor follows the standard LAPACK convention for rank-revealing decompositions._rank_tolerance_dtype— a helper that existed solely to feed the old storage-dtype floor — is removed along with its call site.An explicit
rtolargument still takes precedence over the default.Measured effect
768x64 matrix, condition number 1000:
rtolrtolfloat16bfloat16Test-fixture correction
test_low_precision_default_handles_realistic_ambient_dimensionpreviously built its "rank-deficient" column as0.3 * col0 + 0.7 * col1. That is only near-degenerate, and it passed solely because the loosebfloat16floor masked the residual. Under the corrected tolerance it is rightly measured as full rank.The fixture now uses an exactly dependent column (
= col0), so the test exercises structural deficiency rather than quantization noise — which is what its name and docstring always claimed.Eight further tests encoded the old storage-dtype contract and were updated. One of them,
test_wrapper_uses_least_precise_storage_dtype_for_default_rtol, was renamed totest_wrapper_default_rtol_uses_compute_dtype_not_storage_dtypeand now assertsresult.rtol < torch.finfo(dtype).eps— that assertion is what actually pins the new contract, since the old name would otherwise be a lie.Integration coverage
tests/integration/model_bridge/test_projection_kernel.pygains agpt2-smallcase that loads the model inbfloat16, runs the defaultO->Qcall without an explicitrtol, and asserts the effective tolerance sits below the bfloat16 epsilon, that ranks match thefloat32run, and that scores are finite and in bounds.Limitation, stated plainly:
gpt2-smallcannot reproduce the rank collapse. Its worst-conditioned head has condition number ~40, while the bfloat16 collapse threshold is1/eps ~ 128. The discriminating assertion in this test is therefore the tolerance itself; the rank and bound checks guard the end-to-end contract rather than demonstrating the bug. The collapse itself is pinned by the synthetic unit cases, which construct spectra that do decay past the threshold.Files changed
transformer_lens/tools/analysis/projection_kernel.pyrtolfrom compute dtype; remove_rank_tolerance_dtype; docstringstests/unit/tools/test_projection_kernel.pytests/integration/model_bridge/test_projection_kernel.pygpt2-smalldocs/source/content/projection_kernel.mdVerification
tests/unit/tools/test_projection_kernel.pytests/unit/tools/tests/integration/model_bridge/test_projection_kernel.pyuv run mypy .make check-formatuv run build-docsprojection_kernelwarningsNotes for reviewers
rtolfix only. Same-role pairings and thetop_pairstensor top-k are separate PRs under [Proposal] Validate, generalize, and stress-test Projection-Kernel Head Affinity (follow-up to #1721) #1784.HookedTransformercode paths. The module isTransformerBridge-only by construction; theHooked*model classes were removed in 4.0.gpt2-smallwould demonstrate the collapse. It cannot, for the conditioning reason above. The synthetic unit tests are what actually pin the bug.