Optimizers & Learning-Rate Schedules

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

An optimizer turns gradients into weight updates; a learning-rate schedule changes the step size over time. This page covers the Keras 3 keras.optimizers classes, the arguments they share (weight decay, gradient clipping, exponential moving average of weights, gradient accumulation, loss scaling), the schedules in keras.optimizers.schedules, what changed from the Keras 2 optimizers, and how to write your own. The theory (momentum, adaptive step sizes, warmup, why decoupled weight decay) is in Gradient Descent & Optimization and Optimizers & Learning-Rate Schedules; the PyTorch equivalents are Optimizers and Learning-Rate Schedulers. Optimizers are passed to compile() (see compile, fit, evaluate & predict) and the loss they minimise is on Losses.

Targets: Python 3.13, TensorFlow 2.21 with Keras 3.15 (TensorFlow 2.22 is upcoming), checked against keras.io on 2026-10-30. Examples were run on Python 3.13 with TensorFlow 2.21 and Keras 3.15 (CPU) on 2026-10-31. Snippets that continue an earlier example, or use names such as model and train_ds defined elsewhere, were run with small synthetic stand-ins. The keras.io overview page lists the optimizers and schedules but not the shared constructor arguments; those are taken from the signature of the Keras 3.15 optimizer base class.

The optimizers

The keras.io optimizers page lists:

Class Notes

SGD

Optional momentum and nesterov=True; the baseline, often best-generalising with a good schedule

RMSprop, Adagrad, Adadelta

Adaptive per-parameter methods; Adagrad accumulates squared gradients forever

Adam, Adamax, Nadam

Adam variants: moment estimates with bias correction; Nadam adds Nesterov momentum

AdamW

Adam with decoupled weight decay; the default choice for transformers

Adafactor

Factored second moments, small optimizer state; used for large language models

Lion

Sign-based update with momentum; usually wants a smaller learning rate and larger weight decay than Adam

Lamb

Layer-wise adaptive large-batch optimizer

Ftrl

Follow-the-regularised-leader, for sparse linear models

Muon

Orthogonalised-momentum optimizer for hidden weight matrices; listed on the Keras 3 page

The page also lists LossScaleOptimizer (used with float16 mixed precision, see Mixed Precision), MultiOptimizer and OptimizerMap, which apply different optimizers to different sets of variables (for example a large embedding table versus the dense layers). Check the class pages for their constructors: they are newer than the classic optimizers and are the ones most likely to differ between Keras versions.

Using an optimizer

import keras

model = keras.Sequential([keras.Input((20,)), keras.layers.Dense(64, activation="relu"), keras.layers.Dense(1)])

# String identifier: default hyperparameters (Adam, learning_rate=0.001)
model.compile(optimizer="adam", loss="mse")

# Instance: tuned hyperparameters
opt = keras.optimizers.AdamW(learning_rate=3e-4, weight_decay=0.01, beta_1=0.9, beta_2=0.999)
model.compile(optimizer=opt, loss="mse")

# One optimizer object is bound to one model. Create a fresh one for a second model.
print(opt.iterations)           # step counter variable
print(opt.learning_rate)        # variable holding the current learning rate (when not a schedule)

An optimizer builds its state (momentum, moments) the first time it sees the trainable variables. Reusing one instance across two models, or across a model that was rebuilt, leads to variable-mismatch errors; create a new instance. opt.iterations is the number of applied updates and is what schedules read.

Setting the learning rate on the fly: opt.learning_rate = 1e-4 assigns a new value when a plain number was used. If a schedule was given, the learning rate is computed from iterations; replace it by assigning a new schedule object only before training, and prefer the LearningRateScheduler or ReduceLROnPlateau callbacks (see Callbacks) for epoch-level changes, which work with plain-number learning rates.

Learning-rate schedules

A schedule is a callable that maps the step to a learning rate and is passed as learning_rate. The Keras 3 page lists these classes in keras.optimizers.schedules:

Class Behaviour

LearningRateSchedule

Base class for custom schedules

ExponentialDecay

Multiplies by decay_rate every decay_steps (smoothly, or in stairs with staircase=True)

PiecewiseConstantDecay

Fixed values between boundaries (step schedule)

PolynomialDecay

Decays from an initial to an end value along a polynomial; power=1 is linear

InverseTimeDecay

Decays like initial / (1 + decay_rate * step / decay_steps)

CosineDecay

Cosine decay to alpha times the initial rate; supports a linear warmup via warmup_target and warmup_steps

CosineDecayRestarts

Cosine decay with warm restarts; period grown by t_mul, peak scaled by m_mul

import keras

steps_per_epoch = 500
epochs = 30
total = steps_per_epoch * epochs

# Warmup then cosine decay: step counts are optimizer steps, not epochs
cosine = keras.optimizers.schedules.CosineDecay(
    initial_learning_rate=0.0,
    decay_steps=total - 1000,
    alpha=0.01,
    warmup_target=3e-4,
    warmup_steps=1000,
)

steps = keras.optimizers.schedules.PiecewiseConstantDecay(
    boundaries=[10 * steps_per_epoch, 20 * steps_per_epoch],
    values=[1e-3, 1e-4, 1e-5],
)

opt = keras.optimizers.AdamW(learning_rate=cosine, weight_decay=0.05)

# Inspect the curve without training
for s in (0, 500, 1000, 5000, total):
    print(s, float(cosine(s)))

Source: https://keras.io/api/optimizers/learning_rate_schedules/ (the CosineDecay and PiecewiseConstantDecay pages)

Details that cause errors:

  • Schedules count optimizer steps (batches), not epochs. Multiply by steps_per_epoch when you think in epochs. With gradient accumulation (below), Keras 3.15 evaluates a schedule on the internal micro-batch counter, while optimizer.iterations reports applied updates: after 8 batches with gradient_accumulation_steps=4, iterations is 2 but the schedule has advanced 8 steps. Size decay_steps and warmup_steps in micro-batches.

  • The warmup arguments of CosineDecay (warmup_target, warmup_steps) are part of the Keras 3.15 API (the example above uses them); older tutorials implement warmup by hand with a custom schedule.

  • A schedule is serialisable, so a compiled model saves and reloads it with its optimizer state (see Saving Keras Models).

  • ReduceLROnPlateau cannot be combined with a schedule object: it needs a settable numeric learning rate.

Custom schedule:

import keras
from keras import ops


@keras.saving.register_keras_serializable(package="docs")
class WarmupInverseSqrt(keras.optimizers.schedules.LearningRateSchedule):
    def __init__(self, peak_lr, warmup_steps):
        super().__init__()
        self.peak_lr = peak_lr
        self.warmup_steps = warmup_steps

    def __call__(self, step):
        step = ops.cast(step, "float32") + 1.0
        warm = step / self.warmup_steps
        decay = ops.sqrt(self.warmup_steps / step)
        return self.peak_lr * ops.minimum(warm, decay)

    def get_config(self):
        return {"peak_lr": self.peak_lr, "warmup_steps": self.warmup_steps}


opt = keras.optimizers.Adam(learning_rate=WarmupInverseSqrt(1e-3, 4000))

Source: https://keras.io/api/optimizers/learning_rate_schedules/ (the LearningRateSchedule base class)

Shared optimizer arguments

All Keras 3 optimizers inherit from a base class that accepts the arguments below. They are listed here from the signature of the Keras 3.15 optimizer base class (the keras.io overview page does not enumerate them); the defaults are weight_decay=None, use_ema=False, ema_momentum=0.99, ema_overwrite_frequency=None and None for the others.

Argument Effect

learning_rate

Float, variable or LearningRateSchedule

weight_decay

Decoupled decay: each step multiplies weights by a factor proportional to the learning rate; None or 0 disables it

clipnorm

Clips the gradient of each variable separately so its norm is at most this value

clipvalue

Clips every gradient element to [-clipvalue, clipvalue]

global_clipnorm

Clips all gradients together by their global norm; the usual choice for transformers and RNNs

use_ema, ema_momentum, ema_overwrite_frequency

Keep an exponential moving average of the weights, optionally overwriting the weights with it every N steps

loss_scale_factor

Static scaling of the loss before gradients are computed

gradient_accumulation_steps

Accumulate gradients over N batches before applying one update

name

Optimizer name

Use at most one of clipnorm, clipvalue and global_clipnorm; the base class rejects combinations with a ValueError saying that only one of them can be set.

Weight decay

Keras 2 optimizers such as Adam had no weight decay, and Keras 2 AdamW lived in tf.keras.optimizers.experimental. In Keras 3 every optimizer accepts weight_decay, and it is always decoupled: it shrinks the weights directly instead of adding an L2 term to the loss. This differs from kernel_regularizer=L2(...), which adds a penalty to the loss and therefore passes through the adaptive scaling of Adam. For SGD without momentum the two coincide up to the learning rate; for Adam-style methods they do not, which is why AdamW is recommended over Adam plus an L2 regulariser.

import keras

opt = keras.optimizers.AdamW(learning_rate=1e-3, weight_decay=0.01)

# Exclude biases and normalisation parameters from decay
opt.exclude_from_weight_decay(var_names=["bias", "beta", "gamma"])

Source: https://keras.io/api/optimizers/ (the Optimizer base class)

exclude_from_weight_decay(var_list=None, var_names=None) is a method of the Keras 3 base class and matches variables by object or by a substring of the variable path; call it before the first training step. Typical values of weight_decay: around 0.01 for AdamW on pre-trained fine-tuning, 0.05 to 0.1 for training transformers from scratch, and larger for Lion. See Generalization & Regularization for how decay interacts with other regularisers.

Gradient clipping

import keras

# Exploding gradients in an RNN or transformer: clip by the global norm
opt = keras.optimizers.Adam(learning_rate=1e-3, global_clipnorm=1.0)

# Per-variable alternatives
opt_a = keras.optimizers.SGD(learning_rate=0.1, clipnorm=1.0)
opt_b = keras.optimizers.SGD(learning_rate=0.1, clipvalue=0.5)

Source: https://keras.io/api/optimizers/ (the Optimizer base class)

global_clipnorm rescales the whole gradient vector when its joint norm exceeds the threshold, preserving direction. clipnorm rescales each variable’s gradient independently, which changes the direction of the combined update. clipvalue truncates elements and also changes direction. Clipping runs on the gradients before the update; with a LossScaleOptimizer it runs after unscaling, so thresholds mean the same in float16 and float32. Training instabilities and the broader recipe are in Training Deep Networks and Deep Learning Tuning Playbook.

Exponential moving average of weights

With use_ema=True the optimizer keeps a smoothed copy of the weights, \(\theta_{ema} \leftarrow m \, \theta_{ema} + (1 - m)\, \theta\) with ema_momentum \(m\) (a value like 0.99 is typical). EMA weights often generalise slightly better and are smoother at the end of training.

import keras

opt = keras.optimizers.SGD(
    learning_rate=0.1,
    momentum=0.9,
    use_ema=True,
    ema_momentum=0.99,
    ema_overwrite_frequency=None,   # None: overwrite only at the end of training
)
model.compile(optimizer=opt, loss="sparse_categorical_crossentropy", metrics=["accuracy"])
model.fit(x_train, y_train, epochs=20, validation_data=(x_val, y_val))

Source: https://keras.io/api/optimizers/ (the Optimizer base class)

How the averaged weights reach the model depends on ema_overwrite_frequency. With None the weights are replaced by the average when fit() finishes. With an integer the model weights are overwritten periodically, which disturbs training. The EMA weights are not what evaluate uses during an epoch, so the validation metric printed mid-training reflects the raw weights unless you swap in the average yourself. The Keras 3 optimizer also exposes finalize_variable_values(var_list) to perform that swap manually in a custom loop; fit() calls it on the trainable weights when training ends. The keras.callbacks.SwapEMAWeights callback swaps the average in for validation.

Gradient accumulation

import keras

# Effective batch size = batch_size * gradient_accumulation_steps
opt = keras.optimizers.AdamW(learning_rate=2e-4, gradient_accumulation_steps=4)
model.compile(optimizer=opt, loss="sparse_categorical_crossentropy")
model.fit(train_ds.batch(16), epochs=3)    # behaves like batch 64 for the weight updates

Source: https://keras.io/api/optimizers/ (the Optimizer base class)

The optimizer sums (averages) gradients over N consecutive batches and applies one update on every Nth call. Consequences: memory is that of the small batch; batch-normalisation statistics still see the small batch; the loss is not rescaled for you in custom loops, so check how your gradients are normalised; iterations and any step-based schedule need care (see above). This is the standard way to fit a large effective batch on a small GPU, and the Keras 2 equivalent required a custom wrapper or train step.

Optimizers in a custom training step

import tensorflow as tf
import keras

model = keras.Sequential([keras.Input((8,)), keras.layers.Dense(1)])
opt = keras.optimizers.Adam(1e-3, global_clipnorm=1.0)
loss_fn = keras.losses.MeanSquaredError()


@tf.function
def train_step(x, y):
    with tf.GradientTape() as tape:
        loss = loss_fn(y, model(x, training=True))
    grads = tape.gradient(loss, model.trainable_variables)
    opt.apply(grads, model.trainable_variables)        # Keras 3 name; apply_gradients is also available
    return loss

Source: https://keras.io/api/optimizers/ (the Optimizer base class)

In Keras 3 optimizer.apply(grads, trainable_variables) and optimizer.apply_gradients(grads_and_vars) apply an update; clipping, weight decay, EMA and accumulation happen inside them, so a custom loop gets the same behaviour as fit(). More in Customizing fit() with train_step and Writing a Training Loop from Scratch.

Per-layer learning rates and freezing

There is no param_groups as in PyTorch (see Optimizers). Options: freeze layers with layer.trainable = False and recompile (see Transfer Learning & Fine-Tuning), use MultiOptimizer/OptimizerMap from the optimizers page to assign different optimizers per layer, or write a custom loop with several optimizer objects. Setting trainable after compile only takes effect after calling compile() again.

Legacy optimizers and migration

Keras 2 had two optimizer families: the original tf.keras.optimizers.Adam and the newer tf.keras.optimizers.experimental.*, with the old ones moved to tf.keras.optimizers.legacy. Keras 3 has a single implementation; there is no legacy namespace in Keras 3, and tf.keras now refers to Keras 3 by default. In practice:

Older code Keras 3

tf.keras.optimizers.legacy.Adam

keras.optimizers.Adam; if Keras 2 behaviour is required, install tf_keras and set TF_USE_LEGACY_KERAS=1 (see Migrating from Keras 2 to Keras 3)

optimizer.lr, optimizer.decay

optimizer.learning_rate; the decay argument is gone, use a schedule

tfa.optimizers.* (TensorFlow Addons)

Several are now in core Keras (AdamW, Lion, Lamb); TF Addons is no longer maintained (see Ecosystem & Project Status)

apply_gradients(zip(grads, vars)) only

Still works; apply(grads, vars) is the new form

Optimizer weights as optimizer.weights lists

optimizer.variables (a list of variables) in Keras 3

Optimizer state saved by Keras 2 does not load into Keras 3 optimizers; resume training from weights and restart the optimizer state if needed. Checkpoint formats are on Training Checkpoints.

Writing a custom optimizer

Keras 3 optimizers subclass keras.optimizers.Optimizer, create their state in build(var_list) with add_variable_from_reference, and implement update_step(gradient, variable, learning_rate).

import keras
from keras import ops


class SignSGDMomentum(keras.optimizers.Optimizer):
    def __init__(self, learning_rate=0.01, momentum=0.9, name="sign_sgd_momentum", **kwargs):
        super().__init__(learning_rate=learning_rate, name=name, **kwargs)
        self.momentum = momentum

    def build(self, var_list):
        if self.built:
            return
        super().build(var_list)
        self.velocities = [self.add_variable_from_reference(v, name="velocity") for v in var_list]

    def update_step(self, gradient, variable, learning_rate):
        lr = ops.cast(learning_rate, variable.dtype)
        v = self.velocities[self._get_variable_index(variable)]
        v.assign(self.momentum * v + (1.0 - self.momentum) * gradient)
        variable.assign(variable - lr * ops.sign(v))

    def get_config(self):
        cfg = super().get_config()
        cfg["momentum"] = self.momentum
        return cfg

Source: https://keras.io/api/optimizers/ (the Optimizer base class: build, update_step, get_config)

This API replaces the Keras 2 _resource_apply_dense, _create_slots and get_slot hooks. update_step must use ops and in-place assign, because it is traced.

Choosing and tuning

  • Start with AdamW (learning rate 1e-3 for small networks, 1e-4 to 3e-4 for transformers, 1e-5 to 5e-5 for fine-tuning a pre-trained model) with a warmup and cosine decay.

  • SGD(momentum=0.9, nesterov=True) with a stepped or cosine schedule is a strong baseline for CNNs and often generalises better than Adam.

  • Tune the learning rate first, on a log scale (see KerasTuner); then the schedule length, weight decay and batch size.

  • Use global_clipnorm for RNNs and transformers, and loss scaling only with float16 (see Mixed Precision).

  • Scale the learning rate when changing the batch size or the number of replicas (see Distributed Training).

  • Watch the learning rate in TensorBoard (see TensorBoard); a schedule bug is easy to miss otherwise.

Common mistakes

  • Counting schedule steps in epochs instead of batches.

  • Passing a schedule and also using ReduceLROnPlateau.

  • Adding both weight_decay and a heavy L2 regulariser, doubling the shrinkage.

  • Sharing one optimizer between two models or after rebuilding the model.

  • Changing trainable without recompiling.

  • Expecting EMA weights to be used for mid-training validation.

  • Porting lr= or decay= keyword arguments from Keras 2 code.