This error is raised, if the backward pass tries to calculate gradients in a part of the computation graph, which was already processed in a previous iterations and thus the intermediate tensors were freed.
Usually this can happen if you are trying to either call loss.backward() multiple times without recalculating the output and loss or if you are reusing tensors which are attached to the computation graph e.g. in a recurrent layer.
You’ve previously mentioned that calling detach() solved the issue. Where did you add this detach operation?