code: def calculate_adaptive_weight(
      self, nll_loss, g_loss, last_layer=None
  ):
      if last_layer is not None:
          nll_grads = torch.autograd.grad(
              nll_loss, last_layer, retain_graph=True
          )[0]
          g_grads = torch.autograd.grad(
              g_loss, last_layer, retain_graph=True
          )[0]
      else:
          nll_grads = torch.autograd.grad(
              nll_loss, self.last_layer[0], retain_graph=True
          )[0]
          g_grads = torch.autograd.grad(
              g_loss, self.last_layer[0], retain_graph=True
          )[0]
  
      d_weight = torch.norm(nll_grads) / (torch.norm(g_grads) + 1e-4)
      d_weight = torch.clamp(d_weight, 0.0, 1e4).detach()
      d_weight = d_weight * self.discriminator_weight
      return d_weight
  
file_path: compvis-stable-diffusion/ldm/modules/losses/vqperceptual.py
imports: import torch
  from torch import nn
  import torch.nn.functional
  from einops import repeat
  from taming.modules.discriminator.model import NLayerDiscriminator, weights_init
  from taming.modules.losses.lpips import LPIPS
  from taming.modules.losses.vqperceptual import hinge_d_loss, vanilla_d_loss
label_desc: Use image node_id 2 for calling the VQLPIPSWithDiscriminator obj's underlying member method code with example usage: obj.calculate_adaptive_weight(nll_loss, g_loss, last_layer) and returns: d_weight