I’m not sure if I understand your question.
If you are trying to predict y using x with a function, why do you need to set y to require gradient? Your code should just work by commenting out the following line:
y.requires_grad = True
Alternatively, if you have to set y to require gradient, you can change the line which calculates loss to:
loss= criterion(y_pred, y.requires_grad_(False))
This should also work.