AI Logic

Optimizers

Schedule-Free

Updated:

How Schedule-Free works. Left: one step that forms the gradient point y between the base sequence z and the averaged sequence x, updates z with a constant learning rate, and takes a weighted average into x. Right: a graph computed from the formulas showing how much a gradient from time s contributes to the current x, y, and z, with x taking the same shape as a linear-decay schedule

Background and Overview

Schedule-Free is an optimization method that achieves the same effect as a learning rate scheduler through weight averaging, without using a scheduler. It was presented by Defazio et al. at NeurIPS in 2024 (the paper is titled "The Road Less Scheduled"). There are SGD and AdamW versions, and neither adds hyperparameters to the base method.

In deep learning, schedules that lower the learning rate toward the end of training, such as cosine annealing and linear decay, are widely used. They require fixing the number of training steps TT in advance. Some schedules do not require TT, but according to the paper they perform far worse than schedules that use TT.

Meanwhile, optimization theory has long known that taking the average of SGD iterates (Polyak–Ruppert averaging) as the answer achieves the optimal convergence rate. Averaging does not require fixing TT, but in practical deep learning it gives much worse results than the last iterate, which has been regarded as a gap between theory and practice.

By modifying how the average is taken and unifying schedules and averaging under the same theory, Schedule-Free achieves the following properties at once.

  • No need to fix TT: At any point during a single training run, the weights are about as good as those obtained by a schedule that ends at that point (Figure 1 of the paper).
  • No extra hyperparameters: The number is the same as for SGD (with momentum) or Adam.
  • Track record: Schedule-Free AdamW won the self-tuning track of MLCommons AlgoPerf 2024 (the track where a single set of hyperparameters must solve all tasks).

Theory (Computation in One Step)

Schedule-Free uses three sequences.

  • Base sequence zz: The weights updated directly by the base optimizer (SGD or Adam)
  • Averaged sequence xx: The average of zz. These weights are used for evaluation and saving
  • Gradient point yy: The point interpolating zz and xx with coefficient Ξ²\beta. Gradients are computed here

Schedule-Free SGD consists of the following three equations (Eqs. (3)–(5)). Starting from x1=z1x_1 = z_1, with ct+1=1/(t+1)c_{t+1} = 1/(t+1), xx is the simple average of zz.

yt=(1βˆ’Ξ²) zt+β xt,zt+1=ztβˆ’Ξ³β€‰βˆ‡f(yt,ΞΆt),xt+1=(1βˆ’ct+1) xt+ct+1 zt+1y_t = (1-\beta)\, z_t + \beta\, x_t, \qquad z_{t+1} = z_t - \gamma\, \nabla f(y_t, \zeta_t), \qquad x_{t+1} = (1 - c_{t+1})\, x_t + c_{t+1}\, z_{t+1}

With Ξ²=0\beta = 0 this is Polyak–Ruppert averaging, where gradients are computed at zz; with Ξ²=1\beta = 1 it is primal averaging, where gradients are computed at the averaged point xx. Schedule-Free sits in between, and in practice Ξ²β‰ˆ0.9\beta \approx 0.9 works well.

Schedule-Free AdamW (Algorithm 1 of the paper) performs the following computation at each step tt.

  1. Form the gradient point yt=(1βˆ’Ξ²1)zt+Ξ²1xty_t = (1-\beta_1) z_t + \beta_1 x_t and compute the gradient gtg_t there.
  2. Update the moving average vtv_t of squared gradients, as in Adam.
  3. Compute the learning rate Ξ³t=Ξ³1βˆ’Ξ²2t min⁑(1,t/Twarmup)\gamma_t = \gamma \sqrt{1-\beta_2^t}\, \min(1, t/T_{\mathrm{warmup}}), which combines warmup and Adam's bias correction.
  4. Update the base sequence zz together with weight decay applied at yty_t.
  5. Update the averaged sequence xx with weight ct+1c_{t+1}.
zt+1=ztβˆ’Ξ³tgtvt+Ο΅βˆ’Ξ³tλ yt,ct+1=Ξ³t2βˆ‘i=1tΞ³i2,xt+1=(1βˆ’ct+1) xt+ct+1 zt+1z_{t+1} = z_t - \gamma_t \frac{g_t}{\sqrt{v_t} + \epsilon} - \gamma_t \lambda\, y_t, \qquad c_{t+1} = \frac{\gamma_t^2}{\sum_{i=1}^{t} \gamma_i^2}, \qquad x_{t+1} = (1 - c_{t+1})\, x_t + c_{t+1}\, z_{t+1}

The averaging weight is proportional to the square of the learning rate so that the zz obtained with small learning rates during warmup does not enter the average too heavily. After warmup, ct+1c_{t+1} decreases at a rate of 1/t1/t.

There is no first moment (moving average of gradients) as in Adam. The role of momentum is played by making yy an interpolation of zz and xx. The paper explains that with Ξ²=0.9\beta = 0.9, 0.1 gt0.1\, g_t of the gradient gtg_t enters yy immediately, and the rest enters slowly through the average xx. Like ordinary momentum, this dampens the effect of sudden gradients, while for convex problems the optimal convergence rate is guaranteed regardless of the value of Ξ²\beta (Theorem 1).

Why No Schedule Is Needed

Section 2.3 of the paper explains that the averaged sequence xx acts like a linear-decay schedule that ends at the current time.

The right side of the figure at the top shows, for Schedule-Free SGD with a constant learning rate Ξ³\gamma, how much a gradient computed at time ss contributes to each sequence at the current time TT.

  • Base sequence zz: Since it is plain constant-learning-rate SGD, gradients from every time contribute equally (Ξ³\gamma).
  • Averaged sequence xx: Since it is the average of zz, the gradient from time ss is contained only in the later zz. Its contribution is (Tβˆ’s)/T(T - s)/T: larger for older gradients and smaller for recent ones. This has the same shape as how gradients enter the final weights when training with a linear-decay schedule that lowers the learning rate linearly to 0 at TT.
  • Gradient point yy: (1βˆ’Ξ²)+Ξ²(Tβˆ’s)/T(1-\beta) + \beta (T-s)/T, so recent gradients contribute slightly more.

In other words, simply taking the average automatically performs, at every step, "the linear decay that would apply if training ended now," so there is no need to fix TT. The paper proves a theorem that generally relates averaging schemes to learning rate sequences (Theorem 2, a new theorem converting regret bounds from online learning into convergence rates for stochastic optimization) and derives Polyak averaging, primal averaging, and linear decay all as special cases.

The paper also shows that Schedule-Free is less prone to divergence even with relatively large learning rates. In a quadratic experiment, Ξ²\beta had almost no effect while the learning rate was small, but with large learning rates, Ξ²<1\beta < 1 was essential for convergence (Figure 3). In addition, with scheduled SGD on CIFAR-10, the training loss and gradient norm dropped to almost 0 in the second half of training and learning stalled, whereas with Schedule-Free this did not happen and learning continued (Figure 6).

Experimental Results

The paper evaluates on 28 problems ranging from logistic regression to large-scale deep learning. For the deep learning problems, the learning rate and weight decay are grid-searched for both the baseline schedules and Schedule-Free, and Ξ²\beta is chosen from 0.9 and 0.98. CIFAR, SVHN, and ImageNet use Schedule-Free SGD; the others use Schedule-Free AdamW.

Nine deep learning problems (values from the legends of Figures 2 and 5 of the paper; higher accuracy and lower loss are better)

ProblemSchedule-FreeBaseline schedules
CIFAR-10 (Wide ResNet-16-8), accuracy96.03%Cosine 95.73%, step 95.59%
CIFAR-100 (DenseNet), accuracy78.71%Cosine 77.41%, step 76.41%
SVHN (ResNet-3-96), accuracy98.40%Cosine 98.27%, step 98.20%
ImageNet (ResNet-50), accuracy76.90%Cosine 76.90%, step 76.49%
IWSLT14 (LSTM), test loss4.18Cosine 4.23 (Polyak averaging 4.35, primal averaging 4.44)
fastMRI (VarNet 2.0), SSIM0.9112Cosine 0.9110
Criteo (DLRM), accuracy0.7915Linear decay 0.7906
MAE fine-tuning on ImageNet (ViT), accuracy83.54%Cosine 83.52%
OpenWebText (GPT-2 124M), test loss2.831Cosine 2.853

Schedule-Free outperformed the best schedule in 7 of the 9 problems and matched it on ImageNet ResNet-50 and MAE fine-tuning. Conventional Polyak and primal averaging fall far behind the schedules.

Other results are as follows.

  • AlgoPerf (MLCommons): Compared with the NAdamW baseline, it was better on 4 workloads (WMT, ViT, fastMRI, OGBG), on par on Conformer and Criteo, and slightly worse on DeepSpeech. The paper attributes the two speech workloads where it underperformed to the inability to recompute the batch normalization statistics with xx.
  • Learning rate: The optimal learning rate for Schedule-Free was larger than for the base method.
  • Ξ²\beta: 0.9 worked for almost all problems, but for GPT-2 alone the loss began to spike with 0.9 and was stable with 0.98. In ImageNet experiments trained for 200 epochs, the optimal Ξ²\beta was 0.9 regardless of training length.

Practical Considerations

You need to switch the weights in use between training and evaluation, because gradients are computed at yy while xx is used for evaluation and saving. The authors' PyTorch implementation (the schedulefree package) swaps yy and xx in a single weight buffer, so call optimizer.train() together with model.train(), and optimizer.eval() together with model.eval(). Also switch to optimizer.eval() before saving a checkpoint.

  • Recompute batch normalization statistics: The running statistics of batch normalization are collected at yy during training. Before evaluation, run a few batches of training data through the xx weights to recompute the statistics (the paper also mentions methods such as PreciseBN). This is unnecessary for normalization without running statistics (such as LayerNorm).
  • Warmup is required: No schedule is needed, but warmup at the start of training is used. The paper uses linear warmup over a fixed period.
  • Re-tune the learning rate and weight decay: The paper lists the fact that their optimal values differ from those with schedules as a main practical limitation. The official implementation's documentation recommends starting from learning rates 10–50x the usual for SGD and 1–10x for AdamW.
  • Use a larger Ξ²\beta for long training runs: GPT-2 in the paper was stable with 0.98. The official implementation's documentation also says that 0.95 or 0.98 may be needed for long runs.
  • Apply weight decay at yy: The paper states that applying it at yy gave large improvements on ImageNet and GPT-2. The official implementation changed its handling of weight decay after the paper, and it keeps a version that follows the paper (AdamWScheduleFreePaper).
  • Memory does not increase: Schedule-Free SGD needs two sets of weights (xx and zz), the same as SGD with momentum, and yy can be computed on the fly. The AdamW version also stores zz in place of the first moment, so it uses the same memory as AdamW.

Comparison with Other Methods

The table below compares methods that lower the learning rate and methods that average weights from the same perspective.

MethodFinal step count TTGradient computed at the averaged weights?Practical performance (paper's evaluation)Extra memory
Cosine annealing, linear decayRequired in advance-High (baseline)None
WSDTime to start decay required--None
Polyak–Ruppert averagingNot requiredNo (Ξ²=0\beta = 0)Far below schedulesOne set of weights
Primal averagingNot requiredAt the averaged point (Ξ²=1\beta = 1)Slow convergenceOne set of weights
LookaheadNot requiredRestarts from slow weights (exponential moving average)-One set of weights
Schedule-FreeNot requiredAt the interpolated point yy (Ξ²β‰ˆ0.9\beta \approx 0.9)On par with or better than scheduleszz in place of momentum (no increase)

The paper positions Lookahead as "an exponential-moving-average version of primal averaging." It notes that end-of-training averaging such as SWA is not a substitute for a schedule but a way to improve final performance, and that it can be used on top of Schedule-Free.

Rough guidelines for choosing are as follows.

  • If you want to run training without fixing its length and want good weights wherever you stop, use Schedule-Free: A single run traces the Pareto frontier of loss versus training time.
  • If you already have a tuned schedule and settings, keeping them is fine: Switching to Schedule-Free requires re-tuning the learning rate and weight decay.
  • For models that rely heavily on batch normalization, do not forget to recompute the statistics before evaluation: If you want to avoid that hassle, a conventional schedule may be easier to handle.

PyTorch example

Show code
python
import torch
import torch.nn as nn


class AdamWScheduleFree(torch.optim.Optimizer):
    # A direct transcription of Algorithm 1 in the paper (x, z, y are kept separately for clarity)
    def __init__(self, params, lr=2.5e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0.0, warmup_steps=100):
        super().__init__(params, dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay, warmup_steps=warmup_steps))
        self.t = 0
        for g in self.param_groups:
            for p in g["params"]:
                st = self.state[p]
                st["z"] = p.detach().clone()        # base sequence z_1 = x_1
                st["x"] = p.detach().clone()        # averaged sequence x_1
                st["v"] = torch.zeros_like(p)       # v_0 = 0
                p.data.copy_(st["x"])               # gradients are taken at y, so load y before training
        self.train()

    @torch.no_grad()
    def train(self):   # load y_t = (1 βˆ’ Ξ²1) z_t + Ξ²1 x_t into the parameters
        for g in self.param_groups:
            b1 = g["betas"][0]
            for p in g["params"]:
                st = self.state[p]
                p.copy_((1 - b1) * st["z"] + b1 * st["x"])

    @torch.no_grad()
    def eval(self):    # load x_t into the parameters for evaluation and saving
        for g in self.param_groups:
            for p in g["params"]:
                p.copy_(self.state[p]["x"])

    @torch.no_grad()
    def step(self):
        self.t += 1
        for g in self.param_groups:
            b1, b2 = g["betas"]
            lr_t = g["lr"] * (1 - b2 ** self.t) ** 0.5 * min(1.0, self.t / g["warmup_steps"])
            g["lr_sq_sum"] = g.get("lr_sq_sum", 0.0) + lr_t ** 2
            c = lr_t ** 2 / g["lr_sq_sum"]                       # c_{t+1} = Ξ³_t^2 / Ξ£ Ξ³_i^2
            for p in g["params"]:
                if p.grad is None:
                    continue
                st = self.state[p]
                y = p.detach()                                    # the current parameters are y_t
                st["v"].mul_(b2).addcmul_(p.grad, p.grad, value=1 - b2)
                st["z"].add_(p.grad / (st["v"].sqrt() + g["eps"]) + g["weight_decay"] * y, alpha=-lr_t)
                st["x"].mul_(1 - c).add_(st["z"], alpha=c)        # weighted average
                p.copy_((1 - b1) * st["z"] + b1 * st["x"])        # next y_{t+1}


model = nn.Sequential(nn.Linear(32, 64), nn.GELU(), nn.Linear(64, 10))
optimizer = AdamWScheduleFree(model.parameters(), lr=2.5e-3, warmup_steps=5)

model.train(); optimizer.train()          # y during training
for step in range(10):
    x = torch.randn(16, 32)
    y = torch.randint(0, 10, (16,))
    loss = nn.functional.cross_entropy(model(x), y)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

model.eval(); optimizer.eval()            # x for evaluation and saving (no schedule; stop at any time)

FAQ

Q. Is a learning rate scheduler not needed at all?
A.

A schedule that lowers the learning rate (such as cosine or linear decay) is not needed. However, warmup at the start of training is still required. Because the averaged sequence xx acts like a linear decay ending at the current time, there is no need to fix the final step count TT.

Q. What should I watch out for during evaluation?
A.

Use the averaged sequence xx, not the gradient point yy, for evaluation and saving. In the authors' implementation, optimizer.eval() switches to it. For models with batch normalization, run a few batches through the xx weights to recompute the statistics before evaluating.

Q. What value should Ξ² be?
A.

In the paper, 0.9 worked for almost all problems, and the optimal value did not change with training length. Only GPT-2 training required 0.98. For long training runs, also try 0.95 or 0.98.

References

  1. A. Defazio, X. Yang, H. Mehta, K. Mishchenko, A. Khaled, and A. Cutkosky, "The Road Less Scheduled," NeurIPS, 2024.
  2. Meta Research, "schedule_free" (official implementation of the paper), GitHub.