Thanks! This seems to work and is very elegant.
I guess the idea is that when y gets added to the computation graph, f requires_grad=True.
Then setting f to requires_grad=False does not affect y as it is already part of the graph.
But now when adding z, no new gradients are required.
Is that the correct reasoning?
Thanks again