-
Notifications
You must be signed in to change notification settings - Fork 29
Fix FP64 promotion in PSGD running_lower_bound #95
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+85
−1
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
8458ad2
test & benchmark for reproducer
dlyr3 df06e13
fix
dlyr3 03a3bfe
fix benchmark and test for profiler API compatibility
dlyr3 e2ae8d7
prod bench + convergence tests with plot gen
dlyr3 601cbc7
removed reproducer
dlyr3 6443832
fix
dlyr3 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| """Test that PSGD preconditioner does not promote matrices to fp64. | ||
|
|
||
| Verifies: | ||
| 1. Convergence is not degraded | ||
| 2. No fp64 matrices leak into optimizer state (scalar/vector fp64 is intentional) | ||
| """ | ||
|
|
||
| import pytest | ||
| import torch | ||
| from torch import nn | ||
|
|
||
| import heavyball | ||
| from heavyball.utils import clean, set_torch | ||
|
|
||
| pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required") | ||
|
|
||
| _PSGD_OPTIMIZERS = [ | ||
| (heavyball.PSGDPRO, 1e-3, {}), | ||
| (heavyball.PSGDKron, 1e-3, {}), | ||
| ] | ||
|
|
||
|
|
||
| def _train(model, opt, data, target, steps): | ||
| losses = [] | ||
| for _ in range(steps): | ||
| p = next(model.parameters()) | ||
| d = data.to(p.dtype) if p.dtype != data.dtype else data | ||
| loss = ((model(d) - target.to(d.dtype)) ** 2).mean().float() | ||
| loss.backward() | ||
| opt.step() | ||
| opt.zero_grad() | ||
| losses.append(loss.item()) | ||
| return losses | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("opt_cls,lr,extra_kw", _PSGD_OPTIMIZERS, ids=[t[0].__name__ for t in _PSGD_OPTIMIZERS]) | ||
| def test_psgd_convergence_fp32_lb(opt_cls, lr, extra_kw): | ||
| set_torch() | ||
| torch.manual_seed(42) | ||
| data = torch.randn(128, 64, device="cuda") | ||
| target = torch.randn(128, 32, device="cuda") | ||
|
|
||
| torch.manual_seed(0) | ||
| model = nn.Linear(64, 32, bias=False, device="cuda") | ||
| opt = opt_cls(model.parameters(), lr=lr, **extra_kw) | ||
|
|
||
| losses = _train(model, opt, data, target, 200) | ||
| assert losses[-1] < losses[0] * 0.5, f"Loss did not converge: {losses[0]:.4f} -> {losses[-1]:.4f}" | ||
|
|
||
| del model, opt | ||
| clean() | ||
|
|
||
|
|
||
| def _check_no_fp64_matrices(obj, path=""): | ||
| if isinstance(obj, torch.Tensor) and obj.is_floating_point(): | ||
| if obj.ndim >= 2 and obj.dtype == torch.float64: | ||
| assert False, f"fp64 matrix at {path}: shape={obj.shape}, dtype={obj.dtype}" | ||
| elif isinstance(obj, dict): | ||
| for k, v in obj.items(): | ||
| _check_no_fp64_matrices(v, f"{path}.{k}" if path else str(k)) | ||
| elif isinstance(obj, (list, tuple)): | ||
| for i, v in enumerate(obj): | ||
| _check_no_fp64_matrices(v, f"{path}[{i}]") | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("opt_cls,lr,extra_kw", _PSGD_OPTIMIZERS, ids=[t[0].__name__ for t in _PSGD_OPTIMIZERS]) | ||
| def test_psgd_no_fp64_matrices_in_state(opt_cls, lr, extra_kw): | ||
| set_torch() | ||
| torch.manual_seed(42) | ||
| data = torch.randn(32, 64, device="cuda") | ||
| target = torch.randn(32, 32, device="cuda") | ||
|
|
||
| torch.manual_seed(0) | ||
| model = nn.Linear(64, 32, bias=False, device="cuda") | ||
| opt = opt_cls(model.parameters(), lr=lr, **extra_kw) | ||
|
|
||
| _train(model, opt, data, target, 5) | ||
|
|
||
| for param in model.parameters(): | ||
| _check_no_fp64_matrices(opt.state[param]) | ||
|
|
||
| del model, opt | ||
| clean() | ||
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The scalar lower bound arithmethic should be fp64, only matmul and matrix-level elementwise computation should be standard precision