[BUG] Adopt foreach path takes the first-step check and the clip value from device_state_steps[0], so a param whose gradient arrives late is never initialized and steps by grad / eps

Author: Nicholas022400701Created Sep 28, 2026Updated Sep 28, 2026

Describe the bug

_multi_tensor_adopt in timm/optim/adopt.py decides two things for the whole (device, dtype) group from the first param's step count:

python
if device_state_steps[0] == 1:
    torch._foreach_addcmul_(device_exp_avg_sqs, device_grads, device_grads)
    continue
...
clip_val = (device_state_steps[0] - 1) ** clip_exp

The params of a group do not all have the same state['step']. A param whose p.grad is None in some steps is skipped in _init_group and does not advance (zero_grad(set_to_none=True) leaves every unused param like that: a layer frozen for the first epochs, an MoE expert that received no tokens, a head that is only trained on some batches). Once the counts differ:

  • Lagging param not first in the group: on its first step device_state_steps[0] != 1, so it skips the exp_avg_sq = g^2 initialization and goes straight through the regular update with exp_avg_sq = 0, that is normed_grad = grad / eps. With the default clip_exp=0.333 it is clipped at (step_0 - 1) ** 0.333 and keeps running at the clip ceiling because exp_avg_sq only fills at (1 - beta2) = 1e-4 per step; with clip_exp=None the first update is grad / 1e-6 * lr.
  • Lagging param first in the group: on its first step the whole group takes the == 1 branch, so every other param gets exp_avg_sq += g^2 (undecayed, roughly doubling it) and skips its update that step. Afterwards their clip value is computed from the lagging param's step.

The single-tensor path uses each param's own step, so foreach=True and foreach=False diverge (with foreach=None the multi-tensor path is picked on CUDA). torch.optim.Adam has the same lag and its foreach path handles it per param. The reference implementation at iShohei220/adopt uses device_state_steps[0] the same way, so this was inherited from it.

To Reproduce

Two params in one group, params[lag_index] gets its first gradient at step 5 of 12, lr=1e-3, compare foreach=True with foreach=False:

python
import torch
from timm.optim import Adopt

grads = [torch.randn(2, 10, 8, generator=torch.Generator().manual_seed(step)) for step in range(12)]


def run(foreach, lag_index, **kwargs):
    # two params in one group; params[lag_index] has p.grad = None for the first 4 steps (a frozen layer,
    # an expert that got no tokens, zero_grad(set_to_none=True)) and gets its first gradient at step 5
    params = [torch.nn.Parameter(torch.full((10, 8), 1.0 + i)) for i in range(2)]
    opt = Adopt(params, lr=1e-3, foreach=foreach, **kwargs)
    updates = []
    for step, step_grads in enumerate(grads):
        for i, p in enumerate(params):
            p.grad = None if (i == lag_index and step < 4) else step_grads[i].clone()
        before = params[lag_index].detach().clone()
        opt.step()
        updates.append((params[lag_index].detach() - before).abs().max().item() / 1e-3)
    return params, opt, updates


for lag_index, kwargs in [(1, {}), (0, {}), (1, {"clip_exp": None})]:
    (ps, os_, us), (pf, of, uf) = run(False, lag_index, **kwargs), run(True, lag_index, **kwargs)
    other = 1 - lag_index
    print(f"lagging param = params[{lag_index}], {kwargs or 'defaults'}")
    print(f"  max |foreach - single| after 12 steps: params[{lag_index}] {(pf[lag_index] - ps[lag_index]).abs().max():.2e}, "
          f"params[{other}] {(pf[other] - ps[other]).abs().max():.2e}")
    print(f"  |update| / lr of params[{lag_index}] per step, single : {' '.join(f'{u:.2f}' for u in us)}")
    print(f"  |update| / lr of params[{lag_index}] per step, foreach: {' '.join(f'{u:.2f}' for u in uf)}")
    for name, o, p in (("single", os_, ps), ("foreach", of, pf)):
        st, so = o.state[p[lag_index]], o.state[p[other]]
        print(f"  {name:7s} state: params[{lag_index}] step {st['step'].item():.0f} exp_avg_sq mean {st['exp_avg_sq'].mean():.4f},"
              f" params[{other}] step {so['step'].item():.0f} exp_avg_sq mean {so['exp_avg_sq'].mean():.4f}")


def run_adam(foreach):
    params = [torch.nn.Parameter(torch.full((10, 8), 1.0 + i)) for i in range(2)]
    opt = torch.optim.Adam(params, lr=1e-3, foreach=foreach)
    for step, step_grads in enumerate(grads):
        for i, p in enumerate(params):
            p.grad = None if (i == 1 and step < 4) else step_grads[i].clone()
        opt.step()
    return params[1].detach()


print(f"torch.optim.Adam, same setup: max |foreach - single| = {(run_adam(True) - run_adam(False)).abs().max():.2e}")

Output on main (7cb8dca):

lagging param = params[1], defaults
  max |foreach - single| after 12 steps: params[1] 3.61e-03, params[0] 0.00e+00
  |update| / lr of params[1] per step, single : 0.00 0.00 0.00 0.00 0.00 0.10 0.22 0.34 0.41 0.41 0.55 0.69
  |update| / lr of params[1] per step, foreach: 0.00 0.00 0.00 0.00 0.16 0.31 0.46 0.61 0.75 0.88 1.01 1.13
  single  state: params[1] step 8 exp_avg_sq mean 1.0967, params[0] step 12 exp_avg_sq mean 1.1216
  foreach state: params[1] step 8 exp_avg_sq mean 0.0008, params[0] step 12 exp_avg_sq mean 1.1216
lagging param = params[0], defaults
  max |foreach - single| after 12 steps: params[0] 0.00e+00, params[1] 2.84e-03
  |update| / lr of params[0] per step, single : 0.00 0.00 0.00 0.00 0.00 0.10 0.22 0.34 0.46 0.59 0.71 0.62
  |update| / lr of params[0] per step, foreach: 0.00 0.00 0.00 0.00 0.00 0.10 0.22 0.34 0.46 0.59 0.71 0.62
  single  state: params[0] step 8 exp_avg_sq mean 1.0215, params[1] step 12 exp_avg_sq mean 0.8276
  foreach state: params[0] step 8 exp_avg_sq mean 1.0215, params[1] step 12 exp_avg_sq mean 1.9236
lagging param = params[1], {'clip_exp': None}
  max |foreach - single| after 12 steps: params[1] 1.61e+03, params[0] 0.00e+00
  |update| / lr of params[1] per step, single : 0.00 0.00 0.00 0.00 0.00 8.58 10.81 9.79 4.91 3.11 2.93 3.58
  |update| / lr of params[1] per step, foreach: 0.00 0.00 0.00 0.00 283451.84 255111.02 229598.02 206641.60 185975.95 167377.20 150638.67 135572.39
  single  state: params[1] step 8 exp_avg_sq mean 1.0967, params[0] step 12 exp_avg_sq mean 1.1216
  foreach state: params[1] step 8 exp_avg_sq mean 0.0008, params[0] step 12 exp_avg_sq mean 1.1216
torch.optim.Adam, same setup: max |foreach - single| = 0.00e+00

Expected behavior

The foreach path gives the same trajectory as the single-tensor path: a param takes its first-step initialization when its own step is 1 and is clipped with its own step. The last three lines of the patch's test run with the attached fix are all 0.00e+00.

Desktop (please complete the following information):

  • OS: Linux
  • This repository version: main at 7cb8dca (1.0.31.dev0), same on 1.0.30 from PyPI
  • PyTorch version: 2.14.0+cpu

Additional context

Fix on Nicholas022400701:fix/adopt-foreach-lagging-steps (diff below): the first-step params are split off and initialized, the rest of the group goes through the regular update, and clip_vals is a per-param list (_get_value(step) scalars, or _foreach_pow tensors when capturable). Groups whose params all have the same step count, which is every case where each param gets a gradient every step, run exactly the same ops as before, so their results are unchanged. Regression test test_adopt_multi_tensor_lagging_step_matches_single_tensor (lag index 0 and 1, clip_exp 0.333 and None) fails on main in all four cases and passes with the fix; pytest tests/test_optim.py: 202 passed. I also compared foreach against single-tensor over the 64 weight_decay / decoupled / corrected_weight_decay / caution / maximize / clip_exp combinations with one param skipping a step: 32 mismatches on main (all with clip_exp=0.333, the clip_exp=None ones only differ once the lag hits a first step), none with the fix. Happy to open the PR if this looks right to you.

AI disclosure: I used an AI coding agent to help find this, to write the reproduction, the patch, the tests and this report. I have read and checked the report, the patch and the tests myself and I will answer questions personally.

Patch (git diff against main, 2 files, +55 -6)
diff
diff --git a/tests/test_optim.py b/tests/test_optim.py
index 0be1d84..5dba4e5 100644
--- a/tests/test_optim.py
+++ b/tests/test_optim.py
@@ -945,6 +945,37 @@ def test_sgdw_multi_tensor_weight_decay_matches_single_tensor():
     torch.testing.assert_close(multi64, single64)
 
 
[email protected]('lag_index', [0, 1])
[email protected]('clip_exp', [None, 0.333])
+def test_adopt_multi_tensor_lagging_step_matches_single_tensor(lag_index, clip_exp):
+    # A param without a gradient in some steps (frozen for a while, an expert that got no tokens) lags behind
+    # the other params of its group in state['step']. The foreach path took the first-step initialization and
+    # the clip value from device_state_steps[0] for the whole group, so a lagging param never got its
+    # exp_avg_sq initialized (or the whole group was re-initialized and skipped an update when the lagging
+    # param came first) and was clipped with the wrong step. Compare against the single-tensor reference.
+    from timm.optim.adopt import Adopt
+
+    grads = [torch.randn(2, 5, 4, generator=torch.Generator().manual_seed(step)) for step in range(12)]
+
+    def run(foreach):
+        params = [Parameter(torch.full((5, 4), 1.0 + i)) for i in range(2)]
+        optimizer = Adopt(params, lr=1e-3, clip_exp=clip_exp, foreach=foreach)
+        for step, step_grads in enumerate(grads):
+            for i, p in enumerate(params):
+                p.grad = None if (i == lag_index and step < 4) else step_grads[i].clone()
+            optimizer.step()
+        return params, [optimizer.state[p] for p in params]
+
+    multi_params, multi_state = run(True)
+    single_params, single_state = run(False)
+    for multi, single in zip(multi_params, single_params):
+        torch.testing.assert_close(multi, single)
+    for multi, single in zip(multi_state, single_state):
+        assert multi['step'] == single['step']
+        torch.testing.assert_close(multi['exp_avg'], single['exp_avg'])
+        torch.testing.assert_close(multi['exp_avg_sq'], single['exp_avg_sq'])
+
+
 def test_mars_last_grad_is_copied_not_aliased():
     # Mars keeps the previous gradient in state['last_grad'] for its variance reduction term. It used
     # to store a reference to p.grad instead of a copy. With zero_grad(set_to_none=False) the gradient
diff --git a/timm/optim/adopt.py b/timm/optim/adopt.py
index b1f9405..4be994d 100644
--- a/timm/optim/adopt.py
+++ b/timm/optim/adopt.py
@@ -419,9 +419,24 @@ def _multi_tensor_adopt(
             else:
                 device_grads = torch._foreach_add(device_grads, device_params, alpha=weight_decay)
 
-        if device_state_steps[0] == 1:
-            torch._foreach_addcmul_(device_exp_avg_sqs, device_grads, device_grads)
-            continue
+        # Params that had no gradient in some steps (frozen for a while, an expert without tokens) lag behind in
+        # their step count, so the first-step initialization and the clip value are decided per param rather
+        # than from device_state_steps[0].
+        first_step = [i for i, step in enumerate(device_state_steps) if step == 1]
+        if first_step:
+            torch._foreach_addcmul_(
+                [device_exp_avg_sqs[i] for i in first_step],
+                [device_grads[i] for i in first_step],
+                [device_grads[i] for i in first_step],
+            )
+            if len(first_step) == len(device_params):
+                continue
+            later_step = [i for i, step in enumerate(device_state_steps) if step != 1]
+            device_params = [device_params[i] for i in later_step]
+            device_grads = [device_grads[i] for i in later_step]
+            device_exp_avgs = [device_exp_avgs[i] for i in later_step]
+            device_exp_avg_sqs = [device_exp_avg_sqs[i] for i in later_step]
+            device_state_steps = [device_state_steps[i] for i in later_step]
 
         if weight_decay != 0 and decoupled:
             wd_scale = lr ** 2 / max_lr if max_lr is not None else lr
@@ -433,9 +448,12 @@ def _multi_tensor_adopt(
         normed_grad = torch._foreach_div(device_grads, exp_avg_sq_sqrt)
 
         if clip_exp is not None:
-            clip_val = (device_state_steps[0] - 1) ** clip_exp
-            torch._foreach_maximum_(normed_grad, -clip_val)
-            torch._foreach_minimum_(normed_grad, clip_val)
+            if capturable:
+                clip_vals = torch._foreach_pow(torch._foreach_sub(device_state_steps, 1), clip_exp)
+            else:
+                clip_vals = [(_get_value(step) - 1) ** clip_exp for step in device_state_steps]
+            torch._foreach_maximum_(normed_grad, [-clip_val for clip_val in clip_vals])
+            torch._foreach_minimum_(normed_grad, clip_vals)
 
         torch._foreach_lerp_(device_exp_avgs, normed_grad, 1 - beta1)

Source: huggingface/pytorch-image-models