How to do gradient clipping in pytorch?

Gulzar picture Gulzar · Feb 15, 2019 · Viewed 40.7k times · Source

What is the correct way to perform gradient clipping in pytorch?

I have an exploding gradients problem, and I need to program my way around it.

Answer

Rahul picture Rahul · May 10, 2019

A more complete example

optimizer.zero_grad()        
loss, hidden = model(data, hidden, targets)
loss.backward()

torch.nn.utils.clip_grad_norm_(model.parameters(), args.clip)
optimizer.step()

Source: https://github.com/pytorch/pytorch/issues/309