Ok.
So you don’t actually want the gradient for x, only W right?
I think the +1 difference in the size comes from the bias term that is often added in linear regression that you are missing when you do x*W only.
You can either have another parameter of size 1 b and compute x*W + b. And now you get gradient for both W and b (this is the recommended way to do with NN-based libraries like pytorch).
Another approach that is used in more classical ML, is to add one more element to x in your function and have W be of size |x|+1:
extended_x = torch.cat([x, torch.tensor([1.])], dim=0) and then y = extended_x * W.
Hope this helps !