Hi Kiruto!



 KirutoCode:

My loss.backward() can’t work!
…
RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
…
Maybe I shouldn’t use torch.argmax() ?


In short, yes, don’t use argmax() in your loss function.
loss.backward() computes the gradient (derivative) of loss
with respect to your model parameters.  (The optimizer then uses
a gradient-descent algorithm to adjust those parameters to make
the loss smaller.)
For this to work, your loss function has to be differentiable.
argmax() isn’t differentiable, so you can’t use it as part of
your loss.
I don’t follow what you are doing in your code, so I don’t know
specifically how you might fix it.  But as a general comment,
you might investigate whether a differentiable approximation
to argmax() would still make sense in your loss function.
softmax() (which should more accurately be called softargmax())
can be understood to be a differentiable approximation to argmax()
(much in the same way that sigmoid() is a differentiable
approximation to a step function).
If you can reformulate your loss function to use softmax(), you
can make it differentiable and loss.backward() should work.
Good luck.
K. Frank