class_docstr: ## Configuration class
  
  We extend [original GAN implementation](../../original/experiment.html) and override the discriminator (critic) loss
  calculation to include gradient penalty.
docstr: This overrides the original discriminator loss calculation and
  includes gradient penalty.
docstr_tok: ["This","overrides","the","original","discriminator","loss","calculation","and","includes","gradient","penalty","."]
code: def calc_discriminator_loss(self, data: torch.Tensor):
      """
      This overrides the original discriminator loss calculation and
      includes gradient penalty.
      """
      # Require gradients on $x$ to calculate gradient penalty
      data.requires_grad_()
      # Sample $z \sim p(z)$
      latent = self.sample_z(data.shape[0])
      # $D(x)$
      f_real = self.discriminator(data)
      # $D(G_\theta(z))$
      f_fake = self.discriminator(self.generator(latent).detach())
      # Get discriminator losses
      loss_true, loss_false = self.discriminator_loss(f_real, f_fake)
      # Calculate gradient penalties in training mode
      if self.mode.is_train:
          gradient_penalty = self.gradient_penalty(data, f_real)
          tracker.add("loss.gp.", gradient_penalty)
          loss = (
              loss_true
              + loss_false
              + self.gradient_penalty_coefficient * gradient_penalty
          )
      # Skip gradient penalty otherwise
      else:
          loss = loss_true + loss_false
  
      # Log stuff
      tracker.add("loss.discriminator.true.", loss_true)
      tracker.add("loss.discriminator.false.", loss_false)
      tracker.add("loss.discriminator.", loss)
  
      return loss
  
file_path: annotated_deep_learning_paper_implementations/labml_nn/gan/wasserstein/gradient_penalty/experiment.py
imports: import torch
  from labml import experiment, tracker
  from labml_nn.gan.wasserstein.experiment import Configs
  from labml_nn.gan.wasserstein.gradient_penalty import GradientPenalty
label_desc: Use image node_id 1 for calling the Configs obj's underlying member method code with example usage: obj.calc_discriminator_loss(data) and returns: loss