Skip to content

unitorch.cli.tasks.supervised¤

SupervisedTask¤

Tip

core/task/supervised is the section for configuration of SupervisedTask.

Initialize the SupervisedTask.

Parameters:

Name Type Description Default
configure

The configuration object.

required
model

The model for the task.

required
datasets

The datasets for training and evaluation.

required
local_rank optional

The local rank for distributed training. Defaults to -1.

-1
seed optional

The random seed. Defaults to 1123.

1123
Source code in src/unitorch/cli/tasks/supervised.py
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
def __init__(
    self,
    configure,
    model,
    datasets,
    local_rank: Optional[int] = -1,
    seed: Optional[int] = 1123,
    cpu_offload: Optional[bool] = False,
):
    """
    Initialize the SupervisedTask.

    Args:
        configure: The configuration object.
        model: The model for the task.
        datasets: The datasets for training and evaluation.
        local_rank (optional): The local rank for distributed training. Defaults to -1.
        seed (optional): The random seed. Defaults to 1123.
    """
    set_seed(seed)
    self.n_gpu = 1 if torch.cuda.is_available() else 0
    if dist.is_initialized():
        self.n_gpu = dist.get_world_size()

    self.config = configure
    self.model = model
    self.datasets = datasets
    self.local_rank = local_rank

    if self.local_rank != -1:
        torch.cuda.set_device(self.local_rank)

    if torch.cuda.is_available() and not cpu_offload:
        self.model = self.model.cuda()

    self.best_score = -np.inf

eval ¤

eval(
    monitor_fns: Union[str, List[str]],
    from_ckpt_dir: Optional[str] = "./from_ckpt",
    dev_batch_size: Optional[int] = 128,
    pin_memory: Optional[bool] = True,
    num_workers: Optional[int] = 4,
)

Perform evaluation on the model.

Parameters:

Name Type Description Default
monitor_fns Union[str, List[str]]

The monitoring functions for evaluation.

required
from_ckpt_dir optional

The directory path to load checkpoints from. Defaults to "./from_ckpt".

'./from_ckpt'
dev_batch_size optional

The batch size for evaluation. Defaults to 128.

128
pin_memory optional

Whether to pin memory during data loading. Defaults to True.

True
num_workers optional

The number of worker processes for data loading. Defaults to 4.

4
Source code in src/unitorch/cli/tasks/supervised.py
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
@torch.no_grad()
@add_default_section_for_function("core/task/supervised")
def eval(
    self,
    monitor_fns: Union[str, List[str]],
    from_ckpt_dir: Optional[str] = "./from_ckpt",
    dev_batch_size: Optional[int] = 128,
    pin_memory: Optional[bool] = True,
    num_workers: Optional[int] = 4,
):
    """
    Perform evaluation on the model.

    Args:
        monitor_fns: The monitoring functions for evaluation.
        from_ckpt_dir (optional): The directory path to load checkpoints from. Defaults to "./from_ckpt".
        dev_batch_size (optional): The batch size for evaluation. Defaults to 128.
        pin_memory (optional): Whether to pin memory during data loading. Defaults to True.
        num_workers (optional): The number of worker processes for data loading. Defaults to 4.
    """
    monitor_fns = [
        init_registered_module(monitor_fn, self.config, registered_score)
        for monitor_fn in monitor_fns
        if monitor_fn in registered_score
    ]

    if os.path.exists(from_ckpt_dir):
        self.model.from_checkpoint(from_ckpt_dir)

    global_rank = -1
    if self.n_gpu > 1:
        self.model = nn.parallel.DistributedDataParallel(
            self.model,
            device_ids=[self.local_rank],
            output_device=self.local_rank,
            find_unused_parameters=False,
            broadcast_buffers=False,
        )
        global_rank = dist.get_rank()

    dev_sampler = DistributedSampler if self.n_gpu > 1 else SequentialSampler
    dataset_dev = self.datasets.get("dev")
    iter_dev = DataLoader(
        dataset_dev,
        sampler=dev_sampler(dataset_dev)
        if not isinstance(dataset_dev, Iterable)
        else None,
        batch_size=dev_batch_size,
        shuffle=False,
        pin_memory=pin_memory,
        num_workers=num_workers,
        collate_fn=collate_fn,
    )

    results = infer(self.model.module if self.n_gpu > 1 else self.model, iter_dev)
    if global_rank in [-1, 0]:
        monitor(
            outputs=results.outputs,
            targets=results.targets,
            monitor_fns=monitor_fns,
        )

from_core_configure classmethod ¤

from_core_configure(config, **kwargs)

Create a SupervisedTask instance from the core configuration.

Parameters:

Name Type Description Default
config

The core configuration object.

required
**kwargs

Additional keyword arguments.

{}

Returns:

Type Description

A dictionary containing the configuration, model, datasets, and local rank.

Source code in src/unitorch/cli/tasks/supervised.py
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
@classmethod
@add_default_section_for_init("core/task/supervised")
def from_core_configure(cls, config, **kwargs):
    """
    Create a SupervisedTask instance from the core configuration.

    Args:
        config: The core configuration object.
        **kwargs: Additional keyword arguments.

    Returns:
        A dictionary containing the configuration, model, datasets, and local rank.
    """
    try:
        torch.distributed.init_process_group(backend="nccl", init_method="env://")
    except:
        logging.info("PyTorch is not in distributed mode")

    config.set_default_section("core/task/supervised")

    model = config.getoption("model", None)
    dataset = config.getoption("dataset", None)

    if model is not None:
        model = init_registered_module(model, config, registered_model)

    if dataset is not None:
        dataset = init_registered_module(dataset, config, registered_dataset)

    local_rank = config.getdefault(
        "core/cli",
        "local_rank",
        get_local_rank(),
    )
    cpu_offload = config.getoption("cpu_offload", False)

    return dict(
        configure=config,
        model=model,
        datasets=dataset,
        local_rank=local_rank,
        cpu_offload=cpu_offload,
    )

infer ¤

infer(
    postprocess_fn: str,
    writer: str,
    test_batch_size: Optional[int] = 128,
    pin_memory: Optional[bool] = True,
    num_workers: Optional[int] = 4,
    max_size: Optional[int] = 10000,
    from_ckpt_dir: Optional[str] = "./from_ckpt",
    output_header: Optional[List] = None,
    output_path: Optional[str] = "./output.txt",
    postprocess_workers: Optional[int] = 2,
)

Perform inference using the model.

Parameters:

Name Type Description Default
postprocess_fn str

The postprocessing function for inference.

required
writer str

The writer to save the inference results.

required
test_batch_size optional

The batch size for inference. Defaults to 128.

128
pin_memory optional

Whether to pin memory during data loading. Defaults to True.

True
num_workers optional

The number of worker processes for data loading. Defaults to 4.

4
max_size optional

The maximum number of samples to process. Defaults to 10000.

10000
from_ckpt_dir optional

The directory path to load checkpoints from. Defaults to "./from_ckpt".

'./from_ckpt'
output_header optional

The header for the output file. Defaults to None.

None
output_path optional

The path to save the output file. Defaults to "./output.txt".

'./output.txt'
postprocess_workers optional

The number of worker processes for postprocessing. Defaults to 2.

2
Source code in src/unitorch/cli/tasks/supervised.py
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
@torch.no_grad()
@add_default_section_for_function("core/task/supervised")
def infer(
    self,
    postprocess_fn: str,
    writer: str,
    test_batch_size: Optional[int] = 128,
    pin_memory: Optional[bool] = True,
    num_workers: Optional[int] = 4,
    max_size: Optional[int] = 10000,
    from_ckpt_dir: Optional[str] = "./from_ckpt",
    output_header: Optional[List] = None,
    output_path: Optional[str] = "./output.txt",
    postprocess_workers: Optional[int] = 2,
):
    """
    Perform inference using the model.

    Args:
        postprocess_fn: The postprocessing function for inference.
        writer: The writer to save the inference results.
        test_batch_size (optional): The batch size for inference. Defaults to 128.
        pin_memory (optional): Whether to pin memory during data loading. Defaults to True.
        num_workers (optional): The number of worker processes for data loading. Defaults to 4.
        max_size (optional): The maximum number of samples to process. Defaults to 10000.
        from_ckpt_dir (optional): The directory path to load checkpoints from. Defaults to "./from_ckpt".
        output_header (optional): The header for the output file. Defaults to None.
        output_path (optional): The path to save the output file. Defaults to "./output.txt".
        postprocess_workers (optional): The number of worker processes for postprocessing. Defaults to 2.
    """
    assert self.n_gpu <= 1
    assert writer is not None

    output_dir = os.path.dirname(output_path)
    if not os.path.exists(output_dir):
        os.makedirs(output_dir, exist_ok=True)

    if postprocess_fn is not None:
        postprocess_fn = init_registered_process(postprocess_fn, self.config)

    if writer is not None:
        writer = init_registered_module(
            writer,
            self.config,
            registered_writer,
            output_file=output_path,
        )

    skip_step = writer.skip_n_samples

    if os.path.exists(from_ckpt_dir):
        self.model.from_checkpoint(from_ckpt_dir)

    if skip_step == 0:
        sampler = SequentialSampler
    else:
        sampler = SequentialSkipSampler

    dataset_test = self.datasets.get("test")

    iter_test = DataLoader(
        dataset_test,
        sampler=sampler(dataset_test)
        if not isinstance(dataset_test, Iterable)
        else None,
        batch_size=test_batch_size,
        shuffle=False,
        pin_memory=pin_memory,
        num_workers=num_workers,
        collate_fn=collate_fn,
    )

    if skip_step > 0 and hasattr(dataset_test, "set_skip_step"):
        dataset_test.set_skip_step(skip_step)

    if skip_step > 0 and hasattr(iter_test.sampler, "set_skip_step"):
        iter_test.sampler.set_skip_step(skip_step)

    if hasattr(dataset_test, "dataset"):
        data_info = dataset_test.dataset
        data_info = DatasetFeature(data_info)
        iter_data = DataLoader(
            deepcopy(data_info),
            sampler=sampler(data_info)
            if not isinstance(dataset_test, Iterable)
            else None,
            batch_size=test_batch_size,
            shuffle=False,
            pin_memory=pin_memory,
            num_workers=num_workers,
            collate_fn=None,
        )
    else:
        iter_data = None

    if skip_step > 0 and hasattr(iter_data.sampler, "set_skip_step"):
        iter_data.sampler.set_skip_step(skip_step)

    self.model.eval()
    start = time.time()

    data_queue = Queue(maxsize=max_size)
    msg_queue = Queue(maxsize=max_size)
    postprocess_list = []
    for _ in range(postprocess_workers):
        p = PostProcess(
            postprocess_fn,
            data_queue,
            msg_queue,
        )
        postprocess_list.append(p)
        p.start()

    io_process = IOProcess(msg_queue, writer=writer)
    io_process.start()

    if iter_data is None:
        for step, (inputs, _) in enumerate(iter_test):
            if torch.cuda.is_available():
                inputs = inputs.cuda()
            outputs = self.model(**inputs.dict())
            outputs = outputs.cpu()
            data_queue.put((step, outputs))
    else:
        for step, ((inputs, _), _infos) in enumerate(zip(iter_test, iter_data)):
            if torch.cuda.is_available():
                inputs = inputs.cuda()
            outputs = self.model(**inputs.dict())
            outputs = outputs.cpu()
            if output_header is not None:
                _infos = {k: _infos[k] for k in output_header if k in _infos}
                outputs.from_pandas(pd.DataFrame(_infos))
            data_queue.put((step, outputs))

    data_queue.put((-1, GENERATE_FINISHED))
    for p in postprocess_list:
        p.join()

    msg_queue.put((-1, GENERATE_FINISHED))
    io_process.join()

    end = time.time()
    ms = (end - start) * 1000
    logging.info(
        "{:.2f} ms, {:.2f} sample/s".format(
            ms,
            ((len(dataset_test) - skip_step) / ms * 1000),
        )
    )

train ¤

train(
    optim: str,
    loss_fn: str,
    score_fn: str,
    monitor_fns: Optional[Union[str, List[str]]] = None,
    scheduler: Optional[str] = None,
    from_ckpt_dir: Optional[str] = "./from_ckpt",
    to_ckpt_dir: Optional[str] = "./to_ckpt",
    train_batch_size: Optional[int] = 128,
    dev_batch_size: Optional[int] = 128,
    pin_memory: Optional[bool] = True,
    num_workers: Optional[int] = 4,
    save_optimizer: Optional[bool] = True,
    save_scheduler: Optional[bool] = True,
    save_checkpoint: Optional[str] = "all",
    log_freq: Optional[int] = 100,
    ckpt_freq: Optional[int] = 10000,
    grad_acc_step: Optional[int] = 1,
    max_grad_norm: Optional[float] = 1.0,
    num_training_samples: Optional[int] = 1000000000,
    epochs: Optional[int] = 5,
    use_ema: Optional[bool] = False,
    ema_decay: Optional[float] = 0.9999,
    ema_tau: Optional[int] = 2000,
)

Train the model.

Parameters:

Name Type Description Default
optim str

The optimizer for training.

required
loss_fn str

The loss function for training.

required
score_fn str

The scoring function for evaluation.

required
monitor_fns optional

The monitoring functions for evaluation. Defaults to None.

None
scheduler optional

The scheduler for adjusting the learning rate. Defaults to None.

None
from_ckpt_dir optional

The directory path to load checkpoints from. Defaults to "./from_ckpt".

'./from_ckpt'
to_ckpt_dir optional

The directory path to save checkpoints to. Defaults to "./to_ckpt".

'./to_ckpt'
train_batch_size optional

The batch size for training. Defaults to 128.

128
dev_batch_size optional

The batch size for evaluation. Defaults to 128.

128
pin_memory optional

Whether to pin memory during data loading. Defaults to True.

True
num_workers optional

The number of worker processes for data loading. Defaults to 4.

4
save_optimizer optional

Whether to save the optimizer. Defaults to True.

True
save_scheduler optional

Whether to save the scheduler. Defaults to True.

True
log_freq optional

The frequency of logging training information. Defaults to 100.

100
ckpt_freq optional

The frequency of saving checkpoints. Defaults to 10000.

10000
grad_acc_step optional

The number of gradient accumulation steps. Defaults to 1.

1
max_grad_norm optional

The maximum gradient norm for gradient clipping. Defaults to 1.0.

1.0
num_training_samples optional

The number of training samples. Defaults to 1000000000.

1000000000
epochs optional

The number of training epochs. Defaults to 5.

5
use_ema optional

Whether to use exponential moving average. Defaults to False.

False
ema_decay optional

The decay rate for exponential moving average. Defaults to 0.9999.

0.9999
ema_tau optional

The time constant for exponential moving average. Defaults to 2000.

2000
gpu_mode optional

Whether to make GPU active. Defaults to False.

required
Source code in src/unitorch/cli/tasks/supervised.py
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
@add_default_section_for_function("core/task/supervised")
def train(
    self,
    optim: str,
    loss_fn: str,
    score_fn: str,
    monitor_fns: Optional[Union[str, List[str]]] = None,
    scheduler: Optional[str] = None,
    from_ckpt_dir: Optional[str] = "./from_ckpt",
    to_ckpt_dir: Optional[str] = "./to_ckpt",
    train_batch_size: Optional[int] = 128,
    dev_batch_size: Optional[int] = 128,
    pin_memory: Optional[bool] = True,
    num_workers: Optional[int] = 4,
    save_optimizer: Optional[bool] = True,
    save_scheduler: Optional[bool] = True,
    save_checkpoint: Optional[str] = "all",
    log_freq: Optional[int] = 100,
    ckpt_freq: Optional[int] = 10000,
    grad_acc_step: Optional[int] = 1,
    max_grad_norm: Optional[float] = 1.0,
    num_training_samples: Optional[int] = 1000000000,
    epochs: Optional[int] = 5,
    use_ema: Optional[bool] = False,
    ema_decay: Optional[float] = 0.9999,
    ema_tau: Optional[int] = 2000,
):
    """
    Train the model.

    Args:
        optim: The optimizer for training.
        loss_fn: The loss function for training.
        score_fn: The scoring function for evaluation.
        monitor_fns (optional): The monitoring functions for evaluation. Defaults to None.
        scheduler (optional): The scheduler for adjusting the learning rate. Defaults to None.
        from_ckpt_dir (optional): The directory path to load checkpoints from. Defaults to "./from_ckpt".
        to_ckpt_dir (optional): The directory path to save checkpoints to. Defaults to "./to_ckpt".
        train_batch_size (optional): The batch size for training. Defaults to 128.
        dev_batch_size (optional): The batch size for evaluation. Defaults to 128.
        pin_memory (optional): Whether to pin memory during data loading. Defaults to True.
        num_workers (optional): The number of worker processes for data loading. Defaults to 4.
        save_optimizer (optional): Whether to save the optimizer. Defaults to True.
        save_scheduler (optional): Whether to save the scheduler. Defaults to True.
        log_freq (optional): The frequency of logging training information. Defaults to 100.
        ckpt_freq (optional): The frequency of saving checkpoints. Defaults to 10000.
        grad_acc_step (optional): The number of gradient accumulation steps. Defaults to 1.
        max_grad_norm (optional): The maximum gradient norm for gradient clipping. Defaults to 1.0.
        num_training_samples (optional): The number of training samples. Defaults to 1000000000.
        epochs (optional): The number of training epochs. Defaults to 5.
        use_ema (optional): Whether to use exponential moving average. Defaults to False.
        ema_decay (optional): The decay rate for exponential moving average. Defaults to 0.9999.
        ema_tau (optional): The time constant for exponential moving average. Defaults to 2000.
        gpu_mode (optional): Whether to make GPU active. Defaults to False.
    """
    if not os.path.exists(to_ckpt_dir) and self.local_rank in [-1, 0]:
        os.makedirs(to_ckpt_dir, exist_ok=True)

    if loss_fn is not None:
        loss_fn = init_registered_module(loss_fn, self.config, registered_loss)

    if score_fn is not None:
        score_fn = init_registered_module(score_fn, self.config, registered_score)

    if monitor_fns is not None:
        monitor_fns = [
            init_registered_module(monitor_fn, self.config, registered_score)
            for monitor_fn in monitor_fns
            if monitor_fn in registered_score
        ]

    if optim is not None and self.model is not None:
        optim = init_registered_module(
            optim,
            self.config,
            registered_optim,
            params=filter(lambda x: x.requires_grad, self.model.parameters()),
        )

    if os.path.exists(from_ckpt_dir):
        self.model.from_checkpoint(from_ckpt_dir)
        optim.from_checkpoint(
            from_ckpt_dir,
            weight_name="pytorch_optim.bin",
        )

    if os.path.exists(to_ckpt_dir):
        self.model.from_checkpoint(
            to_ckpt_dir,
            weight_name="pytorch_model_latest.bin",
        )
        optim.from_checkpoint(
            to_ckpt_dir,
            weight_name="pytorch_optim_latest.bin",
        )

    info_path = os.path.join(to_ckpt_dir, "info.json")
    if os.path.exists(info_path):
        info = json.load(open(os.path.join(to_ckpt_dir, "info.json")))
    else:
        info = dict()

    global_epoch = info.get("global_epoch", 0)
    global_step = info.get("global_step", 0)
    self.best_score = info.get("best_score", self.best_score)

    logging.info(f"the best score is {self.best_score}")

    self.ema_model = None
    if use_ema:
        num_ema_steps = info.get("num_ema_steps", 0)
        self.ema_model = ExponentialMovingAverage(
            self.model,
            decay=ema_decay,
            tau=ema_tau,
            num_steps=num_ema_steps,
        )
        if os.path.exists(from_ckpt_dir):
            self.ema_model.from_checkpoint(
                from_ckpt_dir,
                weight_name="pytorch_ema_model.bin",
            )
        if os.path.exists(to_ckpt_dir):
            self.ema_model.from_checkpoint(
                to_ckpt_dir,
                weight_name="pytorch_ema_model_latest.bin",
            )

    for n, p in self.model.named_parameters():
        logging.debug(
            f"{n}: trainable - {p.requires_grad} | tensor dtype - {p.dtype} | tensor shape - {p.shape}"
        )

    global_rank = -1
    if self.n_gpu > 1:
        self.model = nn.parallel.DistributedDataParallel(
            self.model,
            device_ids=[self.local_rank],
            output_device=self.local_rank,
            find_unused_parameters=True,
            broadcast_buffers=False,
        )
        global_rank = dist.get_rank()

    train_sampler = DistributedSkipSampler if self.n_gpu > 1 else RandomSkipSampler
    dev_sampler = DistributedSampler if self.n_gpu > 1 else SequentialSampler

    dataset_train = self.datasets.get("train")
    dataset_dev = self.datasets.get("dev")

    iter_train = DataLoader(
        dataset_train,
        sampler=train_sampler(dataset_train)
        if not isinstance(dataset_train, Iterable)
        else None,
        batch_size=train_batch_size,
        shuffle=False,
        pin_memory=pin_memory,
        num_workers=num_workers,
        collate_fn=collate_fn,
    )

    iter_dev = DataLoader(
        dataset_dev,
        sampler=dev_sampler(dataset_dev)
        if not isinstance(dataset_dev, Iterable)
        else None,
        batch_size=dev_batch_size,
        shuffle=False,
        pin_memory=pin_memory,
        num_workers=num_workers,
        collate_fn=collate_fn,
    )

    if scheduler is not None:
        if not isinstance(dataset_train, Iterable):
            num_training_steps = int(
                epochs
                * len(dataset_train)
                // train_batch_size
                // max(1, self.n_gpu)
                // grad_acc_step
            )
        else:
            num_training_steps = int(
                epochs
                * num_training_samples
                // train_batch_size
                // max(1, self.n_gpu)
                // grad_acc_step
            )

        scheduler = init_registered_module(
            scheduler,
            self.config,
            registered_scheduler,
            optimizer=optim,
            num_training_steps=num_training_steps,
        )

    if scheduler and os.path.exists(to_ckpt_dir):
        scheduler.from_checkpoint(
            to_ckpt_dir,
            weight_name="pytorch_scheduler_latest.bin",
        )

    scaler = GradScaler()

    log_loss = 0
    dev_epoch = 0
    for e in range(0, epochs):
        torch.cuda.empty_cache()
        if e < global_epoch:
            continue

        if hasattr(dataset_train, "set_epoch"):
            dataset_train.set_epoch(e)

        if hasattr(dataset_train, "set_skip_step"):
            dataset_train.set_skip_step(global_step * train_batch_size)

        if hasattr(iter_train.sampler, "set_epoch"):
            iter_train.sampler.set_epoch(e)

        if hasattr(iter_train.sampler, "set_skip_step"):
            iter_train.sampler.set_skip_step(global_step * train_batch_size)

        self.model.train()
        is_update_step = True
        for step, (inputs, targets) in enumerate(iter_train):
            step = step + global_step
            is_update_step = False
            if torch.cuda.is_available():
                inputs = inputs.cuda()
                targets = targets.cuda()

            with torch.autocast(enabled=True):
                outputs = self.model(**inputs.dict())
                if isinstance(outputs, LossOutputs):
                    loss = outputs.loss / grad_acc_step
                else:
                    loss = loss_fn(outputs=outputs, targets=targets) / grad_acc_step

            nn.utils.clip_grad_norm_(self.model.parameters(), max_grad_norm)
            scaler.scale(loss).backward()
            log_loss += loss.data * grad_acc_step
            if (step + 1) % grad_acc_step == 0:
                is_update_step = True
                scaler.step(optim)
                scaler.update()
                if scheduler is not None:
                    scheduler.step()
                optim.zero_grad()

                if use_ema and self.ema_model is not None:
                    self.ema_model.step(
                        self.model.module if self.n_gpu > 1 else self.model
                    )

            if (step + 1) % log_freq == 0 and global_rank in [-1, 0]:
                logging.info(
                    f"epoch {e} step {step}: loss -- { log_loss / log_freq }"
                )
                log_loss = 0

            if (step + 1) % ckpt_freq == 0:
                if hasattr(dataset_dev, "set_epoch"):
                    dataset_dev.set_epoch(dev_epoch)

                if hasattr(iter_dev.sampler, "set_epoch"):
                    iter_dev.sampler.set_epoch(dev_epoch)

                dev_epoch += 1
                self.best_score = save_snapshot(
                    self.model.module if self.n_gpu > 1 else self.model,
                    to_ckpt_dir,
                    iter_dev,
                    score_fn,
                    monitor_fns,
                    optim=optim if save_optimizer else None,
                    scheduler=scheduler if save_scheduler else None,
                    save_checkpoint=save_checkpoint,
                    ema_model=self.ema_model if use_ema else None,
                    best_score=self.best_score,
                    info_path=info_path,
                    local_rank=self.local_rank,
                    global_epoch=e,
                    global_step=step + 1,
                )

        if not is_update_step:
            scaler.step(optim)
            scaler.update()
            if scheduler is not None:
                scheduler.step()
            optim.zero_grad()

            if use_ema and self.ema_model is not None:
                self.ema_model.step(
                    self.model.module if self.n_gpu > 1 else self.model
                )

        log_loss = 0

        if hasattr(dataset_dev, "set_epoch"):
            dataset_dev.set_epoch(dev_epoch)

        if hasattr(iter_dev.sampler, "set_epoch"):
            iter_dev.sampler.set_epoch(dev_epoch)

        dev_epoch += 1

        global_step = 0
        self.best_score = save_snapshot(
            self.model.module if self.n_gpu > 1 else self.model,
            to_ckpt_dir,
            iter_dev,
            score_fn,
            monitor_fns,
            optim=optim if save_optimizer else None,
            scheduler=scheduler if save_scheduler else None,
            save_checkpoint=save_checkpoint,
            ema_model=self.ema_model if use_ema else None,
            best_score=self.best_score,
            info_path=info_path,
            local_rank=self.local_rank,
            global_epoch=e,
            global_step=0,
        )