Skip to content

Clip gradients in configure_gradient_clipping instead of training_step - #22

Merged
knightnemo merged 1 commit into
simchowitzlabpublic:mainfrom
eshaanpathak:upstream-fix-grad-clipping
Sep 14, 2026
Merged

knightnemo merged 1 commit into
simchowitzlabpublic:mainfrom
eshaanpathak:upstream-fix-grad-clipping

Conversation

@eshaanpathak

Copy link
Copy Markdown
Contributor

Gradient clipping wasn't working :(

The clip call (clip_grad_norm_) was inside training_step, before .backward() runs. Lightning calls training_step --> backward() --> clip --> optimizer.step(), so at the point this ran, p.grad was either None or leftover from the previous step, not the gradient about to be used. With gradient_accumulation: 1 (the default config), clipping did nothing. With accumulation > 1, it scales down the gradient mid-accumulation before later micro-batches even get added in.

Moved the clip into configure_gradient_clipping, which Lightning runs after backward (and after DDP grad sync), once per optimizer step.

Checked this against pytorch-lightning 1.9.5 (what's pinned) with a small repro, with and without accumulation. Before the fix, the optimizer's gradient was never capped no matter what gradient_clip_norm was set to. After the fix it is, every step.

Also added a gradient_norm_clipped log (post-clip) next to the existing gradient_norm (now correctly the current step's value, not the previous one).

All of the HF checkpoints may have been trained without clipping. Since it looks like clipping was enabled at 20K steps, it may have unlikely affected the checkpoints, but you would need to check your training run charts to confirm this!

Here are two charts to visualize the gradient getting clipped at 100 steps to 0.1: true_gradient_norm is the main branch right now before my changes, and gradient_norm_clipped is with my changes in this PR.

Screenshot 2026-09-14 at 4 49 33 AM

training_step runs before backward in Lightning's closure, so the clip scaled the
previous step's stale grads (no effect on the update, and with gradient accumulation
it shrank earlier micro-batches' grads). Also logs the post-clip norm as
gradient_norm_clipped.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018SMDa4kp6u9QUxuvWWcXi1
@eshaanpathak
eshaanpathak force-pushed the upstream-fix-grad-clipping branch from e5ff4dd to 42dbfaf Compare September 14, 2026 12:13
@knightnemo

Copy link
Copy Markdown
Member

lgtm.

@knightnemo
knightnemo merged commit cc1f151 into simchowitzlabpublic:main Sep 14, 2026
@eshaanpathak
eshaanpathak deleted the upstream-fix-grad-clipping branch September 14, 2026 12:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants