跳转至

BaseRunner

danling.runner.BaseRunner

Base class for all runners.

BaseRunner sets up basic running environment, including seed, deterministic, and logging.

BaseRunner also provides some basic methods, such as, step, state_dict, save_checkpoint, load_checkpoint.

BaseRunner defines all basic attributes and relevant properties such as scores, progress, etc.

ID:

Name Type Description
timestamp str

A time string representing the creation time of run.

name str

f"{self.config.experiment_name}-{self.config.run_name}".

id str

f"{self.config.experiment_id:.8}{self.config.run_id:.8}".

uuid (UUID, property)

uuid5(self.config.run_id, self.id).

Core:

Name Type Description
mode (RunnerMode, property)

Running mode.

config Config

Running config. See [Config] for details.

Model:

Name Type Description
model Callable
criterion Callable
optimizer Any | None
scheduler Any | None

Data:

Name Type Description
datasets FlatDict

All datasets, should be in the form of {subset: dataset}. Initialised to FlatDict by default.

datasamplers FlatDict

All datasamplers, should be in the form of {subset: datasampler}. Initialised to FlatDict by default.

dataloaders FlatDict

All dataloaders, should be in the form of {subset: dataloader}. Initialised to FlatDict by default.

split str

Current running split.

batch_size (int, property)

Number of samples per batch in current running split.

batch_size_equivalent (int, property)

Total batch_size (batch_size * world_size * accum_steps).

datasets, datasamplers, dataloaders should be a dict with the same keys. Their keys should be split (e.g. train, val, test).

Progress:

Name Type Description
progress (float, property)

Running Progress, in range(0, 1).

Results:

Name Type Description
results NestedDict

Results include all metric information of the model. Results should be in the form of {epoch: {subset: {metric: score}}}.

latest_result (NestedDict, property)

Most recent result, should be in the form of {subset: {metric: score}}.

best_result (NestedDict, property)

Best result, should be in the form of {subset: {metric: score}}.

scores (List[float], property)

Score is the core metric that is used to evaluate the performance of the model. Scores should be in the form of {epoch: score}.

latest_score (float, property)

Most recent score, should be in the form of score.

best_score (float, property)

Best score, should be in the form of score.

score_split Optional[str]

The subset to calculate the score. If is None, will use the last set of the result.

score_name str

The metric name of score. Defaults to "loss".

is_best (bool, property)

If latest_score == best_score.

A result is a dict with the same split as keys, like dataloaders. A typical result shall look like this:

Python
{
    "train": {
        "loss": 0.1,
        "accuracy": 0.9,
    },
    "val": {
        "loss": 0.2,
        "accuracy": 0.8,
    },
    "test": {
        "loss": 0.3,
        "accuracy": 0.7,
    },
}

scores are dynamically extracted from results by score_split and score_name. They represent the core metric that is used in comparing the performance against different models and settings. For the above results, If score_split = "val", score_name = "accuracy", then scores = 0.9.

IO:

Name Type Description
dir (str, property)

Directory of the run. Defaults to ${self.project_root}/${self.name}-${self.id}/${self.timestamp}).

checkpoint_dir (str, property)

Directory of checkpoints.

log_path (str, property)

Path of log file.

checkpoint_dir_name str

The name of the directory under runner.dir to save checkpoints. Defaults to "checkpoints".

Parallel Training:

Name Type Description
world_size (int, property)

Number of processes.

rank (int, property)

Process index of all processes.

local_rank (int, property)

Process index of local processes.

distributed (bool, property)

If runner is running in distributed mode.

is_main_process (bool, property)

If current process is the main process of all processes.

is_local_main_process (bool, property)

If current process is the main process of local processes.

logging:

Name Type Description
meters AverageMeters | MultiTaskAverageMeters

Average meters. Initialised to AverageMeters by default.

metrics Metrics | MultiTaskMetrics | MetricMeters | None

Metrics for evaluating.

logger Logger | None
writer Any | None
See Also

Config: The runeer base that stores runtime information. BaseRunner: The base runner class.

Source code in danling/runner/base_runner.py
Python
  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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
class BaseRunner(metaclass=RunnerMeta):  # pylint: disable=too-many-public-methods
    r"""
    Base class for all runners.

    `BaseRunner` sets up basic running environment, including `seed`, `deterministic`, and `logging`.

    `BaseRunner` also provides some basic methods, such as, `step`, `state_dict`, `save_checkpoint`, `load_checkpoint`.

    `BaseRunner` defines all basic attributes and relevant properties such as `scores`, `progress`, etc.

    Attributes: ID:
        timestamp (str): A time string representing the creation time of run.
        name (str): `f"{self.config.experiment_name}-{self.config.run_name}"`.
        id (str): `f"{self.config.experiment_id:.8}{self.config.run_id:.8}"`.
        uuid (UUID, property): `uuid5(self.config.run_id, self.id)`.

    Attributes: Core:
        mode (RunnerMode, property): Running mode.
        config (Config): Running config. See [`Config`] for details.

    Attributes: Model:
        model (Callable):
        criterion (Callable):
        optimizer:
        scheduler:

    Attributes: Data:
        datasets (FlatDict): All datasets, should be in the form of ``{subset: dataset}``.
            Initialised to `FlatDict` by default.
        datasamplers (FlatDict): All datasamplers, should be in the form of ``{subset: datasampler}``.
            Initialised to `FlatDict` by default.
        dataloaders (FlatDict): All dataloaders, should be in the form of ``{subset: dataloader}``.
            Initialised to `FlatDict` by default.
        split (str): Current running split.
        batch_size (int, property): Number of samples per batch in current running split.
        batch_size_equivalent (int, property): Total batch_size (`batch_size * world_size * accum_steps`).

    `datasets`, `datasamplers`, `dataloaders` should be a dict with the same keys.
    Their keys should be `split` (e.g. `train`, `val`, `test`).

    Attributes: Progress:
        progress (float, property): Running Progress, in `range(0, 1)`.

    Attributes: Results:
        results (NestedDict): Results include all metric information of the model.
            Results should be in the form of `{epoch: {subset: {metric: score}}}`.
        latest_result (NestedDict, property): Most recent result, should be in the form of `{subset: {metric: score}}`.
        best_result (NestedDict, property): Best result, should be in the form of `{subset: {metric: score}}`.
        scores (List[float], property): Score is the core metric that is used to evaluate the performance of the model.
            Scores should be in the form of `{epoch: score}`.
        latest_score (float, property): Most recent score, should be in the form of `score`.
        best_score (float, property): Best score, should be in the form of `score`.
        score_split (Optional[str]): The subset to calculate the score.
            If is `None`, will use the last set of the result.
        score_name (str): The metric name of score.
            Defaults to `"loss"`.
        is_best (bool, property): If `latest_score == best_score`.

    A `result` is a dict with the same `split` as keys, like `dataloaders`.
    A typical `result` shall look like this:
    ```python
    {
        "train": {
            "loss": 0.1,
            "accuracy": 0.9,
        },
        "val": {
            "loss": 0.2,
            "accuracy": 0.8,
        },
        "test": {
            "loss": 0.3,
            "accuracy": 0.7,
        },
    }
    ```

    `scores` are dynamically extracted from `results` by `score_split` and `score_name`.
    They represent the core metric that is used in comparing the performance against different models and settings.
    For the above `results`, If `score_split = "val"`, `score_name = "accuracy"`, then `scores = 0.9`.

    Attributes: IO:
        dir (str, property): Directory of the run.
            Defaults to `${self.project_root}/${self.name}-${self.id}/${self.timestamp})`.
        checkpoint_dir (str, property): Directory of checkpoints.
        log_path (str, property):  Path of log file.
        checkpoint_dir_name (str): The name of the directory under `runner.dir` to save checkpoints.
            Defaults to `"checkpoints"`.

    Attributes: Parallel Training:
        world_size (int, property): Number of processes.
        rank (int, property): Process index of all processes.
        local_rank (int, property): Process index of local processes.
        distributed (bool, property): If runner is running in distributed mode.
        is_main_process (bool, property): If current process is the main process of all processes.
        is_local_main_process (bool, property): If current process is the main process of local processes.

    Attributes: logging:
        meters (AverageMeters | MultiTaskAverageMeters): Average meters.
            Initialised to `AverageMeters` by default.
        metrics (Metrics | MultiTaskMetrics | MetricMeters | None): Metrics for evaluating.
        logger:
        writer:

    See Also:
        [`Config`][danling.runner.Config]: The runeer base that stores runtime information.
        [`BaseRunner`][danling.runner.BaseRunner]: The base runner class.
    """

    # DO NOT set default value in class, as they won't be stored in `__dict__`.

    timestamp: str

    _mode: RunnerMode
    _config: Config
    inited: bool = False

    model: Callable | None = None
    criterion: Callable | None = None
    optimizer: Any | None = None
    scheduler: Any | None = None

    datasets: FlatDict
    datasamplers: FlatDict
    dataloaders: FlatDict
    split: str | None = None

    results: NestedDict
    meters: AverageMeters
    metrics: Metrics | MetricMeters | None = None
    logger: logging.Logger | None = None
    writer: Any | None = None

    def __init__(self, config: Config) -> None:
        self.timestamp = get_time_str()
        if "datasets" not in self.__dict__:
            self.datasets = FlatDict()
        if "datasamplers" not in self.__dict__:
            self.datasamplers = FlatDict()
        if "dataloaders" not in self.__dict__:
            self.dataloaders = FlatDict()
        if "results" not in self.__dict__:
            self.results = NestedDict()
        self.meters = AverageMeters()
        self._mode = RunnerMode.train  # type: ignore[assignment]
        # must init config at last to avoid name conflicts
        if not isinstance(config, Config):
            config = Config(config)
        self._config = config
        self.init_distributed()
        self.inited = True

    def __post_init__(self):
        if self.config.seed is not None:
            self.set_seed()
        if self.config.deterministic:
            self.set_deterministic()
        if self.config.log:
            self.init_logging()
        self.init_print()
        if self.config.tensorboard:
            self.init_tensorboard()

    def init_distributed(self) -> None:
        r"""
        Initialise distributed running environment.
        """

    @on_main_process
    def init_logging(self) -> None:
        r"""
        Set up logging.
        """

        os.makedirs(os.path.dirname(self.log_path), exist_ok=True)
        # Why is setting up proper logging so !@?#! ugly?
        logging.config.dictConfig(
            {
                "version": 1,
                "disable_existing_loggers": False,
                "formatters": {
                    "standard": {"format": "%(asctime)s [%(levelname)s] %(name)s: %(message)s"},
                },
                "handlers": {
                    "stdout": {
                        "level": "INFO",
                        "formatter": "standard",
                        "class": "logging.StreamHandler",
                        "stream": "ext://sys.stdout",
                    },
                    "logfile": {
                        "level": "DEBUG",
                        "formatter": "standard",
                        "class": "logging.FileHandler",
                        "filename": self.log_path,
                        "mode": "a",
                    },
                },
                "loggers": {
                    "": {
                        "handlers": ["stdout", "logfile"],
                        "level": "DEBUG",
                        "propagate": True,
                    },
                },
            }
        )
        logging.captureWarnings(True)
        self.logger = logging.getLogger("runner")
        self.logger.flush = lambda: [h.flush() for h in self.logger.handlers]  # type: ignore

    def init_print(self, process: int = 0) -> None:
        r"""
        Set up `print`.

        Only print on a specific `process` or when `force = True`.

        Args:
            process: The process to `print` on.

        Notes
        -----
        If `self.config.log = True`, the default `print` function will be override by `logging.info`.
        """

        logger = logging.getLogger("print")
        logger.flush = lambda: [h.flush for h in logger.handlers]  # type: ignore
        import builtins as __builtin__  # pylint: disable=C0415

        builtin_print = __builtin__.print

        @catch
        def print(*args, force=False, end="\n", file=None, flush=False, **kwargs):  # pylint: disable=redefined-builtin
            if self.rank == process or force:
                if self.config.log:
                    logger.info(*args, **kwargs)
                else:
                    builtin_print(*args, end=end, file=file, flush=flush, **kwargs)

        __builtin__.print = print

    @on_main_process
    def init_tensorboard(self, *args, **kwargs) -> None:
        r"""
        Set up Tensoraoard SummaryWriter.
        """
        raise NotImplementedError

    def set_seed(self, seed: int = None, bias: int = None) -> int:  # type: ignore[assignment]
        r"""
        Set up random seed.

        Args:
            seed: Random seed to set.
                Defaults to `self.config.seed` (`config.seed`).

            bias: Make the seed different for each processes.

                This avoids same data augmentation are applied on every processes.

                Defaults to `self.rank`.

                Set to `False` to disable this feature.
        Returns:
            Random seed set.
        """

        seed = seed or self.config.seed  # type: ignore[assignment]
        bias = bias or self.rank
        if bias:
            seed += bias
        if np_random is not None:
            np_random.seed(seed)
        random.seed(seed)
        return seed

    def set_deterministic(self) -> None:
        r"""
        Set up deterministic.
        """

        raise NotImplementedError

    def scale_lr(
        self,
        lr: float,
        lr_scale_factor: float | None = None,
        batch_size_base: int | None = None,
    ) -> float:
        r"""
        Scale learning rate according to [linear scaling rule](https://arxiv.org/abs/1706.02677).
        """

        if lr_scale_factor in self.config:
            lr_scale_factor = self.config.lr_scale_factor

        if lr_scale_factor is None:
            if batch_size_base is None:
                batch_size_base = getattr(self, "batch_size_base", None)
                if batch_size_base is None:
                    raise ValueError("batch_size_base must be specified to auto scale lr")
            lr_scale_factor = self.batch_size_equivalent / batch_size_base
        elif batch_size_base is not None:
            warn(
                "batch_size_base will be ignored if lr_scale_factor is specified", category=RuntimeWarning, stacklevel=2
            )
        lr = lr * lr_scale_factor
        self.config.lr_scale_factor = lr_scale_factor
        return lr

    def update(self, loss, *args, **kwargs) -> None:
        r"""
        Backward loss and step optimizer & scheduler.

        Args:
            loss: loss.
        """

        raise NotImplementedError

    def state_dict(self, cls: Callable = dict) -> Mapping:
        r"""
        Return dict of all attributes for checkpoint.
        """

        return cls(self.config)

    def dict(self, cls: Callable = dict) -> Mapping:
        r"""
        Convert config to Mapping.

        Args:
            cls: Target `clc to convert to.
        """

        return self.config.dict(cls)

    @catch
    def save(self, obj: Any, file: PathStr, main_process_only: bool = True, *args, **kwargs) -> File:
        r"""
        Save any file with supported extensions.

        `Runner.save` internally calls `dl.save`,
        but with additional arguments to allow it save only on the main process.
        Moreover, any error raised by `Runner.save` will be caught and logged.
        """

        if main_process_only and self.is_main_process or not main_process_only:
            return save(obj, file, *args, **kwargs)
        return file

    @staticmethod
    def load(file: PathStr, *args, **kwargs) -> Any:
        r"""
        Load any file with supported extensions.

        `Runner.load` is identical to `dl.load`.
        """

        return load(file, *args, **kwargs)

    @catch
    def json(self, file: File, main_process_only: bool = True, *args, **kwargs) -> None:  # pylint: disable=R1710
        r"""
        Dump Runner config to json file.
        """

        if main_process_only and self.is_main_process or not main_process_only:
            return self.config.json(file, *args, **kwargs)

    @classmethod
    def from_json(cls, file: File, *args, **kwargs) -> BaseRunner:
        r"""
        Construct Runner from json file.

        This function calls `self.from_jsons()` to construct object from json string.
        You may overwrite `from_jsons` in case something is not json serializable.
        """

        with FlatDict.open(file) as fp:
            return cls.from_jsons(fp.read(), *args, **kwargs)

    def jsons(self, *args, **kwargs) -> str:
        r"""
        Dump Runner config to json string.
        """

        return self.config.jsons(*args, **kwargs)

    @classmethod
    def from_jsons(cls, string: str, *args, **kwargs) -> BaseRunner:
        r"""
        Construct Runner from json string.
        """

        return cls(Config.from_jsons(string, *args, **kwargs))

    @catch
    def yaml(self, file: File, main_process_only: bool = True, *args, **kwargs) -> None:  # pylint: disable=R1710
        r"""
        Dump Runner config to yaml file.
        """

        if main_process_only and self.is_main_process or not main_process_only:
            return self.config.yaml(file, *args, **kwargs)

    @classmethod
    def from_yaml(cls, file: File, *args, **kwargs) -> BaseRunner:
        r"""
        Construct Runner from yaml file.

        This function calls `self.from_yamls()` to construct object from yaml string.
        You may overwrite `from_yamls` in case something is not yaml serializable.
        """

        with FlatDict.open(file) as fp:
            return cls.from_yamls(fp.read(), *args, **kwargs)

    def yamls(self, *args, **kwargs) -> str:
        r"""
        Dump Runner config to yaml string.
        """

        return self.config.yamls(*args, **kwargs)

    @classmethod
    def from_yamls(cls, string: str, *args, **kwargs) -> BaseRunner:
        r"""
        Construct Runner from yaml string.
        """

        return cls(Config.from_yamls(string, *args, **kwargs))

    def check_dir(self, action: str = "warn") -> bool:
        r"""
        Check if `self.dir` is not empty.

        Args:
            action (str): The action to perform if `self.dir` is not empty.
            Can be one of ("warn", "raise", "ignore"), default is "warn".
        """

        if action and action not in ("warn", "raise", "ignore"):
            raise ValueError(f"action should be one of warn, raise or ignore, but got {action}")
        if os.listdir(self.dir):
            if action == "warn":
                warn(
                    f"Directory `{self.dir}` is not empty",
                    category=RuntimeWarning,
                    stacklevel=2,
                )
            if action == "raise":
                raise RuntimeError(f"Directory `{self.dir}` is not empty")
            return False
        return True

    @catch
    @on_main_process
    def save_checkpoint(self, epoch: int | None = None) -> None:
        r"""
        Save checkpoint to `self.checkpoint_dir`.

        The checkpoint will be saved to `self.checkpoint_dir/latest.pth`.

        If `self.config.save_interval` is positive and `self.config.epoch + 1` is a multiple of `save_interval`,
        the checkpoint will also be copied to `self.checkpoint_dir/epoch-{self.config.epoch}.pth`.

        If `self.is_best` is `True`, the checkpoint will also be copied to `self.checkpoint_dir/best.pth`.
        """

        epoch = epoch or self.config.epoch
        save_interval = self.config.get("save_interval", -1)
        latest_path = os.path.join(self.checkpoint_dir, "latest.pth")
        self.save(self.state_dict(), latest_path)
        if save_interval > 0 and (epoch + 1) % save_interval == 0:
            save_path = os.path.join(self.checkpoint_dir, f"epoch-{epoch}.pth")
            shutil.copy(latest_path, save_path)
        if self.is_best:
            best_path = os.path.join(self.checkpoint_dir, "best.pth")
            shutil.copy(latest_path, best_path)

    def load_checkpoint(
        self,
        checkpoint: Mapping | bytes | str | os.PathLike | None = None,
        auto_resume: bool | None = None,
        override_config: bool = False,
        *args,
        **kwargs,
    ) -> None:
        """
        Load info from checkpoint.

        Args:
            checkpoint: Checkpoint (or its path) to load.
                Defaults to `self.config.checkpoint`.
            auto_resume: Automatically resume from latest checkpoint if exists.
                Defaults to `False`.
                If is `True` and `checkpoint` is None, will set it to `self.checkpoint_dir/latest.pth`.
            override_config: If True, override runner config with checkpoint config.
                Defaults to `False`.
            *args: Additional arguments to pass to `self.load`.
            **kwargs: Additional keyword arguments to pass to `self.load`.

        Raises:
            FileNotFoundError: If `checkpoint` does not exists.

        See Also:
            [`from_checkpoint`][danling.BaseRunner.from_checkpoint]: Build runner from checkpoint.
            [`load_pretrained`][danling.BaseRunner.load_pretrained]: Load parameters from pretrained checkpoint.
        """

        checkpoint = checkpoint if checkpoint is not None else self.config.get("checkpoint")
        auto_resume = auto_resume if auto_resume is not None else self.config.get("auto_resume", False)

        # TODO: Support loading checkpoints in other format
        if checkpoint is not None:
            if auto_resume:
                warn(
                    "latest checkpoint is preempted by value specified in checkpoint",
                    RuntimeWarning,
                    stacklevel=2,
                )
            if isinstance(checkpoint, (bytes, str, os.PathLike)):
                if not os.path.exists(checkpoint):
                    raise FileNotFoundError(f"checkpoint is set to {checkpoint!r} but does not exist")
                self.config.checkpoint = checkpoint
                ckpt = self.load(checkpoint, *args, **kwargs)
            elif isinstance(checkpoint, Mapping):
                ckpt = checkpoint
            else:
                raise ValueError(f"pretrained is set to {checkpoint!r} but is not a valid checkpoint")
        elif auto_resume:
            checkpoint = os.path.join(self.checkpoint_dir, "latest.pth")
            if os.path.exists(checkpoint):
                self.config.checkpoint = checkpoint
                ckpt = self.load(checkpoint, *args, **kwargs)
            else:
                warn("latest checkpoint does not exits", category=RuntimeWarning, stacklevel=2)
                return
        else:
            raise ValueError("checkpoint is not specified and auto_resume is not set to True")

        # TODO: Wrap state_dict in a dataclass
        self.config.merge(ckpt["runner"], overwrite=override_config)
        if self.model is not None and "model" in ckpt:
            model = self.unwrap(self.model)
            model.load_state_dict(ckpt["model"])
        if self.optimizer is not None and "optimizer" in ckpt:
            self.optimizer.load_state_dict(ckpt["optimizer"])
        if self.scheduler is not None and "scheduler" in ckpt:
            self.scheduler.load_state_dict(ckpt["scheduler"])
        self.config.iter_begin = self.config.iter
        self.config.step_begin = self.config.step
        self.config.epoch_begin = self.config.epoch

    @classmethod
    def from_checkpoint(cls, checkpoint: Mapping | bytes | str | os.PathLike, *args, **kwargs) -> BaseRunner:
        r"""
        Build BaseRunner from checkpoint.

        Args:
            checkpoint: Checkpoint (or its path) to load.
            *args: Additional arguments to pass to `cls.load`.
            **kwargs: Additional keyword arguments to pass to `cls.load`.

        Returns:
            (BaseRunner):
        """

        if isinstance(checkpoint, (bytes, str, os.PathLike)):
            ckpt = cls.load(checkpoint, *args, **kwargs)
        elif isinstance(checkpoint, Mapping):
            ckpt = checkpoint
        else:
            raise ValueError(f"checkpoint is set to {checkpoint} but is not a valid checkpoint")
        runner = cls(**ckpt["runner"])
        runner.load_checkpoint(ckpt, override_config=False)
        return runner

    def load_pretrained(self, checkpoint: Mapping | bytes | str | os.PathLike | None = None, *args, **kwargs) -> None:
        """
        Load parameters from pretrained checkpoint.

        This method only loads the model weights.

        Args:
            checkpoint: Pretrained checkpoint (or its path) to load.
                Defaults to `self.config.pretrained`.
            *args: Additional arguments to pass to `self.load`.
            **kwargs: Additional keyword arguments to pass to `self.load`.

        Raises:
            FileNotFoundError: If `checkpoint` does not exists.

        See Also:
            [`load_checkpoint`][danling.BaseRunner.load_checkpoint]: Load info from checkpoint.
        """

        # TODO: Support loading checkpoints in other format
        checkpoint = checkpoint if checkpoint is not None else self.config.get("pretrained")
        if checkpoint is None:
            raise ValueError("pretrained is not specified")
        if isinstance(checkpoint, (bytes, str, os.PathLike)):
            if not os.path.exists(checkpoint):
                raise FileNotFoundError(f"pretrained is set to {checkpoint!r} but does not exist")
            ckpt = self.load(checkpoint, *args, **kwargs)
        elif isinstance(checkpoint, Mapping):
            ckpt = checkpoint
        else:
            raise ValueError(f"pretrained is set to {checkpoint!r} but is not a valid checkpoint")
        if self.model is not None and "model" in ckpt:
            model = self.unwrap(self.model)
            model.load_state_dict(ckpt["model"])
        else:
            raise ValueError(f"Unable to find model weights in {checkpoint!r}")

    def get_result(self, level: str) -> NestedDict:
        metric = None
        if level == "step":
            result = self.meters.val.clone()
            if self.metrics is not None:
                metric = self.metrics.val
        elif level == "epoch":
            result = self.meters.avg.clone()
            if self.metrics is not None:
                metric = self.metrics.avg
        else:
            raise ValueError(f"level should be one of step or epoch, but got {level}")
        if metric is not None:
            if isinstance(self.metrics, MultiTaskMetrics):
                m = NestedDict()
                for key, value in metric.items():
                    if len(value) == 1:
                        value = next(iter(value.values()))
                    m[key] = value
                metric = m
            if len(metric) == 1:
                metric = next(iter(metric.values()))
            result.update(metric)
        return result

    def append_result(self, result: NestedDict, index: int | None = None) -> None:
        r"""
        Append result to `self.results`.

        Warnings:
            `self.results` is heavily relied upon for computing metrics.

            Failed to use this method may lead to unexpected behavior.
        """

        if index is None:
            index = self.config.epoch
            global __APPEND_RESULT_COUNTER__  # pylint: disable=global-statement
            __APPEND_RESULT_COUNTER__ += 1
            if index == 0 and __APPEND_RESULT_COUNTER__ > 1:
                warn(
                    """
                    Automatically set index to `self.config.epoch`.
                    Please ensure `self.config.epoch` updates before calling `append_result`
                    """,
                    category=RuntimeWarning,
                    stacklevel=2,
                )
        if index in self.results:
            self.results[index].merge(result)
        else:
            self.results[index] = result

    def print_result(self) -> None:
        r"""
        Print latest and best result.
        """

        print(f"latest result: {self.latest_result}")
        print(f"best result: {self.best_result}")

    def step_log(self, split: str, iteration: int, length: int | None = None):
        if length is None:
            length = len(self.dataloaders[split]) - 1
        result = self.get_result("step")
        print(self.format_step_result(result, split, iteration, length))
        if self.mode == "train":
            self.write_result(result, split)
        return result

    def format_step_result(
        self, result: NestedDict, split: str, step: int, length: int, format_spec: str = ".4f"
    ) -> str:
        repr_str = ""
        if split is not None:
            if self.mode == "train":
                repr_str = f"training on {split} "
            elif self.mode == "eval":
                repr_str = f"evaluating on {split} "
            else:
                repr_str = f"running in {self.mode} mode on {split} "
        repr_str += f"[{step}/{length}]\t"
        return repr_str + self.format_result(result, format_spec=format_spec)

    def format_epoch_result(
        self, result: NestedDict, epoch: int | None = None, epoch_end: int | None = None, format_spec: str = ".4f"
    ) -> str:
        epoch = epoch or self.config.epoch
        epoch_end = epoch_end or self.config.epoch_end
        repr_str = f"epoch [{epoch}/{epoch_end - 1}]" if epoch is not None and epoch_end else ""
        return repr_str + self.format_result(result, format_spec=format_spec)

    def format_result(self, result: Mapping, format_spec: str = ".4f") -> str:
        return format_result(result, format_spec=format_spec)

    def write_result(self, result: NestedDict, split: str, step: int | None = None):
        if step is None:
            step = self.step
        for name, score in result.all_items():
            name = name.replace(".", "/")
            if name == "loss" and isinstance(score, AverageMeter):
                score = score.avg
            if isinstance(score, Sequence):
                for i, s in enumerate(score):
                    self.write_score(f"{name}/{i}", s, split, step)
            elif isinstance(score, Mapping):
                for k, s in score.items():
                    self.write_score(f"{name}/{k}", s, split, step)
            else:
                self.write_score(name, score, split, step)

    def write_score(self, name: str, score: float, split: str, step: int):
        if self.writer:
            self.writer.add_scalar(f"{split}/{name}", score, step)

    @catch
    @on_main_process
    def save_result(self) -> None:
        r"""
        Save result to `self.dir`.

        This method will save latest and best result to
        `self.dir/latest.json` and `self.dir/best.json` respectively.
        """

        results_path = os.path.join(self.dir, "results.json")
        self.save(
            {
                "name": self.name,
                "id": self.id,
                "timestamp": self.timestamp,
                "results": self.results,
            },
            results_path,
            indent=4,
        )
        ret = {"name": self.name, "id": self.id, "timestamp": self.timestamp}
        result = self.latest_result
        if isinstance(result, FlatDict):
            result = result.dict()
        # This is slower but ensure id is the first key
        if result is not None:
            ret.update(result)
        latest_path = os.path.join(self.dir, "latest.json")
        self.save(ret, latest_path, indent=4)
        if self.is_best:
            best_path = os.path.join(self.dir, "best.json")
            shutil.copy(latest_path, best_path)

    def unwrap(self, model: Any) -> Any:
        return model

    @cached_property
    def name(self):
        if "name" in self.config:
            return self.config["name"]
        return f"{self.config.experiment_name}-{self.config.run_name}"

    @cached_property
    def id(self):
        return f"{self.config.experiment_id:.8}{self.config.run_id:.8}"

    @cached_property
    def uuid(self) -> UUID:
        r"""
        UUID of the config.
        """

        return uuid5(self.run_uuid, self.id)

    @property
    def mode(self) -> RunnerMode:
        return self._mode

    @mode.setter
    def mode(self, mode: str | RunnerMode) -> None:
        if isinstance(mode, str):
            mode = RunnerMode(mode)
        self._mode = mode

    @property
    def config(self) -> Config:
        return self._config

    @property
    def batch_size(self) -> int:
        r"""
        Batch size.

        Notes:
            If `train` is in `dataloaders`, then `batch_size` is the batch size of `train`.
            Otherwise, `batch_size` is the batch size of the first dataloader.

        Returns:
            (int):
        """

        if self.dataloaders and self.split:
            return self.dataloaders[self.split].batch_size
        batch_size = self.config.get("dataloader.batch_size")
        if batch_size:
            return batch_size
        raise AttributeError("batch_size could not be inferred and is not in config")

    @property
    def batch_size_equivalent(self) -> int:
        r"""
        Actual batch size.

        Returns:
            (int): `batch_size` * `world_size` * `accum_steps`
        """

        return self.batch_size * self.world_size * self.accum_steps

    @cached_property
    def total_epochs(self) -> int:
        if self.config.epoch_end:
            return self.config.epoch_end - self.config.epoch_begin
        raise ValueError("epoch_end is not specified")

    @cached_property
    def total_steps(self) -> int:
        if self.config.step_end:
            return self.config.step_end - self.config.step_begin
        dataset = self.datasets.get("train", next(iter(self.datasets.values())))
        return self.total_epochs * ceil(len(dataset) / self.batch_size / self.world_size)

    @cached_property
    def trainable_steps(self) -> int:
        return ceil(self.total_steps / self.accum_steps)

    @cached_property
    def accum_steps(self) -> int:
        r"""
        Accumulated steps.

        Returns:
            (int):
        """

        return self.config.get("accum_steps", 1)

    @property
    def progress(self) -> float:
        r"""
        Training Progress.

        Returns:
            (float):

        Raises:
            RuntimeError: If no terminal is defined.
        """

        return self.step / self.total_steps

    @property
    def world_size(self) -> int:
        r"""
        Number of processes.
        """

        return 1

    @property
    def rank(self) -> int:
        r"""
        Process index of all processes.
        """

        return 0

    @property
    def local_rank(self) -> int:
        r"""
        Process index of local processes.
        """

        return 0

    @property
    def distributed(self) -> bool:
        r"""
        If runner is running in distributed mode.
        """

        return self.world_size > 1

    @property
    def is_main_process(self) -> bool:
        r"""
        If current process is the main process of all processes.
        """

        return self.rank == 0

    @property
    def is_local_main_process(self) -> bool:
        r"""
        If current process is the main process of local processes.
        """

        return self.local_rank == 0

    @property
    def best_fn(self) -> Callable:
        r"""
        Function to determine the best score from a list of scores.

        By default, the `best_fn` returns `min` if `self.config.score_name` is `loss`,
        otherwise, returns `max`.

        Subclass can override this method to accommodate needs, such as `min`.

        Returns:
            (callable):
        """

        return max if self.config.score_name != "loss" else min

    @property
    def best_index(self) -> int:
        r"""
        Find the best index from all scores.

        Returns:
            (int):
        """

        if not self.scores:
            return 0
        values = list(self.scores.values())
        return self.best_fn(range(len(values)), key=values.__getitem__)

    @property
    def latest_result(self) -> NestedDict | None:
        r"""
        Latest result.
        """

        if not self.results:
            return None
        latest_index = next(reversed(self.results if PY38_PLUS else list(self.results)))  # type: ignore
        ret = self.results[latest_index].clone()
        ret["index"] = latest_index
        return ret

    @property
    def best_result(self) -> NestedDict | None:
        r"""
        Best result.
        """

        if not self.results:
            return None
        best_index = self.best_index
        ret = self.results[best_index].clone()
        ret["index"] = best_index
        return ret

    @property
    def scores(self) -> FlatDict | None:
        r"""
        All scores.

        Scores are extracted from results by `score_split` and `runner.config.score_name`,
        following `[r[score_split][self.config.score_name] for r in self.results]`.

        Scores are considered as the index of the performance of the model.
        It is useful to determine the best model and the best hyper-parameters.

        `score_split` is defined in `self.config.score_split`.
        If it is not set, `DanLing` will use `val` or `validate` if they appear in the `latest_result`.
        If `DanLing` still could not find, it will fall back to the second key in the `latest_result`
        if it contains more that one element, or the first key.

        Note that certain keys are ignored when falling back, they are defined in {IGNORED_SET_NAMES}.
        """

        if not self.results:
            return None
        subsets = [i for i in self.latest_result.keys() if i not in IGNORED_SET_NAMES]  # type: ignore
        score_split = self.config.get("score_split")
        if score_split is None and "val" in subsets:
            score_split = "val"
        if score_split is None and "validate" in subsets:
            score_split = "validate"
        if score_split is None:
            score_split = subsets[1] if len(subsets) > 1 else subsets[0]
        return FlatDict({k: v[score_split][self.config.score_name] for k, v in self.results.items()})

    @property
    def latest_score(self) -> float | None:
        r"""
        Latest score.
        """

        if not self.results:
            return None
        if not PY38_PLUS:
            return next(reversed(list(self.scores.values())))  # type: ignore
        return next(reversed(self.scores.values()))  # type: ignore

    @property
    def best_score(self) -> float | None:
        r"""
        Best score.
        """

        if not self.results:
            return None
        return self.scores[self.best_index]  # type: ignore

    @property
    def is_best(self) -> bool:
        r"""
        If current epoch is the best epoch.
        """

        if not self.results:
            return True
        try:
            return abs(self.latest_score - self.best_score) < 1e-7  # type: ignore
        except TypeError:
            return True

    @property
    @ensure_dir
    def dir(self) -> str:
        r"""
        Directory of the run.
        """

        if "dir" in self.config:
            return self.config.dir
        return os.path.join(self.project_root, f"{self.name}-{self.id}", self.timestamp)

    @cached_property
    def log_path(self) -> str:
        r"""
        Path of log file.
        """

        if "log_path" in self.config:
            return self.config.log_path
        return os.path.join(self.dir, "run.log")

    @property
    @ensure_dir
    def checkpoint_dir(self) -> str:
        r"""
        Directory of checkpoints.
        """

        if "checkpoint_dir" in self.config:
            return self.config.checkpoint_dir
        return os.path.join(self.dir, self.config.checkpoint_dir_name)

    # def __getattribute__(self, name) -> Any:
    #     if name in ("__class__", "__dict__"):
    #         return super().__getattribute__(name)
    #     if name in self.__dict__:
    #         return self.__dict__[name]
    #     if name in dir(self):
    #         return super().__getattribute__(name)
    #     if "config" in self and name in self.config:
    #         return self.config[name]
    #     return super().__getattribute__(name)

    def __getattr__(self, name) -> Any:
        if self.inited:
            if name in self.config:
                return self.config[name]
            if name in dir(self.config):
                return getattr(self.config, name)
        return super().__getattribute__(name)

    def __setattr__(self, name, value) -> None:
        if name in self.__dict__:
            if isinstance(self.__dict__[name], Variable):
                self.__dict__[name].set(value)
            else:
                self.__dict__[name] = value
            return
        if name in dir(self):
            if isinstance(super().__getattribute__(name), Variable):
                super().__getattribute__(name).set(value)
            else:
                object.__setattr__(self, name, value)
            return
        if self.inited:
            if name in self.config:
                if isinstance(self.config[name], Variable):
                    self.config[name].set(value)
                else:
                    self.config[name] = value
                return
            if name in dir(self.config):
                setattr(self.config, name, value)
                return
        object.__setattr__(self, name, value)

    def __contains__(self, name) -> bool:
        return name in dir(self) or ("config" in self.__dict__ and name in dir(self.config))

    def __repr__(self):
        lines = []
        for key, value in self.__dict__.items():
            value_str = repr(value)
            value_str = self._add_indent(value_str)
            lines.append("(" + key + "): " + value_str)

        main_str = self.__class__.__name__ + "("
        if lines:
            main_str += "\n  " + "\n  ".join(lines) + "\n"

        main_str += ")"
        return main_str

    def _add_indent(self, text):
        lines = text.split("\n")
        # don't do anything for single-line stuff
        if len(lines) == 1:
            return text
        first = lines.pop(0)
        # add 2 spaces to each line but the first
        lines = [(2 * " ") + line for line in lines]
        lines = "\n".join(lines)
        lines = first + "\n" + lines
        return lines

uuid cached property

Python
uuid: UUID

UUID of the config.

batch_size property

Python
batch_size: int

Batch size.

Notes

If train is in dataloaders, then batch_size is the batch size of train. Otherwise, batch_size is the batch size of the first dataloader.

Returns:

Type Description
int

batch_size_equivalent property

Python
batch_size_equivalent: int

Actual batch size.

Returns:

Type Description
int

batch_size * world_size * accum_steps

accum_steps cached property

Python
accum_steps: int

Accumulated steps.

Returns:

Type Description
int

progress property

Python
progress: float

Training Progress.

Returns:

Type Description
float

Raises:

Type Description
RuntimeError

If no terminal is defined.

world_size property

Python
world_size: int

Number of processes.

rank property

Python
rank: int

Process index of all processes.

local_rank property

Python
local_rank: int

Process index of local processes.

distributed property

Python
distributed: bool

If runner is running in distributed mode.

is_main_process property

Python
is_main_process: bool

If current process is the main process of all processes.

is_local_main_process property

Python
is_local_main_process: bool

If current process is the main process of local processes.

best_fn property

Python
best_fn: Callable

Function to determine the best score from a list of scores.

By default, the best_fn returns min if self.config.score_name is loss, otherwise, returns max.

Subclass can override this method to accommodate needs, such as min.

Returns:

Type Description
callable

best_index property

Python
best_index: int

Find the best index from all scores.

Returns:

Type Description
int

latest_result property

Python
latest_result: NestedDict | None

Latest result.

best_result property

Python
best_result: NestedDict | None

Best result.

scores property

Python
scores: FlatDict | None

All scores.

Scores are extracted from results by score_split and runner.config.score_name, following [r[score_split][self.config.score_name] for r in self.results].

Scores are considered as the index of the performance of the model. It is useful to determine the best model and the best hyper-parameters.

score_split is defined in self.config.score_split. If it is not set, DanLing will use val or validate if they appear in the latest_result. If DanLing still could not find, it will fall back to the second key in the latest_result if it contains more that one element, or the first key.

Note that certain keys are ignored when falling back, they are defined in {IGNORED_SET_NAMES}.

latest_score property

Python
latest_score: float | None

Latest score.

best_score property

Python
best_score: float | None

Best score.

is_best property

Python
is_best: bool

If current epoch is the best epoch.

dir property

Python
dir: str

Directory of the run.

log_path cached property

Python
log_path: str

Path of log file.

checkpoint_dir property

Python
checkpoint_dir: str

Directory of checkpoints.

init_distributed

Python
init_distributed() -> None

Initialise distributed running environment.

Source code in danling/runner/base_runner.py
Python
def init_distributed(self) -> None:
    r"""
    Initialise distributed running environment.
    """

init_logging

Python
init_logging() -> None

Set up logging.

Source code in danling/runner/base_runner.py
Python
@on_main_process
def init_logging(self) -> None:
    r"""
    Set up logging.
    """

    os.makedirs(os.path.dirname(self.log_path), exist_ok=True)
    # Why is setting up proper logging so !@?#! ugly?
    logging.config.dictConfig(
        {
            "version": 1,
            "disable_existing_loggers": False,
            "formatters": {
                "standard": {"format": "%(asctime)s [%(levelname)s] %(name)s: %(message)s"},
            },
            "handlers": {
                "stdout": {
                    "level": "INFO",
                    "formatter": "standard",
                    "class": "logging.StreamHandler",
                    "stream": "ext://sys.stdout",
                },
                "logfile": {
                    "level": "DEBUG",
                    "formatter": "standard",
                    "class": "logging.FileHandler",
                    "filename": self.log_path,
                    "mode": "a",
                },
            },
            "loggers": {
                "": {
                    "handlers": ["stdout", "logfile"],
                    "level": "DEBUG",
                    "propagate": True,
                },
            },
        }
    )
    logging.captureWarnings(True)
    self.logger = logging.getLogger("runner")
    self.logger.flush = lambda: [h.flush() for h in self.logger.handlers]  # type: ignore

init_print

Python
init_print(process: int = 0) -> None

Set up print.

Only print on a specific process or when force = True.

Parameters:

Name Type Description Default
process int

The process to print on.

0
Notes

If self.config.log = True, the default print function will be override by logging.info.

Source code in danling/runner/base_runner.py
Python
def init_print(self, process: int = 0) -> None:
    r"""
    Set up `print`.

    Only print on a specific `process` or when `force = True`.

    Args:
        process: The process to `print` on.

    Notes
    -----
    If `self.config.log = True`, the default `print` function will be override by `logging.info`.
    """

    logger = logging.getLogger("print")
    logger.flush = lambda: [h.flush for h in logger.handlers]  # type: ignore
    import builtins as __builtin__  # pylint: disable=C0415

    builtin_print = __builtin__.print

    @catch
    def print(*args, force=False, end="\n", file=None, flush=False, **kwargs):  # pylint: disable=redefined-builtin
        if self.rank == process or force:
            if self.config.log:
                logger.info(*args, **kwargs)
            else:
                builtin_print(*args, end=end, file=file, flush=flush, **kwargs)

    __builtin__.print = print

init_tensorboard

Python
init_tensorboard(*args, **kwargs) -> None

Set up Tensoraoard SummaryWriter.

Source code in danling/runner/base_runner.py
Python
@on_main_process
def init_tensorboard(self, *args, **kwargs) -> None:
    r"""
    Set up Tensoraoard SummaryWriter.
    """
    raise NotImplementedError

set_seed

Python
set_seed(seed: int = None, bias: int = None) -> int

Set up random seed.

Parameters:

Name Type Description Default
seed int

Random seed to set. Defaults to self.config.seed (config.seed).

None
bias int

Make the seed different for each processes.

This avoids same data augmentation are applied on every processes.

Defaults to self.rank.

Set to False to disable this feature.

None
Source code in danling/runner/base_runner.py
Python
def set_seed(self, seed: int = None, bias: int = None) -> int:  # type: ignore[assignment]
    r"""
    Set up random seed.

    Args:
        seed: Random seed to set.
            Defaults to `self.config.seed` (`config.seed`).

        bias: Make the seed different for each processes.

            This avoids same data augmentation are applied on every processes.

            Defaults to `self.rank`.

            Set to `False` to disable this feature.
    Returns:
        Random seed set.
    """

    seed = seed or self.config.seed  # type: ignore[assignment]
    bias = bias or self.rank
    if bias:
        seed += bias
    if np_random is not None:
        np_random.seed(seed)
    random.seed(seed)
    return seed

set_deterministic

Python
set_deterministic() -> None

Set up deterministic.

Source code in danling/runner/base_runner.py
Python
def set_deterministic(self) -> None:
    r"""
    Set up deterministic.
    """

    raise NotImplementedError

scale_lr

Python
scale_lr(lr: float, lr_scale_factor: float | None = None, batch_size_base: int | None = None) -> float

Scale learning rate according to linear scaling rule.

Source code in danling/runner/base_runner.py
Python
def scale_lr(
    self,
    lr: float,
    lr_scale_factor: float | None = None,
    batch_size_base: int | None = None,
) -> float:
    r"""
    Scale learning rate according to [linear scaling rule](https://arxiv.org/abs/1706.02677).
    """

    if lr_scale_factor in self.config:
        lr_scale_factor = self.config.lr_scale_factor

    if lr_scale_factor is None:
        if batch_size_base is None:
            batch_size_base = getattr(self, "batch_size_base", None)
            if batch_size_base is None:
                raise ValueError("batch_size_base must be specified to auto scale lr")
        lr_scale_factor = self.batch_size_equivalent / batch_size_base
    elif batch_size_base is not None:
        warn(
            "batch_size_base will be ignored if lr_scale_factor is specified", category=RuntimeWarning, stacklevel=2
        )
    lr = lr * lr_scale_factor
    self.config.lr_scale_factor = lr_scale_factor
    return lr

update

Python
update(loss, *args, **kwargs) -> None

Backward loss and step optimizer & scheduler.

Parameters:

Name Type Description Default
loss

loss.

required
Source code in danling/runner/base_runner.py
Python
def update(self, loss, *args, **kwargs) -> None:
    r"""
    Backward loss and step optimizer & scheduler.

    Args:
        loss: loss.
    """

    raise NotImplementedError

state_dict

Python
state_dict(cls: Callable = dict) -> Mapping

Return dict of all attributes for checkpoint.

Source code in danling/runner/base_runner.py
Python
def state_dict(self, cls: Callable = dict) -> Mapping:
    r"""
    Return dict of all attributes for checkpoint.
    """

    return cls(self.config)

dict

Python
dict(cls: Callable = dict) -> Mapping

Convert config to Mapping.

Parameters:

Name Type Description Default
cls Callable

Target `clc to convert to.

dict
Source code in danling/runner/base_runner.py
Python
def dict(self, cls: Callable = dict) -> Mapping:
    r"""
    Convert config to Mapping.

    Args:
        cls: Target `clc to convert to.
    """

    return self.config.dict(cls)

save

Python
save(obj: Any, file: PathStr, main_process_only: bool = True, *args, **kwargs) -> File

Save any file with supported extensions.

Runner.save internally calls dl.save, but with additional arguments to allow it save only on the main process. Moreover, any error raised by Runner.save will be caught and logged.

Source code in danling/runner/base_runner.py
Python
@catch
def save(self, obj: Any, file: PathStr, main_process_only: bool = True, *args, **kwargs) -> File:
    r"""
    Save any file with supported extensions.

    `Runner.save` internally calls `dl.save`,
    but with additional arguments to allow it save only on the main process.
    Moreover, any error raised by `Runner.save` will be caught and logged.
    """

    if main_process_only and self.is_main_process or not main_process_only:
        return save(obj, file, *args, **kwargs)
    return file

load staticmethod

Python
load(file: PathStr, *args, **kwargs) -> Any

Load any file with supported extensions.

Runner.load is identical to dl.load.

Source code in danling/runner/base_runner.py
Python
@staticmethod
def load(file: PathStr, *args, **kwargs) -> Any:
    r"""
    Load any file with supported extensions.

    `Runner.load` is identical to `dl.load`.
    """

    return load(file, *args, **kwargs)

json

Python
json(file: File, main_process_only: bool = True, *args, **kwargs) -> None

Dump Runner config to json file.

Source code in danling/runner/base_runner.py
Python
@catch
def json(self, file: File, main_process_only: bool = True, *args, **kwargs) -> None:  # pylint: disable=R1710
    r"""
    Dump Runner config to json file.
    """

    if main_process_only and self.is_main_process or not main_process_only:
        return self.config.json(file, *args, **kwargs)

from_json classmethod

Python
from_json(file: File, *args, **kwargs) -> BaseRunner

Construct Runner from json file.

This function calls self.from_jsons() to construct object from json string. You may overwrite from_jsons in case something is not json serializable.

Source code in danling/runner/base_runner.py
Python
@classmethod
def from_json(cls, file: File, *args, **kwargs) -> BaseRunner:
    r"""
    Construct Runner from json file.

    This function calls `self.from_jsons()` to construct object from json string.
    You may overwrite `from_jsons` in case something is not json serializable.
    """

    with FlatDict.open(file) as fp:
        return cls.from_jsons(fp.read(), *args, **kwargs)

jsons

Python
jsons(*args, **kwargs) -> str

Dump Runner config to json string.

Source code in danling/runner/base_runner.py
Python
def jsons(self, *args, **kwargs) -> str:
    r"""
    Dump Runner config to json string.
    """

    return self.config.jsons(*args, **kwargs)

from_jsons classmethod

Python
from_jsons(string: str, *args, **kwargs) -> BaseRunner

Construct Runner from json string.

Source code in danling/runner/base_runner.py
Python
@classmethod
def from_jsons(cls, string: str, *args, **kwargs) -> BaseRunner:
    r"""
    Construct Runner from json string.
    """

    return cls(Config.from_jsons(string, *args, **kwargs))

yaml

Python
yaml(file: File, main_process_only: bool = True, *args, **kwargs) -> None

Dump Runner config to yaml file.

Source code in danling/runner/base_runner.py
Python
@catch
def yaml(self, file: File, main_process_only: bool = True, *args, **kwargs) -> None:  # pylint: disable=R1710
    r"""
    Dump Runner config to yaml file.
    """

    if main_process_only and self.is_main_process or not main_process_only:
        return self.config.yaml(file, *args, **kwargs)

from_yaml classmethod

Python
from_yaml(file: File, *args, **kwargs) -> BaseRunner

Construct Runner from yaml file.

This function calls self.from_yamls() to construct object from yaml string. You may overwrite from_yamls in case something is not yaml serializable.

Source code in danling/runner/base_runner.py
Python
@classmethod
def from_yaml(cls, file: File, *args, **kwargs) -> BaseRunner:
    r"""
    Construct Runner from yaml file.

    This function calls `self.from_yamls()` to construct object from yaml string.
    You may overwrite `from_yamls` in case something is not yaml serializable.
    """

    with FlatDict.open(file) as fp:
        return cls.from_yamls(fp.read(), *args, **kwargs)

yamls

Python
yamls(*args, **kwargs) -> str

Dump Runner config to yaml string.

Source code in danling/runner/base_runner.py
Python
def yamls(self, *args, **kwargs) -> str:
    r"""
    Dump Runner config to yaml string.
    """

    return self.config.yamls(*args, **kwargs)

from_yamls classmethod

Python
from_yamls(string: str, *args, **kwargs) -> BaseRunner

Construct Runner from yaml string.

Source code in danling/runner/base_runner.py
Python
@classmethod
def from_yamls(cls, string: str, *args, **kwargs) -> BaseRunner:
    r"""
    Construct Runner from yaml string.
    """

    return cls(Config.from_yamls(string, *args, **kwargs))

check_dir

Python
check_dir(action: str = 'warn') -> bool

Check if self.dir is not empty.

Parameters:

Name Type Description Default
action str

The action to perform if self.dir is not empty.

'warn'
Source code in danling/runner/base_runner.py
Python
def check_dir(self, action: str = "warn") -> bool:
    r"""
    Check if `self.dir` is not empty.

    Args:
        action (str): The action to perform if `self.dir` is not empty.
        Can be one of ("warn", "raise", "ignore"), default is "warn".
    """

    if action and action not in ("warn", "raise", "ignore"):
        raise ValueError(f"action should be one of warn, raise or ignore, but got {action}")
    if os.listdir(self.dir):
        if action == "warn":
            warn(
                f"Directory `{self.dir}` is not empty",
                category=RuntimeWarning,
                stacklevel=2,
            )
        if action == "raise":
            raise RuntimeError(f"Directory `{self.dir}` is not empty")
        return False
    return True

save_checkpoint

Python
save_checkpoint(epoch: int | None = None) -> None

Save checkpoint to self.checkpoint_dir.

The checkpoint will be saved to self.checkpoint_dir/latest.pth.

If self.config.save_interval is positive and self.config.epoch + 1 is a multiple of save_interval, the checkpoint will also be copied to self.checkpoint_dir/epoch-{self.config.epoch}.pth.

If self.is_best is True, the checkpoint will also be copied to self.checkpoint_dir/best.pth.

Source code in danling/runner/base_runner.py
Python
@catch
@on_main_process
def save_checkpoint(self, epoch: int | None = None) -> None:
    r"""
    Save checkpoint to `self.checkpoint_dir`.

    The checkpoint will be saved to `self.checkpoint_dir/latest.pth`.

    If `self.config.save_interval` is positive and `self.config.epoch + 1` is a multiple of `save_interval`,
    the checkpoint will also be copied to `self.checkpoint_dir/epoch-{self.config.epoch}.pth`.

    If `self.is_best` is `True`, the checkpoint will also be copied to `self.checkpoint_dir/best.pth`.
    """

    epoch = epoch or self.config.epoch
    save_interval = self.config.get("save_interval", -1)
    latest_path = os.path.join(self.checkpoint_dir, "latest.pth")
    self.save(self.state_dict(), latest_path)
    if save_interval > 0 and (epoch + 1) % save_interval == 0:
        save_path = os.path.join(self.checkpoint_dir, f"epoch-{epoch}.pth")
        shutil.copy(latest_path, save_path)
    if self.is_best:
        best_path = os.path.join(self.checkpoint_dir, "best.pth")
        shutil.copy(latest_path, best_path)

load_checkpoint

Python
load_checkpoint(checkpoint: Mapping | bytes | str | PathLike | None = None, auto_resume: bool | None = None, override_config: bool = False, *args, **kwargs) -> None

Load info from checkpoint.

Parameters:

Name Type Description Default
checkpoint Mapping | bytes | str | PathLike | None

Checkpoint (or its path) to load. Defaults to self.config.checkpoint.

None
auto_resume bool | None

Automatically resume from latest checkpoint if exists. Defaults to False. If is True and checkpoint is None, will set it to self.checkpoint_dir/latest.pth.

None
override_config bool

If True, override runner config with checkpoint config. Defaults to False.

False
*args

Additional arguments to pass to self.load.

()
**kwargs

Additional keyword arguments to pass to self.load.

{}

Raises:

Type Description
FileNotFoundError

If checkpoint does not exists.

See Also

from_checkpoint: Build runner from checkpoint. load_pretrained: Load parameters from pretrained checkpoint.

Source code in danling/runner/base_runner.py
Python
def load_checkpoint(
    self,
    checkpoint: Mapping | bytes | str | os.PathLike | None = None,
    auto_resume: bool | None = None,
    override_config: bool = False,
    *args,
    **kwargs,
) -> None:
    """
    Load info from checkpoint.

    Args:
        checkpoint: Checkpoint (or its path) to load.
            Defaults to `self.config.checkpoint`.
        auto_resume: Automatically resume from latest checkpoint if exists.
            Defaults to `False`.
            If is `True` and `checkpoint` is None, will set it to `self.checkpoint_dir/latest.pth`.
        override_config: If True, override runner config with checkpoint config.
            Defaults to `False`.
        *args: Additional arguments to pass to `self.load`.
        **kwargs: Additional keyword arguments to pass to `self.load`.

    Raises:
        FileNotFoundError: If `checkpoint` does not exists.

    See Also:
        [`from_checkpoint`][danling.BaseRunner.from_checkpoint]: Build runner from checkpoint.
        [`load_pretrained`][danling.BaseRunner.load_pretrained]: Load parameters from pretrained checkpoint.
    """

    checkpoint = checkpoint if checkpoint is not None else self.config.get("checkpoint")
    auto_resume = auto_resume if auto_resume is not None else self.config.get("auto_resume", False)

    # TODO: Support loading checkpoints in other format
    if checkpoint is not None:
        if auto_resume:
            warn(
                "latest checkpoint is preempted by value specified in checkpoint",
                RuntimeWarning,
                stacklevel=2,
            )
        if isinstance(checkpoint, (bytes, str, os.PathLike)):
            if not os.path.exists(checkpoint):
                raise FileNotFoundError(f"checkpoint is set to {checkpoint!r} but does not exist")
            self.config.checkpoint = checkpoint
            ckpt = self.load(checkpoint, *args, **kwargs)
        elif isinstance(checkpoint, Mapping):
            ckpt = checkpoint
        else:
            raise ValueError(f"pretrained is set to {checkpoint!r} but is not a valid checkpoint")
    elif auto_resume:
        checkpoint = os.path.join(self.checkpoint_dir, "latest.pth")
        if os.path.exists(checkpoint):
            self.config.checkpoint = checkpoint
            ckpt = self.load(checkpoint, *args, **kwargs)
        else:
            warn("latest checkpoint does not exits", category=RuntimeWarning, stacklevel=2)
            return
    else:
        raise ValueError("checkpoint is not specified and auto_resume is not set to True")

    # TODO: Wrap state_dict in a dataclass
    self.config.merge(ckpt["runner"], overwrite=override_config)
    if self.model is not None and "model" in ckpt:
        model = self.unwrap(self.model)
        model.load_state_dict(ckpt["model"])
    if self.optimizer is not None and "optimizer" in ckpt:
        self.optimizer.load_state_dict(ckpt["optimizer"])
    if self.scheduler is not None and "scheduler" in ckpt:
        self.scheduler.load_state_dict(ckpt["scheduler"])
    self.config.iter_begin = self.config.iter
    self.config.step_begin = self.config.step
    self.config.epoch_begin = self.config.epoch

from_checkpoint classmethod

Python
from_checkpoint(checkpoint: Mapping | bytes | str | PathLike, *args, **kwargs) -> BaseRunner

Build BaseRunner from checkpoint.

Parameters:

Name Type Description Default
checkpoint Mapping | bytes | str | PathLike

Checkpoint (or its path) to load.

required
*args

Additional arguments to pass to cls.load.

()
**kwargs

Additional keyword arguments to pass to cls.load.

{}

Returns:

Type Description
BaseRunner
Source code in danling/runner/base_runner.py
Python
@classmethod
def from_checkpoint(cls, checkpoint: Mapping | bytes | str | os.PathLike, *args, **kwargs) -> BaseRunner:
    r"""
    Build BaseRunner from checkpoint.

    Args:
        checkpoint: Checkpoint (or its path) to load.
        *args: Additional arguments to pass to `cls.load`.
        **kwargs: Additional keyword arguments to pass to `cls.load`.

    Returns:
        (BaseRunner):
    """

    if isinstance(checkpoint, (bytes, str, os.PathLike)):
        ckpt = cls.load(checkpoint, *args, **kwargs)
    elif isinstance(checkpoint, Mapping):
        ckpt = checkpoint
    else:
        raise ValueError(f"checkpoint is set to {checkpoint} but is not a valid checkpoint")
    runner = cls(**ckpt["runner"])
    runner.load_checkpoint(ckpt, override_config=False)
    return runner

load_pretrained

Python
load_pretrained(checkpoint: Mapping | bytes | str | PathLike | None = None, *args, **kwargs) -> None

Load parameters from pretrained checkpoint.

This method only loads the model weights.

Parameters:

Name Type Description Default
checkpoint Mapping | bytes | str | PathLike | None

Pretrained checkpoint (or its path) to load. Defaults to self.config.pretrained.

None
*args

Additional arguments to pass to self.load.

()
**kwargs

Additional keyword arguments to pass to self.load.

{}

Raises:

Type Description
FileNotFoundError

If checkpoint does not exists.

See Also

load_checkpoint: Load info from checkpoint.

Source code in danling/runner/base_runner.py
Python
def load_pretrained(self, checkpoint: Mapping | bytes | str | os.PathLike | None = None, *args, **kwargs) -> None:
    """
    Load parameters from pretrained checkpoint.

    This method only loads the model weights.

    Args:
        checkpoint: Pretrained checkpoint (or its path) to load.
            Defaults to `self.config.pretrained`.
        *args: Additional arguments to pass to `self.load`.
        **kwargs: Additional keyword arguments to pass to `self.load`.

    Raises:
        FileNotFoundError: If `checkpoint` does not exists.

    See Also:
        [`load_checkpoint`][danling.BaseRunner.load_checkpoint]: Load info from checkpoint.
    """

    # TODO: Support loading checkpoints in other format
    checkpoint = checkpoint if checkpoint is not None else self.config.get("pretrained")
    if checkpoint is None:
        raise ValueError("pretrained is not specified")
    if isinstance(checkpoint, (bytes, str, os.PathLike)):
        if not os.path.exists(checkpoint):
            raise FileNotFoundError(f"pretrained is set to {checkpoint!r} but does not exist")
        ckpt = self.load(checkpoint, *args, **kwargs)
    elif isinstance(checkpoint, Mapping):
        ckpt = checkpoint
    else:
        raise ValueError(f"pretrained is set to {checkpoint!r} but is not a valid checkpoint")
    if self.model is not None and "model" in ckpt:
        model = self.unwrap(self.model)
        model.load_state_dict(ckpt["model"])
    else:
        raise ValueError(f"Unable to find model weights in {checkpoint!r}")

append_result

Python
append_result(result: NestedDict, index: int | None = None) -> None

Append result to self.results.

Source code in danling/runner/base_runner.py
Python
def append_result(self, result: NestedDict, index: int | None = None) -> None:
    r"""
    Append result to `self.results`.

    Warnings:
        `self.results` is heavily relied upon for computing metrics.

        Failed to use this method may lead to unexpected behavior.
    """

    if index is None:
        index = self.config.epoch
        global __APPEND_RESULT_COUNTER__  # pylint: disable=global-statement
        __APPEND_RESULT_COUNTER__ += 1
        if index == 0 and __APPEND_RESULT_COUNTER__ > 1:
            warn(
                """
                Automatically set index to `self.config.epoch`.
                Please ensure `self.config.epoch` updates before calling `append_result`
                """,
                category=RuntimeWarning,
                stacklevel=2,
            )
    if index in self.results:
        self.results[index].merge(result)
    else:
        self.results[index] = result

print_result

Python
print_result() -> None

Print latest and best result.

Source code in danling/runner/base_runner.py
Python
def print_result(self) -> None:
    r"""
    Print latest and best result.
    """

    print(f"latest result: {self.latest_result}")
    print(f"best result: {self.best_result}")

save_result

Python
save_result() -> None

Save result to self.dir.

This method will save latest and best result to self.dir/latest.json and self.dir/best.json respectively.

Source code in danling/runner/base_runner.py
Python
@catch
@on_main_process
def save_result(self) -> None:
    r"""
    Save result to `self.dir`.

    This method will save latest and best result to
    `self.dir/latest.json` and `self.dir/best.json` respectively.
    """

    results_path = os.path.join(self.dir, "results.json")
    self.save(
        {
            "name": self.name,
            "id": self.id,
            "timestamp": self.timestamp,
            "results": self.results,
        },
        results_path,
        indent=4,
    )
    ret = {"name": self.name, "id": self.id, "timestamp": self.timestamp}
    result = self.latest_result
    if isinstance(result, FlatDict):
        result = result.dict()
    # This is slower but ensure id is the first key
    if result is not None:
        ret.update(result)
    latest_path = os.path.join(self.dir, "latest.json")
    self.save(ret, latest_path, indent=4)
    if self.is_best:
        best_path = os.path.join(self.dir, "best.json")
        shutil.copy(latest_path, best_path)