# How does PyTorchs SGD work?

I have recently learned, that SGD does normally not converge, if the learning rate is fixed.
I wondered, how PyTorch handles the learning rate then when using

`optimizer = optim.SGD()`

as the optimizer, since it requires no parameters that seem to affect the learning rate. I wondered if momentum is actually enough to guarantee convergence? Or does the learning rate gets adjusted behind the scenes?

Hi Florian!

`SGD` converges just fine with a fixed learning rate. Here is a simple example
script with `SGD` (with a fixed learning rate and no momentum):

``````import torch
print (torch.__version__)

x = torch.ones (1, requires_grad = True)
t = torch.tensor ([16.0])
opt = torch.optim.SGD ([x], lr = 0.01)
loss_fn = torch.nn.MSELoss()

for  i in range (20):
p = x**2   # "model" is x**2
loss = loss_fn (p, t)
loss.backward()
opt.step()
print (x, loss)

``````

And here is its output:

``````1.13.0
``````

It is true that complex models can converge (very) slowly and that training
can sometimes be improved by varying the learning rate (e.g., “cycling” it)
or by using momentum or fancier optimizers.

It is also possible (but, in my experience, unlikely) for training of a model
to converge to a true local minimum, rather than to the “correct” solution
of a lower local minimum or the actual global minimum. Increasing the
learning rate a lot so that a large optimization step jumps out of the local
minimum can get training to progress further (but that’s kind of like whacking
your starter motor with a sledgehammer to get your car started …).

Best.

K. Frank

Hi Frank,

Thanks for your extensive response and explanation. However, your example is not really convincing to me. How does it differ from gradient descent? I am not understanding where the stochastic part comes into play, since you are not really dealing with different samples SGD could choose from?

Correct me if I am wrong though!

The “stochastic” part in SGD comes from computing the gradient for mini-batches of the dataset, since Gradient Descent involves calculating the gradient for the full dataset.
This forum post might be helpful.