code: def r1_regularization(
      real_data: Union[tf.Tensor, Sequence[tf.Tensor]],
      discriminator: tf.keras.Model,
      weight: float = 10.0,
      name="r1_regularization",
  ) -> tf.Tensor:
      """Implements the r1 regulariztion loss.
  
      This regularization loss for discriminators is proposed in "Which Training
      Methods for GANs do actually Converge?"
      https://arxiv.org/abs/1801.04406
      This version also implements the multi-scale extension proposed in "MSG-GAN:
      Multi-Scale Gradient GAN for Stable Image Synthesis"
      https://arxiv.org/abs/1903.06048
  
      Args:
        real_data: Samples from the real data.
        discriminator: The Keras model of the discriminator. This model is expected
          to take as input a tf.Tensor or a sequence of tf.Tensor depending on what
          is provided as real_data.
        weight: The weight of the loss.
        name: The name scope of the loss.
  
      Returns:
        The r1 regulatization loss per example as tensor of shape [batch_size].
      """
      with tf.name_scope(name):
          with tf.GradientTape() as tape:
              tape.watch(real_data)
              discriminator_output = discriminator(real_data)
  
              with tf.name_scope(name="gradients"):
                  gradients = tape.gradient(
                      target=discriminator_output, sources=real_data
                  )
  
          if isinstance(real_data, tf.Tensor):
              gradient_squares = _sum_of_squares(gradients)
  
              return weight * 0.5 * gradient_squares
          else:
              gradient_squares_level = [
                  _sum_of_squares(gradients_level)
                  for gradients_level in gradients
              ]
  
              return (
                  weight
                  * 0.5
                  * tf.add_n(gradient_squares_level)
                  * 1.0
                  / len(real_data)
              )
  
file_path: graphics/tensorflow_graphics/projects/gan/losses.py
imports: from collections import abc
  from typing import Sequence, Union
  import tensorflow
label_desc: Use image node_id 3 for calling a global function with example usage: r1_regularization(real_data, discriminator, weight, name) and returns: unknown, unknown