-
-
Notifications
You must be signed in to change notification settings - Fork 134
/
tabular_model.py
2205 lines (1956 loc) · 99.3 KB
/
tabular_model.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
# Pytorch Tabular
# Author: Manu Joseph <manujoseph@gmail.com>
# For license information, see LICENSE.TXT
"""Tabular Model."""
import inspect
import os
import warnings
from collections import defaultdict
from functools import partial
from pathlib import Path
from typing import Callable, Dict, Iterable, List, Optional, Tuple, Union
import joblib
import numpy as np
import pandas as pd
import pytorch_lightning as pl
import torch
import torchmetrics
from omegaconf import OmegaConf
from omegaconf.dictconfig import DictConfig
from pandas import DataFrame
from pytorch_lightning import seed_everything
from pytorch_lightning.callbacks import RichProgressBar
from pytorch_lightning.callbacks.gradient_accumulation_scheduler import (
GradientAccumulationScheduler,
)
from pytorch_lightning.tuner.tuning import Tuner
from pytorch_lightning.utilities.model_summary import summarize
from rich import print as rich_print
from rich.pretty import pprint
from sklearn.base import TransformerMixin
from sklearn.model_selection import BaseCrossValidator, KFold, StratifiedKFold
from torch import nn
from pytorch_tabular.config import (
DataConfig,
ExperimentConfig,
ExperimentRunManager,
ModelConfig,
OptimizerConfig,
TrainerConfig,
)
from pytorch_tabular.config.config import InferredConfig
from pytorch_tabular.models.base_model import BaseModel, _CaptumModel, _GenericModel
from pytorch_tabular.models.common.layers.embeddings import (
Embedding1dLayer,
Embedding2dLayer,
PreEncoded1dLayer,
)
from pytorch_tabular.tabular_datamodule import TabularDatamodule
from pytorch_tabular.utils import (
OOMException,
OutOfMemoryHandler,
count_parameters,
get_logger,
getattr_nested,
pl_load,
suppress_lightning_logs,
)
try:
import captum.attr
CAPTUM_INSTALLED = True
except ImportError:
CAPTUM_INSTALLED = False
logger = get_logger(__name__)
class TabularModel:
def __init__(
self,
config: Optional[DictConfig] = None,
data_config: Optional[Union[DataConfig, str]] = None,
model_config: Optional[Union[ModelConfig, str]] = None,
optimizer_config: Optional[Union[OptimizerConfig, str]] = None,
trainer_config: Optional[Union[TrainerConfig, str]] = None,
experiment_config: Optional[Union[ExperimentConfig, str]] = None,
model_callable: Optional[Callable] = None,
model_state_dict_path: Optional[Union[str, Path]] = None,
verbose: bool = True,
suppress_lightning_logger: bool = False,
) -> None:
"""The core model which orchestrates everything from initializing the datamodule, the model, trainer, etc.
Args:
config (Optional[Union[DictConfig, str]], optional): Single OmegaConf DictConfig object or
the path to the yaml file holding all the config parameters. Defaults to None.
data_config (Optional[Union[DataConfig, str]], optional):
DataConfig object or path to the yaml file. Defaults to None.
model_config (Optional[Union[ModelConfig, str]], optional):
A subclass of ModelConfig or path to the yaml file.
Determines which model to run from the type of config. Defaults to None.
optimizer_config (Optional[Union[OptimizerConfig, str]], optional):
OptimizerConfig object or path to the yaml file. Defaults to None.
trainer_config (Optional[Union[TrainerConfig, str]], optional):
TrainerConfig object or path to the yaml file. Defaults to None.
experiment_config (Optional[Union[ExperimentConfig, str]], optional):
ExperimentConfig object or path to the yaml file.
If Provided configures the experiment tracking. Defaults to None.
model_callable (Optional[Callable], optional):
If provided, will override the model callable that will be loaded from the config.
Typically used when providing Custom Models
model_state_dict_path (Optional[Union[str, Path]], optional):
If provided, will load the state dict after initializing the model from config.
verbose (bool): turns off and on the logging. Defaults to True.
suppress_lightning_logger (bool): If True, will suppress the default logging from PyTorch Lightning.
Defaults to False.
"""
super().__init__()
if suppress_lightning_logger:
suppress_lightning_logs()
self.verbose = verbose
self.exp_manager = ExperimentRunManager()
if config is None:
assert any(c is not None for c in (data_config, model_config, optimizer_config, trainer_config)), (
"If `config` is None, `data_config`, `model_config`,"
" `trainer_config`, and `optimizer_config` cannot be None"
)
data_config = self._read_parse_config(data_config, DataConfig)
model_config = self._read_parse_config(model_config, ModelConfig)
trainer_config = self._read_parse_config(trainer_config, TrainerConfig)
optimizer_config = self._read_parse_config(optimizer_config, OptimizerConfig)
if model_config.task != "ssl":
assert data_config.target is not None, (
"`target` in data_config should not be None for" f" {model_config.task} task"
)
if experiment_config is None:
if self.verbose:
logger.info("Experiment Tracking is turned off")
self.track_experiment = False
self.config = OmegaConf.merge(
OmegaConf.to_container(data_config),
OmegaConf.to_container(model_config),
OmegaConf.to_container(trainer_config),
OmegaConf.to_container(optimizer_config),
)
else:
experiment_config = self._read_parse_config(experiment_config, ExperimentConfig)
self.track_experiment = True
self.config = OmegaConf.merge(
OmegaConf.to_container(data_config),
OmegaConf.to_container(model_config),
OmegaConf.to_container(trainer_config),
OmegaConf.to_container(experiment_config),
OmegaConf.to_container(optimizer_config),
)
else:
self.config = config
if hasattr(config, "log_target") and (config.log_target is not None):
# experiment_config = OmegaConf.structured(experiment_config)
self.track_experiment = True
else:
if self.verbose:
logger.info("Experiment Tracking is turned off")
self.track_experiment = False
self.run_name, self.uid = self._get_run_name_uid()
if self.track_experiment:
self._setup_experiment_tracking()
else:
self.logger = None
self.exp_manager = ExperimentRunManager()
if model_callable is None:
self.model_callable = getattr_nested(self.config._module_src, self.config._model_name)
self.custom_model = False
else:
self.model_callable = model_callable
self.custom_model = True
self.model_state_dict_path = model_state_dict_path
self._is_config_updated_with_data = False
self._run_validation()
self._is_fitted = False
@property
def has_datamodule(self):
if hasattr(self, "datamodule") and self.datamodule is not None:
return True
else:
return False
@property
def has_model(self):
if hasattr(self, "model") and self.model is not None:
return True
else:
return False
@property
def is_fitted(self):
return self._is_fitted
@property
def name(self):
if self.has_model:
return self.model.__class__.__name__
else:
return self.config._model_name
@property
def num_params(self):
if self.has_model:
return count_parameters(self.model)
def _run_validation(self):
"""Validates the Config params and throws errors if something is wrong."""
if self.config.task == "classification":
if len(self.config.target) > 1:
raise NotImplementedError("Multi-Target Classification is not implemented.")
if self.config.task == "regression":
if self.config.target_range is not None:
if (
(len(self.config.target_range) != len(self.config.target))
or any(len(range_) != 2 for range_ in self.config.target_range)
or any(range_[0] > range_[1] for range_ in self.config.target_range)
):
raise ValueError(
"Targe Range, if defined, should be list tuples of length"
" two(min,max). The length of the list should be equal to hte"
" length of target columns"
)
if self.config.task == "ssl":
assert not self.config.handle_unknown_categories, (
"SSL only supports handle_unknown_categories=False. Please set this" " in your DataConfig"
)
assert not self.config.handle_missing_values, (
"SSL only supports handle_missing_values=False. Please set this in" " your DataConfig"
)
def _read_parse_config(self, config, cls):
if isinstance(config, str):
if os.path.exists(config):
_config = OmegaConf.load(config)
if cls == ModelConfig:
cls = getattr_nested(_config._module_src, _config._config_name)
config = cls(
**{
k: v
for k, v in _config.items()
if (k in cls.__dataclass_fields__.keys()) and (cls.__dataclass_fields__[k].init)
}
)
else:
raise ValueError(f"{config} is not a valid path")
config = OmegaConf.structured(config)
return config
def _get_run_name_uid(self) -> Tuple[str, int]:
"""Gets the name of the experiment and increments version by 1.
Returns:
tuple[str, int]: Returns the name and version number
"""
if hasattr(self.config, "run_name") and self.config.run_name is not None:
name = self.config.run_name
elif hasattr(self.config, "checkpoints_name") and self.config.checkpoints_name is not None:
name = self.config.checkpoints_name
else:
name = self.config.task
uid = self.exp_manager.update_versions(name)
return name, uid
def _setup_experiment_tracking(self):
"""Sets up the Experiment Tracking Framework according to the choices made in the Experimentconfig."""
if self.config.log_target == "tensorboard":
self.logger = pl.loggers.TensorBoardLogger(
name=self.run_name, save_dir=self.config.project_name, version=self.uid
)
elif self.config.log_target == "wandb":
self.logger = pl.loggers.WandbLogger(
name=f"{self.run_name}_{self.uid}",
project=self.config.project_name,
offline=False,
)
else:
raise NotImplementedError(
f"{self.config.log_target} is not implemented. Try one of [wandb," " tensorboard]"
)
def _prepare_callbacks(self, callbacks=None) -> List:
"""Prepares the necesary callbacks to the Trainer based on the configuration.
Returns:
List: A list of callbacks
"""
callbacks = [] if callbacks is None else callbacks
if self.config.early_stopping is not None:
early_stop_callback = pl.callbacks.early_stopping.EarlyStopping(
monitor=self.config.early_stopping,
min_delta=self.config.early_stopping_min_delta,
patience=self.config.early_stopping_patience,
mode=self.config.early_stopping_mode,
**self.config.early_stopping_kwargs,
)
callbacks.append(early_stop_callback)
if self.config.checkpoints:
ckpt_name = f"{self.run_name}-{self.uid}"
ckpt_name = ckpt_name.replace(" ", "_") + "_{epoch}-{valid_loss:.2f}"
model_checkpoint = pl.callbacks.ModelCheckpoint(
monitor=self.config.checkpoints,
dirpath=self.config.checkpoints_path,
filename=ckpt_name,
save_top_k=self.config.checkpoints_save_top_k,
mode=self.config.checkpoints_mode,
every_n_epochs=self.config.checkpoints_every_n_epochs,
**self.config.checkpoints_kwargs,
)
callbacks.append(model_checkpoint)
self.config.enable_checkpointing = True
else:
self.config.enable_checkpointing = False
if self.config.progress_bar == "rich" and self.config.trainer_kwargs.get("enable_progress_bar", True):
callbacks.append(RichProgressBar())
if self.verbose:
logger.debug(f"Callbacks used: {callbacks}")
return callbacks
def _prepare_trainer(self, callbacks: List, max_epochs: int = None, min_epochs: int = None) -> pl.Trainer:
"""Prepares the Trainer object.
Args:
callbacks (List): A list of callbacks to be used
max_epochs (int, optional): Maximum number of epochs to train for. Defaults to None.
min_epochs (int, optional): Minimum number of epochs to train for. Defaults to None.
Returns:
pl.Trainer: A PyTorch Lightning Trainer object
"""
if self.verbose:
logger.info("Preparing the Trainer")
if max_epochs is not None:
self.config.max_epochs = max_epochs
if min_epochs is not None:
self.config.min_epochs = min_epochs
# Getting Trainer Arguments from the init signature
trainer_sig = inspect.signature(pl.Trainer.__init__)
trainer_args = [p for p in trainer_sig.parameters.keys() if p != "self"]
trainer_args_config = {k: v for k, v in self.config.items() if k in trainer_args}
# For some weird reason, checkpoint_callback is not appearing in the Trainer vars
trainer_args_config["enable_checkpointing"] = self.config.enable_checkpointing
# turn off progress bar if progress_bar=='none'
trainer_args_config["enable_progress_bar"] = self.config.progress_bar != "none"
# Adding trainer_kwargs from config to trainer_args
trainer_args_config.update(self.config.trainer_kwargs)
if trainer_args_config["devices"] == -1:
# Setting devices to auto if -1 so that lightning will use all available GPUs/CPUs
trainer_args_config["devices"] = "auto"
return pl.Trainer(
logger=self.logger,
callbacks=callbacks,
**trainer_args_config,
)
def _check_and_set_target_transform(self, target_transform):
if target_transform is not None:
if isinstance(target_transform, Iterable):
assert len(target_transform) == 2, (
"If `target_transform` is a tuple, it should have and only have"
" forward and backward transformations"
)
elif isinstance(target_transform, TransformerMixin):
pass
else:
raise ValueError(
"`target_transform` should wither be an sklearn Transformer or a" " tuple of callables."
)
if self.config.task == "classification" and target_transform is not None:
logger.warning("For classification task, target transform is not used. Ignoring the" " parameter")
target_transform = None
return target_transform
def _prepare_for_training(self, model, datamodule, callbacks=None, max_epochs=None, min_epochs=None):
self.callbacks = self._prepare_callbacks(callbacks)
self.trainer = self._prepare_trainer(self.callbacks, max_epochs, min_epochs)
self.model = model
self.datamodule = datamodule
@classmethod
def _load_weights(cls, model, path: Union[str, Path]) -> None:
"""Loads the model weights in the specified directory.
Args:
path (str): The path to the file to load the model from
Returns:
None
"""
ckpt = pl_load(path, map_location=lambda storage, loc: storage)
model.load_state_dict(ckpt.get("state_dict") or ckpt)
@classmethod
def load_model(cls, dir: str, map_location=None, strict=True):
"""Loads a saved model from the directory.
Args:
dir (str): The directory where the model wa saved, along with the checkpoints
map_location (Union[Dict[str, str], str, device, int, Callable, None]) : If your checkpoint
saved a GPU model and you now load on CPUs or a different number of GPUs, use this to map
to the new setup. The behaviour is the same as in torch.load()
strict (bool) : Whether to strictly enforce that the keys in checkpoint_path match the keys
returned by this module's state dict. Default: True.
Returns:
TabularModel (TabularModel): The saved TabularModel
"""
config = OmegaConf.load(os.path.join(dir, "config.yml"))
datamodule = joblib.load(os.path.join(dir, "datamodule.sav"))
if (
hasattr(config, "log_target")
and (config.log_target is not None)
and os.path.exists(os.path.join(dir, "exp_logger.sav"))
):
logger = joblib.load(os.path.join(dir, "exp_logger.sav"))
else:
logger = None
if os.path.exists(os.path.join(dir, "callbacks.sav")):
callbacks = joblib.load(os.path.join(dir, "callbacks.sav"))
# Excluding Gradient Accumulation Scheduler Callback as we are creating
# a new one in trainer
callbacks = [c for c in callbacks if not isinstance(c, GradientAccumulationScheduler)]
else:
callbacks = []
if os.path.exists(os.path.join(dir, "custom_model_callable.sav")):
model_callable = joblib.load(os.path.join(dir, "custom_model_callable.sav"))
custom_model = True
else:
model_callable = getattr_nested(config._module_src, config._model_name)
# model_callable = getattr(
# getattr(models, config._module_src), config._model_name
# )
custom_model = False
inferred_config = datamodule.update_config(config)
inferred_config = OmegaConf.structured(inferred_config)
model_args = {
"config": config,
"inferred_config": inferred_config,
}
custom_params = joblib.load(os.path.join(dir, "custom_params.sav"))
if custom_params.get("custom_loss") is not None:
model_args["loss"] = "MSELoss" # For compatibility. Not Used
if custom_params.get("custom_metrics") is not None:
model_args["metrics"] = ["mean_squared_error"] # For compatibility. Not Used
model_args["metrics_params"] = [{}] # For compatibility. Not Used
model_args["metrics_prob_inputs"] = [False] # For compatibility. Not Used
if custom_params.get("custom_optimizer") is not None:
model_args["optimizer"] = "Adam" # For compatibility. Not Used
if custom_params.get("custom_optimizer_params") is not None:
model_args["optimizer_params"] = {} # For compatibility. Not Used
# Initializing with default metrics, losses, and optimizers. Will revert once initialized
try:
model = model_callable.load_from_checkpoint(
checkpoint_path=os.path.join(dir, "model.ckpt"),
map_location=map_location,
strict=strict,
**model_args,
)
except RuntimeError as e:
if (
"Unexpected key(s) in state_dict" in str(e)
and "loss.weight" in str(e)
and "custom_loss.weight" in str(e)
):
# Custom loss will be loaded after the model is initialized
# continuing with strict=False
model = model_callable.load_from_checkpoint(
checkpoint_path=os.path.join(dir, "model.ckpt"),
map_location=map_location,
strict=False,
**model_args,
)
else:
raise e
if custom_params.get("custom_optimizer") is not None:
model.custom_optimizer = custom_params["custom_optimizer"]
if custom_params.get("custom_optimizer_params") is not None:
model.custom_optimizer_params = custom_params["custom_optimizer_params"]
if custom_params.get("custom_loss") is not None:
model.loss = custom_params["custom_loss"]
if custom_params.get("custom_metrics") is not None:
model.custom_metrics = custom_params.get("custom_metrics")
model.hparams.metrics = [m.__name__ for m in custom_params.get("custom_metrics")]
model.hparams.metrics_params = [{}]
model.hparams.metrics_prob_input = custom_params.get("custom_metrics_prob_inputs")
model._setup_loss()
model._setup_metrics()
tabular_model = cls(config=config, model_callable=model_callable)
tabular_model.model = model
tabular_model.custom_model = custom_model
tabular_model.datamodule = datamodule
tabular_model.callbacks = callbacks
tabular_model.trainer = tabular_model._prepare_trainer(callbacks=callbacks)
# tabular_model.trainer.model = model
tabular_model.logger = logger
return tabular_model
def prepare_dataloader(
self,
train: DataFrame,
validation: Optional[DataFrame] = None,
train_sampler: Optional[torch.utils.data.Sampler] = None,
target_transform: Optional[Union[TransformerMixin, Tuple]] = None,
seed: Optional[int] = 42,
cache_data: str = "memory",
) -> TabularDatamodule:
"""Prepares the dataloaders for training and validation.
Args:
train (DataFrame): Training Dataframe
validation (Optional[DataFrame], optional):
If provided, will use this dataframe as the validation while training.
Used in Early Stopping and Logging. If left empty, will use 20% of Train data as validation.
Defaults to None.
train_sampler (Optional[torch.utils.data.Sampler], optional):
Custom PyTorch batch samplers which will be passed to the DataLoaders.
Useful for dealing with imbalanced data and other custom batching strategies
target_transform (Optional[Union[TransformerMixin, Tuple(Callable)]], optional):
If provided, applies the transform to the target before modelling and inverse the transform during
prediction. The parameter can either be a sklearn Transformer which has an inverse_transform method, or
a tuple of callables (transform_func, inverse_transform_func)
seed (Optional[int], optional): Random seed for reproducibility. Defaults to 42.
cache_data (str): Decides how to cache the data in the dataloader. If set to
"memory", will cache in memory. If set to a valid path, will cache in that path. Defaults to "memory".
Returns:
TabularDatamodule: The prepared datamodule
"""
if self.verbose:
logger.info("Preparing the DataLoaders")
target_transform = self._check_and_set_target_transform(target_transform)
datamodule = TabularDatamodule(
train=train,
validation=validation,
config=self.config,
target_transform=target_transform,
train_sampler=train_sampler,
seed=seed,
cache_data=cache_data,
verbose=self.verbose,
)
datamodule.prepare_data()
datamodule.setup("fit")
return datamodule
def prepare_model(
self,
datamodule: TabularDatamodule,
loss: Optional[torch.nn.Module] = None,
metrics: Optional[List[Callable]] = None,
metrics_prob_inputs: Optional[List[bool]] = None,
optimizer: Optional[torch.optim.Optimizer] = None,
optimizer_params: Dict = None,
) -> BaseModel:
"""Prepares the model for training.
Args:
datamodule (TabularDatamodule): The datamodule
loss (Optional[torch.nn.Module], optional): Custom Loss functions which are not in standard pytorch library
metrics (Optional[List[Callable]], optional): Custom metric functions(Callable) which has the
signature metric_fn(y_hat, y) and works on torch tensor inputs
metrics_prob_inputs (Optional[List[bool]], optional): This is a mandatory parameter for
classification metrics. If the metric function requires probabilities as inputs, set this to True.
The length of the list should be equal to the number of metrics. Defaults to None.
optimizer (Optional[torch.optim.Optimizer], optional):
Custom optimizers which are a drop in replacements for standard PyTorch optimizers.
This should be the Class and not the initialized object
optimizer_params (Optional[Dict], optional): The parameters to initialize the custom optimizer.
Returns:
BaseModel: The prepared model
"""
if self.verbose:
logger.info(f"Preparing the Model: {self.config._model_name}")
# Fetching the config as some data specific configs have been added in the datamodule
self.inferred_config = self._read_parse_config(datamodule.update_config(self.config), InferredConfig)
model = self.model_callable(
self.config,
custom_loss=loss, # Unused in SSL tasks
custom_metrics=metrics, # Unused in SSL tasks
custom_metrics_prob_inputs=metrics_prob_inputs, # Unused in SSL tasks
custom_optimizer=optimizer,
custom_optimizer_params=optimizer_params or {},
inferred_config=self.inferred_config,
)
# Data Aware Initialization(for the models that need it)
model.data_aware_initialization(datamodule)
if self.model_state_dict_path is not None:
self._load_weights(model, self.model_state_dict_path)
if self.track_experiment and self.config.log_target == "wandb":
self.logger.watch(model, log=self.config.exp_watch, log_freq=self.config.exp_log_freq)
return model
def train(
self,
model: pl.LightningModule,
datamodule: TabularDatamodule,
callbacks: Optional[List[pl.Callback]] = None,
max_epochs: int = None,
min_epochs: int = None,
handle_oom: bool = True,
) -> pl.Trainer:
"""Trains the model.
Args:
model (pl.LightningModule): The PyTorch Lightning model to be trained.
datamodule (TabularDatamodule): The datamodule
callbacks (Optional[List[pl.Callback]], optional):
List of callbacks to be used during training. Defaults to None.
max_epochs (Optional[int]): Overwrite maximum number of epochs to be run. Defaults to None.
min_epochs (Optional[int]): Overwrite minimum number of epochs to be run. Defaults to None.
handle_oom (bool): If True, will try to handle OOM errors elegantly. Defaults to True.
Returns:
pl.Trainer: The PyTorch Lightning Trainer instance
"""
self._prepare_for_training(model, datamodule, callbacks, max_epochs, min_epochs)
train_loader, val_loader = (
self.datamodule.train_dataloader(),
self.datamodule.val_dataloader(),
)
self.model.train()
if self.config.auto_lr_find and (not self.config.fast_dev_run):
if self.verbose:
logger.info("Auto LR Find Started")
with OutOfMemoryHandler(handle_oom=handle_oom) as oom_handler:
result = Tuner(self.trainer).lr_find(
self.model,
train_dataloaders=train_loader,
val_dataloaders=val_loader,
)
if oom_handler.oom_triggered:
raise OOMException(
"OOM detected during LR Find. Try reducing your batch_size or the"
" model parameters." + "/n" + "Original Error: " + oom_handler.oom_msg
)
if self.verbose:
logger.info(
f"Suggested LR: {result.suggestion()}. For plot and detailed"
" analysis, use `find_learning_rate` method."
)
self.model.reset_weights()
# Parameters in models needs to be initialized again after LR find
self.model.data_aware_initialization(self.datamodule)
self.model.train()
if self.verbose:
logger.info("Training Started")
with OutOfMemoryHandler(handle_oom=handle_oom) as oom_handler:
self.trainer.fit(self.model, train_loader, val_loader)
if oom_handler.oom_triggered:
raise OOMException(
"OOM detected during Training. Try reducing your batch_size or the"
" model parameters."
"/n" + "Original Error: " + oom_handler.oom_msg
)
self._is_fitted = True
if self.verbose:
logger.info("Training the model completed")
if self.config.load_best:
self.load_best_model()
return self.trainer
def fit(
self,
train: Optional[DataFrame],
validation: Optional[DataFrame] = None,
loss: Optional[torch.nn.Module] = None,
metrics: Optional[List[Callable]] = None,
metrics_prob_inputs: Optional[List[bool]] = None,
optimizer: Optional[torch.optim.Optimizer] = None,
optimizer_params: Dict = None,
train_sampler: Optional[torch.utils.data.Sampler] = None,
target_transform: Optional[Union[TransformerMixin, Tuple]] = None,
max_epochs: Optional[int] = None,
min_epochs: Optional[int] = None,
seed: Optional[int] = 42,
callbacks: Optional[List[pl.Callback]] = None,
datamodule: Optional[TabularDatamodule] = None,
cache_data: str = "memory",
handle_oom: bool = True,
) -> pl.Trainer:
"""The fit method which takes in the data and triggers the training.
Args:
train (DataFrame): Training Dataframe
validation (Optional[DataFrame], optional):
If provided, will use this dataframe as the validation while training.
Used in Early Stopping and Logging. If left empty, will use 20% of Train data as validation.
Defaults to None.
loss (Optional[torch.nn.Module], optional): Custom Loss functions which are not in standard pytorch library
metrics (Optional[List[Callable]], optional): Custom metric functions(Callable) which has the
signature metric_fn(y_hat, y) and works on torch tensor inputs. y_hat is expected to be of shape
(batch_size, num_classes) for classification and (batch_size, 1) for regression and y is expected to be
of shape (batch_size, 1)
metrics_prob_inputs (Optional[List[bool]], optional): This is a mandatory parameter for
classification metrics. If the metric function requires probabilities as inputs, set this to True.
The length of the list should be equal to the number of metrics. Defaults to None.
optimizer (Optional[torch.optim.Optimizer], optional):
Custom optimizers which are a drop in replacements for
standard PyTorch optimizers. This should be the Class and not the initialized object
optimizer_params (Optional[Dict], optional): The parameters to initialize the custom optimizer.
train_sampler (Optional[torch.utils.data.Sampler], optional):
Custom PyTorch batch samplers which will be passed
to the DataLoaders. Useful for dealing with imbalanced data and other custom batching strategies
target_transform (Optional[Union[TransformerMixin, Tuple(Callable)]], optional):
If provided, applies the transform to the target before modelling and inverse the transform during
prediction. The parameter can either be a sklearn Transformer
which has an inverse_transform method, or a tuple of callables (transform_func, inverse_transform_func)
max_epochs (Optional[int]): Overwrite maximum number of epochs to be run. Defaults to None.
min_epochs (Optional[int]): Overwrite minimum number of epochs to be run. Defaults to None.
seed: (int): Random seed for reproducibility. Defaults to 42.
callbacks (Optional[List[pl.Callback]], optional):
List of callbacks to be used during training. Defaults to None.
datamodule (Optional[TabularDatamodule], optional): The datamodule.
If provided, will ignore the rest of the parameters like train, test etc and use the datamodule.
Defaults to None.
cache_data (str): Decides how to cache the data in the dataloader. If set to
"memory", will cache in memory. If set to a valid path, will cache in that path. Defaults to "memory".
handle_oom (bool): If True, will try to handle OOM errors elegantly. Defaults to True.
Returns:
pl.Trainer: The PyTorch Lightning Trainer instance
"""
assert self.config.task != "ssl", (
"`fit` is not valid for SSL task. Please use `pretrain` for" " semi-supervised learning"
)
if metrics is not None:
assert len(metrics) == len(
metrics_prob_inputs or []
), "The length of `metrics` and `metrics_prob_inputs` should be equal"
seed = seed or self.config.seed
if seed:
seed_everything(seed)
if datamodule is None:
datamodule = self.prepare_dataloader(
train,
validation,
train_sampler,
target_transform,
seed,
cache_data,
)
else:
if train is not None:
warnings.warn(
"train data and datamodule is provided."
" Ignoring the train data and using the datamodule."
" Set either one of them to None to avoid this warning."
)
model = self.prepare_model(
datamodule,
loss,
metrics,
metrics_prob_inputs,
optimizer,
optimizer_params or {},
)
return self.train(model, datamodule, callbacks, max_epochs, min_epochs, handle_oom)
def pretrain(
self,
train: Optional[DataFrame],
validation: Optional[DataFrame] = None,
optimizer: Optional[torch.optim.Optimizer] = None,
optimizer_params: Dict = None,
# train_sampler: Optional[torch.utils.data.Sampler] = None,
max_epochs: Optional[int] = None,
min_epochs: Optional[int] = None,
seed: Optional[int] = 42,
callbacks: Optional[List[pl.Callback]] = None,
datamodule: Optional[TabularDatamodule] = None,
cache_data: str = "memory",
) -> pl.Trainer:
"""The pretrained method which takes in the data and triggers the training.
Args:
train (DataFrame): Training Dataframe
validation (Optional[DataFrame], optional): If provided, will use this dataframe as the validation while
training. Used in Early Stopping and Logging. If left empty, will use 20% of Train data as validation.
Defaults to None.
optimizer (Optional[torch.optim.Optimizer], optional): Custom optimizers which are a drop in replacements
for standard PyTorch optimizers. This should be the Class and not the initialized object
optimizer_params (Optional[Dict], optional): The parameters to initialize the custom optimizer.
max_epochs (Optional[int]): Overwrite maximum number of epochs to be run. Defaults to None.
min_epochs (Optional[int]): Overwrite minimum number of epochs to be run. Defaults to None.
seed: (int): Random seed for reproducibility. Defaults to 42.
callbacks (Optional[List[pl.Callback]], optional): List of callbacks to be used during training.
Defaults to None.
datamodule (Optional[TabularDatamodule], optional): The datamodule. If provided, will ignore the rest of the
parameters like train, test etc. and use the datamodule. Defaults to None.
cache_data (str): Decides how to cache the data in the dataloader. If set to
"memory", will cache in memory. If set to a valid path, will cache in that path. Defaults to "memory".
Returns:
pl.Trainer: The PyTorch Lightning Trainer instance
"""
assert self.config.task == "ssl", (
f"`pretrain` is not valid for {self.config.task} task. Please use `fit`" " instead."
)
seed = seed or self.config.seed
if seed:
seed_everything(seed)
if datamodule is None:
datamodule = self.prepare_dataloader(
train,
validation,
train_sampler=None,
target_transform=None,
seed=seed,
cache_data=cache_data,
)
else:
if train is not None:
warnings.warn(
"train data and datamodule is provided."
" Ignoring the train data and using the datamodule."
" Set either one of them to None to avoid this warning."
)
model = self.prepare_model(
datamodule,
optimizer,
optimizer_params or {},
)
return self.train(model, datamodule, callbacks, max_epochs, min_epochs)
def create_finetune_model(
self,
task: str,
head: str,
head_config: Dict,
train: DataFrame,
validation: Optional[DataFrame] = None,
train_sampler: Optional[torch.utils.data.Sampler] = None,
target_transform: Optional[Union[TransformerMixin, Tuple]] = None,
target: Optional[str] = None,
optimizer_config: Optional[OptimizerConfig] = None,
trainer_config: Optional[TrainerConfig] = None,
experiment_config: Optional[ExperimentConfig] = None,
loss: Optional[torch.nn.Module] = None,
metrics: Optional[List[Union[Callable, str]]] = None,
metrics_prob_input: Optional[List[bool]] = None,
metrics_params: Optional[Dict] = None,
optimizer: Optional[torch.optim.Optimizer] = None,
optimizer_params: Dict = None,
learning_rate: Optional[float] = None,
target_range: Optional[Tuple[float, float]] = None,
seed: Optional[int] = 42,
):
"""Creates a new TabularModel model using the pretrained weights and the new task and head.
Args:
task (str): The task to be performed. One of "regression", "classification"
head (str): The head to be used for the model. Should be one of the heads defined
in `pytorch_tabular.models.common.heads`. Defaults to LinearHead. Choices are:
[`None`,`LinearHead`,`MixtureDensityHead`].
head_config (Dict): The config as a dict which defines the head. If left empty,
will be initialized as default linear head.
train (DataFrame): The training data with labels
validation (Optional[DataFrame], optional): The validation data with labels. Defaults to None.
train_sampler (Optional[torch.utils.data.Sampler], optional): If provided, will be used as a batch sampler
for training. Defaults to None.
target_transform (Optional[Union[TransformerMixin, Tuple]], optional): If provided, will be used
to transform the target before training and inverse transform the predictions.
target (Optional[str], optional): The target column name if not provided in the initial pretraining stage.
Defaults to None.
optimizer_config (Optional[OptimizerConfig], optional):
If provided, will redefine the optimizer for fine-tuning stage. Defaults to None.
trainer_config (Optional[TrainerConfig], optional):
If provided, will redefine the trainer for fine-tuning stage. Defaults to None.
experiment_config (Optional[ExperimentConfig], optional):
If provided, will redefine the experiment for fine-tuning stage. Defaults to None.
loss (Optional[torch.nn.Module], optional):
If provided, will be used as the loss function for the fine-tuning.
By default, it is MSELoss for regression and CrossEntropyLoss for classification.
metrics (Optional[List[Callable]], optional): List of metrics (either callables or str) to be used for the
fine-tuning stage. If str, it should be one of the functional metrics implemented in
``torchmetrics.functional``. Defaults to None.
metrics_prob_input (Optional[List[bool]], optional): Is a mandatory parameter for classification metrics
This defines whether the input to the metric function is the probability or the class.
Length should be same as the number of metrics. Defaults to None.
metrics_params (Optional[Dict], optional): The parameters for the metrics in the same order as metrics.
For eg. f1_score for multi-class needs a parameter `average` to fully define the metric.
Defaults to None.
optimizer (Optional[torch.optim.Optimizer], optional):
Custom optimizers which are a drop in replacements for standard PyTorch optimizers. If provided,
the OptimizerConfig is ignored in favor of this. Defaults to None.
optimizer_params (Dict, optional): The parameters for the optimizer. Defaults to {}.
learning_rate (Optional[float], optional): The learning rate to be used. Defaults to 1e-3.
target_range (Optional[Tuple[float, float]], optional): The target range for the regression task.
Is ignored for classification. Defaults to None.
seed (Optional[int], optional): Random seed for reproducibility. Defaults to 42.
Returns:
TabularModel (TabularModel): The new TabularModel model for fine-tuning
"""
config = self.config
optimizer_params = optimizer_params or {}
if target is None:
assert (
hasattr(config, "target") and config.target is not None
), "`target` cannot be None if it was not set in the initial `DataConfig`"
else:
assert isinstance(target, list), "`target` should be a list of strings"
config.target = target
config.task = task
# Add code to update configs with newly provided ones
if optimizer_config is not None:
for key, value in optimizer_config.__dict__.items():
config[key] = value
if len(optimizer_params) > 0:
config.optimizer_params = optimizer_params
else:
config.optimizer_params = {}
if trainer_config is not None:
for key, value in trainer_config.__dict__.items():
config[key] = value
if experiment_config is not None:
for key, value in experiment_config.__dict__.items():
config[key] = value
else: