|
20 | 20 | import pytest
|
21 | 21 | import torch
|
22 | 22 | from tests_fabric.helpers.runif import RunIf
|
| 23 | +from torch.optim import Optimizer |
23 | 24 |
|
24 | 25 | from lightning_fabric.accelerators import CPUAccelerator
|
25 | 26 | from lightning_fabric.strategies import DeepSpeedStrategy
|
@@ -151,3 +152,172 @@ def test_deepspeed_requires_joint_setup():
|
151 | 152 | NotImplementedError, match=escape("does not support setting up the module and optimizer(s) independently")
|
152 | 153 | ):
|
153 | 154 | strategy.setup_optimizer(Mock())
|
| 155 | + |
| 156 | + |
| 157 | +@RunIf(deepspeed=True) |
| 158 | +def test_deepspeed_save_checkpoint_storage_options(tmp_path): |
| 159 | + """Test that the DeepSpeed strategy does not accept storage options for saving checkpoints.""" |
| 160 | + strategy = DeepSpeedStrategy() |
| 161 | + with pytest.raises(TypeError, match=escape("DeepSpeedStrategy.save_checkpoint(..., storage_options=...)` is not")): |
| 162 | + strategy.save_checkpoint(path=tmp_path, state=Mock(), storage_options=Mock()) |
| 163 | + |
| 164 | + |
| 165 | +@RunIf(deepspeed=True) |
| 166 | +def test_deepspeed_save_checkpoint_one_deepspeed_engine_required(tmp_path): |
| 167 | + """Test that the DeepSpeed strategy can only save one DeepSpeedEngine per checkpoint.""" |
| 168 | + from deepspeed import DeepSpeedEngine |
| 169 | + |
| 170 | + strategy = DeepSpeedStrategy() |
| 171 | + |
| 172 | + # missing DeepSpeedEngine |
| 173 | + with pytest.raises(ValueError, match="Could not find a DeepSpeed model in the provided checkpoint state."): |
| 174 | + strategy.save_checkpoint(path=tmp_path, state={}) |
| 175 | + with pytest.raises(ValueError, match="Could not find a DeepSpeed model in the provided checkpoint state."): |
| 176 | + strategy.save_checkpoint(path=tmp_path, state={"model": torch.nn.Linear(3, 3)}) |
| 177 | + |
| 178 | + # multiple DeepSpeedEngine |
| 179 | + model1 = Mock(spec=torch.nn.Module) |
| 180 | + model1.modules.return_value = [Mock(spec=DeepSpeedEngine)] |
| 181 | + model2 = Mock(spec=torch.nn.Module) |
| 182 | + model2.modules.return_value = [Mock(spec=DeepSpeedEngine)] |
| 183 | + with pytest.raises(ValueError, match="Found multiple DeepSpeed engine modules in the given state."): |
| 184 | + strategy.save_checkpoint(path=tmp_path, state={"model1": model1, "model2": model2}) |
| 185 | + |
| 186 | + |
| 187 | +@RunIf(deepspeed=True) |
| 188 | +def test_deepspeed_save_checkpoint_client_state_separation(tmp_path): |
| 189 | + """Test that the DeepSpeed engine and optimizer get separated from the client state.""" |
| 190 | + from deepspeed import DeepSpeedEngine |
| 191 | + |
| 192 | + strategy = DeepSpeedStrategy() |
| 193 | + |
| 194 | + # Model only |
| 195 | + model = Mock(spec=DeepSpeedEngine, optimizer=None) |
| 196 | + model.modules.return_value = [model] |
| 197 | + strategy.save_checkpoint(path=tmp_path, state={"model": model, "test": "data"}) |
| 198 | + # the client_state should not contain any deepspeed engine or deepspeed optimizer |
| 199 | + model.save_checkpoint.assert_called_with(tmp_path, client_state={"test": "data"}, tag="checkpoint") |
| 200 | + |
| 201 | + # Model and optimizer |
| 202 | + optimizer = Mock() |
| 203 | + model = Mock(spec=DeepSpeedEngine, optimizer=optimizer) |
| 204 | + model.modules.return_value = [model] |
| 205 | + strategy.save_checkpoint(path=tmp_path, state={"model": model, "optimizer": optimizer, "test": "data"}) |
| 206 | + # the client_state should not contain any deepspeed engine or deepspeed optimizer |
| 207 | + model.save_checkpoint.assert_called_with(tmp_path, client_state={"test": "data"}, tag="checkpoint") |
| 208 | + |
| 209 | + |
| 210 | +@RunIf(deepspeed=True) |
| 211 | +def test_deepspeed_save_checkpoint_warn_colliding_keys(tmp_path): |
| 212 | + """Test that the strategy warns if there are keys in the user dict that collide internally with DeepSpeed.""" |
| 213 | + from deepspeed import DeepSpeedEngine |
| 214 | + |
| 215 | + strategy = DeepSpeedStrategy() |
| 216 | + optimizer = Mock() |
| 217 | + model = Mock(spec=DeepSpeedEngine, optimizer=optimizer) |
| 218 | + model.modules.return_value = [model] |
| 219 | + # `mp_world_size` is an internal key |
| 220 | + with pytest.warns(UserWarning, match="Your state has keys that collide with DeepSpeed's internal"): |
| 221 | + strategy.save_checkpoint(path=tmp_path, state={"model": model, "optimizer": optimizer, "mp_world_size": 2}) |
| 222 | + |
| 223 | + |
| 224 | +@RunIf(deepspeed=True) |
| 225 | +def test_deepspeed_load_checkpoint_no_state(tmp_path): |
| 226 | + """Test that DeepSpeed can't load the full state without access to a model instance from the user.""" |
| 227 | + strategy = DeepSpeedStrategy() |
| 228 | + with pytest.raises(ValueError, match=escape("Got DeepSpeedStrategy.load_checkpoint(..., state=None")): |
| 229 | + strategy.load_checkpoint(path=tmp_path, state=None) |
| 230 | + with pytest.raises(ValueError, match=escape("Got DeepSpeedStrategy.load_checkpoint(..., state={})")): |
| 231 | + strategy.load_checkpoint(path=tmp_path, state={}) |
| 232 | + |
| 233 | + |
| 234 | +@RunIf(deepspeed=True) |
| 235 | +def test_deepspeed_load_checkpoint_one_deepspeed_engine_required(tmp_path): |
| 236 | + """Test that the DeepSpeed strategy can only load one DeepSpeedEngine per checkpoint.""" |
| 237 | + from deepspeed import DeepSpeedEngine |
| 238 | + |
| 239 | + strategy = DeepSpeedStrategy() |
| 240 | + |
| 241 | + # missing DeepSpeedEngine |
| 242 | + with pytest.raises(ValueError, match="Could not find a DeepSpeed model in the provided checkpoint state."): |
| 243 | + strategy.load_checkpoint(path=tmp_path, state={"other": "data"}) |
| 244 | + with pytest.raises(ValueError, match="Could not find a DeepSpeed model in the provided checkpoint state."): |
| 245 | + strategy.load_checkpoint(path=tmp_path, state={"model": torch.nn.Linear(3, 3)}) |
| 246 | + |
| 247 | + # multiple DeepSpeedEngine |
| 248 | + model1 = Mock(spec=torch.nn.Module) |
| 249 | + model1.modules.return_value = [Mock(spec=DeepSpeedEngine)] |
| 250 | + model2 = Mock(spec=torch.nn.Module) |
| 251 | + model2.modules.return_value = [Mock(spec=DeepSpeedEngine)] |
| 252 | + with pytest.raises(ValueError, match="Found multiple DeepSpeed engine modules in the given state."): |
| 253 | + strategy.load_checkpoint(path=tmp_path, state={"model1": model1, "model2": model2}) |
| 254 | + |
| 255 | + |
| 256 | +@RunIf(deepspeed=True) |
| 257 | +def test_deepspeed_load_checkpoint_client_state_missing(tmp_path): |
| 258 | + """Test that the DeepSpeed strategy raises a custom error when client state couldn't be loaded by DeepSpeed.""" |
| 259 | + from deepspeed import DeepSpeedEngine |
| 260 | + |
| 261 | + strategy = DeepSpeedStrategy() |
| 262 | + optimizer = Mock() |
| 263 | + model = Mock(spec=DeepSpeedEngine, optimizer=optimizer) |
| 264 | + model.modules.return_value = [model] |
| 265 | + |
| 266 | + # If the DeepSpeed engine fails to load the checkpoint file (e.g., file not found), it prints a warning and |
| 267 | + # returns None from its function call |
| 268 | + model.load_checkpoint.return_value = [None, None] |
| 269 | + |
| 270 | + # Check for our custom user error |
| 271 | + with pytest.raises(RuntimeError, match="DeepSpeed was unable to load the checkpoint"): |
| 272 | + strategy.load_checkpoint(path=tmp_path, state={"model": model, "optimizer": optimizer, "test": "data"}) |
| 273 | + |
| 274 | + |
| 275 | +@RunIf(deepspeed=True) |
| 276 | +def test_deepspeed_load_checkpoint_state_updated_with_client_state(tmp_path): |
| 277 | + """Test that the DeepSpeed strategy properly updates the state variables and returns additional metadata.""" |
| 278 | + from deepspeed import DeepSpeedEngine |
| 279 | + |
| 280 | + strategy = DeepSpeedStrategy() |
| 281 | + optimizer = Mock() |
| 282 | + model = Mock(spec=DeepSpeedEngine, optimizer=optimizer) |
| 283 | + model.modules.return_value = [model] |
| 284 | + |
| 285 | + # the client state contains the additional user data that was proveded when saving, plus some deepspeed metadata |
| 286 | + loaded_client_state = {"user_data": {"iteration": 5}, "deepspeed_metadata": "data"} |
| 287 | + model.load_checkpoint.return_value = [None, loaded_client_state] |
| 288 | + |
| 289 | + state = {"model": model, "user_data": {"iteration": 0}} |
| 290 | + metadata = strategy.load_checkpoint(path=tmp_path, state=state) |
| 291 | + |
| 292 | + # the user's state gets updated with the loaded value |
| 293 | + assert state == {"model": model, "user_data": {"iteration": 5}} |
| 294 | + # additional metadata gets separated from client state |
| 295 | + assert metadata == {"deepspeed_metadata": "data"} |
| 296 | + |
| 297 | + |
| 298 | +@RunIf(deepspeed=True) |
| 299 | +@pytest.mark.parametrize("optimzer_state_requested", [True, False]) |
| 300 | +def test_deepspeed_load_checkpoint_optimzer_state_requested(optimzer_state_requested, tmp_path): |
| 301 | + """Test that the DeepSpeed strategy loads the optimizer state only when requested.""" |
| 302 | + from deepspeed import DeepSpeedEngine |
| 303 | + |
| 304 | + strategy = DeepSpeedStrategy() |
| 305 | + optimizer = Mock(spec=Optimizer) |
| 306 | + model = Mock(spec=DeepSpeedEngine, optimizer=optimizer) |
| 307 | + model.modules.return_value = [model] |
| 308 | + |
| 309 | + # required, otherwise mock cannot be unpacked |
| 310 | + model.load_checkpoint.return_value = [None, {}] |
| 311 | + |
| 312 | + state = {"model": model} |
| 313 | + if optimzer_state_requested: |
| 314 | + state["optimizer"] = optimizer |
| 315 | + |
| 316 | + strategy.load_checkpoint(path=tmp_path, state=state) |
| 317 | + model.load_checkpoint.assert_called_with( |
| 318 | + tmp_path, |
| 319 | + tag="checkpoint", |
| 320 | + load_optimizer_states=optimzer_state_requested, |
| 321 | + load_lr_scheduler_states=False, |
| 322 | + load_module_strict=True, |
| 323 | + ) |
0 commit comments