|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +import torch |
| 16 | +from absl import flags, logging |
| 17 | +from absl.testing import absltest, parameterized |
| 18 | +from muown_reference import MuownReference |
| 19 | + |
| 20 | +from emerging_optimizers.orthogonalized_optimizers.muown import Muown |
| 21 | + |
| 22 | + |
| 23 | +flags.DEFINE_enum("device", "cpu", ["cpu", "cuda"], "Device to run tests on") |
| 24 | +flags.DEFINE_integer("seed", None, "Random seed for reproducible tests") |
| 25 | +FLAGS = flags.FLAGS |
| 26 | + |
| 27 | + |
| 28 | +def setUpModule() -> None: |
| 29 | + if FLAGS.seed is not None: |
| 30 | + logging.info("Setting random seed to %d", FLAGS.seed) |
| 31 | + torch.manual_seed(FLAGS.seed) |
| 32 | + if torch.cuda.is_available(): |
| 33 | + torch.cuda.manual_seed_all(FLAGS.seed) |
| 34 | + # Use the most precise fp32 matmul path so the reference (which calls the optimizer's |
| 35 | + # orthogonalization outside the fp32_matmul_precision context) computes bit-comparable results. |
| 36 | + torch.set_float32_matmul_precision("highest") |
| 37 | + |
| 38 | + |
| 39 | +class MuownTest(parameterized.TestCase): |
| 40 | + def setUp(self): |
| 41 | + super().setUp() |
| 42 | + self.device = FLAGS.device |
| 43 | + |
| 44 | + @parameterized.product(shape=[(8, 16), (16, 8), (33, 65)]) |
| 45 | + def test_smoke(self, shape): |
| 46 | + """A few steps run and keep the weight finite.""" |
| 47 | + p = torch.nn.Parameter(torch.randn(shape, device=self.device)) |
| 48 | + opt = Muown([p], lr=1e-2, weight_decay=0.01) |
| 49 | + for _ in range(3): |
| 50 | + p.grad = torch.randn_like(p) |
| 51 | + opt.step() |
| 52 | + self.assertTrue(torch.isfinite(p).all()) |
| 53 | + |
| 54 | + def test_raises_on_non_2d(self): |
| 55 | + """Muown supports 2D parameters only.""" |
| 56 | + for shape in [(8,), (2, 3, 4)]: |
| 57 | + p = torch.nn.Parameter(torch.randn(shape, device=self.device)) |
| 58 | + p.grad = torch.randn_like(p) |
| 59 | + opt = Muown([p], lr=1e-2) |
| 60 | + with self.assertRaises(TypeError): |
| 61 | + opt.step() |
| 62 | + |
| 63 | + def test_raises_on_closure(self): |
| 64 | + """Closures are not supported.""" |
| 65 | + p = torch.nn.Parameter(torch.randn((8, 16), device=self.device)) |
| 66 | + p.grad = torch.randn_like(p) |
| 67 | + opt = Muown([p], lr=1e-2) |
| 68 | + with self.assertRaises(ValueError): |
| 69 | + opt.step(lambda: 0.0) |
| 70 | + |
| 71 | + @parameterized.product(shape=[(8, 16), (16, 8)], weight_decay=[0.0, 0.1]) |
| 72 | + def test_row_norm_equals_magnitude_state(self, shape, weight_decay): |
| 73 | + """The reparameterization invariant ||W_row|| == g holds after each step.""" |
| 74 | + p = torch.nn.Parameter(torch.randn(shape, device=self.device)) |
| 75 | + opt = Muown([p], lr=1e-2, weight_decay=weight_decay) |
| 76 | + for _ in range(4): |
| 77 | + p.grad = torch.randn_like(p) |
| 78 | + opt.step() |
| 79 | + row_norm = p.detach().norm(dim=1, keepdim=True) |
| 80 | + torch.testing.assert_close( |
| 81 | + row_norm, |
| 82 | + opt.state[p]["g"], |
| 83 | + atol=1e-5, |
| 84 | + rtol=1e-5, |
| 85 | + msg=lambda m: f"Row norms of W must equal the magnitude state g.\n\n{m}", |
| 86 | + ) |
| 87 | + |
| 88 | + def test_weight_decay_shrinks_magnitude(self): |
| 89 | + """Decoupled weight decay shrinks the magnitude g relative to the no-decay run.""" |
| 90 | + p_wd = torch.nn.Parameter(torch.randn((16, 32), device=self.device)) |
| 91 | + p_no = torch.nn.Parameter(p_wd.detach().clone()) |
| 92 | + opt_wd = Muown([p_wd], lr=1e-2, weight_decay=0.1) |
| 93 | + opt_no = Muown([p_no], lr=1e-2, weight_decay=0.0) |
| 94 | + for _ in range(5): |
| 95 | + grad = torch.randn_like(p_wd) |
| 96 | + p_wd.grad = grad.clone() |
| 97 | + p_no.grad = grad.clone() |
| 98 | + opt_wd.step() |
| 99 | + opt_no.step() |
| 100 | + self.assertLess(opt_wd.state[p_wd]["g"].sum().item(), opt_no.state[p_no]["g"].sum().item()) |
| 101 | + |
| 102 | + @parameterized.product(shape=[(8, 16), (16, 8), (33, 65)], momentum=[0.0, 0.95]) |
| 103 | + def test_agrees_with_reference(self, shape, momentum): |
| 104 | + """Muown matches the authors' reference implementation (no weight decay). |
| 105 | +
|
| 106 | + The reference uses classic (heavy-ball) momentum while Muown uses EMA momentum; the two differ by |
| 107 | + a constant factor that the scale-invariant Newton-Schulz orthogonalization removes, so the updates |
| 108 | + agree. Both use the same injected orthogonalization, so only float rounding (lerp vs mul/add, |
| 109 | + Newton-Schulz normalization) separates them — hence a tight tolerance rather than bit-identity. |
| 110 | + """ |
| 111 | + p = torch.nn.Parameter(torch.randn(shape, device=self.device)) |
| 112 | + p_ref = torch.nn.Parameter(p.detach().clone()) |
| 113 | + |
| 114 | + opt = Muown( |
| 115 | + [p], |
| 116 | + lr=1e-2, |
| 117 | + momentum=momentum, |
| 118 | + weight_decay=0.0, |
| 119 | + extra_scale_factor=0.2, |
| 120 | + fp32_matmul_prec="highest", |
| 121 | + ) |
| 122 | + # Hold orthogonalization identical: feed the reference Muown's own scaled_orthogonalize_fn. |
| 123 | + opt_ref = MuownReference( |
| 124 | + [p_ref], |
| 125 | + orthogonalize_fn=opt.scaled_orthogonalize_fn, |
| 126 | + lr=1e-2, |
| 127 | + momentum=momentum, |
| 128 | + nesterov=False, |
| 129 | + weight_decay=0.0, |
| 130 | + ) |
| 131 | + |
| 132 | + for _ in range(5): |
| 133 | + grad = torch.randn_like(p) |
| 134 | + p.grad = grad.clone() |
| 135 | + p_ref.grad = grad.clone() |
| 136 | + opt.step() |
| 137 | + opt_ref.step() |
| 138 | + |
| 139 | + torch.testing.assert_close( |
| 140 | + p.detach(), |
| 141 | + p_ref.detach(), |
| 142 | + atol=1e-5, |
| 143 | + rtol=1e-4, |
| 144 | + msg=lambda m: f"Muown weight diverged from the reference implementation.\n\n{m}", |
| 145 | + ) |
| 146 | + torch.testing.assert_close( |
| 147 | + opt.state[p]["g"], |
| 148 | + opt_ref.state[p_ref]["g"], |
| 149 | + atol=1e-5, |
| 150 | + rtol=1e-4, |
| 151 | + msg=lambda m: f"Muown magnitude g diverged from the reference implementation.\n\n{m}", |
| 152 | + ) |
| 153 | + |
| 154 | + |
| 155 | +if __name__ == "__main__": |
| 156 | + absltest.main() |
0 commit comments