I don’t know where tensor t is coming from but based on your code I would guess that these inplace operations are causing the issue:
t[0,i+1]=t0
t[1,i+1]=t1
t[2,i+1]=t2

Replace these calls with:
t = torch.stack((t0, t1, t2))

(or torch.cat depending on the shape of the tensors) and it might work.
Also, recreating a new tensor will detach it from the computation graph, so replace:
lgtensor=torch.tensor(2+lgcount)

with:
lgtensor = 2+lgcount

assuming lgcount is a tensor attached to a computation graph.