I am really sorry, I am a bit stress and though  no one see my post. Please accept my apology.
Regarding the code, I used torch and no detach and just focus on the second loss (loss2) it gives me
( print(param.grad.data.sum())
AttributeError: ‘NoneType’ object has no attribute ‘data’)
I think it creates no gradient again.
        for p in netG.parameters():
            p.requires_grad = True
            
        netG.zero_grad()   
        label.fill_(real_label)  
        label=label.to(device)
        output = netD(fake).view(-1)
        # Calculate G's loss based on this output
        xxx=torch.histc(Gaussy.squeeze(1).view(-1).cpu(),100, min=0, max=1, out=None)
        ddGaussy=xxx/xxx.sum()

        xxx1=torch.histc(fake.squeeze(1).view(-1).cpu(),100, min=0, max=1, out=None)
        ddFake=xxx1/xxx1.sum()

        loss2=abs(ddGaussy-ddFake).sum().item()

        ## ----- total loss --------------------------
        loss= loss2

        loss=torch.tensor(loss,requires_grad=True)
        loss=Variable(loss, requires_grad = True)
        loss.backward()
        for param in netG.parameters():
            print(param.grad.data.sum())
        optimizerG.step()