Skip to content

chuchichaestli.training.optim

Optimizer and learning-rate schedule specifications.

Classes:

Name Description
OptimSpec

Describes an optimizer and the schedule attached to it.

SchedulerSpec

Describes a learning-rate scheduler.

SequentialScheduler

Torch's SequentialLR, admitting a plateau schedule among its members.

SequentialSchedulerSpec

Describes schedules run one after another, e.g. a warmup then a decay.

Functions:

Name Description
disjoint_params

Return the groups with each parameter kept only in the first that claims it.

OptimSpec dataclass

OptimSpec(
    cls: str = "adamw",
    lr: float = 0.0001,
    kwargs: Mapping[str, Any] = dict(),
    params: str
    | Sequence[str]
    | Callable[..., ParamsT]
    | None = None,
    scheduler: SchedulerSpec
    | SequentialSchedulerSpec
    | None = None,
)

Describes an optimizer and the schedule attached to it.

Attributes:

Name Type Description
cls str

Registered name, or "module:QualName" for one of your own.

lr float

Learning rate, the one argument every optimizer takes.

kwargs Mapping[str, Any]

Further arguments the optimizer is built with.

params str | Sequence[str] | Callable[..., ParamsT] | None

Which parameters this optimizer owns: a binding name, several of them, or a callable selecting them. Defaults to the stage's own model.

scheduler SchedulerSpec | SequentialSchedulerSpec | None

The schedule attached to this optimizer, if any.

Methods:

Name Description
adagrad

Describe an Adagrad optimizer.

adam

Describe an Adam optimizer.

adamw

Describe an AdamW optimizer.

build

Build the optimizer.

lbfgs

Describe an L-BFGS optimizer.

needs_closure

Whether an optimizer requires a closure to step.

rmsprop

Describe an RMSprop optimizer.

sgd

Describe an SGD optimizer.

with_cosine_schedule

Return a copy with a cosine annealing schedule.

with_cosine_warm_restarts_schedule

Return a copy with a cosine annealing schedule that restarts.

with_exponential_schedule

Return a copy with an exponential decay schedule.

with_linear_schedule

Return a copy with a linear schedule.

with_multistep_schedule

Return a copy with a schedule dropping the rate at given milestones.

with_onecycle_schedule

Return a copy with a one-cycle schedule.

with_params

Return a copy owning the given parameters.

with_plateau_schedule

Return a copy with a schedule dropping the rate on a plateau.

with_schedule

Return a copy with a schedule attached.

with_step_schedule

Return a copy with a schedule dropping the rate at a fixed interval.

with_warmup

Return a copy running a warmup schedule before the attached one.

requires_closure property

requires_closure: bool

Whether stepping this optimizer needs a closure.

adagrad classmethod

adagrad(
    lr: float = 0.01,
    params: str
    | Sequence[str]
    | Callable[..., ParamsT]
    | None = None,
    **kwargs: Any,
) -> OptimSpec

Describe an Adagrad optimizer.

Parameters:

Name Type Description Default
lr float

Learning rate.

0.01
params str | Sequence[str] | Callable[..., ParamsT] | None

Which parameters this optimizer owns.

None
kwargs Any

Further arguments, e.g. lr_decay, weight_decay.

{}
Source code in src/chuchichaestli/training/optim.py
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
@classmethod
def adagrad(
    cls,
    lr: float = 1e-2,
    params: str | Sequence[str] | Callable[..., ParamsT] | None = None,
    **kwargs: Any,
) -> OptimSpec:
    """Describe an Adagrad optimizer.

    Args:
        lr: Learning rate.
        params: Which parameters this optimizer owns.
        kwargs: Further arguments, e.g. `lr_decay`, `weight_decay`.
    """
    return cls(cls="adagrad", lr=lr, kwargs=kwargs, params=params)

adam classmethod

adam(
    lr: float = 0.001,
    params: str
    | Sequence[str]
    | Callable[..., ParamsT]
    | None = None,
    **kwargs: Any,
) -> OptimSpec

Describe an Adam optimizer.

Parameters:

Name Type Description Default
lr float

Learning rate.

0.001
params str | Sequence[str] | Callable[..., ParamsT] | None

Which parameters this optimizer owns.

None
kwargs Any

Further arguments, e.g. betas, eps, weight_decay.

{}
Source code in src/chuchichaestli/training/optim.py
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
@classmethod
def adam(
    cls,
    lr: float = 1e-3,
    params: str | Sequence[str] | Callable[..., ParamsT] | None = None,
    **kwargs: Any,
) -> OptimSpec:
    """Describe an Adam optimizer.

    Args:
        lr: Learning rate.
        params: Which parameters this optimizer owns.
        kwargs: Further arguments, e.g. `betas`, `eps`, `weight_decay`.
    """
    return cls(cls="adam", lr=lr, kwargs=kwargs, params=params)

adamw classmethod

adamw(
    lr: float = 0.0001,
    params: str
    | Sequence[str]
    | Callable[..., ParamsT]
    | None = None,
    **kwargs: Any,
) -> OptimSpec

Describe an AdamW optimizer.

Parameters:

Name Type Description Default
lr float

Learning rate.

0.0001
params str | Sequence[str] | Callable[..., ParamsT] | None

Which parameters this optimizer owns.

None
kwargs Any

Further arguments, e.g. betas, eps, weight_decay.

{}
Source code in src/chuchichaestli/training/optim.py
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
@classmethod
def adamw(
    cls,
    lr: float = 1e-4,
    params: str | Sequence[str] | Callable[..., ParamsT] | None = None,
    **kwargs: Any,
) -> OptimSpec:
    """Describe an AdamW optimizer.

    Args:
        lr: Learning rate.
        params: Which parameters this optimizer owns.
        kwargs: Further arguments, e.g. `betas`, `eps`, `weight_decay`.
    """
    return cls(cls="adamw", lr=lr, kwargs=kwargs, params=params)

build

build(params: ParamsT, **overrides: Any) -> Optimizer

Build the optimizer.

Parameters:

Name Type Description Default
params ParamsT

Parameters or parameter groups to optimize.

required
overrides Any

Arguments to replace, for building a variant.

{}
Source code in src/chuchichaestli/training/optim.py
379
380
381
382
383
384
385
386
387
388
389
390
391
392
def build(self, params: ParamsT, **overrides: Any) -> Optimizer:
    """Build the optimizer.

    Args:
        params: Parameters or parameter groups to optimize.
        overrides: Arguments to replace, for building a variant.
    """
    optimizer = require(
        self.cls,
        OPTIMIZER_MAP,
        "optimizer",
        fallback=ModelSpec.import_class if ":" in self.cls else None,
    )
    return optimizer(params, lr=self.lr, **{**self.kwargs, **overrides})

lbfgs classmethod

lbfgs(
    lr: float = 1.0,
    params: str
    | Sequence[str]
    | Callable[..., ParamsT]
    | None = None,
    **kwargs: Any,
) -> OptimSpec

Describe an L-BFGS optimizer.

Parameters:

Name Type Description Default
lr float

Learning rate.

1.0
params str | Sequence[str] | Callable[..., ParamsT] | None

Which parameters this optimizer owns.

None
kwargs Any

Further arguments, e.g. max_iter, history_size.

{}
Source code in src/chuchichaestli/training/optim.py
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
@classmethod
def lbfgs(
    cls,
    lr: float = 1.0,
    params: str | Sequence[str] | Callable[..., ParamsT] | None = None,
    **kwargs: Any,
) -> OptimSpec:
    """Describe an L-BFGS optimizer.

    Args:
        lr: Learning rate.
        params: Which parameters this optimizer owns.
        kwargs: Further arguments, e.g. `max_iter`, `history_size`.
    """
    return cls(cls="lbfgs", lr=lr, kwargs=kwargs, params=params)

needs_closure staticmethod

needs_closure(optimizer: Optimizer | str) -> bool

Whether an optimizer requires a closure to step.

Parameters:

Name Type Description Default
optimizer Optimizer | str

A built optimizer, or the name of one.

required
Source code in src/chuchichaestli/training/optim.py
361
362
363
364
365
366
367
368
369
370
371
372
@staticmethod
def needs_closure(optimizer: Optimizer | str) -> bool:
    """Whether an optimizer requires a closure to step.

    Args:
        optimizer: A built optimizer, or the name of one.
    """
    if isinstance(optimizer, str):
        return optimizer in CLOSURE_OPTIMIZERS
    return isinstance(
        optimizer, tuple(OPTIMIZER_MAP[name] for name in CLOSURE_OPTIMIZERS)
    )

rmsprop classmethod

rmsprop(
    lr: float = 0.01,
    params: str
    | Sequence[str]
    | Callable[..., ParamsT]
    | None = None,
    **kwargs: Any,
) -> OptimSpec

Describe an RMSprop optimizer.

Parameters:

Name Type Description Default
lr float

Learning rate.

0.01
params str | Sequence[str] | Callable[..., ParamsT] | None

Which parameters this optimizer owns.

None
kwargs Any

Further arguments, e.g. alpha, momentum.

{}
Source code in src/chuchichaestli/training/optim.py
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
@classmethod
def rmsprop(
    cls,
    lr: float = 1e-2,
    params: str | Sequence[str] | Callable[..., ParamsT] | None = None,
    **kwargs: Any,
) -> OptimSpec:
    """Describe an RMSprop optimizer.

    Args:
        lr: Learning rate.
        params: Which parameters this optimizer owns.
        kwargs: Further arguments, e.g. `alpha`, `momentum`.
    """
    return cls(cls="rmsprop", lr=lr, kwargs=kwargs, params=params)

sgd classmethod

sgd(
    lr: float = 0.01,
    params: str
    | Sequence[str]
    | Callable[..., ParamsT]
    | None = None,
    **kwargs: Any,
) -> OptimSpec

Describe an SGD optimizer.

Parameters:

Name Type Description Default
lr float

Learning rate.

0.01
params str | Sequence[str] | Callable[..., ParamsT] | None

Which parameters this optimizer owns.

None
kwargs Any

Further arguments, e.g. momentum, nesterov.

{}
Source code in src/chuchichaestli/training/optim.py
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
@classmethod
def sgd(
    cls,
    lr: float = 1e-2,
    params: str | Sequence[str] | Callable[..., ParamsT] | None = None,
    **kwargs: Any,
) -> OptimSpec:
    """Describe an SGD optimizer.

    Args:
        lr: Learning rate.
        params: Which parameters this optimizer owns.
        kwargs: Further arguments, e.g. `momentum`, `nesterov`.
    """
    return cls(cls="sgd", lr=lr, kwargs=kwargs, params=params)

with_cosine_schedule

with_cosine_schedule(
    t_max: int,
    eta_min: float = 0.0,
    interval: IntervalTypes = "epoch",
) -> OptimSpec

Return a copy with a cosine annealing schedule.

Parameters:

Name Type Description Default
t_max int

Steps or epochs over which the rate reaches eta_min.

required
eta_min float

Rate at the end of the schedule.

0.0
interval IntervalTypes

Whether the runner steps it per step or per epoch.

'epoch'
Source code in src/chuchichaestli/training/optim.py
564
565
566
567
568
569
570
571
572
573
574
575
576
def with_cosine_schedule(
    self, t_max: int, eta_min: float = 0.0, interval: IntervalTypes = "epoch"
) -> OptimSpec:
    """Return a copy with a cosine annealing schedule.

    Args:
        t_max: Steps or epochs over which the rate reaches `eta_min`.
        eta_min: Rate at the end of the schedule.
        interval: Whether the runner steps it per step or per epoch.
    """
    return self.with_schedule(
        "cosine", interval=interval, T_max=t_max, eta_min=eta_min
    )

with_cosine_warm_restarts_schedule

with_cosine_warm_restarts_schedule(
    t_0: int,
    t_mult: int = 1,
    eta_min: float = 0.0,
    interval: IntervalTypes = "epoch",
) -> OptimSpec

Return a copy with a cosine annealing schedule that restarts.

Parameters:

Name Type Description Default
t_0 int

Steps or epochs until the first restart.

required
t_mult int

Factor the period grows by after each restart.

1
eta_min float

Rate at the end of each period.

0.0
interval IntervalTypes

Whether the runner steps it per step or per epoch.

'epoch'
Source code in src/chuchichaestli/training/optim.py
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
def with_cosine_warm_restarts_schedule(
    self,
    t_0: int,
    t_mult: int = 1,
    eta_min: float = 0.0,
    interval: IntervalTypes = "epoch",
) -> OptimSpec:
    """Return a copy with a cosine annealing schedule that restarts.

    Args:
        t_0: Steps or epochs until the first restart.
        t_mult: Factor the period grows by after each restart.
        eta_min: Rate at the end of each period.
        interval: Whether the runner steps it per step or per epoch.
    """
    return self.with_schedule(
        "cosine_warm_restarts",
        interval=interval,
        T_0=t_0,
        T_mult=t_mult,
        eta_min=eta_min,
    )

with_exponential_schedule

with_exponential_schedule(
    gamma: float = 0.95, interval: IntervalTypes = "epoch"
) -> OptimSpec

Return a copy with an exponential decay schedule.

Parameters:

Name Type Description Default
gamma float

Factor the rate is multiplied by each time.

0.95
interval IntervalTypes

Whether the runner steps it per step or per epoch.

'epoch'
Source code in src/chuchichaestli/training/optim.py
632
633
634
635
636
637
638
639
640
641
def with_exponential_schedule(
    self, gamma: float = 0.95, interval: IntervalTypes = "epoch"
) -> OptimSpec:
    """Return a copy with an exponential decay schedule.

    Args:
        gamma: Factor the rate is multiplied by each time.
        interval: Whether the runner steps it per step or per epoch.
    """
    return self.with_schedule("exponential", interval=interval, gamma=gamma)

with_linear_schedule

with_linear_schedule(
    start_factor: float = 1.0,
    end_factor: float = 0.1,
    total_iters: int = 10,
    interval: IntervalTypes = "epoch",
) -> OptimSpec

Return a copy with a linear schedule.

Parameters:

Name Type Description Default
start_factor float

Fraction of the rate to begin at.

1.0
end_factor float

Fraction of the rate to end at.

0.1
total_iters int

Steps or epochs the line spans.

10
interval IntervalTypes

Whether the runner steps it per step or per epoch.

'epoch'
Source code in src/chuchichaestli/training/optim.py
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
def with_linear_schedule(
    self,
    start_factor: float = 1.0,
    end_factor: float = 0.1,
    total_iters: int = 10,
    interval: IntervalTypes = "epoch",
) -> OptimSpec:
    """Return a copy with a linear schedule.

    Args:
        start_factor: Fraction of the rate to begin at.
        end_factor: Fraction of the rate to end at.
        total_iters: Steps or epochs the line spans.
        interval: Whether the runner steps it per step or per epoch.
    """
    return self.with_schedule(
        "linear",
        interval=interval,
        start_factor=start_factor,
        end_factor=end_factor,
        total_iters=total_iters,
    )

with_multistep_schedule

with_multistep_schedule(
    milestones: Sequence[int],
    gamma: float = 0.1,
    interval: IntervalTypes = "epoch",
) -> OptimSpec

Return a copy with a schedule dropping the rate at given milestones.

Parameters:

Name Type Description Default
milestones Sequence[int]

Steps or epochs at which the rate drops.

required
gamma float

Factor the rate is multiplied by at each drop.

0.1
interval IntervalTypes

Whether the runner steps it per step or per epoch.

'epoch'
Source code in src/chuchichaestli/training/optim.py
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
def with_multistep_schedule(
    self,
    milestones: Sequence[int],
    gamma: float = 0.1,
    interval: IntervalTypes = "epoch",
) -> OptimSpec:
    """Return a copy with a schedule dropping the rate at given milestones.

    Args:
        milestones: Steps or epochs at which the rate drops.
        gamma: Factor the rate is multiplied by at each drop.
        interval: Whether the runner steps it per step or per epoch.
    """
    return self.with_schedule(
        "multistep", interval=interval, milestones=list(milestones), gamma=gamma
    )

with_onecycle_schedule

with_onecycle_schedule(
    max_lr: float,
    total_steps: int,
    pct_start: float = 0.3,
    interval: IntervalTypes = "step",
) -> OptimSpec

Return a copy with a one-cycle schedule.

Parameters:

Name Type Description Default
max_lr float

Rate at the peak.

required
total_steps int

Steps the cycle spans.

required
pct_start float

Fraction of the cycle spent warming up.

0.3
interval IntervalTypes

Whether the runner steps it per step or per epoch.

'step'
Source code in src/chuchichaestli/training/optim.py
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
def with_onecycle_schedule(
    self,
    max_lr: float,
    total_steps: int,
    pct_start: float = 0.3,
    interval: IntervalTypes = "step",
) -> OptimSpec:
    """Return a copy with a one-cycle schedule.

    Args:
        max_lr: Rate at the peak.
        total_steps: Steps the cycle spans.
        pct_start: Fraction of the cycle spent warming up.
        interval: Whether the runner steps it per step or per epoch.
    """
    return self.with_schedule(
        "onecycle",
        interval=interval,
        max_lr=max_lr,
        total_steps=total_steps,
        pct_start=pct_start,
    )

with_params

with_params(
    params: str | Sequence[str] | Callable[..., ParamsT],
) -> OptimSpec

Return a copy owning the given parameters.

Parameters:

Name Type Description Default
params str | Sequence[str] | Callable[..., ParamsT]

A binding name, several of them, or a callable.

required
Source code in src/chuchichaestli/training/optim.py
490
491
492
493
494
495
496
497
498
def with_params(
    self, params: str | Sequence[str] | Callable[..., ParamsT]
) -> OptimSpec:
    """Return a copy owning the given parameters.

    Args:
        params: A binding name, several of them, or a callable.
    """
    return replace(self, params=params)

with_plateau_schedule

with_plateau_schedule(
    monitor: str,
    mode: str = "min",
    factor: float = 0.1,
    patience: int = 10,
    interval: IntervalTypes = "epoch",
) -> OptimSpec

Return a copy with a schedule dropping the rate on a plateau.

Parameters:

Name Type Description Default
monitor str

Binding the schedule reads, e.g. "probe/psnr".

required
mode str

"min" when lower is better, "max" when higher is.

'min'
factor float

Factor the rate is multiplied by on a plateau.

0.1
patience int

Readings without improvement before dropping.

10
interval IntervalTypes

Whether the runner steps it per step or per epoch.

'epoch'
Source code in src/chuchichaestli/training/optim.py
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
def with_plateau_schedule(
    self,
    monitor: str,
    mode: str = "min",
    factor: float = 0.1,
    patience: int = 10,
    interval: IntervalTypes = "epoch",
) -> OptimSpec:
    """Return a copy with a schedule dropping the rate on a plateau.

    Args:
        monitor: Binding the schedule reads, e.g. `"probe/psnr"`.
        mode: `"min"` when lower is better, `"max"` when higher is.
        factor: Factor the rate is multiplied by on a plateau.
        patience: Readings without improvement before dropping.
        interval: Whether the runner steps it per step or per epoch.
    """
    return self.with_schedule(
        "plateau",
        interval=interval,
        monitor=monitor,
        mode=mode,
        factor=factor,
        patience=patience,
    )

with_schedule

with_schedule(
    schedule: str,
    interval: IntervalTypes = "epoch",
    monitor: str | None = None,
    **kwargs: Any,
) -> OptimSpec

Return a copy with a schedule attached.

Parameters:

Name Type Description Default
schedule str

Registered name, or "module:QualName".

required
interval IntervalTypes

Whether the runner steps it per step or per epoch.

'epoch'
monitor str | None

Binding a plateau schedule reads.

None
kwargs Any

Arguments the scheduler is built with.

{}
Source code in src/chuchichaestli/training/optim.py
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
def with_schedule(
    self,
    schedule: str,
    interval: IntervalTypes = "epoch",
    monitor: str | None = None,
    **kwargs: Any,
) -> OptimSpec:
    """Return a copy with a schedule attached.

    Args:
        schedule: Registered name, or `"module:QualName"`.
        interval: Whether the runner steps it per step or per epoch.
        monitor: Binding a plateau schedule reads.
        kwargs: Arguments the scheduler is built with.
    """
    return replace(
        self,
        scheduler=SchedulerSpec(
            cls=schedule, kwargs=kwargs, interval=interval, monitor=monitor
        ),
    )

with_step_schedule

with_step_schedule(
    step_size: int,
    gamma: float = 0.1,
    interval: IntervalTypes = "epoch",
) -> OptimSpec

Return a copy with a schedule dropping the rate at a fixed interval.

Parameters:

Name Type Description Default
step_size int

Steps or epochs between drops.

required
gamma float

Factor the rate is multiplied by at each drop.

0.1
interval IntervalTypes

Whether the runner steps it per step or per epoch.

'epoch'
Source code in src/chuchichaestli/training/optim.py
601
602
603
604
605
606
607
608
609
610
611
612
613
def with_step_schedule(
    self, step_size: int, gamma: float = 0.1, interval: IntervalTypes = "epoch"
) -> OptimSpec:
    """Return a copy with a schedule dropping the rate at a fixed interval.

    Args:
        step_size: Steps or epochs between drops.
        gamma: Factor the rate is multiplied by at each drop.
        interval: Whether the runner steps it per step or per epoch.
    """
    return self.with_schedule(
        "step", interval=interval, step_size=step_size, gamma=gamma
    )

with_warmup

with_warmup(
    schedule: str | SchedulerSpec,
    length: int,
    **kwargs: Any,
) -> OptimSpec

Return a copy running a warmup schedule before the attached one.

Without an attached schedule, the rate holds at lr once the warmup ends. The warmup steps at the attached schedule's interval, and is given total_iters=length if it takes one and it is not set.

Parameters:

Name Type Description Default
schedule str | SchedulerSpec

Registered name, "module:QualName", or a spec.

required
length int

Steps or epochs the warmup runs for.

required
kwargs Any

Arguments the warmup is built with, when named.

{}

Raises:

Type Description
ValueError

If length is not positive, or a warmup spec steps at another interval than the attached schedule.

Source code in src/chuchichaestli/training/optim.py
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
def with_warmup(
    self, schedule: str | SchedulerSpec, length: int, **kwargs: Any
) -> OptimSpec:
    """Return a copy running a warmup schedule before the attached one.

    Without an attached schedule, the rate holds at `lr` once the warmup
    ends. The warmup steps at the attached schedule's interval, and is
    given `total_iters=length` if it takes one and it is not set.

    Args:
        schedule: Registered name, `"module:QualName"`, or a spec.
        length: Steps or epochs the warmup runs for.
        kwargs: Arguments the warmup is built with, when named.

    Raises:
        ValueError: If `length` is not positive, or a warmup spec steps at
            another interval than the attached schedule.
    """
    if length < 1:
        raise ValueError(f"A warmup lasts at least one interval, got {length!r}.")
    main = self.scheduler
    interval = main.interval if main is not None else "epoch"
    if isinstance(schedule, str):
        warmup = SchedulerSpec(cls=schedule, kwargs=kwargs, interval=interval)
    elif main is not None and schedule.interval != interval:
        raise ValueError(
            f"The warmup steps per {schedule.interval}, the schedule after "
            f"it per {interval}; give both the same interval."
        )
    else:
        warmup = schedule
    warmup = warmup._with_length(length)
    if main is None:
        main = SchedulerSpec(
            cls="constant",
            kwargs={"factor": 1.0, "total_iters": 0},
            interval=warmup.interval,
        )
    if isinstance(main, SchedulerSpec):
        main = SequentialSchedulerSpec((main,), ())
    return replace(self, scheduler=main.after(warmup, length))

SchedulerSpec dataclass

SchedulerSpec(
    cls: str = "cosine",
    kwargs: Mapping[str, Any] = dict(),
    interval: IntervalTypes = "epoch",
    monitor: str | None = None,
)

Describes a learning-rate scheduler.

Attributes:

Name Type Description
cls str

Registered name, or "module:QualName" for one of your own.

kwargs Mapping[str, Any]

Arguments the scheduler is built with.

interval IntervalTypes

Whether the runner steps it per optimizer step or per epoch.

monitor str | None

Binding a plateau schedule reads, e.g. "probe/psnr".

Methods:

Name Description
build

Build the scheduler.

build

build(
    optimizer: Optimizer, **overrides: Any
) -> LRScheduler

Build the scheduler.

Parameters:

Name Type Description Default
optimizer Optimizer

Optimizer whose learning rate is scheduled.

required
overrides Any

Arguments to replace, for building a variant.

{}
Source code in src/chuchichaestli/training/optim.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
def build(self, optimizer: Optimizer, **overrides: Any) -> LRScheduler:
    """Build the scheduler.

    Args:
        optimizer: Optimizer whose learning rate is scheduled.
        overrides: Arguments to replace, for building a variant.
    """
    scheduler = require(
        self.cls,
        SCHEDULER_MAP,
        "scheduler",
        fallback=ModelSpec.import_class if ":" in self.cls else None,
    )
    return scheduler(optimizer, **{**self.kwargs, **overrides})

SequentialScheduler

SequentialScheduler(
    optimizer: Optimizer,
    schedulers: Sequence[LRScheduler],
    milestones: Sequence[int],
)

Bases: SequentialLR

Torch's SequentialLR, admitting a plateau schedule among its members.

A plateau member is stepped with the value it reads; on entering it, the rate returns to the optimizer's initial one, from which it then drops.

Constructor.

Parameters:

Name Type Description Default
optimizer Optimizer

Optimizer whose learning rate is scheduled.

required
schedulers Sequence[LRScheduler]

The schedules, run one after another.

required
milestones Sequence[int]

Steps or epochs at which each schedule after the first takes over.

required

Raises:

Type Description
ValueError

If there is no schedule, the milestones do not number one fewer than the schedules or do not increase, or a schedule belongs to another optimizer.

Methods:

Name Description
step

Advance the schedule in charge.

Attributes:

Name Type Description
reads_value bool

Whether the next step goes to a plateau schedule, needing its value.

Source code in src/chuchichaestli/training/optim.py
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
def __init__(
    self,
    optimizer: Optimizer,
    schedulers: Sequence[LRScheduler],
    milestones: Sequence[int],
):
    """Constructor.

    Args:
        optimizer: Optimizer whose learning rate is scheduled.
        schedulers: The schedules, run one after another.
        milestones: Steps or epochs at which each schedule after the first
            takes over.

    Raises:
        ValueError: If there is no schedule, the milestones do not number
            one fewer than the schedules or do not increase, or a schedule
            belongs to another optimizer.
    """
    if not schedulers:
        raise ValueError("A sequence of schedules needs at least one.")
    if len(milestones) != len(schedulers) - 1:
        raise ValueError(
            f"{len(schedulers)} schedules take {len(schedulers) - 1} "
            f"milestones, got {len(milestones)}."
        )
    if any(b <= a for a, b in zip(milestones, milestones[1:])) or any(
        m < 1 for m in milestones
    ):
        raise ValueError(
            f"Milestones must be positive and increasing, got {list(milestones)}."
        )
    for scheduler in schedulers:
        if scheduler.optimizer is not optimizer:
            raise ValueError(
                f"{type(scheduler).__name__} schedules another optimizer."
            )
    self._schedulers = list(schedulers)
    self._milestones = list(milestones)
    self.last_epoch = 0
    self.optimizer = optimizer
    for group in optimizer.param_groups:
        group["lr"] = group["initial_lr"]
    self.recursive_undo()
    first = self._schedulers[0]
    if isinstance(first, ReduceLROnPlateau):
        first._last_lr = [group["lr"] for group in optimizer.param_groups]
    else:
        first._initial_step()
    self._last_lr = first.get_last_lr()

reads_value property

reads_value: bool

Whether the next step goes to a plateau schedule, needing its value.

step

step(metrics: float | None = None) -> None

Advance the schedule in charge.

Parameters:

Name Type Description Default
metrics float | None

The value a plateau schedule reads; ignored by the others.

None

Raises:

Type Description
ValueError

If a plateau schedule is in charge and no value is given.

Source code in src/chuchichaestli/training/optim.py
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
def step(self, metrics: float | None = None) -> None:  # type: ignore[override]
    """Advance the schedule in charge.

    Args:
        metrics: The value a plateau schedule reads; ignored by the others.

    Raises:
        ValueError: If a plateau schedule is in charge and no value is given.
    """
    scheduler, starts = self._upcoming()
    if self.reads_value and metrics is None:
        raise ValueError(
            "The schedule in charge is a plateau one, which steps on a value."
        )
    self.last_epoch += 1
    if isinstance(scheduler, ReduceLROnPlateau):
        if starts:
            for group in self.optimizer.param_groups:
                group["lr"] = group["initial_lr"]
            scheduler._last_lr = [g["lr"] for g in self.optimizer.param_groups]
        else:
            scheduler.step(metrics)
    elif starts:
        scheduler._update_lr(0)
    else:
        scheduler.step()
    self._last_lr = scheduler.get_last_lr()

SequentialSchedulerSpec dataclass

SequentialSchedulerSpec(
    schedulers: Sequence[SchedulerSpec],
    milestones: Sequence[int],
)

Describes schedules run one after another, e.g. a warmup then a decay.

Each schedule counts from zero when it takes over, so a cosine taking over at milestone 10 with T_max=90 reaches its minimum at step 100.

Attributes:

Name Type Description
schedulers Sequence[SchedulerSpec]

The schedules, in the order they run.

milestones Sequence[int]

Steps or epochs at which each schedule after the first takes over.

Methods:

Name Description
after

Return the sequence with a schedule run for length before it.

build

Build every schedule and run them in sequence.

interval property

interval: IntervalTypes

Whether the runner steps the sequence per step or per epoch.

monitor property

monitor: str | None

Binding a plateau schedule in the sequence reads, if any.

after

after(
    spec: SchedulerSpec, length: int
) -> SequentialSchedulerSpec

Return the sequence with a schedule run for length before it.

Parameters:

Name Type Description Default
spec SchedulerSpec

The schedule to run first.

required
length int

Steps or epochs it runs for.

required
Source code in src/chuchichaestli/training/optim.py
328
329
330
331
332
333
334
335
336
337
338
def after(self, spec: SchedulerSpec, length: int) -> SequentialSchedulerSpec:
    """Return the sequence with a schedule run for `length` before it.

    Args:
        spec: The schedule to run first.
        length: Steps or epochs it runs for.
    """
    return SequentialSchedulerSpec(
        (spec, *self.schedulers),
        (length, *(m + length for m in self.milestones)),
    )

build

build(optimizer: Optimizer) -> SequentialScheduler

Build every schedule and run them in sequence.

Parameters:

Name Type Description Default
optimizer Optimizer

Optimizer whose learning rate is scheduled.

required
Source code in src/chuchichaestli/training/optim.py
316
317
318
319
320
321
322
323
324
325
326
def build(self, optimizer: Optimizer) -> SequentialScheduler:
    """Build every schedule and run them in sequence.

    Args:
        optimizer: Optimizer whose learning rate is scheduled.
    """
    return SequentialScheduler(
        optimizer,
        [spec.build(optimizer) for spec in self.schedulers],
        self.milestones,
    )

disjoint_params

disjoint_params(
    groups: Mapping[str, Iterable[nn.Parameter]],
) -> dict[str, list[nn.Parameter]]

Return the groups with each parameter kept only in the first that claims it.

Two optimizers stepping the same parameter would apply its update twice.

Parameters:

Name Type Description Default
groups Mapping[str, Iterable[nn.Parameter]]

Parameters each update group selected, in priority order.

required
Source code in src/chuchichaestli/training/optim.py
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
def disjoint_params(
    groups: Mapping[str, Iterable[nn.Parameter]],
) -> dict[str, list[nn.Parameter]]:
    """Return the groups with each parameter kept only in the first that claims it.

    Two optimizers stepping the same parameter would apply its update twice.

    Args:
        groups: Parameters each update group selected, in priority order.
    """
    seen: set[int] = set()
    disjoint: dict[str, list[nn.Parameter]] = {}
    for name, params in groups.items():
        disjoint[name] = [
            p for p in params if id(p) not in seen and not seen.add(id(p))
        ]
    return disjoint