accelerate icon indicating copy to clipboard operation
accelerate copied to clipboard

When using gradient accumulation, does the order of optimizer.zero_grad() affect training?

Open polestarss opened this issue 1 year ago • 3 comments

if I use accelerate+deepspeed to train a model, and I set deepspeed_config: gradient_accumulation_steps: 8 offload_optimizer_device: cpu offload_param_device: cpu zero3_init_flag: false zero_stage: 2

does the order of the order of backward(), step(), zero_grad() affect training? For example: for batch in training_dataloader: with accelerator.accumulate(model): inputs, targets = batch outputs = model(inputs) loss = loss_function(outputs, targets) accelerator.backward(loss) optimizer.step() scheduler.step() optimizer.zero_grad()

and for batch in training_dataloader: with accelerator.accumulate(model): optimizer.zero_grad() inputs, targets = batch outputs = model(inputs) loss = loss_function(outputs, targets) accelerator.backward(loss) optimizer.step() scheduler.step()

I want to know whether the two situations will yield the same result. During gradient accumulation training, when the model needs to update the parameters and accelerate.sync_gradients=True, will using the second method clear the gradients, causing the gradient accumulation to be incorrect, so that at this point there is only one sample?

polestarss avatar Nov 10 '25 03:11 polestarss

Those two will yield the same results. If you want to have more info, you can dig into our docs or just check the AcceleratedOptimizer class as we replace the optimizer with this.

SunMarc avatar Nov 13 '25 14:11 SunMarc

Those two will yield the same results. If you want to have more info, you can dig into our docs or just check the AcceleratedOptimizer class as we replace the optimizer with this.

ok, thanks!

polestarss avatar Nov 17 '25 01:11 polestarss

Actually it affects training. If you using grad accumulation, you MUST put zero_grad after opt.step()

You can run simple experiments:

import torch import torch.nn as nn from torch.utils.data import DataLoader, TensorDataset from accelerate import Accelerator import logging

logging.getLogger("accelerate").setLevel(logging.ERROR)

def run_experiment(mode="back"):

accelerator = Accelerator(gradient_accumulation_steps=64)

X = torch.ones(64, 1)
y = torch.zeros(64, 1)
dataset = TensorDataset(X, y)
dataloader = DataLoader(dataset, batch_size=1)

model = nn.Linear(1, 1, bias=False)
with torch.no_grad():
    model.weight.fill_(1.0) 
optimizer = torch.optim.SGD(model.parameters(), lr=1.0)

model, optimizer, dataloader = accelerator.prepare(model, optimizer, dataloader)
model.train()

print(f"init weight: {model.weight.item():.5f}")

for i, (inputs, targets) in enumerate(dataloader):
    with accelerator.accumulate(model):
        if mode == 'front':
            optimizer.zero_grad()
        outputs = model(inputs)
        loss = nn.MSELoss()(outputs, targets)
        accelerator.backward(loss)
        optimizer.step()


        if mode == 'back':
            optimizer.zero_grad()

final_weight = model.weight.item()
delta = 1.0 - final_weight

print(f"final weight: {final_weight:.5f}")
print(f"Delta: {delta:.5f}")

wkdgnsgo avatar Dec 20 '25 15:12 wkdgnsgo