y depends on x - the output of model1.
If you call loss2.backward() Autograd tries to calculate the gradients using the computation graph.
Since model2 and model1 are connected through x, Autograd also tries to calculate the gradients again for the parameters in model1.
So save memory, the intermediate activations in model1 (which are necessary to compute the gradients) will be cleared after the loss1.backward() call.
If you don’t want the gradients w.r.t. loss2 in model1, you should detach x:
y = model2(data[2], x.detach())

Otherwise, you should set retain_graph=True so that the intermediates will be kept alive.