def test_no_val_end_module(tmpdir): """Tests use case where trainer saves the model, and user loads it from tags independently.""" tutils.reset_seed() class CurrentTestModel(LightningValidationStepMixin, LightningTestModelBase): pass hparams = tutils.get_hparams() model = CurrentTestModel(hparams) # logger file to get meta logger = tutils.get_test_tube_logger(tmpdir, False) trainer_options = dict(max_epochs=1, logger=logger, checkpoint_callback=ModelCheckpoint(tmpdir)) # fit model trainer = Trainer(**trainer_options) result = trainer.fit(model) # traning complete assert result == 1, 'amp + ddp model failed to complete' # save model new_weights_path = os.path.join(tmpdir, 'save_test.ckpt') trainer.save_checkpoint(new_weights_path) # load new model tags_path = tutils.get_data_path(logger, path_dir=tmpdir) tags_path = os.path.join(tags_path, 'meta_tags.csv') model_2 = LightningTestModel.load_from_metrics( weights_path=new_weights_path, tags_csv=tags_path) model_2.eval()
def test_multiple_test_dataloader(tmpdir): """Verify multiple test_dataloader.""" tutils.reset_seed() class CurrentTestModel(LightningTestMultipleDataloadersMixin, LightningTestModelBase): pass hparams = tutils.get_hparams() model = CurrentTestModel(hparams) # logger file to get meta trainer_options = dict( default_save_path=tmpdir, max_epochs=1, val_percent_check=0.1, train_percent_check=0.2, ) # fit model trainer = Trainer(**trainer_options) result = trainer.fit(model) # verify there are 2 val loaders assert len(trainer.get_test_dataloaders()) == 2, \ 'Multiple test_dataloaders not initiated properly' # make sure predictions are good for each test set for dataloader in trainer.get_test_dataloaders(): tutils.run_prediction(dataloader, trainer.model) # run the test method trainer.test()
def test_simple_cpu(): """ Verify continue training session on CPU :return: """ tutils.reset_seed() hparams = tutils.get_hparams() model = LightningTestModel(hparams) save_dir = tutils.init_save_dir() # logger file to get meta trainer_options = dict( max_nb_epochs=1, val_percent_check=0.1, train_percent_check=0.1, ) # fit model trainer = Trainer(**trainer_options) result = trainer.fit(model) # traning complete assert result == 1, 'amp + ddp model failed to complete' tutils.clear_save_dir()
def test_ddp_sampler_error(tmpdir): """ Make sure DDP + AMP work :return: """ if not tutils.can_run_gpu_test(): return tutils.reset_seed() tutils.set_random_master_port() hparams = tutils.get_hparams() model = LightningTestModel(hparams, force_remove_distributed_sampler=True) logger = tutils.get_test_tube_logger(tmpdir, True) trainer = Trainer( logger=logger, show_progress_bar=False, max_nb_epochs=1, gpus=[0, 1], distributed_backend='ddp', use_amp=True ) with pytest.warns(UserWarning): trainer.get_dataloaders(model)
def test_comet_pickle(tmpdir): """Verify that pickling trainer with comet logger works.""" tutils.reset_seed() try: from pytorch_lightning.logging import CometLogger except ModuleNotFoundError: return hparams = tutils.get_hparams() model = LightningTestModel(hparams) comet_dir = os.path.join(tmpdir, "cometruns") # We test CometLogger in offline mode with local saves logger = CometLogger( save_dir=comet_dir, project_name="general", workspace="dummy-test", ) trainer_options = dict(max_num_epochs=1, logger=logger) trainer = Trainer(**trainer_options) pkl_bytes = pickle.dumps(trainer) trainer2 = pickle.loads(pkl_bytes) trainer2.logger.log_metrics({"acc": 1.0})
def test_comet_pickle(tmpdir, monkeypatch): """Verify that pickling trainer with comet logger works.""" # prevent comet logger from trying to print at exit, since # pytest's stdout/stderr redirection breaks it import atexit monkeypatch.setattr(atexit, "register", lambda _: None) tutils.reset_seed() try: from pytorch_lightning.logging import CometLogger except ModuleNotFoundError: return hparams = tutils.get_hparams() model = LightningTestModel(hparams) comet_dir = os.path.join(tmpdir, "cometruns") # We test CometLogger in offline mode with local saves logger = CometLogger( save_dir=comet_dir, project_name="general", workspace="dummy-test", ) trainer_options = dict(max_epochs=1, logger=logger) trainer = Trainer(**trainer_options) pkl_bytes = pickle.dumps(trainer) trainer2 = pickle.loads(pkl_bytes) trainer2.logger.log_metrics({"acc": 1.0})
def test_multiple_val_dataloader(): """ Verify multiple val_dataloader :return: """ tutils.reset_seed() class CurrentTestModel(LightningValidationMultipleDataloadersMixin, LightningTestModelBase): pass hparams = tutils.get_hparams() model = CurrentTestModel(hparams) # logger file to get meta trainer_options = dict( max_nb_epochs=1, val_percent_check=0.1, train_percent_check=1.0, ) # fit model trainer = Trainer(**trainer_options) result = trainer.fit(model) # verify training completed assert result == 1 # verify there are 2 val loaders assert len(trainer.get_val_dataloaders()) == 2, \ 'Multiple val_dataloaders not initiated properly' # make sure predictions are good for each val set for dataloader in trainer.get_val_dataloaders(): tutils.run_prediction(dataloader, trainer.model)
def test_mlflow_logger(tmpdir): """Verify that basic functionality of mlflow logger works.""" tutils.reset_seed() try: from pytorch_lightning.logging import MLFlowLogger except ModuleNotFoundError: return hparams = tutils.get_hparams() model = LightningTestModel(hparams) mlflow_dir = os.path.join(tmpdir, "mlruns") logger = MLFlowLogger("test", tracking_uri=f"file:{os.sep * 2}{mlflow_dir}") trainer_options = dict(default_save_path=tmpdir, max_epochs=1, train_percent_check=0.01, logger=logger) trainer = Trainer(**trainer_options) result = trainer.fit(model) print('result finished') assert result == 1, "Training failed"
def test_running_test_after_fitting(tmpdir): """Verify test() on fitted model.""" tutils.reset_seed() hparams = tutils.get_hparams() model = LightningTestModel(hparams) # logger file to get meta logger = tutils.get_test_tube_logger(tmpdir, False) # logger file to get weights checkpoint = tutils.init_checkpoint_callback(logger) trainer_options = dict(default_save_path=tmpdir, show_progress_bar=False, max_epochs=4, train_percent_check=0.4, val_percent_check=0.2, test_percent_check=0.2, checkpoint_callback=checkpoint, logger=logger) # fit model trainer = Trainer(**trainer_options) result = trainer.fit(model) assert result == 1, 'training failed to complete' trainer.test() # test we have good test accuracy tutils.assert_ok_model_acc(trainer)
def test_running_test_without_val(tmpdir): """Verify `test()` works on a model with no `val_loader`.""" tutils.reset_seed() class CurrentTestModel(LightningTestMixin, LightningTestModelBase): pass hparams = tutils.get_hparams() model = CurrentTestModel(hparams) # logger file to get meta logger = tutils.get_test_tube_logger(tmpdir, False) # logger file to get weights checkpoint = tutils.init_checkpoint_callback(logger) trainer_options = dict(show_progress_bar=False, max_epochs=1, train_percent_check=0.4, val_percent_check=0.2, test_percent_check=0.2, checkpoint_callback=checkpoint, logger=logger) # fit model trainer = Trainer(**trainer_options) result = trainer.fit(model) assert result == 1, 'training failed to complete' trainer.test() # test we have good test accuracy tutils.assert_ok_model_acc(trainer)
def test_running_test_pretrained_model(tmpdir): tutils.reset_seed() """Verify test() on pretrained model""" hparams = tutils.get_hparams() model = LightningTestModel(hparams) # logger file to get meta logger = tutils.get_test_tube_logger(tmpdir, False) # logger file to get weights checkpoint = tutils.init_checkpoint_callback(logger) trainer_options = dict(show_progress_bar=False, max_num_epochs=4, train_percent_check=0.4, val_percent_check=0.2, checkpoint_callback=checkpoint, logger=logger) # fit model trainer = Trainer(**trainer_options) result = trainer.fit(model) # correct result and ok accuracy assert result == 1, 'training failed to complete' pretrained_model = tutils.load_model(logger.experiment, trainer.checkpoint_callback.filepath, module_class=LightningTestModel) new_trainer = Trainer(**trainer_options) new_trainer.test(pretrained_model) # test we have good test accuracy tutils.assert_ok_test_acc(new_trainer)
def test_load_model_from_checkpoint(tmpdir): tutils.reset_seed() """Verify test() on pretrained model""" hparams = tutils.get_hparams() model = LightningTestModel(hparams) trainer_options = dict( show_progress_bar=False, max_num_epochs=1, train_percent_check=0.4, val_percent_check=0.2, checkpoint_callback=True, logger=False, default_save_path=tmpdir, ) # fit model trainer = Trainer(**trainer_options) result = trainer.fit(model) # correct result and ok accuracy assert result == 1, 'training failed to complete' pretrained_model = LightningTestModel.load_from_checkpoint( os.path.join(trainer.checkpoint_callback.filepath, "_ckpt_epoch_0.ckpt")) # test that hparams loaded correctly for k, v in vars(hparams).items(): assert getattr(pretrained_model.hparams, k) == v new_trainer = Trainer(**trainer_options) new_trainer.test(pretrained_model) # test we have good test accuracy tutils.assert_ok_test_acc(new_trainer)
def test_mlflow_pickle(): """ verify that pickling trainer with mlflow logger works """ tutils.reset_seed() try: from pytorch_lightning.logging import MLFlowLogger except ModuleNotFoundError: return hparams = tutils.get_hparams() model = LightningTestModel(hparams) root_dir = os.path.dirname(os.path.realpath(__file__)) mlflow_dir = os.path.join(root_dir, "mlruns") logger = MLFlowLogger("test", f"file://{mlflow_dir}") trainer_options = dict(max_nb_epochs=1, logger=logger) trainer = Trainer(**trainer_options) pkl_bytes = pickle.dumps(trainer) trainer2 = pickle.loads(pkl_bytes) trainer2.logger.log_metrics({"acc": 1.0}) tutils.clear_save_dir()
def test_comet_logger(tmpdir): """Verify that basic functionality of Comet.ml logger works.""" tutils.reset_seed() try: from pytorch_lightning.logging import CometLogger except ModuleNotFoundError: return hparams = tutils.get_hparams() model = LightningTestModel(hparams) comet_dir = os.path.join(tmpdir, "cometruns") # We test CometLogger in offline mode with local saves logger = CometLogger( save_dir=comet_dir, project_name="general", workspace="dummy-test", ) trainer_options = dict(max_num_epochs=1, train_percent_check=0.01, logger=logger) trainer = Trainer(**trainer_options) result = trainer.fit(model) print('result finished') assert result == 1, "Training failed"
def test_mlflow_logger(): """ verify that basic functionality of mlflow logger works """ tutils.reset_seed() try: from pytorch_lightning.logging import MLFlowLogger except ModuleNotFoundError: return hparams = tutils.get_hparams() model = LightningTestModel(hparams) root_dir = os.path.dirname(os.path.realpath(__file__)) mlflow_dir = os.path.join(root_dir, "mlruns") logger = MLFlowLogger("test", f"file://{mlflow_dir}") trainer_options = dict(max_nb_epochs=1, train_percent_check=0.01, logger=logger) trainer = Trainer(**trainer_options) result = trainer.fit(model) print('result finished') assert result == 1, "Training failed" tutils.clear_save_dir()
def test_testtube_pickle(): """ Verify that pickling a trainer containing a test tube logger works """ tutils.reset_seed() hparams = tutils.get_hparams() model = LightningTestModel(hparams) save_dir = tutils.init_save_dir() logger = tutils.get_test_tube_logger(False) logger.log_hyperparams(hparams) logger.save() trainer_options = dict(max_nb_epochs=1, train_percent_check=0.01, logger=logger) trainer = Trainer(**trainer_options) pkl_bytes = pickle.dumps(trainer) trainer2 = pickle.loads(pkl_bytes) trainer2.logger.log_metrics({"acc": 1.0}) tutils.clear_save_dir()
def test_comet_logger(tmpdir, monkeypatch): """Verify that basic functionality of Comet.ml logger works.""" # prevent comet logger from trying to print at exit, since # pytest's stdout/stderr redirection breaks it import atexit monkeypatch.setattr(atexit, "register", lambda _: None) tutils.reset_seed() hparams = tutils.get_hparams() model = LightningTestModel(hparams) comet_dir = os.path.join(tmpdir, "cometruns") # We test CometLogger in offline mode with local saves logger = CometLogger( save_dir=comet_dir, project_name="general", workspace="dummy-test", ) trainer_options = dict(default_save_path=tmpdir, max_epochs=1, train_percent_check=0.01, logger=logger) trainer = Trainer(**trainer_options) result = trainer.fit(model) print('result finished') assert result == 1, "Training failed"
def test_cpu_restore_training(tmpdir): """Verify continue training session on CPU.""" tutils.reset_seed() hparams = tutils.get_hparams() model = LightningTestModel(hparams) # logger file to get meta test_logger_version = 10 logger = tutils.get_test_tube_logger(tmpdir, False, version=test_logger_version) trainer_options = dict( max_epochs=8, val_check_interval=0.50, val_percent_check=0.2, train_percent_check=0.2, logger=logger, checkpoint_callback=ModelCheckpoint(tmpdir, save_top_k=-1) ) # fit model trainer = Trainer(**trainer_options) result = trainer.fit(model) real_global_epoch = trainer.current_epoch # traning complete assert result == 1, 'amp + ddp model failed to complete' # wipe-out trainer and model # retrain with not much data... this simulates picking training back up after slurm # we want to see if the weights come back correctly new_logger = tutils.get_test_tube_logger(tmpdir, False, version=test_logger_version) trainer_options = dict( max_epochs=2, val_check_interval=0.50, val_percent_check=0.2, train_percent_check=0.2, logger=new_logger, checkpoint_callback=ModelCheckpoint(tmpdir), ) trainer = Trainer(**trainer_options) model = LightningTestModel(hparams) # set the epoch start hook so we can predict before the model does the full training def assert_good_acc(): assert trainer.current_epoch == real_global_epoch assert trainer.current_epoch >= 0 # if model and state loaded correctly, predictions will be good even though we # haven't trained with the new loaded model trainer.model.eval() for dataloader in trainer.get_val_dataloaders(): tutils.run_prediction(dataloader, trainer.model) model.on_train_start = assert_good_acc # by calling fit again, we trigger training, loading weights from the cluster # and our hook to predict using current model before any more weight updates trainer.fit(model)
def test_model_freeze_unfreeze(): tutils.reset_seed() hparams = tutils.get_hparams() model = LightningTestModel(hparams) model.freeze() model.unfreeze()
def test_model_saving_loading(): """ Tests use case where trainer saves the model, and user loads it from tags independently :return: """ tutils.reset_seed() hparams = tutils.get_hparams() model = LightningTestModel(hparams) save_dir = tutils.init_save_dir() # logger file to get meta logger = tutils.get_test_tube_logger(False) trainer_options = dict( max_nb_epochs=1, logger=logger, checkpoint_callback=ModelCheckpoint(save_dir) ) # fit model trainer = Trainer(**trainer_options) result = trainer.fit(model) # traning complete assert result == 1, 'amp + ddp model failed to complete' # make a prediction for dataloader in model.test_dataloader(): for batch in dataloader: break x, y = batch x = x.view(x.size(0), -1) # generate preds before saving model model.eval() pred_before_saving = model(x) # save model new_weights_path = os.path.join(save_dir, 'save_test.ckpt') trainer.save_checkpoint(new_weights_path) # load new model tags_path = logger.experiment.get_data_path(logger.experiment.name, logger.experiment.version) tags_path = os.path.join(tags_path, 'meta_tags.csv') model_2 = LightningTestModel.load_from_metrics(weights_path=new_weights_path, tags_csv=tags_path) model_2.eval() # make prediction # assert that both predictions are the same new_pred = model_2(x) assert torch.all(torch.eq(pred_before_saving, new_pred)).item() == 1 tutils.clear_save_dir()
def test_running_test_pretrained_model_ddp(): """Verify test() on pretrained model""" if not tutils.can_run_gpu_test(): return tutils.reset_seed() tutils.set_random_master_port() hparams = tutils.get_hparams() model = LightningTestModel(hparams) save_dir = tutils.init_save_dir() # exp file to get meta logger = tutils.get_test_tube_logger(False) # exp file to get weights checkpoint = tutils.init_checkpoint_callback(logger) trainer_options = dict( show_progress_bar=False, max_nb_epochs=1, train_percent_check=0.4, val_percent_check=0.2, checkpoint_callback=checkpoint, logger=logger, gpus=[0, 1], distributed_backend='ddp' ) # fit model trainer = Trainer(**trainer_options) result = trainer.fit(model) exp = logger.experiment logging.info(os.listdir(exp.get_data_path(exp.name, exp.version))) # correct result and ok accuracy assert result == 1, 'training failed to complete' pretrained_model = tutils.load_model(logger.experiment, trainer.checkpoint_callback.filepath, module_class=LightningTestModel) # run test set new_trainer = Trainer(**trainer_options) new_trainer.test(pretrained_model) for dataloader in model.test_dataloader(): tutils.run_prediction(dataloader, pretrained_model) tutils.clear_save_dir()
def test_testtube_logger(tmpdir): """Verify that basic functionality of test tube logger works.""" tutils.reset_seed() hparams = tutils.get_hparams() model = LightningTestModel(hparams) logger = tutils.get_test_tube_logger(tmpdir, False) trainer_options = dict(max_num_epochs=1, train_percent_check=0.01, logger=logger) trainer = Trainer(**trainer_options) result = trainer.fit(model) assert result == 1, "Training failed"
def test_neptune_logger(tmpdir): """Verify that basic functionality of neptune logger works.""" tutils.reset_seed() hparams = tutils.get_hparams() model = LightningTestModel(hparams) logger = NeptuneLogger(offline_mode=True) trainer_options = dict(default_save_path=tmpdir, max_epochs=1, train_percent_check=0.01, logger=logger) trainer = Trainer(**trainer_options) result = trainer.fit(model) print('result finished') assert result == 1, "Training failed"
def test_tensorboard_logger(tmpdir): """Verify that basic functionality of Tensorboard logger works.""" hparams = tutils.get_hparams() model = LightningTestModel(hparams) logger = TensorBoardLogger(save_dir=tmpdir, name="tensorboard_logger_test") trainer_options = dict(max_epochs=1, train_percent_check=0.01, logger=logger) trainer = Trainer(**trainer_options) result = trainer.fit(model) print("result finished") assert result == 1, "Training failed"
def test_running_test_pretrained_model_dp(): tutils.reset_seed() """Verify test() on pretrained model""" if not tutils.can_run_gpu_test(): return hparams = tutils.get_hparams() model = LightningTestModel(hparams) save_dir = tutils.init_save_dir() # logger file to get meta logger = tutils.get_test_tube_logger(False) # logger file to get weights checkpoint = tutils.init_checkpoint_callback(logger) trainer_options = dict( show_progress_bar=True, max_nb_epochs=1, train_percent_check=0.4, val_percent_check=0.2, checkpoint_callback=checkpoint, logger=logger, gpus=[0, 1], distributed_backend='dp' ) # fit model trainer = Trainer(**trainer_options) result = trainer.fit(model) # correct result and ok accuracy assert result == 1, 'training failed to complete' pretrained_model = tutils.load_model(logger.experiment, trainer.checkpoint_callback.filepath, module_class=LightningTestModel) new_trainer = Trainer(**trainer_options) new_trainer.test(pretrained_model) # test we have good test accuracy tutils.assert_ok_test_acc(new_trainer) tutils.clear_save_dir()
def test_loading_meta_tags(tmpdir): tutils.reset_seed() from argparse import Namespace hparams = tutils.get_hparams() # save tags logger = tutils.get_test_tube_logger(tmpdir, False) logger.log_hyperparams(Namespace(some_str='a_str', an_int=1, a_float=2.0)) logger.log_hyperparams(hparams) logger.save() # load tags tags_path = logger.experiment.get_data_path( logger.experiment.name, logger.experiment.version) + '/meta_tags.csv' tags = training_io.load_hparams_from_tags_csv(tags_path) assert tags.batch_size == 32 and tags.hidden_dim == 1000
def test_loading_meta_tags(tmpdir): tutils.reset_seed() from argparse import Namespace hparams = tutils.get_hparams() # save tags logger = tutils.get_test_tube_logger(tmpdir, False) logger.log_hyperparams(Namespace(some_str='a_str', an_int=1, a_float=2.0)) logger.log_hyperparams(hparams) logger.save() # load tags path_expt_dir = tutils.get_data_path(logger, path_dir=tmpdir) tags_path = os.path.join(path_expt_dir, 'meta_tags.csv') tags = load_hparams_from_tags_csv(tags_path) assert tags.batch_size == 32 and tags.hidden_dim == 1000
def test_amp_single_gpu(tmpdir): """Make sure DDP + AMP work.""" tutils.reset_seed() if not tutils.can_run_gpu_test(): return hparams = tutils.get_hparams() model = LightningTestModel(hparams) trainer_options = dict(default_save_path=tmpdir, show_progress_bar=True, max_epochs=1, gpus=1, distributed_backend='ddp', use_amp=True) tutils.run_model_test(trainer_options, model)
def test_amp_gpu_ddp_slurm_managed(tmpdir): """Make sure DDP + AMP work.""" if not tutils.can_run_gpu_test(): return tutils.reset_seed() # simulate setting slurm flags tutils.set_random_master_port() os.environ['SLURM_LOCALID'] = str(0) hparams = tutils.get_hparams() model = LightningTestModel(hparams) trainer_options = dict(show_progress_bar=True, max_epochs=1, gpus=[0], distributed_backend='ddp', use_amp=True) # exp file to get meta logger = tutils.get_test_tube_logger(tmpdir, False) # exp file to get weights checkpoint = tutils.init_checkpoint_callback(logger) # add these to the trainer options trainer_options['checkpoint_callback'] = checkpoint trainer_options['logger'] = logger # fit model trainer = Trainer(**trainer_options) trainer.is_slurm_managing_tasks = True result = trainer.fit(model) # correct result and ok accuracy assert result == 1, 'amp + ddp model failed to complete' # test root model address assert trainer.resolve_root_node_address('abc') == 'abc' assert trainer.resolve_root_node_address('abc[23]') == 'abc23' assert trainer.resolve_root_node_address('abc[23-24]') == 'abc23' assert trainer.resolve_root_node_address( 'abc[23-24, 45-40, 40]') == 'abc23'
def test_custom_logger(tmpdir): class CustomLogger(LightningLoggerBase): def __init__(self): super().__init__() self.hparams_logged = None self.metrics_logged = None self.finalized = False @rank_zero_only def log_hyperparams(self, params): self.hparams_logged = params @rank_zero_only def log_metrics(self, metrics, step): self.metrics_logged = metrics @rank_zero_only def finalize(self, status): self.finalized_status = status @property def name(self): return "name" @property def version(self): return "1" hparams = tutils.get_hparams() model = LightningTestModel(hparams) logger = CustomLogger() trainer_options = dict(max_epochs=1, train_percent_check=0.05, logger=logger, default_save_path=tmpdir) trainer = Trainer(**trainer_options) result = trainer.fit(model) assert result == 1, "Training failed" assert logger.hparams_logged == hparams assert logger.metrics_logged != {} assert logger.finalized_status == "success"