<jupyter_start><jupyter_text>Copyright 2020 Google LLC.Licensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License athttps://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License.  Generalized contrastive lossThis notebook contains implementation of generalized contrastive loss from ***Intriguing Properties of Contrastive Losses***.<jupyter_code>def generalized_contrastive_loss(
    hidden1,
    hidden2,
    lambda_weight=1.0,
    temperature=1.0,
    dist='normal',
    hidden_norm=True,
    loss_scaling=1.0):
  """Generalized contrastive loss.

  Both hidden1 and hidden2 should have shape of (n, d).

  Configurations to get following losses:
  * decoupled NT-Xent loss: set dist='logsumexp', hidden_norm=True
  * SWD with normal distribution: set dist='normal', hidden_norm=False
  * SWD with uniform hypersphere: set dist='normal', hidden_norm=True
  * SWD with uniform hypercube: set dist='uniform', hidden_norm=False
  """
  hidden_dim = hidden1.shape[-1]  # get hidden dimension
  if hidden_norm:
    hidden1 = tf.math.l2_normalize(hidden1, -1)
    hidden2 = tf.math.l2_normalize(hidden2, -1)
  loss_align = tf.reduce_mean((hidden1 - hidden2)**2) / 2.
  hiddens = tf.concat([hidden1, hidden2], 0)
  if dist == 'logsumexp':
    loss_dist_match = get_logsumexp_loss(hiddens, temperature)
  else:
    initializer = tf.keras.initializers.Orthogonal()
    rand_w = initializer([hidden_dim, hidden_dim])
    loss_dist_match = get_swd_loss(hiddens, rand_w,
                            prior=dist,
                            hidden_norm=hidden_norm)
  return loss_scaling * (loss_align + lambda_weight * loss_dist_match)
# Utilities for loss implementation.


def get_logsumexp_loss(states, temperature):
  scores = tf.matmul(states, states, transpose_b=True)  # (bsz, bsz)
  bias = tf.math.log(tf.cast(tf.shape(states)[1], tf.float32))  # a constant
  return  tf.reduce_mean(
      tf.math.reduce_logsumexp(scores / temperature, 1) - bias)


def sort(x):
  """Returns the matrix x where each row is sorted (ascending)."""
  xshape = tf.shape(x)
  rank = tf.reduce_sum(
      tf.cast(tf.expand_dims(x, 2) > tf.expand_dims(x, 1), tf.int32), axis=2)
  rank_inv = tf.einsum(
      'dbc,c->db',
      tf.transpose(tf.cast(tf.one_hot(rank, xshape[1]), tf.float32), [0, 2, 1]),
      tf.range(xshape[1], dtype='float32'))  # (dim, bsz)
  x = tf.gather(x, tf.cast(rank_inv, tf.int32), axis=-1, batch_dims=-1)
  return x


def get_swd_loss(states, rand_w, prior='normal', stddev=1., hidden_norm=True):
  states_shape = tf.shape(states)
  states = tf.matmul(states, rand_w)
  states_t = sort(tf.transpose(states))  # (dim, bsz)

  if prior == 'normal':
    states_prior = tf.random.normal(states_shape, mean=0, stddev=stddev)
  elif prior == 'uniform':
    states_prior = tf.random.uniform(states_shape, -stddev, stddev)
  else:
    raise ValueError('Unknown prior {}'.format(prior))
  if hidden_norm:
    states_prior = tf.math.l2_normalize(states_prior, -1)
  states_prior = tf.matmul(states_prior, rand_w)
  states_prior_t = sort(tf.transpose(states_prior))  # (dim, bsz)

  return tf.reduce_mean((states_prior_t - states_t)**2)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11709932279909707, 'fraction_numerical': 0.017494356659142212, 'mean_word_length': 4.275297619047619, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 7, 'https://': 1, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '128401', 'license': 'Apache-2.0', 'n_tokens_mistral': 1225, 'n_tokens_neox': 1181, 'n_words': 301, 'path': 'colabs/intriguing_properties/generalized_contrastive_loss.ipynb', 'repo_name': 'ZacCranko/simclr', 'size': '3544'}