Well, if you check some dev answer:

An in-place operation is an operation that changes directly the content of a given Tensor without making a copy. Inplace operations in pytorch are always postfixed with a , like .add() or .scatter_(). Python operations like += or *= are also inplace operation

Try to add cost=cost.clone()
.clone() statement creates a copy of the data.