-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
test_cli.py
1545 lines (1230 loc) · 59 KB
/
test_cli.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import glob
import inspect
import json
import os
from contextlib import contextmanager, ExitStack, redirect_stdout
from io import StringIO
from pathlib import Path
from typing import Callable, List, Optional, Union
from unittest import mock
from unittest.mock import ANY
import pytest
import torch
import yaml
from lightning_utilities.test.warning import no_warning_call
from torch.optim import SGD
from torch.optim.lr_scheduler import ReduceLROnPlateau, StepLR
from lightning.fabric.plugins.environments import SLURMEnvironment
from lightning.pytorch import __version__, Callback, LightningDataModule, LightningModule, seed_everything, Trainer
from lightning.pytorch.callbacks import LearningRateMonitor, ModelCheckpoint
from lightning.pytorch.cli import (
_JSONARGPARSE_SIGNATURES_AVAILABLE,
instantiate_class,
LightningArgumentParser,
LightningCLI,
LRSchedulerCallable,
LRSchedulerTypeTuple,
OptimizerCallable,
SaveConfigCallback,
)
from lightning.pytorch.demos.boring_classes import BoringDataModule, BoringModel
from lightning.pytorch.loggers import _COMET_AVAILABLE, TensorBoardLogger
from lightning.pytorch.loggers.csv_logs import CSVLogger
from lightning.pytorch.loggers.neptune import _NEPTUNE_AVAILABLE
from lightning.pytorch.loggers.wandb import _WANDB_AVAILABLE
from lightning.pytorch.strategies import DDPStrategy
from lightning.pytorch.trainer.states import TrainerFn
from lightning.pytorch.utilities.exceptions import MisconfigurationException
from lightning.pytorch.utilities.imports import _TORCHVISION_AVAILABLE
from tests_pytorch.helpers.runif import RunIf
if _JSONARGPARSE_SIGNATURES_AVAILABLE:
from jsonargparse import lazy_instance, Namespace
else:
from argparse import Namespace
@contextmanager
def mock_subclasses(baseclass, *subclasses):
"""Mocks baseclass so that it only has the given child subclasses."""
with ExitStack() as stack:
mgr = mock.patch.object(baseclass, "__subclasses__", return_value=[*subclasses])
stack.enter_context(mgr)
for mgr in [mock.patch.object(s, "__subclasses__", return_value=[]) for s in subclasses]:
stack.enter_context(mgr)
yield None
@pytest.fixture
def cleandir(tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
yield
@pytest.fixture(autouse=True)
def ensure_cleandir():
yield
# make sure tests don't leave configuration files
assert not glob.glob("*.yaml")
@pytest.mark.parametrize("cli_args", [["--callbacks=1", "--logger"], ["--foo", "--bar=1"]])
def test_add_argparse_args_redefined_error(cli_args, monkeypatch):
"""Asserts error raised in case of passing not default cli arguments."""
class _UnkArgError(Exception):
pass
def _raise():
raise _UnkArgError
parser = LightningArgumentParser(add_help=False, parse_as_dict=False)
parser.add_lightning_class_args(Trainer, None)
monkeypatch.setattr(parser, "exit", lambda *args: _raise(), raising=True)
with pytest.raises(_UnkArgError):
parser.parse_args(cli_args)
class Model(LightningModule):
def __init__(self, model_param: int):
super().__init__()
self.model_param = model_param
def _model_builder(model_param: int) -> Model:
return Model(model_param)
def _trainer_builder(
limit_train_batches: int, fast_dev_run: bool = False, callbacks: Optional[Union[List[Callback], Callback]] = None
) -> Trainer:
return Trainer(limit_train_batches=limit_train_batches, fast_dev_run=fast_dev_run, callbacks=callbacks)
@pytest.mark.parametrize(["trainer_class", "model_class"], [(Trainer, Model), (_trainer_builder, _model_builder)])
def test_lightning_cli(trainer_class, model_class, monkeypatch):
"""Test that LightningCLI correctly instantiates model, trainer and calls fit."""
expected_model = dict(model_param=7)
expected_trainer = dict(limit_train_batches=100)
def fit(trainer, model):
for k, v in expected_model.items():
assert getattr(model, k) == v
for k, v in expected_trainer.items():
assert getattr(trainer, k) == v
save_callback = [x for x in trainer.callbacks if isinstance(x, SaveConfigCallback)]
assert len(save_callback) == 1
save_callback[0].on_train_start(trainer, model)
def on_train_start(callback, trainer, _):
config_dump = callback.parser.dump(callback.config, skip_none=False)
for k, v in expected_model.items():
assert f" {k}: {v}" in config_dump
for k, v in expected_trainer.items():
assert f" {k}: {v}" in config_dump
trainer.ran_asserts = True
monkeypatch.setattr(Trainer, "fit", fit)
monkeypatch.setattr(SaveConfigCallback, "on_train_start", on_train_start)
with mock.patch("sys.argv", ["any.py", "fit", "--model.model_param=7", "--trainer.limit_train_batches=100"]):
cli = LightningCLI(model_class, trainer_class=trainer_class, save_config_callback=SaveConfigCallback)
assert hasattr(cli.trainer, "ran_asserts") and cli.trainer.ran_asserts
def test_lightning_cli_args_callbacks(cleandir):
callbacks = [
dict(
class_path="lightning.pytorch.callbacks.LearningRateMonitor",
init_args=dict(logging_interval="epoch", log_momentum=True),
),
dict(class_path="lightning.pytorch.callbacks.ModelCheckpoint", init_args=dict(monitor="NAME")),
]
class TestModel(BoringModel):
def on_fit_start(self):
callback = [c for c in self.trainer.callbacks if isinstance(c, LearningRateMonitor)]
assert len(callback) == 1
assert callback[0].logging_interval == "epoch"
assert callback[0].log_momentum is True
callback = [c for c in self.trainer.callbacks if isinstance(c, ModelCheckpoint)]
assert len(callback) == 1
assert callback[0].monitor == "NAME"
self.trainer.ran_asserts = True
with mock.patch("sys.argv", ["any.py", "fit", f"--trainer.callbacks={json.dumps(callbacks)}"]):
cli = LightningCLI(TestModel, trainer_defaults=dict(fast_dev_run=True, logger=CSVLogger(".")))
assert cli.trainer.ran_asserts
def test_lightning_cli_single_arg_callback():
with mock.patch("sys.argv", ["any.py", "--trainer.callbacks=DeviceStatsMonitor"]):
cli = LightningCLI(BoringModel, run=False)
assert cli.config.trainer.callbacks.class_path == "lightning.pytorch.callbacks.DeviceStatsMonitor"
assert not isinstance(cli.config_init.trainer, list)
@pytest.mark.parametrize("run", (False, True))
def test_lightning_cli_configurable_callbacks(cleandir, run):
class MyLightningCLI(LightningCLI):
def add_arguments_to_parser(self, parser):
parser.add_lightning_class_args(LearningRateMonitor, "learning_rate_monitor")
def fit(self, **_):
pass
cli_args = ["fit"] if run else []
cli_args += ["--learning_rate_monitor.logging_interval=epoch"]
with mock.patch("sys.argv", ["any.py"] + cli_args):
cli = MyLightningCLI(BoringModel, run=run)
callback = [c for c in cli.trainer.callbacks if isinstance(c, LearningRateMonitor)]
assert len(callback) == 1
assert callback[0].logging_interval == "epoch"
def test_lightning_cli_args_cluster_environments(cleandir):
plugins = [dict(class_path="lightning.fabric.plugins.environments.SLURMEnvironment")]
class TestModel(BoringModel):
def on_fit_start(self):
# Ensure SLURMEnvironment is set, instead of default LightningEnvironment
assert isinstance(self.trainer._accelerator_connector.cluster_environment, SLURMEnvironment)
self.trainer.ran_asserts = True
with mock.patch("sys.argv", ["any.py", "fit", f"--trainer.plugins={json.dumps(plugins)}"]):
cli = LightningCLI(TestModel, trainer_defaults=dict(fast_dev_run=True))
assert cli.trainer.ran_asserts
class DataDirDataModule(BoringDataModule):
def __init__(self, data_dir):
super().__init__()
def test_lightning_cli_args(cleandir):
cli_args = [
"fit",
"--data.data_dir=.",
"--trainer.max_epochs=1",
"--trainer.limit_train_batches=1",
"--trainer.limit_val_batches=0",
"--trainer.enable_model_summary=False",
"--trainer.logger=False",
"--seed_everything=1234",
]
with mock.patch("sys.argv", ["any.py"] + cli_args):
cli = LightningCLI(BoringModel, DataDirDataModule)
config_path = "config.yaml"
assert os.path.isfile(config_path)
with open(config_path) as f:
loaded_config = yaml.safe_load(f.read())
cli_config = cli.config["fit"].as_dict()
assert cli_config["seed_everything"] == 1234
assert "model" not in loaded_config and "model" not in cli_config # no arguments to include
assert loaded_config["data"] == cli_config["data"]
assert loaded_config["trainer"] == cli_config["trainer"]
def test_lightning_env_parse(cleandir):
out = StringIO()
with mock.patch("sys.argv", ["", "fit", "--help"]), redirect_stdout(out), pytest.raises(SystemExit):
LightningCLI(BoringModel, DataDirDataModule, parser_kwargs={"default_env": True})
out = out.getvalue()
assert "PL_FIT__CONFIG" in out
assert "PL_FIT__SEED_EVERYTHING" in out
assert "PL_FIT__TRAINER__LOGGER" in out
assert "PL_FIT__DATA__DATA_DIR" in out
assert "PL_FIT__CKPT_PATH" in out
env_vars = {
"PL_FIT__DATA__DATA_DIR": ".",
"PL_FIT__TRAINER__DEFAULT_ROOT_DIR": ".",
"PL_FIT__TRAINER__MAX_EPOCHS": "1",
"PL_FIT__TRAINER__LOGGER": "False",
}
with mock.patch.dict(os.environ, env_vars), mock.patch("sys.argv", ["", "fit"]):
cli = LightningCLI(BoringModel, DataDirDataModule, parser_kwargs={"default_env": True})
assert cli.config.fit.data.data_dir == "."
assert cli.config.fit.trainer.default_root_dir == "."
assert cli.config.fit.trainer.max_epochs == 1
assert cli.config.fit.trainer.logger is False
def test_lightning_cli_save_config_cases(cleandir):
config_path = "config.yaml"
cli_args = ["fit", "--trainer.logger=false", "--trainer.fast_dev_run=1"]
# With fast_dev_run!=False config should not be saved
with mock.patch("sys.argv", ["any.py"] + cli_args):
LightningCLI(BoringModel)
assert not os.path.isfile(config_path)
# With fast_dev_run==False config should be saved
cli_args[-1] = "--trainer.max_epochs=1"
with mock.patch("sys.argv", ["any.py"] + cli_args):
LightningCLI(BoringModel)
assert os.path.isfile(config_path)
# If run again on same directory exception should be raised since config file already exists
with mock.patch("sys.argv", ["any.py"] + cli_args), pytest.raises(RuntimeError):
LightningCLI(BoringModel)
def test_lightning_cli_save_config_only_once(cleandir):
config_path = "config.yaml"
cli_args = ["--trainer.logger=false", "--trainer.max_epochs=1"]
with mock.patch("sys.argv", ["any.py"] + cli_args):
cli = LightningCLI(BoringModel, run=False)
save_config_callback = next(c for c in cli.trainer.callbacks if isinstance(c, SaveConfigCallback))
assert not save_config_callback.overwrite
assert not save_config_callback.already_saved
cli.trainer.fit(cli.model)
assert os.path.isfile(config_path)
assert save_config_callback.already_saved
cli.trainer.test(cli.model) # Should not fail because config already saved
def test_lightning_cli_config_and_subclass_mode(cleandir):
input_config = {
"fit": {
"model": {"class_path": "lightning.pytorch.demos.boring_classes.BoringModel"},
"data": {
"class_path": "DataDirDataModule",
"init_args": {"data_dir": "."},
},
"trainer": {"max_epochs": 1, "enable_model_summary": False, "logger": False},
}
}
config_path = "config.yaml"
with open(config_path, "w") as f:
f.write(yaml.dump(input_config))
with mock.patch("sys.argv", ["any.py", "--config", config_path]), mock_subclasses(
LightningDataModule, DataDirDataModule
):
cli = LightningCLI(
BoringModel,
BoringDataModule,
subclass_mode_model=True,
subclass_mode_data=True,
save_config_kwargs={"overwrite": True},
)
config_path = "config.yaml"
assert os.path.isfile(config_path)
with open(config_path) as f:
loaded_config = yaml.safe_load(f.read())
cli_config = cli.config["fit"].as_dict()
assert loaded_config["model"] == cli_config["model"]
assert loaded_config["data"] == cli_config["data"]
assert loaded_config["trainer"] == cli_config["trainer"]
def any_model_any_data_cli():
LightningCLI(LightningModule, LightningDataModule, subclass_mode_model=True, subclass_mode_data=True)
def test_lightning_cli_help():
cli_args = ["any.py", "fit", "--help"]
out = StringIO()
with mock.patch("sys.argv", cli_args), redirect_stdout(out), pytest.raises(SystemExit):
any_model_any_data_cli()
out = out.getvalue()
assert "--print_config" in out
assert "--config" in out
assert "--seed_everything" in out
assert "--model.help" in out
assert "--data.help" in out
skip_params = {"self"}
for param in inspect.signature(Trainer.__init__).parameters.keys():
if param not in skip_params:
assert f"--trainer.{param}" in out
cli_args = ["any.py", "fit", "--data.help=DataDirDataModule"]
out = StringIO()
with mock.patch("sys.argv", cli_args), redirect_stdout(out), mock_subclasses(
LightningDataModule, DataDirDataModule
), pytest.raises(SystemExit):
any_model_any_data_cli()
assert "--data.init_args.data_dir" in out.getvalue()
def test_lightning_cli_print_config():
cli_args = [
"any.py",
"predict",
"--seed_everything=1234",
"--model=lightning.pytorch.demos.boring_classes.BoringModel",
"--data=lightning.pytorch.demos.boring_classes.BoringDataModule",
"--print_config",
]
out = StringIO()
with mock.patch("sys.argv", cli_args), redirect_stdout(out), pytest.raises(SystemExit):
any_model_any_data_cli()
text = out.getvalue()
# test dump_header
assert text.startswith(f"# lightning.pytorch=={__version__}")
outval = yaml.safe_load(text)
assert outval["seed_everything"] == 1234
assert outval["model"]["class_path"] == "lightning.pytorch.demos.boring_classes.BoringModel"
assert outval["data"]["class_path"] == "lightning.pytorch.demos.boring_classes.BoringDataModule"
assert outval["ckpt_path"] is None
def test_lightning_cli_submodules(cleandir):
class MainModule(BoringModel):
def __init__(self, submodule1: LightningModule, submodule2: LightningModule, main_param: int = 1):
super().__init__()
self.submodule1 = submodule1
self.submodule2 = submodule2
config = """model:
main_param: 2
submodule1:
class_path: lightning.pytorch.demos.boring_classes.BoringModel
submodule2:
class_path: lightning.pytorch.demos.boring_classes.BoringModel
"""
config_path = Path("config.yaml")
config_path.write_text(config)
cli_args = [f"--config={config_path}"]
with mock.patch("sys.argv", ["any.py"] + cli_args):
cli = LightningCLI(MainModule, run=False)
assert cli.config["model"]["main_param"] == 2
assert isinstance(cli.model.submodule1, BoringModel)
assert isinstance(cli.model.submodule2, BoringModel)
@pytest.mark.skipif(not _TORCHVISION_AVAILABLE, reason=str(_TORCHVISION_AVAILABLE))
def test_lightning_cli_torch_modules(cleandir):
class TestModule(BoringModel):
def __init__(self, activation: torch.nn.Module = None, transform: Optional[List[torch.nn.Module]] = None):
super().__init__()
self.activation = activation
self.transform = transform
config = """model:
activation:
class_path: torch.nn.LeakyReLU
init_args:
negative_slope: 0.2
transform:
- class_path: torchvision.transforms.Resize
init_args:
size: 64
- class_path: torchvision.transforms.CenterCrop
init_args:
size: 64
"""
config_path = Path("config.yaml")
config_path.write_text(config)
cli_args = [f"--config={config_path}"]
with mock.patch("sys.argv", ["any.py"] + cli_args):
cli = LightningCLI(TestModule, run=False)
assert isinstance(cli.model.activation, torch.nn.LeakyReLU)
assert cli.model.activation.negative_slope == 0.2
assert len(cli.model.transform) == 2
assert all(isinstance(v, torch.nn.Module) for v in cli.model.transform)
class BoringModelRequiredClasses(BoringModel):
def __init__(self, num_classes: int, batch_size: int = 8):
super().__init__()
self.num_classes = num_classes
self.batch_size = batch_size
class BoringDataModuleBatchSizeAndClasses(BoringDataModule):
def __init__(self, batch_size: int = 8):
super().__init__()
self.batch_size = batch_size
self.num_classes = 5 # only available after instantiation
def test_lightning_cli_link_arguments():
class MyLightningCLI(LightningCLI):
def add_arguments_to_parser(self, parser):
parser.link_arguments("data.batch_size", "model.batch_size")
parser.link_arguments("data.num_classes", "model.num_classes", apply_on="instantiate")
cli_args = ["--data.batch_size=12"]
with mock.patch("sys.argv", ["any.py"] + cli_args):
cli = MyLightningCLI(BoringModelRequiredClasses, BoringDataModuleBatchSizeAndClasses, run=False)
assert cli.model.batch_size == 12
assert cli.model.num_classes == 5
class MyLightningCLI(LightningCLI):
def add_arguments_to_parser(self, parser):
parser.link_arguments("data.batch_size", "model.init_args.batch_size")
parser.link_arguments("data.num_classes", "model.init_args.num_classes", apply_on="instantiate")
cli_args[-1] = "--model=tests_pytorch.test_cli.BoringModelRequiredClasses"
with mock.patch("sys.argv", ["any.py"] + cli_args):
cli = MyLightningCLI(
BoringModelRequiredClasses, BoringDataModuleBatchSizeAndClasses, subclass_mode_model=True, run=False
)
assert cli.model.batch_size == 8
assert cli.model.num_classes == 5
class EarlyExitTestModel(BoringModel):
def on_fit_start(self):
raise MisconfigurationException("Error on fit start")
# mps not yet supported by distributed
@RunIf(skip_windows=True, mps=False)
@pytest.mark.parametrize("logger", (None, TensorBoardLogger(".")))
@pytest.mark.parametrize("strategy", ("ddp_spawn", "ddp"))
def test_cli_distributed_save_config_callback(cleandir, logger, strategy):
from torch.multiprocessing import ProcessRaisedException
with mock.patch("sys.argv", ["any.py", "fit"]), pytest.raises(
(MisconfigurationException, ProcessRaisedException), match=r"Error on fit start"
):
LightningCLI(
EarlyExitTestModel,
trainer_defaults={
"logger": logger,
"max_steps": 1,
"max_epochs": 1,
"strategy": strategy,
"accelerator": "auto",
"devices": 1,
},
)
if logger:
config_dir = Path("lightning_logs")
# no more version dirs should get created
assert os.listdir(config_dir) == ["version_0"]
config_path = config_dir / "version_0" / "config.yaml"
else:
config_path = "config.yaml"
assert os.path.isfile(config_path)
def test_cli_config_overwrite(cleandir):
trainer_defaults = {"max_steps": 1, "max_epochs": 1, "logger": False}
argv = ["any.py", "fit"]
with mock.patch("sys.argv", argv):
LightningCLI(BoringModel, trainer_defaults=trainer_defaults)
with mock.patch("sys.argv", argv), pytest.raises(RuntimeError, match="Aborting to avoid overwriting"):
LightningCLI(BoringModel, trainer_defaults=trainer_defaults)
with mock.patch("sys.argv", argv):
LightningCLI(BoringModel, save_config_kwargs={"overwrite": True}, trainer_defaults=trainer_defaults)
def test_cli_config_filename(tmpdir):
with mock.patch("sys.argv", ["any.py", "fit"]):
LightningCLI(
BoringModel,
trainer_defaults={"default_root_dir": str(tmpdir), "logger": False, "max_steps": 1, "max_epochs": 1},
save_config_kwargs={"config_filename": "name.yaml"},
)
assert os.path.isfile(tmpdir / "name.yaml")
@pytest.mark.parametrize("run", (False, True))
def test_lightning_cli_optimizer(run):
class MyLightningCLI(LightningCLI):
def add_arguments_to_parser(self, parser):
parser.add_optimizer_args(torch.optim.Adam)
match = "BoringModel.configure_optimizers` will be overridden by " "`MyLightningCLI.configure_optimizers`"
argv = ["fit", "--trainer.fast_dev_run=1"] if run else []
with mock.patch("sys.argv", ["any.py"] + argv), pytest.warns(UserWarning, match=match):
cli = MyLightningCLI(BoringModel, run=run)
assert cli.model.configure_optimizers is not BoringModel.configure_optimizers
if not run:
optimizer = cli.model.configure_optimizers()
assert isinstance(optimizer, torch.optim.Adam)
else:
assert len(cli.trainer.optimizers) == 1
assert isinstance(cli.trainer.optimizers[0], torch.optim.Adam)
assert len(cli.trainer.lr_scheduler_configs) == 0
def test_lightning_cli_optimizer_and_lr_scheduler():
class MyLightningCLI(LightningCLI):
def add_arguments_to_parser(self, parser):
parser.add_optimizer_args(torch.optim.Adam)
parser.add_lr_scheduler_args(torch.optim.lr_scheduler.ExponentialLR)
cli_args = ["fit", "--trainer.fast_dev_run=1", "--lr_scheduler.gamma=0.8"]
with mock.patch("sys.argv", ["any.py"] + cli_args):
cli = MyLightningCLI(BoringModel)
assert cli.model.configure_optimizers is not BoringModel.configure_optimizers
assert len(cli.trainer.optimizers) == 1
assert isinstance(cli.trainer.optimizers[0], torch.optim.Adam)
assert len(cli.trainer.lr_scheduler_configs) == 1
assert isinstance(cli.trainer.lr_scheduler_configs[0].scheduler, torch.optim.lr_scheduler.ExponentialLR)
assert cli.trainer.lr_scheduler_configs[0].scheduler.gamma == 0.8
def test_cli_no_need_configure_optimizers(cleandir):
class BoringModel(LightningModule):
def __init__(self):
super().__init__()
self.layer = torch.nn.Linear(32, 2)
def training_step(self, *_):
...
def train_dataloader(self):
...
# did not define `configure_optimizers`
from lightning.pytorch.trainer.configuration_validator import __verify_train_val_loop_configuration
with mock.patch("sys.argv", ["any.py", "fit", "--optimizer=Adam"]), mock.patch(
"lightning.pytorch.Trainer._run_train"
) as run, mock.patch(
"lightning.pytorch.trainer.configuration_validator.__verify_train_val_loop_configuration",
wraps=__verify_train_val_loop_configuration,
) as verify:
cli = LightningCLI(BoringModel)
run.assert_called_once()
verify.assert_called_once_with(cli.trainer, cli.model)
def test_lightning_cli_optimizer_and_lr_scheduler_subclasses(cleandir):
class MyLightningCLI(LightningCLI):
def add_arguments_to_parser(self, parser):
parser.add_optimizer_args((torch.optim.SGD, torch.optim.Adam))
parser.add_lr_scheduler_args((torch.optim.lr_scheduler.StepLR, torch.optim.lr_scheduler.ExponentialLR))
optimizer_arg = dict(class_path="torch.optim.Adam", init_args=dict(lr=0.01))
lr_scheduler_arg = dict(class_path="torch.optim.lr_scheduler.StepLR", init_args=dict(step_size=50))
cli_args = [
"fit",
"--trainer.max_epochs=1",
f"--optimizer={json.dumps(optimizer_arg)}",
f"--lr_scheduler={json.dumps(lr_scheduler_arg)}",
]
with mock.patch("sys.argv", ["any.py"] + cli_args):
cli = MyLightningCLI(BoringModel)
assert len(cli.trainer.optimizers) == 1
assert isinstance(cli.trainer.optimizers[0], torch.optim.Adam)
assert len(cli.trainer.lr_scheduler_configs) == 1
assert isinstance(cli.trainer.lr_scheduler_configs[0].scheduler, torch.optim.lr_scheduler.StepLR)
assert cli.trainer.lr_scheduler_configs[0].scheduler.step_size == 50
@pytest.mark.parametrize("use_generic_base_class", [False, True])
def test_lightning_cli_optimizers_and_lr_scheduler_with_link_to(use_generic_base_class):
class MyLightningCLI(LightningCLI):
def add_arguments_to_parser(self, parser):
parser.add_optimizer_args(
(torch.optim.Optimizer,) if use_generic_base_class else torch.optim.Adam,
nested_key="optim1",
link_to="model.optim1",
)
parser.add_optimizer_args((torch.optim.ASGD, torch.optim.SGD), nested_key="optim2", link_to="model.optim2")
parser.add_lr_scheduler_args(
LRSchedulerTypeTuple if use_generic_base_class else torch.optim.lr_scheduler.ExponentialLR,
link_to="model.scheduler",
)
class TestModel(BoringModel):
def __init__(self, optim1: dict, optim2: dict, scheduler: dict):
super().__init__()
self.optim1 = instantiate_class(self.parameters(), optim1)
self.optim2 = instantiate_class(self.parameters(), optim2)
self.scheduler = instantiate_class(self.optim1, scheduler)
cli_args = ["fit", "--trainer.fast_dev_run=1"]
if use_generic_base_class:
cli_args += [
"--optim1",
"Adam",
"--optim1.weight_decay",
"0.001",
"--optim2=SGD",
"--optim2.lr=0.01",
"--lr_scheduler=ExponentialLR",
]
else:
cli_args += ["--optim2=SGD", "--optim2.lr=0.01"]
cli_args += ["--lr_scheduler.gamma=0.2"]
with mock.patch("sys.argv", ["any.py"] + cli_args):
cli = MyLightningCLI(TestModel)
assert isinstance(cli.model.optim1, torch.optim.Adam)
assert isinstance(cli.model.optim2, torch.optim.SGD)
assert cli.model.optim2.param_groups[0]["lr"] == 0.01
assert isinstance(cli.model.scheduler, torch.optim.lr_scheduler.ExponentialLR)
def test_lightning_cli_optimizers_and_lr_scheduler_with_callable_type():
class TestModel(BoringModel):
def __init__(
self,
optim1: OptimizerCallable = torch.optim.Adam,
optim2: OptimizerCallable = torch.optim.Adagrad,
scheduler: LRSchedulerCallable = torch.optim.lr_scheduler.ConstantLR,
):
super().__init__()
self.optim1 = optim1
self.optim2 = optim2
self.scheduler = scheduler
def configure_optimizers(self):
optim1 = self.optim1(self.parameters())
optim2 = self.optim2(self.parameters())
scheduler = self.scheduler(optim2)
return (
{"optimizer": optim1},
{"optimizer": optim2, "lr_scheduler": scheduler},
)
out = StringIO()
with mock.patch("sys.argv", ["any.py", "-h"]), redirect_stdout(out), pytest.raises(SystemExit):
LightningCLI(TestModel, run=False, auto_configure_optimizers=False)
out = out.getvalue()
assert "--optimizer" not in out
assert "--lr_scheduler" not in out
assert "--model.optim1" in out
assert "--model.optim2" in out
assert "--model.scheduler" in out
cli_args = [
"--model.optim1=Adagrad",
"--model.optim2=SGD",
"--model.optim2.lr=0.007",
"--model.scheduler=ExponentialLR",
"--model.scheduler.gamma=0.3",
]
with mock.patch("sys.argv", ["any.py"] + cli_args):
cli = LightningCLI(TestModel, run=False, auto_configure_optimizers=False)
init = cli.model.configure_optimizers()
assert isinstance(init[0]["optimizer"], torch.optim.Adagrad)
assert isinstance(init[1]["optimizer"], torch.optim.SGD)
assert isinstance(init[1]["lr_scheduler"], torch.optim.lr_scheduler.ExponentialLR)
assert init[1]["optimizer"].param_groups[0]["lr"] == 0.007
assert init[1]["lr_scheduler"].gamma == 0.3
@pytest.mark.parametrize("fn", [fn.value for fn in TrainerFn])
def test_lightning_cli_trainer_fn(fn):
class TestCLI(LightningCLI):
def __init__(self, *args, **kwargs):
self.called = []
super().__init__(*args, **kwargs)
def before_fit(self):
self.called.append("before_fit")
def fit(self, **_):
self.called.append("fit")
def after_fit(self):
self.called.append("after_fit")
def before_validate(self):
self.called.append("before_validate")
def validate(self, **_):
self.called.append("validate")
def after_validate(self):
self.called.append("after_validate")
def before_test(self):
self.called.append("before_test")
def test(self, **_):
self.called.append("test")
def after_test(self):
self.called.append("after_test")
def before_predict(self):
self.called.append("before_predict")
def predict(self, **_):
self.called.append("predict")
def after_predict(self):
self.called.append("after_predict")
with mock.patch("sys.argv", ["any.py", fn]):
cli = TestCLI(BoringModel)
assert cli.called == [f"before_{fn}", fn, f"after_{fn}"]
def test_lightning_cli_subcommands():
subcommands = LightningCLI.subcommands()
trainer = Trainer()
for subcommand, exclude in subcommands.items():
fn = getattr(trainer, subcommand)
parameters = list(inspect.signature(fn).parameters)
for e in exclude:
# if this fails, it's because the parameter has been removed from the associated `Trainer` function
# and the `LightningCLI` subcommand exclusion list needs to be updated
assert e in parameters
def test_lightning_cli_custom_subcommand():
class TestTrainer(Trainer):
def foo(self, model: LightningModule, x: int, y: float = 1.0):
"""Sample extra function.
Args:
model: A model
x: The x
y: The y
"""
class TestCLI(LightningCLI):
@staticmethod
def subcommands():
subcommands = LightningCLI.subcommands()
subcommands["foo"] = {"model"}
return subcommands
out = StringIO()
with mock.patch("sys.argv", ["any.py", "-h"]), redirect_stdout(out), pytest.raises(SystemExit):
TestCLI(BoringModel, trainer_class=TestTrainer)
out = out.getvalue()
assert "Sample extra function." in out
assert "{fit,validate,test,predict,foo}" in out
out = StringIO()
with mock.patch("sys.argv", ["any.py", "foo", "-h"]), redirect_stdout(out), pytest.raises(SystemExit):
TestCLI(BoringModel, trainer_class=TestTrainer)
out = out.getvalue()
assert "A model" not in out
assert "Sample extra function:" in out
assert "--x X" in out
assert "The x (required, type: int)" in out
assert "--y Y" in out
assert "The y (type: float, default: 1.0)" in out
def test_lightning_cli_run(cleandir):
with mock.patch("sys.argv", ["any.py"]):
cli = LightningCLI(BoringModel, run=False)
assert cli.trainer.global_step == 0
assert isinstance(cli.trainer, Trainer)
assert isinstance(cli.model, LightningModule)
with mock.patch("sys.argv", ["any.py", "fit"]):
cli = LightningCLI(BoringModel, trainer_defaults={"max_steps": 1, "max_epochs": 1})
assert cli.trainer.global_step == 1
assert isinstance(cli.trainer, Trainer)
assert isinstance(cli.model, LightningModule)
class TestModel(BoringModel):
def __init__(self, foo, bar=5):
super().__init__()
self.foo = foo
self.bar = bar
def test_lightning_cli_model_short_arguments():
with mock.patch("sys.argv", ["any.py", "fit", "--model=BoringModel"]), mock.patch(
"lightning.pytorch.Trainer._fit_impl"
) as run, mock_subclasses(LightningModule, BoringModel, TestModel):
cli = LightningCLI(trainer_defaults={"fast_dev_run": 1})
assert isinstance(cli.model, BoringModel)
run.assert_called_once_with(cli.model, ANY, ANY, ANY, ANY)
with mock.patch("sys.argv", ["any.py", "--model=TestModel", "--model.foo", "123"]), mock_subclasses(
LightningModule, BoringModel, TestModel
):
cli = LightningCLI(run=False)
assert isinstance(cli.model, TestModel)
assert cli.model.foo == 123
assert cli.model.bar == 5
class MyDataModule(BoringDataModule):
def __init__(self, foo, bar=5):
super().__init__()
self.foo = foo
self.bar = bar
def test_lightning_cli_datamodule_short_arguments():
# with set model
with mock.patch("sys.argv", ["any.py", "fit", "--data=BoringDataModule"]), mock.patch(
"lightning.pytorch.Trainer._fit_impl"
) as run, mock_subclasses(LightningDataModule, BoringDataModule):
cli = LightningCLI(BoringModel, trainer_defaults={"fast_dev_run": 1})
assert isinstance(cli.datamodule, BoringDataModule)
run.assert_called_once_with(ANY, ANY, ANY, cli.datamodule, ANY)
with mock.patch("sys.argv", ["any.py", "--data=MyDataModule", "--data.foo", "123"]), mock_subclasses(
LightningDataModule, MyDataModule
):
cli = LightningCLI(BoringModel, run=False)
assert isinstance(cli.datamodule, MyDataModule)
assert cli.datamodule.foo == 123
assert cli.datamodule.bar == 5
# with configurable model
with mock.patch("sys.argv", ["any.py", "fit", "--model", "BoringModel", "--data=BoringDataModule"]), mock.patch(
"lightning.pytorch.Trainer._fit_impl"
) as run, mock_subclasses(LightningModule, BoringModel), mock_subclasses(LightningDataModule, BoringDataModule):
cli = LightningCLI(trainer_defaults={"fast_dev_run": 1})
assert isinstance(cli.model, BoringModel)
assert isinstance(cli.datamodule, BoringDataModule)
run.assert_called_once_with(cli.model, ANY, ANY, cli.datamodule, ANY)
with mock.patch("sys.argv", ["any.py", "--model", "BoringModel", "--data=MyDataModule"]), mock_subclasses(
LightningModule, BoringModel
), mock_subclasses(LightningDataModule, MyDataModule):
cli = LightningCLI(run=False)
assert isinstance(cli.model, BoringModel)
assert isinstance(cli.datamodule, MyDataModule)
with mock.patch("sys.argv", ["any.py"]):
cli = LightningCLI(BoringModel, run=False)
# data was not passed but we are adding it automatically because there are datamodules registered
assert "data" in cli.parser.groups
assert not hasattr(cli.parser.groups["data"], "group_class")
with mock.patch("sys.argv", ["any.py"]):
cli = LightningCLI(BoringModel, BoringDataModule, run=False)
# since we are passing the DataModule, that's whats added to the parser
assert cli.parser.groups["data"].group_class is BoringDataModule
@pytest.mark.parametrize("use_class_path_callbacks", [False, True])
def test_callbacks_append(use_class_path_callbacks):
"""This test validates registries are used when simplified command line are being used."""
cli_args = [
"--optimizer",
"Adam",
"--optimizer.lr",
"0.0001",
"--trainer.callbacks+=LearningRateMonitor",
"--trainer.callbacks.logging_interval=epoch",
"--trainer.callbacks.log_momentum=True",
"--model=BoringModel",
"--trainer.callbacks+",
"ModelCheckpoint",
"--trainer.callbacks.monitor=loss",
"--lr_scheduler",
"StepLR",
"--lr_scheduler.step_size=50",
]
extras = []
if use_class_path_callbacks:
callbacks = [
{"class_path": "lightning.pytorch.callbacks.Callback"},
{"class_path": "lightning.pytorch.callbacks.Callback", "init_args": {}},
]
cli_args += [f"--trainer.callbacks+={json.dumps(callbacks)}"]
extras = [Callback, Callback]
with mock.patch("sys.argv", ["any.py"] + cli_args), mock_subclasses(LightningModule, BoringModel):
cli = LightningCLI(run=False)
assert isinstance(cli.model, BoringModel)
optimizers, lr_scheduler = cli.model.configure_optimizers()
assert isinstance(optimizers[0], torch.optim.Adam)
assert optimizers[0].param_groups[0]["lr"] == 0.0001
assert lr_scheduler[0].step_size == 50
callback_types = [type(c) for c in cli.trainer.callbacks]
expected = [LearningRateMonitor, SaveConfigCallback, ModelCheckpoint] + extras
assert all(t in callback_types for t in expected)
def test_optimizers_and_lr_schedulers_reload(cleandir):
base = ["any.py", "--trainer.max_epochs=1"]
input = base + [
"--lr_scheduler",
"OneCycleLR",
"--lr_scheduler.total_steps=10",
"--lr_scheduler.max_lr=1",
"--optimizer",
"Adam",