|
| 1 | +# Copyright 2023–2026 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Tests for post-train RL training hooks.""" |
| 16 | + |
| 17 | +import unittest |
| 18 | +from types import SimpleNamespace |
| 19 | +from unittest import mock |
| 20 | + |
| 21 | +import pytest |
| 22 | + |
| 23 | +pytestmark = [pytest.mark.cpu_only, pytest.mark.post_training] |
| 24 | + |
| 25 | +from maxtext.trainers.post_train.rl import hooks as rl_hooks |
| 26 | +from maxtext.trainers.post_train.rl import utils_rl |
| 27 | + |
| 28 | + |
| 29 | +def _make_trainer_config(**overrides): |
| 30 | + """Build a SimpleNamespace with the trainer-config attributes hooks reads.""" |
| 31 | + defaults = { |
| 32 | + "num_test_batches": 5, |
| 33 | + "eval_interval": 10, |
| 34 | + "num_eval_passes": 1, |
| 35 | + "eval_corr_lst": False, |
| 36 | + "eval_make_lst": False, |
| 37 | + } |
| 38 | + defaults.update(overrides) |
| 39 | + return SimpleNamespace(**defaults) |
| 40 | + |
| 41 | + |
| 42 | +def _make_rl_cluster(global_steps=0): |
| 43 | + cluster = SimpleNamespace() |
| 44 | + cluster.global_steps = global_steps |
| 45 | + cluster.actor_trainer = SimpleNamespace(training_hooks=None) |
| 46 | + return cluster |
| 47 | + |
| 48 | + |
| 49 | +class RLTrainingHooksTest(unittest.TestCase): |
| 50 | + """Verify `RLTrainingHooks.on_train_step_end` step-gating + evaluate dispatch.""" |
| 51 | + |
| 52 | + def setUp(self): |
| 53 | + super().setUp() |
| 54 | + eval_patcher = mock.patch.object(rl_hooks, "evaluate") |
| 55 | + self.mock_evaluate = eval_patcher.start() |
| 56 | + self.addCleanup(eval_patcher.stop) |
| 57 | + # evaluate(...) returns ((corr, total, acc, partial_acc, fmt_acc), _). |
| 58 | + self.mock_evaluate.return_value = ((1, 2, 50.0, 50.0, 100.0), None) |
| 59 | + |
| 60 | + def _build_hook(self, eval_interval=10, global_steps=0): |
| 61 | + cluster = _make_rl_cluster(global_steps=global_steps) |
| 62 | + cfg = _make_trainer_config(eval_interval=eval_interval) |
| 63 | + return rl_hooks.RLTrainingHooks(cluster, cfg, test_dataset=None, eval_interval=eval_interval) |
| 64 | + |
| 65 | + def test_fires_on_matching_step(self): |
| 66 | + hook = self._build_hook(eval_interval=10, global_steps=10) |
| 67 | + hook.on_train_step_end(trainer=None, step=10, loss=None) |
| 68 | + self.mock_evaluate.assert_called_once() |
| 69 | + |
| 70 | + def test_skips_when_step_not_multiple_of_interval(self): |
| 71 | + hook = self._build_hook(eval_interval=10, global_steps=7) |
| 72 | + hook.on_train_step_end(trainer=None, step=7, loss=None) |
| 73 | + self.mock_evaluate.assert_not_called() |
| 74 | + |
| 75 | + def test_skips_when_step_is_zero(self): |
| 76 | + hook = self._build_hook(eval_interval=10, global_steps=0) |
| 77 | + hook.on_train_step_end(trainer=None, step=0, loss=None) |
| 78 | + self.mock_evaluate.assert_not_called() |
| 79 | + |
| 80 | + def test_dedupes_repeat_calls_on_same_step(self): |
| 81 | + hook = self._build_hook(eval_interval=10, global_steps=10) |
| 82 | + hook.on_train_step_end(trainer=None, step=10, loss=None) |
| 83 | + hook.on_train_step_end(trainer=None, step=10, loss=None) |
| 84 | + self.assertEqual(self.mock_evaluate.call_count, 1) |
| 85 | + |
| 86 | + def test_swallows_evaluate_exception(self): |
| 87 | + """A failing evaluate shouldn't propagate and break the training step.""" |
| 88 | + self.mock_evaluate.side_effect = RuntimeError("boom") |
| 89 | + hook = self._build_hook(eval_interval=10, global_steps=10) |
| 90 | + hook.on_train_step_end(trainer=None, step=10, loss=None) # must not raise |
| 91 | + |
| 92 | + def test_falls_back_to_step_arg_when_global_steps_unreadable(self): |
| 93 | + """When rl_cluster.global_steps raises, use the `step` arg instead.""" |
| 94 | + |
| 95 | + class _ClusterWithBadGlobalSteps: |
| 96 | + """Stand-in rl_cluster whose `global_steps` property always raises.""" |
| 97 | + |
| 98 | + def __init__(self): |
| 99 | + self.actor_trainer = SimpleNamespace(training_hooks=None) |
| 100 | + |
| 101 | + @property |
| 102 | + def global_steps(self): |
| 103 | + raise RuntimeError("not ready") |
| 104 | + |
| 105 | + bad_cluster = _ClusterWithBadGlobalSteps() |
| 106 | + cfg = _make_trainer_config(eval_interval=10) |
| 107 | + hook = rl_hooks.RLTrainingHooks(bad_cluster, cfg, test_dataset=None, eval_interval=10) |
| 108 | + hook.on_train_step_end(trainer=None, step=10, loss=None) |
| 109 | + self.mock_evaluate.assert_called_once() |
| 110 | + |
| 111 | + |
| 112 | +class InstallTrainingHooksTest(unittest.TestCase): |
| 113 | + """Verify `utils_rl.install_training_hooks` gating + attach behavior.""" |
| 114 | + |
| 115 | + def test_noop_when_num_test_batches_nonpositive(self): |
| 116 | + cluster = _make_rl_cluster() |
| 117 | + cfg = _make_trainer_config(num_test_batches=0, eval_interval=10) |
| 118 | + utils_rl.install_training_hooks(cluster, cfg, test_dataset=None) |
| 119 | + self.assertIsNone(cluster.actor_trainer.training_hooks) |
| 120 | + |
| 121 | + def test_noop_when_eval_interval_nonpositive(self): |
| 122 | + cluster = _make_rl_cluster() |
| 123 | + cfg = _make_trainer_config(num_test_batches=5, eval_interval=0) |
| 124 | + utils_rl.install_training_hooks(cluster, cfg, test_dataset=None) |
| 125 | + self.assertIsNone(cluster.actor_trainer.training_hooks) |
| 126 | + |
| 127 | + def test_noop_when_eval_interval_attr_missing(self): |
| 128 | + cluster = _make_rl_cluster() |
| 129 | + cfg = SimpleNamespace(num_test_batches=5) # no eval_interval attribute |
| 130 | + utils_rl.install_training_hooks(cluster, cfg, test_dataset=None) |
| 131 | + self.assertIsNone(cluster.actor_trainer.training_hooks) |
| 132 | + |
| 133 | + def test_attaches_hook_on_happy_path(self): |
| 134 | + cluster = _make_rl_cluster() |
| 135 | + cfg = _make_trainer_config(num_test_batches=5, eval_interval=10) |
| 136 | + utils_rl.install_training_hooks(cluster, cfg, test_dataset="dummy") |
| 137 | + self.assertIsInstance(cluster.actor_trainer.training_hooks, rl_hooks.RLTrainingHooks) |
| 138 | + |
| 139 | + def test_does_not_overwrite_existing_training_hooks(self): |
| 140 | + cluster = _make_rl_cluster() |
| 141 | + sentinel = object() |
| 142 | + cluster.actor_trainer.training_hooks = sentinel |
| 143 | + cfg = _make_trainer_config(num_test_batches=5, eval_interval=10) |
| 144 | + utils_rl.install_training_hooks(cluster, cfg, test_dataset=None) |
| 145 | + self.assertIs(cluster.actor_trainer.training_hooks, sentinel) |
| 146 | + |
| 147 | + def test_swallows_importerror_when_hooks_module_missing(self): |
| 148 | + """If `from .hooks import RLTrainingHooks` fails, install soft-skips. |
| 149 | +
|
| 150 | + Setting `sys.modules[name] = None` makes Python's import system raise |
| 151 | + ImportError on the next import attempt for that name (documented behavior). |
| 152 | + """ |
| 153 | + cluster = _make_rl_cluster() |
| 154 | + cfg = _make_trainer_config(num_test_batches=5, eval_interval=10) |
| 155 | + with mock.patch.dict("sys.modules", {"maxtext.trainers.post_train.rl.hooks": None}): |
| 156 | + utils_rl.install_training_hooks(cluster, cfg, test_dataset=None) |
| 157 | + self.assertIsNone(cluster.actor_trainer.training_hooks) |
| 158 | + |
| 159 | + |
| 160 | +if __name__ == "__main__": |
| 161 | + unittest.main() |
0 commit comments