Thank you for the update.
The code that you have posted looks fine to me; this by itself should not result in the “inplace operation” error. The error is not caused just because your training loop looks like this.
Could you give a complete, executable example of code that (i) accepts random tensors of the correct shape as data, and  (ii) results in the error message?