Memory leak with WGAN-GP loss


I have read the other threads related to this, so forgive me if I’ve overlooked something obvious, but I’ve tried to implement according to the advice there given, and am still having a persistent memory leak.

Here’s the code, adapted from Improved Training of Wasserstein GANs

class WassGP(torch.nn.Module):
    def __init__(self,model,config):
    def gradient_penalty(self,imgs,fake_inp,lyrs,dev):
        dev=dev if dev=='cpu' else f'cuda:{dev}'
        grad_loss =*(torch.linalg.norm(gradient.view(outp.size(0),-1),2,dim=1)-1)**2

    def forward(self,real_inpt,fake_inpt,layer,dev,res,alpha):
        real_out=self.model(real_inpt,layer,dev,res=res,alpha=alpha) * real_out * fake_out*real_out.pow(2) if else 0.
        return (fake_out-real_out+drift_loss).mean()

I implemented this as a module subclass because I was experimenting with some things, hooks etc. but the leak occurs whether gradient_penalty is a regular function, a method in a non-module class, or any other way I can think of. I have also tried returning grad_loss and propagating it backward with the other losses with the same result.

If I leave out create_graph=True in the call to autograd.grad(), there is no leak, but also not the intended behavior, as gradients don’t flow backward properly. There are threads related to memory leaks using create_graph=True in .backward(), and they usually recommend using .autograd.grad() with create_graph=True, so I’m very confused.

I looked at python’s garbage collector tensor list, as prescribed in
and it’s unclear what exactly is happening. I see the creation of a lot of non-Parameter tensors (as well as Parameter tensors), but that could be related to the many model submodules not being used in early training (StyleGAN, employing a ProGAN training strategy).

Using torch 1.7.1+cu101

Any help is much appreciated.

Solved. I had torch.autograd.detect_anomaly(True) still in the code from a previous debugging effort. Please, for the sake of you and your loved ones, do not ever leave this line in your code without good reason! Why exactly it caused the memory leak I will perhaps investigate when I’ve finished crying over the time lost.


Wow thanks! I had the exact same issue and you’ve saved me a lot of heartache.