Thanks for the response. So in the actual code, f() is a neural network (actually several) and x is the parameters of these networks.
I thought that the way to apply .detached to the parameters would be something like this:
import torch

x = torch.ones(1, requires_grad=True)
dense = torch.nn.Linear(1, 1)
for var in dense.parameters():
    var.requires_grad = False
y = dense(x)
print(torch.autograd.grad(y, dense.parameters()))

This raises
RuntimeError: One of the differentiated Tensors does not require grad

because torch.no_grad() seems to prevent gradients from flowing back to x.
So I assume that this is not the correct way to detach the parameters of the networks, right?