Slightly neater way.
p = list(model.parameters())
grad_f = torch.autograd.grad(f, p, retrain_graph=True)
grad_g = torch.autograd.grad(g, p)

for i in range(len(p)):
  p[i].grad = func(grad_f[i], grad_g[i])