modelscope / modelscope/DiffSynth-Studio

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

Open
#1,046 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
13.1k
Forks
1.3k
Avg merge
13h 12m
Merged PRs (30d)
45

Description

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?

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the two training-loop variants in the issue, focusing on accelerator.accumulate(model), accelerator.backward(loss), optimizer.step(), scheduler.step(), and optimizer.zero_grad(). Compare their behavior when gradient accumulation is enabled and determine whether both loops preserve the intended accumulated gradients and produce equivalent updates.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
machine-learning
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.