Skip to content

Optimizer

About

The loop creates one optimizer per local model stage through an OptimizerProvider. You can configure a standard optimizer with AutoOptimizerProvider, or implement the OptimizerProvider protocol yourself. The loop combines the optimizers of all local stages into one PipelinedOptimizer.

Auto Optimizer

The d9d.loop.auto package builds standard optimizers from a Pydantic configuration. It supports AdamW, Adam, SGD and StochasticAdamW. The name field selects the optimizer.

Custom Optimizer

For a custom optimizer, implement the OptimizerProvider protocol. It receives the model stage and returns a PyTorch optimizer. Each optimizer step runs with the global generators seeded per step and stage, so an optimizer can draw from them. See Random Numbers in the Loop.

Usage

AutoOptimizerConfig is a discriminated union, so validate it with a Pydantic TypeAdapter:

1
2
3
4
5
6
from pydantic import TypeAdapter

from d9d.loop.auto import AutoOptimizerConfig, AutoOptimizerProvider

config = TypeAdapter(AutoOptimizerConfig).validate_json('{"name": "adamw", "lr": 1e-4}')
provider = AutoOptimizerProvider(config)

Inside a larger Pydantic config, declare a field of type AutoOptimizerConfig instead.

API Reference

d9d.loop.auto.auto_optimizer

Optimizer provider built from a configuration.

AutoOptimizerConfig = Annotated[StochasticAdamWOptimizerConfig | AdamWOptimizerConfig | AdamOptimizerConfig | SGDOptimizerConfig, Field(discriminator='name')] module-attribute

Discriminated union of the supported optimizer configurations.

AdamOptimizerConfig

Bases: BaseModel

Configuration for the PyTorch Adam optimizer.

Attributes:

Name Type Description
name Literal['adam']

Discriminator field. Always "adam".

lr float

The learning rate.

betas tuple[float, float]

Coefficients for computing running averages of gradient and its square.

eps float

Term added to the denominator to improve numerical stability.

weight_decay float

Weight decay coefficient.

decoupled_weight_decay bool

Whether to apply decoupled weight decay.

amsgrad bool

Whether to use the AMSGrad variant.

maximize bool

Whether to maximize the objective instead of minimizing it.

AdamWOptimizerConfig

Bases: BaseModel

Configuration for the PyTorch AdamW optimizer.

Attributes:

Name Type Description
name Literal['adamw']

Discriminator field. Always "adamw".

lr float

The learning rate.

betas tuple[float, float]

Coefficients for computing running averages of gradient and its square.

eps float

Term added to the denominator to improve numerical stability.

weight_decay float

Weight decay coefficient.

amsgrad bool

Whether to use the AMSGrad variant.

maximize bool

Whether to maximize the objective instead of minimizing it.

AutoOptimizerProvider

Bases: OptimizerProvider

Provider that builds a PyTorch optimizer from a configuration object.

The PyTorch optimizers (AdamW, Adam and SGD) are built with fused=True. StochasticAdamW draws its rounding noise from the global generators, which the loop seeds per step and stage.

__init__(config)

Constructs the AutoOptimizerProvider object.

SGDOptimizerConfig

Bases: BaseModel

Configuration for the PyTorch SGD optimizer.

Attributes:

Name Type Description
name Literal['sgd']

Discriminator field. Always "sgd".

lr float

The learning rate.

momentum float

Momentum factor.

dampening float

Dampening for momentum.

weight_decay float

Weight decay (L2 penalty).

nesterov bool

Enables Nesterov momentum.

maximize bool

Whether to maximize the objective instead of minimizing it.

StochasticAdamWOptimizerConfig

Bases: BaseModel

Configuration for the Stochastic AdamW optimizer.

Attributes:

Name Type Description
name Literal['stochastic_adamw']

Discriminator field. Always "stochastic_adamw".

lr float

Learning rate.

betas tuple[float, float]

Coefficients used for computing running averages of gradient and its square.

eps float

Term added to the denominator to improve numerical stability.

weight_decay float

Weight decay coefficient.

state_dtype Literal[float32, bfloat16]

The dtype of the optimizer states.

d9d.loop.control.optimizer_provider

Interface for providing an optimizer.

InitializeOptimizerStageContext dataclass

Context data required to initialize an optimizer.

Attributes:

Name Type Description
dist_context DistributedContext

The distributed context.

model Module

The model instance for which parameters will be optimized.

OptimizerProvider

Bases: Protocol

Protocol for defining how optimizers are created for model pipeline stages.

__call__(context) abstractmethod

Initializes the optimizer for a specific training stage.

Parameters:

Name Type Description Default
context InitializeOptimizerStageContext

Context for this operation.

required

Returns:

Type Description
Optimizer

The instantiated PyTorch optimizer.

d9d.loop.component.PipelinedOptimizer

Bases: OptimizerProtocol, Offloadable

Optimizer that combines the optimizers of all stages hosted on a pipeline-parallel rank.

With pipeline parallelism, one rank can host several stages, each with its own parameters and optimizer. This class exposes them as one optimizer.

__init__(optimizers)

Constructs the PipelinedOptimizer object.

Parameters:

Name Type Description Default
optimizers dict[int, OptimizerProtocol]

One optimizer per stage hosted on this rank, keyed by the global index of the stage.

required

is_offloaded()

Reports whether the optimizer state is currently in host memory.

Returns:

Type Description
bool

True if the state is offloaded, False otherwise.

offload(ctx)

Releases the GPU memory of the optimizer state, moving its tensors to host memory.

Each tensor in optimizer.state keeps its identity, including DTensor wrappers. Only its local storage moves to host memory. The state dict keys and the tensors held by the optimizer stay valid.

Parameters:

Name Type Description Default
ctx OffloadContext

Context for this operation.

required

Raises:

Type Description
RuntimeError

If the optimizer state is already offloaded.

onload(ctx)

Moves the optimizer state released by offload back to GPU memory.

Parameters:

Name Type Description Default
ctx OnloadContext

Context for this operation.

required

Raises:

Type Description
RuntimeError

If the optimizer state is not offloaded.

d9d.optim

Optimizers, learning rate schedulers and the protocols that the training loop expects from them.

LRSchedulerProtocol

Bases: Protocol

Protocol for a learning rate scheduler.

A conforming scheduler supports stepping and checkpointing through the Stateful interface (state_dict and load_state_dict).

load_state_dict(state_dict)

Restores the scheduler's state from a state dict.

Parameters:

Name Type Description Default
state_dict dict[str, Any]

The state dict to restore from.

required
state_dict()

Returns the scheduler's state as a serializable dict.

Returns:

Type Description
dict[str, Any]

A dict containing the scheduler's state, suitable for checkpointing.

step()

Performs a single learning rate scheduling step.

OptimizerProtocol

Bases: Protocol

Protocol for a standard PyTorch optimizer.

A conforming optimizer supports stepping, zeroing gradients and checkpointing through the Stateful interface (state_dict and load_state_dict).

load_state_dict(state_dict)

Restores the optimizer's state from a state dict.

Parameters:

Name Type Description Default
state_dict dict[str, Any]

The state dict to restore from.

required
state_dict()

Returns the optimizer's state as a serializable dict.

Returns:

Type Description
dict[str, Any]

A dict containing the optimizer's state, suitable for checkpointing.

step()

Performs a single optimization step.

zero_grad()

Sets the gradients of all optimized tensors to zero.