|
| 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 | + |
| 16 | +import torch |
| 17 | +from absl import flags, logging |
| 18 | +from absl.testing import absltest, parameterized |
| 19 | + |
| 20 | +from emerging_optimizers.scalar_optimizers import LaProp |
| 21 | +from emerging_optimizers.scalar_optimizers.update_functions import calculate_laprop_update |
| 22 | + |
| 23 | + |
| 24 | +flags.DEFINE_enum("device", "cpu", ["cpu", "cuda"], "Device to run tests on") |
| 25 | +flags.DEFINE_integer("seed", None, "Random seed for reproducible tests") |
| 26 | +FLAGS = flags.FLAGS |
| 27 | + |
| 28 | + |
| 29 | +def setUpModule() -> None: |
| 30 | + if FLAGS.seed is not None: |
| 31 | + logging.info("Setting random seed to %d", FLAGS.seed) |
| 32 | + torch.manual_seed(FLAGS.seed) |
| 33 | + if torch.cuda.is_available(): |
| 34 | + torch.cuda.manual_seed_all(FLAGS.seed) |
| 35 | + |
| 36 | + |
| 37 | +class LaPropOptimizerTest(parameterized.TestCase): |
| 38 | + def setUp(self): |
| 39 | + self.device = FLAGS.device |
| 40 | + |
| 41 | + @parameterized.parameters( |
| 42 | + {"shape": (3, 3)}, |
| 43 | + {"shape": (15, 31)}, |
| 44 | + {"shape": (127, 255)}, |
| 45 | + ) |
| 46 | + def test_smoke(self, shape) -> None: |
| 47 | + """LaProp optimizer can be instantiated and stepped.""" |
| 48 | + param = torch.nn.Parameter(torch.randn(*shape, device=self.device)) |
| 49 | + optimizer = LaProp([param], lr=1e-4) |
| 50 | + param.grad = torch.randn_like(param) |
| 51 | + optimizer.step() |
| 52 | + |
| 53 | + @parameterized.parameters( |
| 54 | + {"shape": (3, 3)}, |
| 55 | + {"shape": (15, 31)}, |
| 56 | + {"shape": (127, 255)}, |
| 57 | + ) |
| 58 | + def test_state_initialization(self, shape) -> None: |
| 59 | + """LaProp initializes first moment, second moment, and step state.""" |
| 60 | + beta1, beta2 = 0.5, 0.75 |
| 61 | + param = torch.nn.Parameter(torch.randint(1, 5, shape, device=self.device, dtype=torch.float32)) |
| 62 | + optimizer = LaProp([param], lr=0.25, betas=(beta1, beta2), weight_decay=0.0, correct_bias=True) |
| 63 | + grad = torch.randint_like(param, 1, 5) |
| 64 | + param.grad = grad.clone() |
| 65 | + optimizer.step() |
| 66 | + |
| 67 | + self.assertEqual(optimizer.state[param]["step"], 1) |
| 68 | + self.assertIn("exp_avg", optimizer.state[param]) |
| 69 | + self.assertIn("exp_avg_sq", optimizer.state[param]) |
| 70 | + |
| 71 | + expected_exp_avg_sq = (1 - beta2) * grad.square() |
| 72 | + normalized_grad = grad / (grad.abs() + optimizer.param_groups[0]["eps"]) |
| 73 | + expected_exp_avg = (1 - beta1) * normalized_grad |
| 74 | + torch.testing.assert_close(optimizer.state[param]["exp_avg_sq"], expected_exp_avg_sq, atol=0, rtol=0) |
| 75 | + torch.testing.assert_close(optimizer.state[param]["exp_avg"], expected_exp_avg, atol=0, rtol=0) |
| 76 | + |
| 77 | + @parameterized.parameters( |
| 78 | + {"shape": (3, 3)}, |
| 79 | + {"shape": (15, 31)}, |
| 80 | + {"shape": (127, 255)}, |
| 81 | + ) |
| 82 | + def test_optimizer_step_matches_update_function(self, shape) -> None: |
| 83 | + """LaProp optimizer delegates update math to calculate_laprop_update.""" |
| 84 | + lr = 0.25 |
| 85 | + betas = (0.5, 0.75) |
| 86 | + eps = 1e-8 |
| 87 | + param = torch.nn.Parameter(torch.randint(-5, 5, shape, device=self.device, dtype=torch.float32)) |
| 88 | + grad = torch.randint(-5, 5, shape, device=self.device, dtype=torch.float32) |
| 89 | + optimizer = LaProp([param], lr=lr, betas=betas, eps=eps, weight_decay=0.0) |
| 90 | + |
| 91 | + old_param = param.detach().clone() |
| 92 | + exp_avg = torch.zeros_like(param) |
| 93 | + exp_avg_sq = torch.zeros_like(param) |
| 94 | + expected_update = calculate_laprop_update(grad, exp_avg, exp_avg_sq, True, betas, 1, eps) |
| 95 | + |
| 96 | + param.grad = grad.clone() |
| 97 | + optimizer.step() |
| 98 | + |
| 99 | + torch.testing.assert_close(param, old_param - lr * expected_update, atol=0, rtol=0) |
| 100 | + torch.testing.assert_close(optimizer.state[param]["exp_avg"], exp_avg, atol=0, rtol=0) |
| 101 | + torch.testing.assert_close(optimizer.state[param]["exp_avg_sq"], exp_avg_sq, atol=0, rtol=0) |
| 102 | + |
| 103 | + @parameterized.parameters( |
| 104 | + {"shape": (3, 3)}, |
| 105 | + {"shape": (15, 31)}, |
| 106 | + {"shape": (127, 255)}, |
| 107 | + ) |
| 108 | + def test_no_grad_no_update_params_unchanged(self, shape) -> None: |
| 109 | + """Parameters without gradients are not updated.""" |
| 110 | + param = torch.nn.Parameter(torch.randn(*shape, device=self.device)) |
| 111 | + original = param.detach().clone() |
| 112 | + optimizer = LaProp([param], lr=1e-4) |
| 113 | + optimizer.step() |
| 114 | + torch.testing.assert_close(param, original, atol=0, rtol=0) |
| 115 | + |
| 116 | + @parameterized.parameters( |
| 117 | + {"shape": (3, 3)}, |
| 118 | + {"shape": (15, 31)}, |
| 119 | + {"shape": (127, 255)}, |
| 120 | + ) |
| 121 | + def test_frob_normalize_preserves_parameter_norm(self, shape) -> None: |
| 122 | + """LaProp can normalize updated parameters back to their pre-update norm.""" |
| 123 | + param = torch.nn.Parameter(torch.randint(1, 5, shape, device=self.device, dtype=torch.float32)) |
| 124 | + optimizer = LaProp([param], lr=0.25, weight_decay=0.0, frob_normalize=True) |
| 125 | + param.grad = torch.randint(1, 5, shape, device=self.device, dtype=torch.float32) |
| 126 | + original_norm = param.norm() |
| 127 | + |
| 128 | + optimizer.step() |
| 129 | + |
| 130 | + torch.testing.assert_close(param.norm(), original_norm) |
| 131 | + |
| 132 | + @parameterized.parameters(True, False) |
| 133 | + def test_init_group_skip_non_grad_params(self, skip_non_grad_params) -> None: |
| 134 | + """Test _init_group with skip_non_grad_params flag.""" |
| 135 | + param_with_grad = torch.nn.Parameter(torch.randn(5, 7, device=self.device)) |
| 136 | + param_without_grad = torch.nn.Parameter(torch.randn(5, 7, device=self.device)) |
| 137 | + param_with_grad.grad = torch.randn_like(param_with_grad) |
| 138 | + |
| 139 | + opt = LaProp([param_with_grad, param_without_grad], lr=1e-4) |
| 140 | + opt._init_group(opt.param_groups[0], skip_non_grad_params=skip_non_grad_params) |
| 141 | + |
| 142 | + self.assertIn("exp_avg", opt.state[param_with_grad]) |
| 143 | + self.assertIn("exp_avg_sq", opt.state[param_with_grad]) |
| 144 | + self.assertEqual(opt.state[param_with_grad]["step"], 0) |
| 145 | + self.assertEqual("exp_avg" in opt.state[param_without_grad], not skip_non_grad_params) |
| 146 | + |
| 147 | + def test_negative_lr_raises_value_error(self) -> None: |
| 148 | + """Test that LaProp raises ValueError for negative learning rate.""" |
| 149 | + param = torch.nn.Parameter(torch.randn(3, 3, device=self.device)) |
| 150 | + with self.assertRaisesRegex(ValueError, "Invalid learning rate"): |
| 151 | + LaProp([param], lr=-1.0) |
| 152 | + |
| 153 | + def test_beta0_out_of_range_raises_value_error(self) -> None: |
| 154 | + """Test that LaProp raises ValueError for invalid beta at index 0.""" |
| 155 | + param = torch.nn.Parameter(torch.randn(3, 3, device=self.device)) |
| 156 | + with self.assertRaisesRegex(ValueError, "Invalid beta at index 0"): |
| 157 | + LaProp([param], betas=(1.0, 0.999)) |
| 158 | + |
| 159 | + def test_beta1_out_of_range_raises_value_error(self) -> None: |
| 160 | + """Test that LaProp raises ValueError for invalid beta at index 1.""" |
| 161 | + param = torch.nn.Parameter(torch.randn(3, 3, device=self.device)) |
| 162 | + with self.assertRaisesRegex(ValueError, "Invalid beta at index 1"): |
| 163 | + LaProp([param], betas=(0.9, 1.0)) |
| 164 | + |
| 165 | + def test_negative_eps_raises_value_error(self) -> None: |
| 166 | + """Test that LaProp raises ValueError for negative eps.""" |
| 167 | + param = torch.nn.Parameter(torch.randn(3, 3, device=self.device)) |
| 168 | + with self.assertRaisesRegex(ValueError, "Invalid epsilon"): |
| 169 | + LaProp([param], eps=-1e-8) |
| 170 | + |
| 171 | + def test_negative_weight_decay_raises_value_error(self) -> None: |
| 172 | + """Test that LaProp raises ValueError for negative weight_decay.""" |
| 173 | + param = torch.nn.Parameter(torch.randn(3, 3, device=self.device)) |
| 174 | + with self.assertRaisesRegex(ValueError, "Invalid weight_decay"): |
| 175 | + LaProp([param], weight_decay=-0.1) |
| 176 | + |
| 177 | + |
| 178 | +if __name__ == "__main__": |
| 179 | + absltest.main() |
0 commit comments