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
| import math import os from collections import Callable from enum import Enum from functools import partial from typing import Iterable
import torch from accelerate import Accelerator, DistributedType from torch.utils.data import DataLoader
from pytorch_accelerated.callbacks import ( CallbackHandler, LogMetricsCallback, PrintProgressCallback, TerminateOnNaNCallback, StopTrainingError, ProgressBarCallback, MoveModulesToDeviceCallback, ) from pytorch_accelerated.run_config import TrainerRunConfig from pytorch_accelerated.tracking import RunHistory, InMemoryRunHistory, LossTracker
DEFAULT_CALLBACKS = ( MoveModulesToDeviceCallback, TerminateOnNaNCallback, PrintProgressCallback, ProgressBarCallback, LogMetricsCallback, )
class TrainerPlaceholderValues(Enum): NUM_EPOCHS = "trainer.run_config.num_epochs" NUM_UPDATE_STEPS_PER_EPOCH = "trainer.run_config.num_update_steps_per_epoch" TRAIN_DATALOADER_LEN = "len(trainer._train_dataloader)" EVAL_DATALOADER_LEN = "len(trainer._eval_dataloader)"
@classmethod def placeholder_set(cls): return {placeholder.name for placeholder in cls}
@staticmethod def __create_new_enum(original_enum, other, operation): enum_members = {k: v.value for k, v in original_enum._member_map_.items()} enum_members[ original_enum.name ] = f"{enum_members[original_enum.name]}{operation}{other}" new_enum = Enum("TrainerPlaceholderValues", enum_members) return new_enum._member_map_[original_enum.name]
def __mul__(self, other): return self.__create_new_enum(self, other, "*")
def __add__(self, other): return self.__create_new_enum(self, other, "+")
def __sub__(self, other): raise NotImplemented( "Subtraction is not supported, please re-write the expression in terms of addition" )
def replace_trainer_placeholder_values(trainer, instance): if isinstance(instance, partial): placeholders = TrainerPlaceholderValues.placeholder_set() keywords = list(instance.keywords.items())
new_keywords = {}
for keyword, value in keywords: if hasattr(value, "name"): if value.name in placeholders: new_keywords[keyword] = eval(value.value) else: new_keywords[keyword] = value else: new_keywords[keyword] = value
instance = partial(instance.func, *instance.args, **new_keywords)
return instance
class Trainer: def __init__( self, model, loss_func, optimizer, callbacks=DEFAULT_CALLBACKS, run_history=None, ): self.model = model self.loss_func = loss_func self.optimizer = optimizer self.callback_handler = CallbackHandler( callbacks, ) self.run_history: RunHistory = ( run_history if run_history is not None else InMemoryRunHistory() ) self._accelerator = self._create_accelerator() self._loss_tracker = LossTracker() self.create_scheduler_fn = None self.scheduler = None self.collate_fn = None self.train_dataset = None self.eval_dataset = None self._train_dataloader = None self._train_dl_kwargs = None self._eval_dl_kwargs = None self._eval_dataloader = None self.run_config: TrainerRunConfig = None
self.callback_handler.call_event("on_init_end", self)
def _create_accelerator(self): """ Create an instance of :class:`accelerate.Accelerator` which will be used to manage training. :return: """ return Accelerator()
def create_train_dataloader( self, batch_size: int, train_dl_kwargs: dict = None ) -> Iterable: default_train_dl_kwargs = self.get_default_train_dl_kwargs(batch_size)
if train_dl_kwargs is not None: default_train_dl_kwargs.update(train_dl_kwargs)
self._train_dl_kwargs = default_train_dl_kwargs
return DataLoader( dataset=self.train_dataset, collate_fn=self.collate_fn, **self._train_dl_kwargs, )
def create_eval_dataloader( self, batch_size: int, eval_dl_kwargs: dict = None ) -> Iterable: default_eval_dl_kwargs = self.get_default_eval_dl_kwargs(batch_size)
if eval_dl_kwargs is not None: default_eval_dl_kwargs.update(eval_dl_kwargs)
self._eval_dl_kwargs = default_eval_dl_kwargs
return DataLoader( dataset=self.eval_dataset, collate_fn=self.collate_fn, **self._eval_dl_kwargs, )
def create_scheduler(self): scheduler_type = replace_trainer_placeholder_values( self, self.create_scheduler_fn ) return scheduler_type(self.optimizer)
def training_run_start(self): """ This method is called at the start of a training run. """ pass
def train_epoch_start(self): self.model.train()
def calculate_train_batch_loss(self, batch) -> dict: """ Calculates the training loss and return this along with the batch size and model outputs. Any additional values returned will be available in the :meth:`~callbacks.TrainerCallback.on_train_step_end` callback method.
:param batch: the output of the train dataloader :return: A dictionary containing the training loss, model outputs and batch size. Can include any keys, but must include the keys 'loss', 'model_outputs' and 'batch_size' """ xb, yb = batch[0], batch[1] model_outputs = self.model(xb) loss = self.loss_func(model_outputs, yb)
return { "loss": loss, "model_outputs": model_outputs, "batch_size": yb.size(0), }
def backward_step(self, loss): """ Use the accelerator to perform the backward pass on the calculated value of the loss returned by :meth:`~Trainer.calculate_train_batch_loss`. If gradient accumulation is enabled, this loss has been scaled by 1 / accumulation steps.
:param loss: The loss tensor returned by :meth:`~Trainer.calculate_train_batch_loss`. """ self._accelerator.backward(loss)
def optimizer_step(self): """ Performs a single optimization step and updates the parameters which have been passed to ``self.optimizer``. """ self.optimizer.step()
def scheduler_step(self): """ Performs a single scheduler step if ``self.scheduler`` has been assigned.
""" if self.scheduler is not None: self.scheduler.step()
def optimizer_zero_grad(self): """ Sets the gradients of all optimized ``torch.Tensor`` s to zero. """ self.optimizer.zero_grad()
def train_epoch_end(self): """ This method is called at the end of each training epoch. """ pass
def eval_epoch_start(self): """ This method is called at the start of an evaluation epoch.
The default behaviour of this method is to call ``self.model.eval()`` """ self.model.eval()
def calculate_eval_batch_loss(self, batch) -> dict: """ Calculates the evaluation loss and return this along with the batch size and model outputs. Any additional values returned will be available in the :meth:`~callbacks.TrainerCallback.on_eval_step_end` callback.
:param batch: the output of the eval dataloader :return: A dictionary containing the evaluation loss, model outputs and batch size. Can include any keys, but must include the keys ``loss``, ``model_outputs`` and ``batch_size`` """ with torch.no_grad(): xb, yb = batch[0], batch[1] model_outputs = self.model(xb) val_loss = self.loss_func(model_outputs, yb)
return { "loss": val_loss, "model_outputs": model_outputs, "batch_size": yb.size(0), }
def eval_epoch_end(self): """ This method is called at the end of an evaluation epoch. """ pass
def training_run_epoch_end(self): """ This method is called during a training run after both training and evaluation epochs have been completed. """ pass
def training_run_end(self): """ This method is called at the end of a training run. """ pass
def evaluation_run_start(self): """ This method is called at the start of an evaluation run. """ pass
def evaluation_run_end(self): """ This method is called at the end of an evaluation run. """ pass
def train( self, train_dataset, num_epochs, eval_dataset=None, per_device_batch_size=8, max_num_train_steps=None, gradient_accumulation_steps=1, gradient_clip_value=None, create_scheduler_fn: Callable = None, train_dataloader_kwargs: dict = None, eval_dataloader_kwargs: dict = None, reset_run_history=True, collate_fn=None, ): self.train_dataset = train_dataset self.eval_dataset = eval_dataset self.create_scheduler_fn = create_scheduler_fn self.collate_fn = collate_fn if reset_run_history: self.run_history.reset()
self._train_dataloader = self.create_train_dataloader( batch_size=per_device_batch_size, train_dl_kwargs=train_dataloader_kwargs )
if self.eval_dataset is not None: self._eval_dataloader = self.create_eval_dataloader( batch_size=per_device_batch_size, eval_dl_kwargs=eval_dataloader_kwargs )
self._prepare_model_optimizer_and_dataloaders()
self.run_config = self._create_run_config( num_epochs=num_epochs, gradient_accumulation_steps=gradient_accumulation_steps, max_num_train_steps=max_num_train_steps, per_device_batch_size=per_device_batch_size, gradient_clip_value=gradient_clip_value, )
if self.create_scheduler_fn is not None: self.scheduler = self.create_scheduler()
self._run_training()
def evaluate( self, dataset=None, per_device_batch_size=8, dataloader_kwargs: dict = None, collate_fn=None, ): """ Start an evaluation run.
.. Note:: Starting an evaluation run will reset the :class:`Trainer`'s run history.
.. Note:: During distributed evaluation, if the `per_device_batch_size` * the number of processes used does not exactly divide the dataset, and `drop_last=False` has not been passed as a dataloader kwarg, the dataloader will repeat from the start in processes that run out of batches. This should be taken into consideration when calculating metrics.
:param dataset: the dataset to use during evaluation :param per_device_batch_size: the batch size to use per device :param dataloader_kwargs: a dictionary of keyword arguments to pass to the dataloader constructor, for details see :class:`torch.utils.data.DataLoader` :param collate_fn: the collate function to be used by the dataloader """ self.eval_dataset = dataset self.collate_fn = collate_fn
self.run_history.reset()
self._train_dataloader = None self._eval_dataloader = self.create_eval_dataloader( batch_size=per_device_batch_size, eval_dl_kwargs=dataloader_kwargs )
self._prepare_model_optimizer_and_dataloaders()
if self.run_config is None: self.run_config = self._create_run_config( num_epochs=1, gradient_accumulation_steps=0, max_num_train_steps=None, per_device_batch_size=per_device_batch_size, gradient_clip_value=None, )
self._run_evaluation()
def get_default_train_dl_kwargs(self, batch_size) -> dict: """ Return the default arguments that will be used by the training dataloader.
:param batch_size: the batch size to use during training :return: a dictionary containing the default arguments for the training dataloader """ return { "shuffle": True, "pin_memory": True if torch.cuda.is_available() else False, "batch_size": batch_size, "num_workers": max( os.cpu_count() // torch.cuda.device_count() if torch.cuda.is_available() else os.cpu_count(), 1, ), }
def get_default_eval_dl_kwargs(self, batch_size) -> dict: """ Return the default arguments that will be used by the evaluation dataloader.
:param batch_size: the batch size to use during evaluation :return: a dictionary containing the default arguments for the evaluation dataloader """ return { "shuffle": False, "pin_memory": True if torch.cuda.is_available() else False, "batch_size": batch_size, "num_workers": max( os.cpu_count() // torch.cuda.device_count() if torch.cuda.is_available() else os.cpu_count(), 1, ), }
@property def device(self): """ Use the internal instance of :class:`accelerate.Accelerator` to get the appropriate device :return: an instance of `torch.device` """ return self._accelerator.device
def _prepare_model_optimizer_and_dataloaders(self): """ 使用`accelerate.Accelerator`将模型、优化器和数据加载器包裹在任何训练所需的包装器中,并确保参数被放置在适当的设备上。 """ self._accelerator.free_memory() self._accelerator = self._create_accelerator()
components = [self.model, self.optimizer]
if self._train_dataloader is not None: components.append(self._train_dataloader)
if self._eval_dataloader is not None: components.append(self._eval_dataloader)
prepared_components = self._accelerator.prepare(*components)
self.model = prepared_components[0] self.optimizer = prepared_components[1]
if self._train_dataloader is not None: self._train_dataloader = prepared_components[2] if self._eval_dataloader is not None: self._eval_dataloader = prepared_components[3]
elif self._eval_dataloader is not None: self._eval_dataloader = prepared_components[2]
def _create_run_config( self, per_device_batch_size, num_epochs, gradient_accumulation_steps, max_num_train_steps, gradient_clip_value, ) -> TrainerRunConfig: if self._train_dl_kwargs is not None: train_per_device_batch_size = self._train_dl_kwargs.get( "batch_size", per_device_batch_size ) else: train_per_device_batch_size = per_device_batch_size
if self._eval_dl_kwargs is not None: eval_per_device_batch_size = self._eval_dl_kwargs.get( "batch_size", train_per_device_batch_size ) else: eval_per_device_batch_size = train_per_device_batch_size
if self._train_dataloader is not None:
num_update_steps_per_epoch = math.ceil( len(self._train_dataloader) / gradient_accumulation_steps ) else: num_update_steps_per_epoch = 0
if max_num_train_steps is None: max_num_train_steps = num_epochs * num_update_steps_per_epoch else: num_epochs = math.ceil(max_num_train_steps / num_update_steps_per_epoch)
config = { "num_epochs": num_epochs, "train_per_device_batch_size": train_per_device_batch_size, "train_dl_kwargs": self._train_dl_kwargs, "eval_per_device_batch_size": eval_per_device_batch_size, "eval_dl_kwargs": self._eval_dl_kwargs, "gradient_accumulation_steps": gradient_accumulation_steps, "train_total_batch_size": train_per_device_batch_size * self._accelerator.num_processes * gradient_accumulation_steps, "eval_total_batch_size": eval_per_device_batch_size * self._accelerator.num_processes, "num_update_steps_per_epoch": num_update_steps_per_epoch, "max_num_train_steps": max_num_train_steps, "is_local_process_zero": self._accelerator.is_local_main_process, "is_world_process_zero": self._accelerator.is_main_process, "is_distributed": True if self._accelerator.distributed_type != DistributedType.NO else False, "mixed_precision": self._accelerator.mixed_precision, "gradient_clip_value": gradient_clip_value, }
return TrainerRunConfig(**config)
def _run_training(self): self.training_run_start() self.callback_handler.call_event( "on_training_run_start", self, )
for epoch in range(self.run_config.num_epochs): try: self._run_train_epoch(self._train_dataloader)
if self.eval_dataset is not None: self._run_eval_epoch(self._eval_dataloader) self.run_history._increment_epoch() self.training_run_epoch_end() self.callback_handler.call_event( "on_training_run_epoch_end", self, ) except StopTrainingError as e: self._accelerator.print(e) self.callback_handler.call_event( "on_stop_training_error", self, ) break self.training_run_end() self.callback_handler.call_event( "on_training_run_end", self, )
def _run_evaluation(self): """ The method responsible for the orchestration of the high level steps which will be executed during an evaluation run. """ self.evaluation_run_start() self.callback_handler.call_event( "on_evaluation_run_start", self, ) try: self._run_eval_epoch(self._eval_dataloader, is_training=False) except StopTrainingError as e: self._accelerator.print(e) self.callback_handler.call_event( "on_stop_training_error", self, ) self.evaluation_run_end() self.callback_handler.call_event( "on_evaluation_run_end", self, )
def _run_train_epoch(self, train_dl): self.train_epoch_start() self._loss_tracker.reset() self.callback_handler.call_event( "on_train_epoch_start", self, ) for step, batch in enumerate(train_dl): self.callback_handler.call_event( "on_train_step_start", self, )
perform_gradient_update = ( (step + 1) % self.run_config.gradient_accumulation_steps == 0 ) or (step + 1 == len(train_dl))
if not perform_gradient_update: with self._accelerator.no_sync(self.model): self._perform_forward_and_backward_passes(batch) else: self._perform_forward_and_backward_passes(batch)
if self.run_config.gradient_clip_value is not None: self._clip_gradients()
if perform_gradient_update: self.optimizer_step() if ( self.scheduler is not None and not self._accelerator.optimizer_step_was_skipped ): self.scheduler_step() self.optimizer_zero_grad()
self.train_epoch_end() self.run_history.update_metric("train_loss_epoch", self._loss_tracker.average) self.callback_handler.call_event( "on_train_epoch_end", self, )
def _perform_forward_and_backward_passes(self, batch): batch_output = self.calculate_train_batch_loss(batch) if self.run_config.gradient_accumulation_steps > 1: batch_output["loss"] /= self.run_config.gradient_accumulation_steps
self._loss_tracker.update( self.gather(batch_output["loss"]).detach().mean().item(), batch_output["batch_size"], )
self.callback_handler.call_event( "on_train_step_end", self, batch_output=batch_output, batch=batch ) self.backward_step(batch_output["loss"])
def _clip_gradients(self): """ Clip the gradients of the model's parameters that fall outside of the threshold specified in :meth:`~Trainer.train`.
By default, this clips the gradients using :meth:`accelerate.Accelerator.clip_grad_value_` """ self._accelerator.clip_grad_value_( self.model.parameters(), clip_value=self.run_config.gradient_clip_value )
def _run_eval_epoch(self, valid_dl, is_training: bool = True): """ The method responsible for the behaviour of each evaluation epoch.
:param valid_dl: the dataloader to be used during evaluation :param is_training: signals whether the evaluation is being run as part of a training run """ self.eval_epoch_start() self._loss_tracker.reset() self.callback_handler.call_event( "on_eval_epoch_start", self, )
for batch in valid_dl: self.callback_handler.call_event( "on_eval_step_start", self, ) batch_output = self.calculate_eval_batch_loss(batch) self._loss_tracker.update( self.gather(batch_output["loss"]).detach().mean().item(), batch_output["batch_size"], ) self.callback_handler.call_event( "on_eval_step_end", self, batch_output=batch_output, batch=batch ) self.eval_epoch_end() metric_name = "eval_loss_epoch" if is_training else "evaluation_loss" self.run_history.update_metric(metric_name, self._loss_tracker.average) self.callback_handler.call_event( "on_eval_epoch_end", self, )
def gather(self, tensor): """ Gather the values in `tensor` across all processes and concatenate them on the first dimension. This can be useful to regroup the predictions from all processes when doing evaluation.
.. Note:: This gather happens in all processes.
:param tensor: (:obj:`torch.Tensor`, or a nested tuple/list/dictionary of :obj:`torch.Tensor`) The tensors to gather across all processes. :return: The gathered tensor(s) (:obj:`torch.Tensor`, or a nested tuple/list/dictionary of :obj:`torch.Tensor`). The first dimension of the result is `num_processes` multiplied by the first dimension of the input tensors. """ return self._accelerator.gather(tensor)
def print(self, *args, **kwargs): """ Use in replacement of ``print()`` to only print once per node. """ if self._accelerator is not None: self._accelerator.print(*args, **kwargs) else: print(*args, **kwargs)
def save_checkpoint( self, save_path, checkpoint_kwargs=None, save_optimizer=True, save_per_node=True ): """ Save the model, optimizer and specified args as a checkpoint file.
:param save_path: the path where to save the checkpoint, this should end in '.pt' :param checkpoint_kwargs: additional objects to include in the checkpoint :param save_optimizer: flag to indicate whether to include the optimizer in the checkpoint :param save_per_node: flag to indicate whether to save the checkpoint once per machine, if False, the checkpoint will only be saved from the world process zero. This is True by default. """
checkpoint = { "model_state_dict": self._accelerator.unwrap_model(self.model).state_dict(), }
if save_optimizer: checkpoint["optimizer_state_dict"] = self.optimizer.state_dict()
if checkpoint_kwargs is not None: checkpoint.update(checkpoint_kwargs)
self._accelerator.wait_for_everyone()
if save_per_node:
self._accelerator.save( checkpoint, save_path, ) else:
if self.run_config.is_world_process_zero: self._accelerator.save( checkpoint, save_path, )
def load_checkpoint(self, checkpoint_path, load_optimizer=True): """ Load the model and optimizer from a checkpoint file.
:param checkpoint_path: the path of the checkpoint file to load :param load_optimizer: flag to indicate whether to load the optimizer if it is included in the checkpoint """ self._accelerator.wait_for_everyone() checkpoint = torch.load(checkpoint_path, map_location="cpu") self._accelerator.unwrap_model(self.model).load_state_dict( checkpoint["model_state_dict"] ) if load_optimizer and "optimizer_state_dict" in checkpoint: if self.optimizer is None: raise ValueError( "You are trying to load an optimizer from a checkpoint, but no optimizer" "has been set in the Trainer. Either pass the correct optimizer instance when" "creating the trainer, or specify load_optimizer=False when loading the checkpoint." ) self.optimizer.load_state_dict(checkpoint["optimizer_state_dict"])
class TrainerWithTimmScheduler(Trainer): """Subclass of the :class:`Trainer` that works with `timm schedulers <https://fastai.github.io/timmdocs/schedulers>`_ instead of standard PyTorch learning rate schedulers """
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.num_updates = None
def train_epoch_start(self): super().train_epoch_start() self.num_updates = self.run_history.current_epoch * len(self._train_dataloader)
def eval_epoch_end(self): if self.scheduler is not None: self.scheduler.step(self.run_history.current_epoch + 1)
def scheduler_step(self): self.num_updates += 1 if self.scheduler is not None: self.scheduler.step_update(num_updates=self.num_updates)
|