Training
Training a Deep Learning model can get arbritarily complex. PyTorch Tabular, by inheriting PyTorch Lightning, offloads the whole workload onto the underlying PyTorch Lightning Framework. It has been made to make training your models easy as a breeze and at the same time give you the flexibility to make the training process your own.
The trainer in PyTorch Tabular have inherited all the features of the Pytorch Lightning trainer, either directly or indirectly.
Basic Usage¶
The parameters that you would set most frequently are:
batch_size
: int: Number of samples in each batch of training. Defaults to64
max_epochs
: int: Maximum number of epochs to be run. The maximum is in case of Early Stopping where this becomes the maximum and without Early Stopping, this is the number of epochs that will be run Defaults to10
-
devices
: (Optional[int]): Number of devices to train on (int). -1 uses all available devices. By default uses all available devices (-1) -
accelerator
: Optional[str]: The accelerator to use for training. Can be one of 'cpu','gpu','tpu','ipu','auto'. Defaults to 'auto'. load_best
: int: Flag to load the best model saved during training. This will be ignored if checkpoint saving is turned off. Defaults to True
Usage Example¶
PyTorch Tabular uses Early Stopping by default and monitors valid_loss
to stop training. Checkpoint saving is also turned on by default, which monitors valid_loss
and saved the best model in a folder saved_models
. All of these are configurable as we will see in the next section.
Advanced Usage¶
Early Stopping and Checkpoint Saving¶
Early Stopping is turned on by default. But you can turn it off by setting early_stopping
to None
. On the other hand, if you want to monitor some other metric, you just need to give that metric name in the early_stopping
parameter. Few other paramters that controls early stopping are:
early_stopping_min_delta
: float: The minimum delta in the loss/metric which qualifies as an improvement in early stopping. Defaults to0.001
early_stopping_mode
: str: The direction in which the loss/metric should be optimized. Choices aremax
andmin
. Defaults tomin
early_stopping_patience
: int: The number of epochs to wait until there is no further improvements in loss/metric. Defaults to3
min_epochs
: int: Minimum number of epochs to be run. This many epochs are run regardless of the stopping criteria. Defaults to1
Checkpoint Saving is also turned on by default and to turn it off you can set the checkpoints
parameter to None
. If you want to monitor some other metric, you just need to give that metric name in the early_stopping
parameter. Few other paramters that controls checkpoint saving are:
checkpoints_path
: str: The path where the saved models will be. Defaults tosaved_models
checkpoints_mode
: str: The direction in which the loss/metric should be optimized. Choices aremax
andmin
. Defaults tomin
checkpoints_save_top_k
: int: The number of best models to save. If you want to save more than one best models, you can set this parameter to >1. Defaults to1
Note
Make sure the name of the metric/loss you want to track exactly matches the ones in the logs. Recommended way is to run a model and check the results by evaluating the model. From the resulting dictionary, you can pick up a key to track during training.
Learning Rate Finder¶
First proposed in this paper Cyclical Learning Rates for Training Neural Networks and the subsequently popularized by fast.ai, is a technique to reach the neighbourhood of optimum learning rate without costly search. PyTorch Tabular let's you find the optimal learning rate(using the method proposed in the paper) and automatically use that for training the network. All this can be turned on with a simple flag auto_lr_find
We can also run the learning rate finder as a separate step using [pytorch_tabular.TabularModel.find_learning_rate].
Controlling the Gradients/Optimization¶
While training, there can be situations where you need to have a heavier control on the gradient optimization process. For eg. if the gradients are exploding, you might want to clip gradient values before each update. gradient_clip_val
let's you do that.
Sometimes, you might want to accumulate gradients across multiple batches before you do a backward propoagation(may be because a larger batch size does not fit in your GPU). PyTorch Tabular let's you do this with accumulate_grad_batches
Debugging¶
Many times, you will need to debug a model and see why it is not performing as it is supposed to. Or even, while developing new models, you will need to debug the model a lot. PyTorch Lightning has a few features for this usecase, which Pytorch Tabular has adopted.
To find out performance bottle necks, we can use:
profiler
: Optional[str]: To profile individual steps during training and assist in identifying bottlenecks. Choices are:None
simple
advanced
. Defaults toNone
To check if the whole setup runs without errors, we can use:
fast_dev_run
: Optional[str]: Quick Debug Run of Val. Defaults toFalse
If the model is not learning properly:
-
overfit_batches
: float: Uses this much data of the training set. If nonzero, will use the same training set for validation and testing. If the training dataloaders have shuffle=True, Lightning will automatically disable it. Useful for quickly debugging or trying to overfit on purpose. Defaults to0
-
track_grad_norm
: bool: This is only used if experiment tracking is setup. Track and Log Gradient Norms in the logger. -1 by default means no tracking. 1 for the L1 norm, 2 for L2 norm, etc. Defaults toFalse
. If the gradient norm falls to zero quickly, then we have a problem.
Using the entire PyTorch Lightning Trainer¶
To unlock the full potential of the PyTorch Lightning Trainer, you can use the trainer_kwargs
parameter. This will let you pass any parameter that is supported by the PyTorch Lightning Trainer. Full documentation can be found here
pytorch_tabular.config.TrainerConfig
dataclass
¶
Trainer configuration.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch_size |
int
|
Number of samples in each batch of training |
64
|
data_aware_init_batch_size |
int
|
Number of samples in each batch of training for the data-aware initialization, when applicable. Defaults to 2000 |
2000
|
fast_dev_run |
bool
|
runs n if set to |
False
|
max_epochs |
int
|
Maximum number of epochs to be run |
10
|
min_epochs |
Optional[int]
|
Force training for at least these many epochs. 1 by default |
1
|
max_time |
Optional[int]
|
Stop training after this amount of time has passed. Disabled by default (None) |
None
|
accelerator |
Optional[str]
|
The accelerator to use for training. Can be one of
'cpu','gpu','tpu','ipu', 'mps', 'auto'. Defaults to 'auto'.
Choices are: [ |
'auto'
|
devices |
Optional[int]
|
Number of devices to train on (int). -1 uses all available devices. By default, uses all available devices (-1) |
-1
|
devices_list |
Optional[List[int]]
|
List of devices to train on (list). If specified, takes
precedence over |
None
|
accumulate_grad_batches |
int
|
Accumulates grads every k batches or as set up in the dict. Trainer also calls optimizer.step() for the last indivisible step number. |
1
|
auto_lr_find |
bool
|
Runs a learning rate finder algorithm when calling trainer.tune(), to find optimal initial learning rate. |
False
|
auto_select_gpus |
bool
|
If enabled and |
True
|
check_val_every_n_epoch |
int
|
Check val every n train epochs. |
1
|
gradient_clip_val |
float
|
Gradient clipping value |
0.0
|
overfit_batches |
float
|
Uses this much data of the training set. If nonzero, will use the same training set for validation and testing. If the training dataloaders have shuffle=True, Lightning will automatically disable it. Useful for quickly debugging or trying to overfit on purpose. |
0.0
|
deterministic |
bool
|
If true enables cudnn.deterministic. Might make your system slower, but ensures reproducibility. |
False
|
profiler |
Optional[str]
|
To profile individual steps during training and assist in identifying
bottlenecks. None, simple or advanced, pytorch. Choices are:
[ |
None
|
early_stopping |
Optional[str]
|
The loss/metric that needed to be monitored for early stopping. If None, there will be no early stopping |
'valid_loss'
|
early_stopping_min_delta |
float
|
The minimum delta in the loss/metric which qualifies as an improvement in early stopping |
0.001
|
early_stopping_mode |
str
|
The direction in which the loss/metric should be optimized. Choices are:
[ |
'min'
|
early_stopping_patience |
int
|
The number of epochs to wait until there is no further improvements in loss/metric |
3
|
early_stopping_kwargs |
Optional[Dict]
|
Additional keyword arguments for the early stopping callback. See the documentation for the PyTorch Lightning EarlyStopping callback for more details. |
lambda: {}()
|
checkpoints |
Optional[str]
|
The loss/metric that needed to be monitored for checkpoints. If None, there will be no checkpoints |
'valid_loss'
|
checkpoints_path |
str
|
The path where the saved models will be |
'saved_models'
|
checkpoints_every_n_epochs |
int
|
Number of training steps between checkpoints |
1
|
checkpoints_name |
Optional[str]
|
The name under which the models will be saved. If left blank,
first it will look for |
None
|
checkpoints_mode |
str
|
The direction in which the loss/metric should be optimized |
'min'
|
checkpoints_save_top_k |
int
|
The number of best models to save |
1
|
checkpoints_kwargs |
Optional[Dict]
|
Additional keyword arguments for the checkpoints callback. See the documentation for the PyTorch Lightning ModelCheckpoint callback for more details. |
lambda: {}()
|
load_best |
bool
|
Flag to load the best model saved during training |
True
|
track_grad_norm |
int
|
Track and Log Gradient Norms in the logger. -1 by default means no tracking. 1 for the L1 norm, 2 for L2 norm, etc. |
-1
|
progress_bar |
str
|
Progress bar type. Can be one of: |
'rich'
|
precision |
str
|
Precision of the model. Defaults to |
'32'
|
seed |
int
|
Seed for random number generators. Defaults to 42 |
42
|
trainer_kwargs |
Dict[str, Any]
|
Additional kwargs to be passed to PyTorch Lightning Trainer. See https://pytorch-lightning.readthedocs.io/en/latest/api/pytorch_lightning.trainer.html#pytorch_lightning.trainer.Trainer |
dict()
|
Source code in src/pytorch_tabular/config/config.py
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 |
|