Skip to content

DanLing

danling

AverageMeter

Computes and stores the average and current value.

Attributes:

Name Type Description
val

Results of current batch on current device.

bat

Results of current batch on all devices.

avg

Results of all results on all devices.

sum float

Sum of values.

count float

Number of values.

See Also

[MetricMeter]: Average Meter with metric function built-in. [AverageMeters]: Manage multiple average meters in one object. [MultiTaskAverageMeters]: Manage multiple average meters in one object with multi-task support.

Examples:

Python Console Session
>>> meter = AverageMeter()
>>> meter.update(0.7)
>>> meter.val
0.7
>>> meter.avg
0.7
>>> meter.update(0.9)
>>> meter.val
0.9
>>> meter.avg
0.8
>>> meter.sum
1.6
>>> meter.count
2
>>> meter.reset()
>>> meter.val
0.0
>>> meter.avg
nan
Source code in danling/metrics/average_meter.py
Python
class AverageMeter:
    r"""
    Computes and stores the average and current value.

    Attributes:
        val: Results of current batch on current device.
        bat: Results of current batch on all devices.
        avg: Results of all results on all devices.
        sum: Sum of values.
        count: Number of values.

    See Also:
        [`MetricMeter`]: Average Meter with metric function built-in.
        [`AverageMeters`]: Manage multiple average meters in one object.
        [`MultiTaskAverageMeters`]: Manage multiple average meters in one object with multi-task support.

    Examples:
        >>> meter = AverageMeter()
        >>> meter.update(0.7)
        >>> meter.val
        0.7
        >>> meter.avg
        0.7
        >>> meter.update(0.9)
        >>> meter.val
        0.9
        >>> meter.avg
        0.8
        >>> meter.sum
        1.6
        >>> meter.count
        2
        >>> meter.reset()
        >>> meter.val
        0.0
        >>> meter.avg
        nan
    """

    v: float = 0
    n: float = 1
    sum: float = 0
    count: float = 0

    def __init__(self) -> None:
        self.reset()

    def reset(self) -> None:
        r"""
        Resets the meter.
        """

        self.v = 0
        self.n = 1
        self.sum = 0
        self.count = 0

    def update(self, value, n: float = 1) -> None:
        r"""
        Updates the average and current value in the meter.

        Args:
            value: Value to be added to the average.
            n: Number of values to be added.
        """

        self.v = value
        self.n = n
        self.sum += value
        self.count += n

    def value(self):
        return self.v / self.n if self.n != 0 else float("nan")

    def batch(self):
        world_size = get_world_size()
        if world_size <= 1:
            return self.value()
        synced_tensor = torch.tensor([self.v * self.n, self.n], dtype=torch.float64).cuda()
        dist.all_reduce(synced_tensor)
        val, count = synced_tensor
        if count == 0:
            return float("nan")
        return (val / count).item()

    def average(self):
        world_size = get_world_size()
        if world_size <= 1:
            return self.sum / self.count if self.count != 0 else float("nan")
        synced_tensor = torch.tensor([self.sum, self.count], dtype=torch.float64).cuda()
        dist.all_reduce(synced_tensor)
        val, count = synced_tensor
        if count == 0:
            return float("nan")
        return (val / count).item()

    @property
    def val(self):
        return self.value()

    @property
    def bat(self):
        return self.batch()

    @property
    def avg(self):
        return self.average()

    def __format__(self, format_spec) -> str:
        return f"{self.val.__format__(format_spec)} ({self.avg.__format__(format_spec)})"

reset

Python
reset() -> None

Resets the meter.

Source code in danling/metrics/average_meter.py
Python
def reset(self) -> None:
    r"""
    Resets the meter.
    """

    self.v = 0
    self.n = 1
    self.sum = 0
    self.count = 0

update

Python
update(value, n: float = 1) -> None

Updates the average and current value in the meter.

Parameters:

Name Type Description Default
value

Value to be added to the average.

required
n
float

Number of values to be added.

1
Source code in danling/metrics/average_meter.py
Python
def update(self, value, n: float = 1) -> None:
    r"""
    Updates the average and current value in the meter.

    Args:
        value: Value to be added to the average.
        n: Number of values to be added.
    """

    self.v = value
    self.n = n
    self.sum += value
    self.count += n

AverageMeters

Bases: MetricsDict

Manages multiple average meters in one object.

See Also

[AverageMeter]: Computes and stores the average and current value. [MultiTaskAverageMeters]: Manage multiple average meters in one object with multi-task support. [MetricMeters]: Manage multiple metric meters in one object.

Examples:

Python Console Session
>>> meters = AverageMeters()
>>> meters.update({"loss": 0.6, "auroc": 0.7, "r2": 0.8})
>>> f"{meters:.4f}"
'loss: 0.6000 (0.6000)\tauroc: 0.7000 (0.7000)\tr2: 0.8000 (0.8000)'
>>> meters['loss'].update(value=0.9, n=1)
>>> f"{meters:.4f}"
'loss: 0.9000 (0.7500)\tauroc: 0.7000 (0.7000)\tr2: 0.8000 (0.8000)'
>>> meters.sum.dict()
{'loss': 1.5, 'auroc': 0.7, 'r2': 0.8}
>>> meters.count.dict()
{'loss': 2, 'auroc': 1, 'r2': 1}
>>> meters.reset()
>>> f"{meters:.4f}"
'loss: 0.0000 (nan)\tauroc: 0.0000 (nan)\tr2: 0.0000 (nan)'
Source code in danling/metrics/average_meter.py
Python
class AverageMeters(MetricsDict):
    r"""
    Manages multiple average meters in one object.

    See Also:
        [`AverageMeter`]: Computes and stores the average and current value.
        [`MultiTaskAverageMeters`]: Manage multiple average meters in one object with multi-task support.
        [`MetricMeters`]: Manage multiple metric meters in one object.

    Examples:
        >>> meters = AverageMeters()
        >>> meters.update({"loss": 0.6, "auroc": 0.7, "r2": 0.8})
        >>> f"{meters:.4f}"
        'loss: 0.6000 (0.6000)\tauroc: 0.7000 (0.7000)\tr2: 0.8000 (0.8000)'
        >>> meters['loss'].update(value=0.9, n=1)
        >>> f"{meters:.4f}"
        'loss: 0.9000 (0.7500)\tauroc: 0.7000 (0.7000)\tr2: 0.8000 (0.8000)'
        >>> meters.sum.dict()
        {'loss': 1.5, 'auroc': 0.7, 'r2': 0.8}
        >>> meters.count.dict()
        {'loss': 2, 'auroc': 1, 'r2': 1}
        >>> meters.reset()
        >>> f"{meters:.4f}"
        'loss: 0.0000 (nan)\tauroc: 0.0000 (nan)\tr2: 0.0000 (nan)'
    """

    def __init__(self, *args, default_factory: Type[AverageMeter] = AverageMeter, **kwargs) -> None:
        for meter in args:
            if not isinstance(meter, AverageMeter):
                raise ValueError(f"Expected meter to be an instance of AverageMeter, but got {type(meter)}")
        for name, meter in kwargs.items():
            if not isinstance(meter, AverageMeter):
                raise ValueError(f"Expected {name} to be an instance of AverageMeter, but got {type(meter)}")
        super().__init__(*args, default_factory=default_factory, **kwargs)

    @property
    def sum(self) -> FlatDict[str, float]:
        return FlatDict({key: meter.sum for key, meter in self.all_items()})

    @property
    def count(self) -> FlatDict[str, int]:
        return FlatDict({key: meter.count for key, meter in self.all_items()})

    def update(self, *args: Dict, **values: int | float) -> None:  # pylint: disable=W0237
        r"""
        Updates the average and current value in all meters.

        Args:
            values: Dict of values to be added to the average.
            n: Number of values to be added.

        Raises:
            ValueError: If the value is not an instance of (int, float).
        """  # noqa: E501

        if args:
            if len(args) > 1:
                raise ValueError("Expected only one positional argument, but got multiple.")
            values = args[0].update(values) or args[0] if values else args[0]

        for meter, value in values.items():
            if not isinstance(value, (int, float)):
                raise ValueError(f"Expected values to be int or float, but got {type(value)}")
            self[meter].update(value)

    def set(self, name: str, meter: AverageMeter) -> None:  # pylint: disable=W0237
        if not isinstance(meter, AverageMeter):
            raise ValueError(f"Expected meter to be an instance of AverageMeter, but got {type(meter)}")
        super().set(name, meter)

update

Python
update(*args: Dict, **values: int | float) -> None

Updates the average and current value in all meters.

Parameters:

Name Type Description Default
values
int | float

Dict of values to be added to the average.

{}
n

Number of values to be added.

required

Raises:

Type Description
ValueError

If the value is not an instance of (int, float).

Source code in danling/metrics/average_meter.py
Python
def update(self, *args: Dict, **values: int | float) -> None:  # pylint: disable=W0237
    r"""
    Updates the average and current value in all meters.

    Args:
        values: Dict of values to be added to the average.
        n: Number of values to be added.

    Raises:
        ValueError: If the value is not an instance of (int, float).
    """  # noqa: E501

    if args:
        if len(args) > 1:
            raise ValueError("Expected only one positional argument, but got multiple.")
        values = args[0].update(values) or args[0] if values else args[0]

    for meter, value in values.items():
        if not isinstance(value, (int, float)):
            raise ValueError(f"Expected values to be int or float, but got {type(value)}")
        self[meter].update(value)

MetricMeter

Bases: AverageMeter

Computes metrics and averages them over time.

Attributes:

Name Type Description
metric Callable

Metric function for computing the value.

ignored_index Optional[int]

Index to be ignored in the computation.

val Optional[int]

Results of current batch on current device.

bat Optional[int]

Results of current batch on all devices.

avg Optional[int]

Results of all results on all devices.

sum Optional[int]

Sum of values.

count Optional[int]

Number of values.

See Also

[AverageMeter]: Average meter for computed values. [MetricMeters]: Manage multiple metric meters in one object.

Examples:

Python Console Session
>>> from danling.metrics.functional import accuracy
>>> meter = MetricMeter(accuracy)
>>> meter.update([0.1, 0.8, 0.6, 0.2], [0, 1, 0, 0])
>>> meter.val
0.75
>>> meter.avg
0.75
>>> meter.update([0.1, 0.7, 0.3, 0.2, 0.8, 0.4], [0, 1, 1, 0, 0, 1])
>>> meter.val
0.5
>>> meter.avg
0.6
>>> meter.sum
6.0
>>> meter.count
10
>>> meter.reset()
>>> meter.val
0.0
>>> meter.avg
nan
Source code in danling/metrics/metric_meter.py
Python
class MetricMeter(AverageMeter):
    r"""
    Computes metrics and averages them over time.

    Attributes:
        metric: Metric function for computing the value.
        ignored_index: Index to be ignored in the computation.
        val: Results of current batch on current device.
        bat: Results of current batch on all devices.
        avg: Results of all results on all devices.
        sum: Sum of values.
        count: Number of values.

    See Also:
        [`AverageMeter`]: Average meter for computed values.
        [`MetricMeters`]: Manage multiple metric meters in one object.

    Examples:
        >>> from danling.metrics.functional import accuracy
        >>> meter = MetricMeter(accuracy)
        >>> meter.update([0.1, 0.8, 0.6, 0.2], [0, 1, 0, 0])
        >>> meter.val
        0.75
        >>> meter.avg
        0.75
        >>> meter.update([0.1, 0.7, 0.3, 0.2, 0.8, 0.4], [0, 1, 1, 0, 0, 1])
        >>> meter.val
        0.5
        >>> meter.avg
        0.6
        >>> meter.sum
        6.0
        >>> meter.count
        10
        >>> meter.reset()
        >>> meter.val
        0.0
        >>> meter.avg
        nan
    """

    metric: Callable
    preprocess: Callable
    ignored_index: Optional[int] = None

    def __init__(
        self, metric: Callable, preprocess: Callable = default_preprocess, ignored_index: int | None = None
    ) -> None:
        self.metric = metric
        self.preprocess = preprocess
        self.ignored_index = ignored_index
        super().__init__()

    def update(  # type: ignore[override] # pylint: disable=W0237
        self,
        input: Tensor | NestedTensor | Sequence,  # pylint: disable=W0622
        target: Tensor | NestedTensor | Sequence,
    ) -> None:
        r"""
        Updates the average and current value in the meter.

        Args:
            value: Value to be added to the average.
            n: Number of values to be added.
        """
        input, target = self.preprocess(input, target, ignored_index=self.ignored_index)
        n = len(input)
        super().update(self.metric(input, target).item() * n, n=n)

update

Python
update(input: Tensor | NestedTensor | Sequence, target: Tensor | NestedTensor | Sequence) -> None

Updates the average and current value in the meter.

Parameters:

Name Type Description Default
value

Value to be added to the average.

required
n

Number of values to be added.

required
Source code in danling/metrics/metric_meter.py
Python
def update(  # type: ignore[override] # pylint: disable=W0237
    self,
    input: Tensor | NestedTensor | Sequence,  # pylint: disable=W0622
    target: Tensor | NestedTensor | Sequence,
) -> None:
    r"""
    Updates the average and current value in the meter.

    Args:
        value: Value to be added to the average.
        n: Number of values to be added.
    """
    input, target = self.preprocess(input, target, ignored_index=self.ignored_index)
    n = len(input)
    super().update(self.metric(input, target).item() * n, n=n)

MetricMeters

Bases: AverageMeters

Manages multiple metric meters in one object.

Attributes:

Name Type Description
ignored_index

Index to be ignored in the computation. Defaults to None.

See Also

[MetricMeter]: Computes metrics and averages them over time. [AverageMeters]: Average meters for computed values.

from danling.metrics.functional import accuracy, auroc, auprc meters = MetricMeters(acc=accuracy, auroc=auroc, auprc=auprc) meters.update([0.1, 0.8, 0.6, 0.2], [0, 1, 0, 0]) meters.sum.dict() {‘acc’: 3.0, ‘auroc’: 4.0, ‘auprc’: 4.0} meters.count.dict() {‘acc’: 4, ‘auroc’: 4, ‘auprc’: 4} meters[‘auroc’].update([0.2, 0.8], [0, 1]) meters.sum.dict() {‘acc’: 3.0, ‘auroc’: 6.0, ‘auprc’: 4.0} meters.count.dict() {‘acc’: 4, ‘auroc’: 6, ‘auprc’: 4} meters.update([[0.1, 0.7, 0.3, 0.2], [0.8, 0.4]], [[0, 0, 1, 0], [0, 0]]) meters.sum.dict() {‘acc’: 6.0, ‘auroc’: 8.4, ‘auprc’: 5.5} meters.count.dict() {‘acc’: 10, ‘auroc’: 12, ‘auprc’: 10} meters[‘auroc’].update([0.4, 0.8, 0.6, 0.2], [0, 1, 1, 0]) meters.avg.dict() {‘acc’: 0.6, ‘auroc’: 0.775, ‘auprc’: 0.55} meters.update(dict(loss=”“)) # doctest: +ELLIPSIS Traceback (most recent call last): TypeError: …update() missing 1 required positional argument: ‘target’

Source code in danling/metrics/metric_meter.py
Python
class MetricMeters(AverageMeters):
    r"""
    Manages multiple metric meters in one object.

    Attributes:
        ignored_index: Index to be ignored in the computation.
            Defaults to None.

    See Also:
        [`MetricMeter`]: Computes metrics and averages them over time.
        [`AverageMeters`]: Average meters for computed values.

    >>> from danling.metrics.functional import accuracy, auroc, auprc
    >>> meters = MetricMeters(acc=accuracy, auroc=auroc, auprc=auprc)
    >>> meters.update([0.1, 0.8, 0.6, 0.2], [0, 1, 0, 0])
    >>> meters.sum.dict()
    {'acc': 3.0, 'auroc': 4.0, 'auprc': 4.0}
    >>> meters.count.dict()
    {'acc': 4, 'auroc': 4, 'auprc': 4}
    >>> meters['auroc'].update([0.2, 0.8], [0, 1])
    >>> meters.sum.dict()
    {'acc': 3.0, 'auroc': 6.0, 'auprc': 4.0}
    >>> meters.count.dict()
    {'acc': 4, 'auroc': 6, 'auprc': 4}
    >>> meters.update([[0.1, 0.7, 0.3, 0.2], [0.8, 0.4]], [[0, 0, 1, 0], [0, 0]])
    >>> meters.sum.dict()
    {'acc': 6.0, 'auroc': 8.4, 'auprc': 5.5}
    >>> meters.count.dict()
    {'acc': 10, 'auroc': 12, 'auprc': 10}
    >>> meters['auroc'].update([0.4, 0.8, 0.6, 0.2], [0, 1, 1, 0])
    >>> meters.avg.dict()
    {'acc': 0.6, 'auroc': 0.775, 'auprc': 0.55}
    >>> meters.update(dict(loss=""))  # doctest: +ELLIPSIS
    Traceback (most recent call last):
    TypeError: ...update() missing 1 required positional argument: 'target'
    """

    preprocess: Callable
    ignored_index = None

    def __init__(
        self, *args, preprocess: Callable = default_preprocess, ignored_index: int | None = None, **kwargs
    ) -> None:
        self.setattr("preprocess", preprocess)
        self.setattr("ignored_index", ignored_index)
        for meter in args:
            if callable(meter):
                meter = MetricMeter(meter, ignored_index=self.ignored_index)
            if not isinstance(meter, MetricMeter):
                raise ValueError(f"Expected meter to be an instance of MetricMeter, but got {type(meter)}")
        for name, meter in kwargs.items():
            if callable(meter):
                kwargs[name] = meter = MetricMeter(meter, ignored_index=self.ignored_index)
            if not isinstance(meter, MetricMeter):
                raise ValueError(f"Expected {name} to be an instance of MetricMeter, but got {type(meter)}")
        if ignored_index is not None:
            self.setattr("ignored_index", ignored_index)
        super().__init__(*args, default_factory=None, **kwargs)  # type: ignore[arg-type]

    def update(  # type: ignore[override] # pylint: disable=W0221
        self,
        input: Tensor | NestedTensor | Sequence,  # pylint: disable=W0622
        target: Tensor | NestedTensor | Sequence,
    ) -> None:
        r"""
        Updates the average and current value in all meters.

        Args:
            input: Input values to compute the metrics.
            target: Target values to compute the metrics.
        """

        input, target = self.preprocess(input, target, ignored_index=self.ignored_index)
        for meter in self.values():
            meter.update(input, target)

    def set(self, name: str, meter: MetricMeter | Callable) -> None:  # type: ignore[override] # pylint: disable=W0237
        if callable(meter):
            meter = MetricMeter(meter, ignored_index=self.ignored_index)
        if not isinstance(meter, MetricMeter):
            raise ValueError(f"Expected meter to be an instance of MetricMeter, but got {type(meter)}")
        super().set(name, meter)

    def __repr__(self):
        keys = tuple(i for i in self.keys())
        return f"{self.__class__.__name__}{keys}"

update

Updates the average and current value in all meters.

Parameters:

Name Type Description Default
input
Tensor | NestedTensor | Sequence

Input values to compute the metrics.

required
target
Tensor | NestedTensor | Sequence

Target values to compute the metrics.

required
Source code in danling/metrics/metric_meter.py
Python
def update(  # type: ignore[override] # pylint: disable=W0221
    self,
    input: Tensor | NestedTensor | Sequence,  # pylint: disable=W0622
    target: Tensor | NestedTensor | Sequence,
) -> None:
    r"""
    Updates the average and current value in all meters.

    Args:
        input: Input values to compute the metrics.
        target: Target values to compute the metrics.
    """

    input, target = self.preprocess(input, target, ignored_index=self.ignored_index)
    for meter in self.values():
        meter.update(input, target)

MultiTaskAverageMeters

Bases: MultiTaskDict

Manages multiple average meters in one object with multi-task support.

See Also

[AverageMeter]: Computes and stores the average and current value. [AverageMeters]: Manage multiple average meters in one object. [MetricMeters]: Manage multiple metric meters in one object.

Examples:

Python Console Session
>>> meters = MultiTaskAverageMeters()
>>> meters.update({"loss": 0.6, "dataset1.cls.auroc": 0.7, "dataset1.reg.r2": 0.8, "dataset2.r2": 0.9})
>>> f"{meters:.4f}"
'loss: 0.6000 (0.6000)\ndataset1.cls.auroc: 0.7000 (0.7000)\ndataset1.reg.r2: 0.8000 (0.8000)\ndataset2.r2: 0.9000 (0.9000)'
>>> meters['loss'].update(0.9, n=1)
>>> f"{meters:.4f}"
'loss: 0.9000 (0.7500)\ndataset1.cls.auroc: 0.7000 (0.7000)\ndataset1.reg.r2: 0.8000 (0.8000)\ndataset2.r2: 0.9000 (0.9000)'
>>> meters.sum.dict()
{'loss': 1.5, 'dataset1': {'cls': {'auroc': 0.7}, 'reg': {'r2': 0.8}}, 'dataset2': {'r2': 0.9}}
>>> meters.count.dict()
{'loss': 2, 'dataset1': {'cls': {'auroc': 1}, 'reg': {'r2': 1}}, 'dataset2': {'r2': 1}}
>>> meters.reset()
>>> f"{meters:.4f}"
'loss: 0.0000 (nan)\ndataset1.cls.auroc: 0.0000 (nan)\ndataset1.reg.r2: 0.0000 (nan)\ndataset2.r2: 0.0000 (nan)'
>>> meters = MultiTaskAverageMeters(return_average=True)
>>> meters.update({"loss": 0.6, "dataset1.a.auroc": 0.7, "dataset1.b.auroc": 0.8, "dataset2.auroc": 0.9})
>>> f"{meters:.4f}"
'loss: 0.6000 (0.6000)\ndataset1.a.auroc: 0.7000 (0.7000)\ndataset1.b.auroc: 0.8000 (0.8000)\ndataset2.auroc: 0.9000 (0.9000)'
>>> meters.update({"loss": 0.9, "dataset1.a.auroc": 0.8, "dataset1.b.auroc": 0.9, "dataset2.auroc": 1.0})
>>> f"{meters:.4f}"
'loss: 0.9000 (0.7500)\ndataset1.a.auroc: 0.8000 (0.7500)\ndataset1.b.auroc: 0.9000 (0.8500)\ndataset2.auroc: 1.0000 (0.9500)'
Source code in danling/metrics/average_meter.py
Python
class MultiTaskAverageMeters(MultiTaskDict):
    r"""
    Manages multiple average meters in one object with multi-task support.

    See Also:
        [`AverageMeter`]: Computes and stores the average and current value.
        [`AverageMeters`]: Manage multiple average meters in one object.
        [`MetricMeters`]: Manage multiple metric meters in one object.

    Examples:
        >>> meters = MultiTaskAverageMeters()
        >>> meters.update({"loss": 0.6, "dataset1.cls.auroc": 0.7, "dataset1.reg.r2": 0.8, "dataset2.r2": 0.9})
        >>> f"{meters:.4f}"
        'loss: 0.6000 (0.6000)\ndataset1.cls.auroc: 0.7000 (0.7000)\ndataset1.reg.r2: 0.8000 (0.8000)\ndataset2.r2: 0.9000 (0.9000)'
        >>> meters['loss'].update(0.9, n=1)
        >>> f"{meters:.4f}"
        'loss: 0.9000 (0.7500)\ndataset1.cls.auroc: 0.7000 (0.7000)\ndataset1.reg.r2: 0.8000 (0.8000)\ndataset2.r2: 0.9000 (0.9000)'
        >>> meters.sum.dict()
        {'loss': 1.5, 'dataset1': {'cls': {'auroc': 0.7}, 'reg': {'r2': 0.8}}, 'dataset2': {'r2': 0.9}}
        >>> meters.count.dict()
        {'loss': 2, 'dataset1': {'cls': {'auroc': 1}, 'reg': {'r2': 1}}, 'dataset2': {'r2': 1}}
        >>> meters.reset()
        >>> f"{meters:.4f}"
        'loss: 0.0000 (nan)\ndataset1.cls.auroc: 0.0000 (nan)\ndataset1.reg.r2: 0.0000 (nan)\ndataset2.r2: 0.0000 (nan)'
        >>> meters = MultiTaskAverageMeters(return_average=True)
        >>> meters.update({"loss": 0.6, "dataset1.a.auroc": 0.7, "dataset1.b.auroc": 0.8, "dataset2.auroc": 0.9})
        >>> f"{meters:.4f}"
        'loss: 0.6000 (0.6000)\ndataset1.a.auroc: 0.7000 (0.7000)\ndataset1.b.auroc: 0.8000 (0.8000)\ndataset2.auroc: 0.9000 (0.9000)'
        >>> meters.update({"loss": 0.9, "dataset1.a.auroc": 0.8, "dataset1.b.auroc": 0.9, "dataset2.auroc": 1.0})
        >>> f"{meters:.4f}"
        'loss: 0.9000 (0.7500)\ndataset1.a.auroc: 0.8000 (0.7500)\ndataset1.b.auroc: 0.9000 (0.8500)\ndataset2.auroc: 1.0000 (0.9500)'
    """  # noqa: E501

    @property
    def sum(self) -> NestedDict[str, float]:
        return NestedDict({key: meter.sum for key, meter in self.all_items()})

    @property
    def count(self) -> NestedDict[str, int]:
        return NestedDict({key: meter.count for key, meter in self.all_items()})

    def update(self, *args: Dict, **values: float) -> None:  # pylint: disable=W0237
        r"""
        Updates the average and current value in all meters.

        Args:
            values: Dict of values to be added to the average.
            n: Number of values to be added.

        Raises:
            ValueError: If the value is not an instance of (int, float, Mapping).
        """  # noqa: E501

        if args:
            if len(args) > 1:
                raise ValueError("Expected only one positional argument, but got multiple.")
            values = args[0].update(values) or args[0] if values else args[0]

        for meter, value in values.items():
            if not isinstance(value, (int, float, Mapping)):
                raise ValueError(f"Expected values to be int, float, or a Mapping, but got {type(value)}")
            self[meter].update(value)

    # evil hack, as the default_factory must not be set to make `NestedDict` happy
    # this have some side effects, it will break attribute style intermediate nested dict auto creation
    # but everything has a price
    def get(self, name: Any, default=None) -> Any:
        if not name.startswith("_") and not name.endswith("_"):
            return self.setdefault(name, AverageMeter())
        return super().get(name, default)

    def set(self, name: str, meter: AverageMeter | AverageMeters) -> None:  # pylint: disable=W0237
        if not isinstance(meter, (AverageMeter, AverageMeters)):
            raise ValueError(
                f"Expected meter to be an instance of AverageMeter or AverageMeters, but got {type(meter)}"
            )
        super().set(name, meter)

update

Python
update(*args: Dict, **values: float) -> None

Updates the average and current value in all meters.

Parameters:

Name Type Description Default
values
float

Dict of values to be added to the average.

{}
n

Number of values to be added.

required

Raises:

Type Description
ValueError

If the value is not an instance of (int, float, Mapping).

Source code in danling/metrics/average_meter.py
Python
def update(self, *args: Dict, **values: float) -> None:  # pylint: disable=W0237
    r"""
    Updates the average and current value in all meters.

    Args:
        values: Dict of values to be added to the average.
        n: Number of values to be added.

    Raises:
        ValueError: If the value is not an instance of (int, float, Mapping).
    """  # noqa: E501

    if args:
        if len(args) > 1:
            raise ValueError("Expected only one positional argument, but got multiple.")
        values = args[0].update(values) or args[0] if values else args[0]

    for meter, value in values.items():
        if not isinstance(value, (int, float, Mapping)):
            raise ValueError(f"Expected values to be int, float, or a Mapping, but got {type(value)}")
        self[meter].update(value)

MultiTaskMetricMeters

Bases: MultiTaskAverageMeters

Examples:

Python Console Session
>>> from danling.metrics.functional import accuracy
>>> metrics = MultiTaskMetricMeters()
>>> metrics.dataset1.cls = MetricMeters(acc=accuracy)
>>> metrics.dataset2 = MetricMeters(acc=accuracy)
>>> metrics
MultiTaskMetricMeters(<class 'danling.metrics.metric_meter.MultiTaskMetricMeters'>,
  ('dataset1'): MultiTaskMetricMeters(<class 'danling.metrics.metric_meter.MultiTaskMetricMeters'>,
    ('cls'): MetricMeters('acc',)
  )
  ('dataset2'): MetricMeters('acc',)
)
>>> metrics.update({"dataset1.cls": {"input": [0.2, 0.4, 0.5, 0.7], "target": [0, 1, 0, 1]}, "dataset2": ([0.1, 0.4, 0.6, 0.8], [1, 0, 0, 0])})
>>> f"{metrics:.4f}"
'dataset1.cls: acc: 0.5000 (0.5000)\ndataset2: acc: 0.2500 (0.2500)'
>>> metrics.setattr("return_average", True)
>>> metrics.update({"dataset1.cls": [[0.1, 0.4, 0.6, 0.8], [0, 0, 1, 0]], "dataset2": {"input": [0.2, 0.3, 0.5, 0.7], "target": [0, 0, 0, 1]}})
>>> f"{metrics:.4f}"
'dataset1.cls: acc: 0.7500 (0.6250)\ndataset2: acc: 0.7500 (0.5000)'
>>> metrics.update(dict(loss=""))
Traceback (most recent call last):
ValueError: Metric loss not found in ...
Source code in danling/metrics/metric_meter.py
Python
class MultiTaskMetricMeters(MultiTaskAverageMeters):
    r"""
    Examples:
        >>> from danling.metrics.functional import accuracy
        >>> metrics = MultiTaskMetricMeters()
        >>> metrics.dataset1.cls = MetricMeters(acc=accuracy)
        >>> metrics.dataset2 = MetricMeters(acc=accuracy)
        >>> metrics
        MultiTaskMetricMeters(<class 'danling.metrics.metric_meter.MultiTaskMetricMeters'>,
          ('dataset1'): MultiTaskMetricMeters(<class 'danling.metrics.metric_meter.MultiTaskMetricMeters'>,
            ('cls'): MetricMeters('acc',)
          )
          ('dataset2'): MetricMeters('acc',)
        )
        >>> metrics.update({"dataset1.cls": {"input": [0.2, 0.4, 0.5, 0.7], "target": [0, 1, 0, 1]}, "dataset2": ([0.1, 0.4, 0.6, 0.8], [1, 0, 0, 0])})
        >>> f"{metrics:.4f}"
        'dataset1.cls: acc: 0.5000 (0.5000)\ndataset2: acc: 0.2500 (0.2500)'
        >>> metrics.setattr("return_average", True)
        >>> metrics.update({"dataset1.cls": [[0.1, 0.4, 0.6, 0.8], [0, 0, 1, 0]], "dataset2": {"input": [0.2, 0.3, 0.5, 0.7], "target": [0, 0, 0, 1]}})
        >>> f"{metrics:.4f}"
        'dataset1.cls: acc: 0.7500 (0.6250)\ndataset2: acc: 0.7500 (0.5000)'
        >>> metrics.update(dict(loss=""))  # doctest: +ELLIPSIS
        Traceback (most recent call last):
        ValueError: Metric loss not found in ...
    """  # noqa: E501

    def __init__(self, *args, **kwargs):
        super().__init__(*args, default_factory=MultiTaskMetricMeters, **kwargs)

    def update(  # type: ignore[override] # pylint: disable=W0221
        self,
        values: Mapping[str, Tuple[Tensor | NestedTensor | Sequence, Tensor | NestedTensor | Sequence]],
    ) -> None:
        r"""
        Updates the average and current value in all meters.

        Args:
            input: Input values to compute the metrics.
            target: Target values to compute the metrics.
        """

        for metric, value in values.items():
            if metric not in self:
                raise ValueError(f"Metric {metric} not found in {self}")
            if isinstance(self[metric], MultiTaskMetricMeters):
                for met in self[metric].all_values():
                    if isinstance(value, Mapping):
                        met.update(**value)
                    elif isinstance(value, Sequence):
                        met.update(*value)
                    else:
                        raise ValueError(f"Expected value to be a Mapping or Sequence, but got {type(value)}")
            elif isinstance(self[metric], (MetricMeters, MetricMeter)):
                if isinstance(value, Mapping):
                    self[metric].update(**value)
                elif isinstance(value, Sequence):
                    self[metric].update(*value)
                else:
                    raise ValueError(f"Expected value to be a Mapping or Sequence, but got {type(value)}")
            else:
                raise ValueError(
                    f"Expected {metric} to be an instance of MultiTaskMetricMeters, MetricMeters, "
                    f"or MetricMeter, but got {type(self[metric])}"
                )

    # MultiTaskAverageMeters.get is hacked
    def get(self, name: Any, default=None) -> Any:
        return MultiTaskDict.get(self, name, default)

    def set(  # pylint: disable=W0237
        self,
        name: str,
        metric: MetricMeter | MetricMeters | Callable,  # type: ignore[override]
    ) -> None:
        if callable(metric):
            metric = MetricMeter(metric)
        if not isinstance(metric, (MetricMeter, MetricMeters)):
            raise ValueError(
                f"Expected {metric} to be an instance of MetricMeter or MetricMeters, but got {type(metric)}"
            )
        super().set(name, metric)

update

Python
update(values: Mapping[str, Tuple[Tensor | NestedTensor | Sequence, Tensor | NestedTensor | Sequence]]) -> None

Updates the average and current value in all meters.

Parameters:

Name Type Description Default
input

Input values to compute the metrics.

required
target

Target values to compute the metrics.

required
Source code in danling/metrics/metric_meter.py
Python
def update(  # type: ignore[override] # pylint: disable=W0221
    self,
    values: Mapping[str, Tuple[Tensor | NestedTensor | Sequence, Tensor | NestedTensor | Sequence]],
) -> None:
    r"""
    Updates the average and current value in all meters.

    Args:
        input: Input values to compute the metrics.
        target: Target values to compute the metrics.
    """

    for metric, value in values.items():
        if metric not in self:
            raise ValueError(f"Metric {metric} not found in {self}")
        if isinstance(self[metric], MultiTaskMetricMeters):
            for met in self[metric].all_values():
                if isinstance(value, Mapping):
                    met.update(**value)
                elif isinstance(value, Sequence):
                    met.update(*value)
                else:
                    raise ValueError(f"Expected value to be a Mapping or Sequence, but got {type(value)}")
        elif isinstance(self[metric], (MetricMeters, MetricMeter)):
            if isinstance(value, Mapping):
                self[metric].update(**value)
            elif isinstance(value, Sequence):
                self[metric].update(*value)
            else:
                raise ValueError(f"Expected value to be a Mapping or Sequence, but got {type(value)}")
        else:
            raise ValueError(
                f"Expected {metric} to be an instance of MultiTaskMetricMeters, MetricMeters, "
                f"or MetricMeter, but got {type(self[metric])}"
            )

LRScheduler

Bases: _LRScheduler

General learning rate scheduler.

PyTorch LRScheduler is hard to extend. This class is a wrapper of PyTorch LRScheduler, which provides a more general interface. You only needs to add a new method which calculates a learning rate ratio (range from 0 to 1) with total progress (range from 0 to 1), and everything else will be done automatically.

Moreover, this class has warmup and cooldown built-in. By default, the first 5% and last 20% of training steps will be warmup and cooldown respectively. You can alternate by passing warmup_steps and cooldown_steps, or disable them by setting them to 0.

Parameters:

Name Type Description Default

optimizer

Optimizer

Wrapped optimizer.

required

total_steps

int

Total number of trainable steps.

required

final_lr_ratio

Optional[float]

Final learning rate ratio to initial learning rate. Defaults to 1e-3.

None

final_lr

Optional[float]

Final learning rate.

None

min_lr

float

Minimal learning rate. Defaults to 1e-9.

1e-09

strategy

str

Scaling strategy. Defaults to “cosine”.

'cosine'

warmup_steps

Optional[int]

Number of warmup steps. Defaults to steps // 20.

None

cooldown_steps

Optional[int]

Number of cooldown steps. Defaults to steps // 5.

None

last_epoch

int

The index of last epoch. Defaults to -1.

-1

method

Optional[str]

Method to calculate learning rate given ratio, should be one of “percentile” or “numerical”. Defaults to “percentile” if final_lr_ratio is set, otherwise “numerical”.

None

Examples:

Python Console Session
>>> from danling.optim import LRScheduler
>>> import torch
>>> from torch import optim
>>> optimizer = optim.SGD([{'params': torch.tensor([0])}], lr=1, momentum=0.9)
>>> scheduler = LRScheduler(optimizer, total_steps=5, final_lr_ratio=1e-5, strategy='linear')
>>> lrs = []
>>> for epoch in range(5):
...     lrs.append(scheduler.get_lr()[0])
...     scheduler.step()
>>> [round(lr, 10) for lr in lrs]
[0.1, 0.01, 0.001, 0.0001, 1e-09]
>>> scheduler = LRScheduler(optimizer, total_steps=5, final_lr_ratio=1e-5, strategy='cosine')
>>> lrs = []
>>> for epoch in range(5):
...     lrs.append(scheduler.get_lr()[0])
...     scheduler.step()
>>> [round(lr, 10) for lr in lrs]
[0.3330753446, 0.0187302031, 0.000533897, 3.00232e-05, 1e-09]
>>> scheduler = LRScheduler(optimizer, total_steps=5, final_lr_ratio=1e-5, strategy='linear', method='numerical')
>>> lrs = []
>>> for epoch in range(5):
...     lrs.append(scheduler.get_lr()[0])
...     scheduler.step()
>>> [round(lr, 2) for lr in lrs]
[0.8, 0.6, 0.4, 0.2, 0.0]
Source code in danling/optim/lr_scheduler/lr_scheduler.py
Python
class LRScheduler(lr_scheduler._LRScheduler):  # pylint: disable=protected-access
    r"""
    General learning rate scheduler.

    PyTorch LRScheduler is hard to extend.
    This class is a wrapper of PyTorch LRScheduler, which provides a more general interface.
    You only needs to add a new method which calculates a learning rate ratio (range from 0 to 1)
    with total progress (range from 0 to 1), and everything else will be done automatically.

    Moreover, this class has warmup and cooldown built-in.
    By default, the first 5% and last 20% of training steps will be warmup and cooldown respectively.
    You can alternate by passing `warmup_steps` and `cooldown_steps`, or disable them by setting them to 0.

    Args:
        optimizer: Wrapped optimizer.
        total_steps: Total number of trainable steps.
        final_lr_ratio: Final learning rate ratio to initial learning rate.
            Defaults to 1e-3.
        final_lr: Final learning rate.
        min_lr: Minimal learning rate.
            Defaults to 1e-9.
        strategy: Scaling strategy.
            Defaults to "cosine".
        warmup_steps: Number of warmup steps.
            Defaults to `steps // 20`.
        cooldown_steps: Number of cooldown steps.
            Defaults to `steps // 5`.
        last_epoch: The index of last epoch.
            Defaults to -1.
        method: Method to calculate learning rate given ratio, should be one of "percentile" or "numerical".
            Defaults to "percentile" if `final_lr_ratio` is set, otherwise "numerical".

    Examples:
        >>> from danling.optim import LRScheduler
        >>> import torch
        >>> from torch import optim
        >>> optimizer = optim.SGD([{'params': torch.tensor([0])}], lr=1, momentum=0.9)
        >>> scheduler = LRScheduler(optimizer, total_steps=5, final_lr_ratio=1e-5, strategy='linear')
        >>> lrs = []
        >>> for epoch in range(5):
        ...     lrs.append(scheduler.get_lr()[0])
        ...     scheduler.step()
        >>> [round(lr, 10) for lr in lrs]
        [0.1, 0.01, 0.001, 0.0001, 1e-09]
        >>> scheduler = LRScheduler(optimizer, total_steps=5, final_lr_ratio=1e-5, strategy='cosine')
        >>> lrs = []
        >>> for epoch in range(5):
        ...     lrs.append(scheduler.get_lr()[0])
        ...     scheduler.step()
        >>> [round(lr, 10) for lr in lrs]
        [0.3330753446, 0.0187302031, 0.000533897, 3.00232e-05, 1e-09]
        >>> scheduler = LRScheduler(optimizer, total_steps=5, final_lr_ratio=1e-5, strategy='linear', method='numerical')
        >>> lrs = []
        >>> for epoch in range(5):
        ...     lrs.append(scheduler.get_lr()[0])
        ...     scheduler.step()
        >>> [round(lr, 2) for lr in lrs]
        [0.8, 0.6, 0.4, 0.2, 0.0]
    """  # noqa: E501

    def __init__(
        self,
        optimizer: Optimizer,
        total_steps: int,
        final_lr_ratio: Optional[float] = None,
        final_lr: Optional[float] = None,
        min_lr: float = 1e-9,
        strategy: str = "cosine",
        warmup_steps: Optional[int] = None,
        cooldown_steps: Optional[int] = None,
        last_epoch: int = -1,
        method: Optional[str] = None,
    ):
        if total_steps <= 0:
            raise ValueError(f"Total steps must be positive, but got {total_steps}")
        if warmup_steps is None:
            warmup_steps = total_steps // 20
        elif warmup_steps > total_steps:
            raise ValueError(f"Warmup steps must be less than total steps, but got {warmup_steps} > {total_steps}")
        elif warmup_steps < 0:
            raise ValueError(f"Warmup steps must be positive, but got {warmup_steps}")
        if cooldown_steps is None:
            cooldown_steps = total_steps // 5
        elif cooldown_steps > total_steps:
            raise ValueError(f"Cooldown steps must be less than total steps, but got {cooldown_steps} > {total_steps}")
        elif cooldown_steps < 0:
            raise ValueError(f"Cooldown steps must be positive, but got {cooldown_steps}")
        if final_lr_ratio is not None:
            if final_lr is not None:
                raise ValueError("Only one of `final_lr_ratio` and `final_lr` should be set, but not both")
            if final_lr_ratio < 0:
                raise ValueError(f"`final_lr_ratio` must be positive, but got {final_lr_ratio}")
            if method is None:
                method = "percentile"
        if final_lr is not None and final_lr < 0:
            raise ValueError(f"`final_lr` must be positive, but got {final_lr}")
        if min_lr < 0:
            raise ValueError(f"`min_lr` must be positive, but got {min_lr}")
        self.strategies = {
            k: v for k, v in self.__class__.__dict__.items() if callable(v) and (not k.startswith("_") or k in "get_lr")
        }
        if strategy not in self.strategies:
            raise ValueError(f"Scaling strategy must be one of {self.strategies.keys()}, but got {strategy}")

        if final_lr_ratio is None and final_lr is None:
            final_lr_ratio = 1e-3
            if method is None:
                method = "percentile"
        if final_lr is not None and min_lr > final_lr:
            min_lr = final_lr
        if method is None:
            method = "numerical"

        self.final_lr_ratio = final_lr_ratio
        self.final_lr = final_lr
        self.total_steps = total_steps
        self.min_lr = min_lr
        self.strategy = strategy
        self.method = method
        self.warmup_steps = warmup_steps
        self.cooldown_steps = cooldown_steps
        self.cooldown_steps_begin = self.total_steps - self.cooldown_steps
        super().__init__(optimizer, last_epoch)

    def get_lr(self) -> List[float]:
        step_count = self._step_count
        if step_count > self.total_steps + 1 or step_count < 1:
            warn(
                f"Step count {step_count} is out of range [1, {self.total_steps + 1}]",
                category=RuntimeWarning,
                stacklevel=2,
            )
        return [self._get_lr(lr, step_count) for lr in self.base_lrs]

    def _get_lr(
        self,
        lr: float,
        step_count: Optional[int] = None,
        progress: Optional[float] = None,
        warmup_ratio: Optional[float] = None,
        cooldown_ratio: Optional[float] = None,
        method: Optional[str] = None,
    ) -> float:
        method = method or self.method
        step_count = step_count or self._step_count
        progress = progress or min(max(step_count / self.total_steps, 0.0), 1.0)
        final_lr = self.final_lr if self.final_lr is not None else lr * self.final_lr_ratio  # type: ignore[operator]
        ratio = getattr(self, self.strategy)(progress)
        if method == "percentile":
            lr *= pow(final_lr / lr, ratio)
        elif method == "numerical":
            lr = (1 - ratio) * (lr - final_lr) + final_lr
        else:
            raise ValueError(f"Method must be one of ['percentile', 'numerical'], but got {method}")
        if self.warmup_steps > step_count > 0:
            warmup_ratio = warmup_ratio or step_count / self.warmup_steps
            lr = warmup_ratio * (lr - self.min_lr) + self.min_lr
        elif self.cooldown_steps > 0 and step_count > self.cooldown_steps_begin:
            cooldown_ratio = cooldown_ratio or 1 - (step_count - self.cooldown_steps_begin) / self.cooldown_steps
            lr = cooldown_ratio * (lr - self.min_lr) + self.min_lr
        return max(self.min_lr, lr)

    def linear(self, progress: float) -> float:
        return progress

    def cosine(self, progress: float) -> float:
        return 1 - ((1 + cos(pi * progress)) / 2)

    def constant(self, progress: float) -> float:  # pylint: disable=unused-argument
        return 0.0

    def __repr__(self) -> str:
        return (
            f"{self.__class__.__name__}({self.strategy}, method={self.method}, "
            f"final_lr_ratio={self.final_lr_ratio}, total_steps={self.total_steps}, "
            f"warmup_steps={self.warmup_steps}, cooldown_steps={self.cooldown_steps})"
        )

AccelerateRunner

Bases: TorchRunner, Accelerator

Set up everything for running a job.

AccelerateRunner uses [accelerate][accelerate] as distributed backend to provide seamless distributed training experience.

AccelerateRunner will automatically prepare everything, including model, criterion, optimizer, scheduler, and dataloaders for distribute training, mixed precision, and deepspeed (optional).

In fact, you don’t even need to create dataloaders, just define datasets and AccelerateRunner will create dataloaders for you. AccelerateRunner will inspect the train flag in corresponding dataset to set shuffle and drop_last automatically.

Source code in danling/runner/accelerate_runner.py
Python
class AccelerateRunner(TorchRunner, Accelerator):  # pylint: disable=too-many-public-methods
    r"""
    Set up everything for running a job.

    `AccelerateRunner` uses [`accelerate`][accelerate] as distributed backend to
    provide seamless distributed training experience.

    `AccelerateRunner` will automatically [`prepare`][accelerate.Accelerator.prepare] everything,
    including `model`, `criterion`, `optimizer`, `scheduler`, and `dataloaders` for distribute training,
    mixed precision, and deepspeed (optional).

    In fact, you don't even need to create `dataloaders`, just define
    `datasets` and `AccelerateRunner` will create `dataloaders` for you.
    `AccelerateRunner` will inspect the `train` flag in corresponding dataset to
    set `shuffle` and `drop_last` automatically.
    """

    _accelerate: FlatDict | None = None

    def __init__(self, config: Config) -> None:
        ac.check()
        TorchRunner.__init__(self, config)
        Accelerator.__init__(self, **self.accelerate)
        if self.distributed:
            object_list = [self.id, self.timestamp]
            dist.broadcast_object_list(object_list)
            self.id, self.timestamp = object_list

    def __post_init__(self) -> None:
        BaseRunner.__post_init__(self)
        self.project_configuration.set_directories(self.dir)
        if self.datasets:
            self.build_dataloaders()
        if self.config.get("log_interval") is None:
            self.config.log_interval = max(ceil(max(len(d) for d in self.dataloaders.values()) / 10), 1)
        self.model, self.criterion, self.optimizer, self.scheduler = self.prepare(
            self.model, self.criterion, self.optimizer, self.scheduler
        )

    def train_step(self, data) -> torch.Tensor:
        with self.autocast(), self.accumulate():
            input = data["input"] if isinstance(data, Mapping) else data[0]
            target = data["target"] if isinstance(data, Mapping) else data[1]
            pred = self.model(**input) if isinstance(input, Mapping) else self.model(input)
            loss = self.criterion(pred, target)
            if self.metrics is not None:
                self.metrics.update(pred.squeeze(-1), target)
            self.advance(loss)
        return loss

    def advance(self, loss) -> None:
        r"""
        Backward loss and step optimizer & scheduler.

        Args:
            zero_grad: Whether to zero the gradients.
        """

        self.backward(loss)
        if self.sync_gradients:
            if self.config.get("max_grad_value") is not None:
                self.clip_grad_value_(self.model.parameters(), self.config.get("max_grad_value"))
            if self.config.get("max_grad_norm") is not None:
                self.clip_grad_norm_(self.model.parameters(), self.config.get("max_grad_norm"))
        self.optimizer.step()
        if self.scheduler is not None:
            self.scheduler.step()
        self.optimizer.zero_grad()
        self.config.step = self.step

    def unwrap(self, model: nn.Module) -> nn.Module:
        return self.unwrap_model(model)

    @property
    def accelerate(self) -> FlatDict:
        if self._accelerate is None:
            self._accelerate = self.get_accelerate_config(self.config)
        return self._accelerate

    @accelerate.setter
    def accelerate(self, config: FlatDict) -> None:
        self._accelerate = config

    @property
    def deepspeed(self) -> dict | None:
        if self.state.deepspeed_plugin is not None:
            return self.state.deepspeed_plugin.deepspeed_config
        return None

    @contextmanager
    def accumulate(self, *models: nn.Module):
        if not models:
            models = (self.model,)
        yield Accelerator.accumulate(self, *models)

    @property
    def device(self) -> torch.device:
        return self.state.device

    @property
    def world_size(self) -> int:
        if "state" in self.__dict__:
            return self.state.num_processes
        return 1

    @property
    def rank(self) -> int:
        if "state" in self.__dict__:
            return self.state.process_index
        return 0

    @property
    def local_rank(self) -> int:
        if "state" in self.__dict__:
            return self.state.local_process_index
        return 0

    @cached_property
    def accum_steps(self) -> int:
        return self.gradient_accumulation_steps

    def get_accelerate_config(self, config) -> FlatDict:
        accelerate = FlatDict()
        if "accelerate" in config:
            accelerate.update(config.accelerate)
        if "precision" in config:
            accelerate.mixed_precision = config.precision
        if "dynamo" in config:
            accelerate.dynamo_backend = config.dynamo.upper()
        if "accum_steps" in config:
            accelerate.gradient_accumulation_steps = config.accum_steps
        if "kwargs_handlers" not in accelerate:
            accelerate.kwargs_handlers = []
        # Must NOT set project_dir here as timestamp is not synced yet
        # config.project_dir = self.dir
        if os.getenv("ACCELERATE_USE_DEEPSPEED", "false").lower() == "true":
            deepspeed_config = config.get("deepspeed", os.getenv("ACCELERATE_DEEPSPEED_CONFIG_FILE"))
            accelerate.deepspeed_plugin = DeepSpeedPlugin(hf_ds_config=self.get_deepspeed_config(deepspeed_config))
        return accelerate

    def build_dataloaders(self):
        datasets = {k: d for k, d in self.datasets.items() if k not in self.dataloaders}
        default_kwargs = self.config.setdefault("dataloader", NestedDict())
        dataloader_kwargs = NestedDict({k: default_kwargs.pop(k) for k in self.datasets if k in default_kwargs})
        for k, d in datasets.items():
            dataloader_kwargs.setdefault(k, NestedDict())
            dataloader_kwargs[k].merge(default_kwargs, overwrite=False)
            dataloader_kwargs[k].setdefault("shuffle", getattr(d, "train", True))
            dataloader_kwargs[k].setdefault("drop_last", not getattr(d, "train", True))
            self.dataloaders[k] = utils.data.DataLoader(d, collate_fn=self.collate_fn, **dataloader_kwargs[k])
        default_kwargs.update(dataloader_kwargs)
        for k, d in self.dataloaders.items():
            self.dataloaders[k] = self.prepare(d)

advance

Python
advance(loss) -> None

Backward loss and step optimizer & scheduler.

Parameters:

Name Type Description Default
zero_grad

Whether to zero the gradients.

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

    Args:
        zero_grad: Whether to zero the gradients.
    """

    self.backward(loss)
    if self.sync_gradients:
        if self.config.get("max_grad_value") is not None:
            self.clip_grad_value_(self.model.parameters(), self.config.get("max_grad_value"))
        if self.config.get("max_grad_norm") is not None:
            self.clip_grad_norm_(self.model.parameters(), self.config.get("max_grad_norm"))
    self.optimizer.step()
    if self.scheduler is not None:
        self.scheduler.step()
    self.optimizer.zero_grad()
    self.config.step = self.step

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
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_step_result(self) -> NestedDict:
        result = self.meters.value()
        if self.metrics is not None:
            return self._merge_result(result, self.metrics.value())
        return result

    def get_epoch_result(self) -> NestedDict:
        result = self.meters.average()
        if self.metrics is not None:
            return self._merge_result(result, self.metrics.average())
        return result

    def _merge_result(self, result, metric_result) -> NestedDict:
        for key, value in metric_result.items():
            if isinstance(value, (Mapping)) and len(value) == 1:
                value = next(iter(value.values()))
            metric_result[key] = value
        result.update(metric_result)
        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_step_result()
        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

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.