prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  Lifted Struct Loss Error
  **System information**
  - OS Platform and Distribution (e.g., Linux Ubuntu 16.04): Google Colab (Linux)
  - TensorFlow version and how it was installed (source or binary): binary 2.0
  - TensorFlow-Addons version and how it was installed (source or binary): binary 0.6.0
  - Python version: 3
  - Is GPU used? (yes/no): Yes
  
  **Describe the bug**
  I get an assert shape error when I try to initialize the LiftedStructLoss obj
  
  `assert lshape.shape == 1 AssertionError` is the error I get. However, it can easily be resolved by removing the assert line. I have one more question, why does it say that the vector should not be l2 normalized? while in the case of semihardtriplet loss it says that the vector should be l2 normalized
  **Code to reproduce the issue**
  `import tensorflow_addons as tfa`
  `tfa.losses.LiftedStructLoss()`
  
  
  
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `tensorflow_addons/losses/lifted.py`
  Content:
  ```
  1 # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
  2 #
  3 # Licensed under the Apache License, Version 2.0 (the "License");
  4 # you may not use this file except in compliance with the License.
  5 # You may obtain a copy of the License at
  6 #
  7 #     http://www.apache.org/licenses/LICENSE-2.0
  8 #
  9 # Unless required by applicable law or agreed to in writing, software
  10 # distributed under the License is distributed on an "AS IS" BASIS,
  11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12 # See the License for the specific language governing permissions and
  13 # limitations under the License.
  14 # ==============================================================================
  15 """Implements lifted_struct_loss."""
  16 
  17 from __future__ import absolute_import
  18 from __future__ import division
  19 from __future__ import print_function
  20 
  21 import tensorflow as tf
  22 from tensorflow_addons.losses import metric_learning
  23 
  24 
  25 @tf.keras.utils.register_keras_serializable(package='Addons')
  26 @tf.function
  27 def lifted_struct_loss(labels, embeddings, margin=1.0):
  28     """Computes the lifted structured loss.
  29 
  30     Args:
  31       labels: 1-D tf.int32 `Tensor` with shape [batch_size] of
  32         multiclass integer labels.
  33       embeddings: 2-D float `Tensor` of embedding vectors. Embeddings should
  34         not be l2 normalized.
  35       margin: Float, margin term in the loss definition.
  36 
  37     Returns:
  38       lifted_loss: tf.float32 scalar.
  39     """
  40     # Reshape [batch_size] label tensor to a [batch_size, 1] label tensor.
  41     lshape = tf.shape(labels)
  42     assert lshape.shape == 1
  43     labels = tf.reshape(labels, [lshape[0], 1])
  44 
  45     # Build pairwise squared distance matrix.
  46     pairwise_distances = metric_learning.pairwise_distance(embeddings)
  47 
  48     # Build pairwise binary adjacency matrix.
  49     adjacency = tf.math.equal(labels, tf.transpose(labels))
  50     # Invert so we can select negatives only.
  51     adjacency_not = tf.math.logical_not(adjacency)
  52 
  53     batch_size = tf.size(labels)
  54 
  55     diff = margin - pairwise_distances
  56     mask = tf.cast(adjacency_not, dtype=tf.dtypes.float32)
  57     # Safe maximum: Temporarily shift negative distances
  58     #   above zero before taking max.
  59     #     this is to take the max only among negatives.
  60     row_minimums = tf.math.reduce_min(diff, 1, keepdims=True)
  61     row_negative_maximums = tf.math.reduce_max(
  62         tf.math.multiply(diff - row_minimums, mask), 1,
  63         keepdims=True) + row_minimums
  64 
  65     # Compute the loss.
  66     # Keep track of matrix of maximums where M_ij = max(m_i, m_j)
  67     #   where m_i is the max of alpha - negative D_i's.
  68     # This matches the Caffe loss layer implementation at:
  69     #   https://github.com/rksltnl/Caffe-Deep-Metric-Learning-CVPR16/blob/0efd7544a9846f58df923c8b992198ba5c355454/src/caffe/layers/lifted_struct_similarity_softmax_layer.cpp  # pylint: disable=line-too-long
  70 
  71     max_elements = tf.math.maximum(row_negative_maximums,
  72                                    tf.transpose(row_negative_maximums))
  73     diff_tiled = tf.tile(diff, [batch_size, 1])
  74     mask_tiled = tf.tile(mask, [batch_size, 1])
  75     max_elements_vect = tf.reshape(tf.transpose(max_elements), [-1, 1])
  76 
  77     loss_exp_left = tf.reshape(
  78         tf.math.reduce_sum(
  79             tf.math.multiply(
  80                 tf.math.exp(diff_tiled - max_elements_vect), mask_tiled),
  81             1,
  82             keepdims=True), [batch_size, batch_size])
  83 
  84     loss_mat = max_elements + tf.math.log(loss_exp_left +
  85                                           tf.transpose(loss_exp_left))
  86     # Add the positive distance.
  87     loss_mat += pairwise_distances
  88 
  89     mask_positives = tf.cast(
  90         adjacency, dtype=tf.dtypes.float32) - tf.linalg.diag(
  91             tf.ones([batch_size]))
  92 
  93     # *0.5 for upper triangular, and another *0.5 for 1/2 factor for loss^2.
  94     num_positives = tf.math.reduce_sum(mask_positives) / 2.0
  95 
  96     lifted_loss = tf.math.truediv(
  97         0.25 * tf.math.reduce_sum(
  98             tf.math.square(
  99                 tf.math.maximum(
  100                     tf.math.multiply(loss_mat, mask_positives), 0.0))),
  101         num_positives)
  102     return lifted_loss
  103 
  104 
  105 @tf.keras.utils.register_keras_serializable(package='Addons')
  106 class LiftedStructLoss(tf.keras.losses.Loss):
  107     """Computes the lifted structured loss.
  108 
  109     The loss encourages the positive distances (between a pair of embeddings
  110     with the same labels) to be smaller than any negative distances (between
  111     a pair of embeddings with different labels) in the mini-batch in a way
  112     that is differentiable with respect to the embedding vectors.
  113     See: https://arxiv.org/abs/1511.06452.
  114 
  115     Args:
  116       margin: Float, margin term in the loss definition.
  117       name: Optional name for the op.
  118     """
  119 
  120     def __init__(self, margin=1.0, name=None):
  121         super(LiftedStructLoss, self).__init__(
  122             name=name, reduction=tf.keras.losses.Reduction.NONE)
  123         self.margin = margin
  124 
  125     def call(self, y_true, y_pred):
  126         return lifted_struct_loss(y_true, y_pred, self.margin)
  127 
  128     def get_config(self):
  129         config = {
  130             "margin": self.margin,
  131         }
  132         base_config = super(LiftedStructLoss, self).get_config()
  133         return dict(list(base_config.items()) + list(config.items()))
  134
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/tensorflow_addons/losses/lifted.py b/tensorflow_addons/losses/lifted.py
  --- a/tensorflow_addons/losses/lifted.py
  +++ b/tensorflow_addons/losses/lifted.py
  @@ -39,7 +39,6 @@
       """
       # Reshape [batch_size] label tensor to a [batch_size, 1] label tensor.
       lshape = tf.shape(labels)
  -    assert lshape.shape == 1
       labels = tf.reshape(labels, [lshape[0], 1])
   
       # Build pairwise squared distance matrix.
  
verification_info: {"golden_diff": "diff --git a/tensorflow_addons/losses/lifted.py b/tensorflow_addons/losses/lifted.py\n--- a/tensorflow_addons/losses/lifted.py\n+++ b/tensorflow_addons/losses/lifted.py\n@@ -39,7 +39,6 @@\n     \"\"\"\n     # Reshape [batch_size] label tensor to a [batch_size, 1] label tensor.\n     lshape = tf.shape(labels)\n-    assert lshape.shape == 1\n     labels = tf.reshape(labels, [lshape[0], 1])\n \n     # Build pairwise squared distance matrix.\n", "issue": "Lifted Struct Loss Error\n**System information**\r\n- OS Platform and Distribution (e.g., Linux Ubuntu 16.04): Google Colab (Linux)\r\n- TensorFlow version and how it was installed (source or binary): binary 2.0\r\n- TensorFlow-Addons version and how it was installed (source or binary): binary 0.6.0\r\n- Python version: 3\r\n- Is GPU used? (yes/no): Yes\r\n\r\n**Describe the bug**\r\nI get an assert shape error when I try to initialize the LiftedStructLoss obj\r\n\r\n`assert lshape.shape == 1 AssertionError` is the error I get. However, it can easily be resolved by removing the assert line. I have one more question, why does it say that the vector should not be l2 normalized? while in the case of semihardtriplet loss it says that the vector should be l2 normalized\r\n**Code to reproduce the issue**\r\n`import tensorflow_addons as tfa`\r\n`tfa.losses.LiftedStructLoss()`\r\n\r\n\r\n\n", "before_files": [{"content": "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Implements lifted_struct_loss.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nfrom tensorflow_addons.losses import metric_learning\n\n\n@tf.keras.utils.register_keras_serializable(package='Addons')\n@tf.function\ndef lifted_struct_loss(labels, embeddings, margin=1.0):\n    \"\"\"Computes the lifted structured loss.\n\n    Args:\n      labels: 1-D tf.int32 `Tensor` with shape [batch_size] of\n        multiclass integer labels.\n      embeddings: 2-D float `Tensor` of embedding vectors. Embeddings should\n        not be l2 normalized.\n      margin: Float, margin term in the loss definition.\n\n    Returns:\n      lifted_loss: tf.float32 scalar.\n    \"\"\"\n    # Reshape [batch_size] label tensor to a [batch_size, 1] label tensor.\n    lshape = tf.shape(labels)\n    assert lshape.shape == 1\n    labels = tf.reshape(labels, [lshape[0], 1])\n\n    # Build pairwise squared distance matrix.\n    pairwise_distances = metric_learning.pairwise_distance(embeddings)\n\n    # Build pairwise binary adjacency matrix.\n    adjacency = tf.math.equal(labels, tf.transpose(labels))\n    # Invert so we can select negatives only.\n    adjacency_not = tf.math.logical_not(adjacency)\n\n    batch_size = tf.size(labels)\n\n    diff = margin - pairwise_distances\n    mask = tf.cast(adjacency_not, dtype=tf.dtypes.float32)\n    # Safe maximum: Temporarily shift negative distances\n    #   above zero before taking max.\n    #     this is to take the max only among negatives.\n    row_minimums = tf.math.reduce_min(diff, 1, keepdims=True)\n    row_negative_maximums = tf.math.reduce_max(\n        tf.math.multiply(diff - row_minimums, mask), 1,\n        keepdims=True) + row_minimums\n\n    # Compute the loss.\n    # Keep track of matrix of maximums where M_ij = max(m_i, m_j)\n    #   where m_i is the max of alpha - negative D_i's.\n    # This matches the Caffe loss layer implementation at:\n    #   https://github.com/rksltnl/Caffe-Deep-Metric-Learning-CVPR16/blob/0efd7544a9846f58df923c8b992198ba5c355454/src/caffe/layers/lifted_struct_similarity_softmax_layer.cpp  # pylint: disable=line-too-long\n\n    max_elements = tf.math.maximum(row_negative_maximums,\n                                   tf.transpose(row_negative_maximums))\n    diff_tiled = tf.tile(diff, [batch_size, 1])\n    mask_tiled = tf.tile(mask, [batch_size, 1])\n    max_elements_vect = tf.reshape(tf.transpose(max_elements), [-1, 1])\n\n    loss_exp_left = tf.reshape(\n        tf.math.reduce_sum(\n            tf.math.multiply(\n                tf.math.exp(diff_tiled - max_elements_vect), mask_tiled),\n            1,\n            keepdims=True), [batch_size, batch_size])\n\n    loss_mat = max_elements + tf.math.log(loss_exp_left +\n                                          tf.transpose(loss_exp_left))\n    # Add the positive distance.\n    loss_mat += pairwise_distances\n\n    mask_positives = tf.cast(\n        adjacency, dtype=tf.dtypes.float32) - tf.linalg.diag(\n            tf.ones([batch_size]))\n\n    # *0.5 for upper triangular, and another *0.5 for 1/2 factor for loss^2.\n    num_positives = tf.math.reduce_sum(mask_positives) / 2.0\n\n    lifted_loss = tf.math.truediv(\n        0.25 * tf.math.reduce_sum(\n            tf.math.square(\n                tf.math.maximum(\n                    tf.math.multiply(loss_mat, mask_positives), 0.0))),\n        num_positives)\n    return lifted_loss\n\n\n@tf.keras.utils.register_keras_serializable(package='Addons')\nclass LiftedStructLoss(tf.keras.losses.Loss):\n    \"\"\"Computes the lifted structured loss.\n\n    The loss encourages the positive distances (between a pair of embeddings\n    with the same labels) to be smaller than any negative distances (between\n    a pair of embeddings with different labels) in the mini-batch in a way\n    that is differentiable with respect to the embedding vectors.\n    See: https://arxiv.org/abs/1511.06452.\n\n    Args:\n      margin: Float, margin term in the loss definition.\n      name: Optional name for the op.\n    \"\"\"\n\n    def __init__(self, margin=1.0, name=None):\n        super(LiftedStructLoss, self).__init__(\n            name=name, reduction=tf.keras.losses.Reduction.NONE)\n        self.margin = margin\n\n    def call(self, y_true, y_pred):\n        return lifted_struct_loss(y_true, y_pred, self.margin)\n\n    def get_config(self):\n        config = {\n            \"margin\": self.margin,\n        }\n        base_config = super(LiftedStructLoss, self).get_config()\n        return dict(list(base_config.items()) + list(config.items()))\n", "path": "tensorflow_addons/losses/lifted.py"}], "after_files": [{"content": "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Implements lifted_struct_loss.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nfrom tensorflow_addons.losses import metric_learning\n\n\n@tf.keras.utils.register_keras_serializable(package='Addons')\n@tf.function\ndef lifted_struct_loss(labels, embeddings, margin=1.0):\n    \"\"\"Computes the lifted structured loss.\n\n    Args:\n      labels: 1-D tf.int32 `Tensor` with shape [batch_size] of\n        multiclass integer labels.\n      embeddings: 2-D float `Tensor` of embedding vectors. Embeddings should\n        not be l2 normalized.\n      margin: Float, margin term in the loss definition.\n\n    Returns:\n      lifted_loss: tf.float32 scalar.\n    \"\"\"\n    # Reshape [batch_size] label tensor to a [batch_size, 1] label tensor.\n    lshape = tf.shape(labels)\n    labels = tf.reshape(labels, [lshape[0], 1])\n\n    # Build pairwise squared distance matrix.\n    pairwise_distances = metric_learning.pairwise_distance(embeddings)\n\n    # Build pairwise binary adjacency matrix.\n    adjacency = tf.math.equal(labels, tf.transpose(labels))\n    # Invert so we can select negatives only.\n    adjacency_not = tf.math.logical_not(adjacency)\n\n    batch_size = tf.size(labels)\n\n    diff = margin - pairwise_distances\n    mask = tf.cast(adjacency_not, dtype=tf.dtypes.float32)\n    # Safe maximum: Temporarily shift negative distances\n    #   above zero before taking max.\n    #     this is to take the max only among negatives.\n    row_minimums = tf.math.reduce_min(diff, 1, keepdims=True)\n    row_negative_maximums = tf.math.reduce_max(\n        tf.math.multiply(diff - row_minimums, mask), 1,\n        keepdims=True) + row_minimums\n\n    # Compute the loss.\n    # Keep track of matrix of maximums where M_ij = max(m_i, m_j)\n    #   where m_i is the max of alpha - negative D_i's.\n    # This matches the Caffe loss layer implementation at:\n    #   https://github.com/rksltnl/Caffe-Deep-Metric-Learning-CVPR16/blob/0efd7544a9846f58df923c8b992198ba5c355454/src/caffe/layers/lifted_struct_similarity_softmax_layer.cpp  # pylint: disable=line-too-long\n\n    max_elements = tf.math.maximum(row_negative_maximums,\n                                   tf.transpose(row_negative_maximums))\n    diff_tiled = tf.tile(diff, [batch_size, 1])\n    mask_tiled = tf.tile(mask, [batch_size, 1])\n    max_elements_vect = tf.reshape(tf.transpose(max_elements), [-1, 1])\n\n    loss_exp_left = tf.reshape(\n        tf.math.reduce_sum(\n            tf.math.multiply(\n                tf.math.exp(diff_tiled - max_elements_vect), mask_tiled),\n            1,\n            keepdims=True), [batch_size, batch_size])\n\n    loss_mat = max_elements + tf.math.log(loss_exp_left +\n                                          tf.transpose(loss_exp_left))\n    # Add the positive distance.\n    loss_mat += pairwise_distances\n\n    mask_positives = tf.cast(\n        adjacency, dtype=tf.dtypes.float32) - tf.linalg.diag(\n            tf.ones([batch_size]))\n\n    # *0.5 for upper triangular, and another *0.5 for 1/2 factor for loss^2.\n    num_positives = tf.math.reduce_sum(mask_positives) / 2.0\n\n    lifted_loss = tf.math.truediv(\n        0.25 * tf.math.reduce_sum(\n            tf.math.square(\n                tf.math.maximum(\n                    tf.math.multiply(loss_mat, mask_positives), 0.0))),\n        num_positives)\n    return lifted_loss\n\n\n@tf.keras.utils.register_keras_serializable(package='Addons')\nclass LiftedStructLoss(tf.keras.losses.Loss):\n    \"\"\"Computes the lifted structured loss.\n\n    The loss encourages the positive distances (between a pair of embeddings\n    with the same labels) to be smaller than any negative distances (between\n    a pair of embeddings with different labels) in the mini-batch in a way\n    that is differentiable with respect to the embedding vectors.\n    See: https://arxiv.org/abs/1511.06452.\n\n    Args:\n      margin: Float, margin term in the loss definition.\n      name: Optional name for the op.\n    \"\"\"\n\n    def __init__(self, margin=1.0, name=None):\n        super(LiftedStructLoss, self).__init__(\n            name=name, reduction=tf.keras.losses.Reduction.NONE)\n        self.margin = margin\n\n    def call(self, y_true, y_pred):\n        return lifted_struct_loss(y_true, y_pred, self.margin)\n\n    def get_config(self):\n        config = {\n            \"margin\": self.margin,\n        }\n        base_config = super(LiftedStructLoss, self).get_config()\n        return dict(list(base_config.items()) + list(config.items()))\n", "path": "tensorflow_addons/losses/lifted.py"}]}