import tensorflow as tf

  anchor_negative_distances, anchor_negative_mining_distances = (
      compute_hard_negative_distances(
          anchor_match_distance_matrix,
          anchor_match_negative_indicator_matrix,
          use_semi_hard=use_semi_hard,
          anchor_positive_mining_distances=anchor_positive_mining_distances,
          anchor_match_mining_distance_matrix=(
              anchor_match_mining_distance_matrix)))

  def compute_triplet_loss(positive_distances, negative_distances):
    losses = tf.nn.relu(positive_distances + margin - negative_distances)
    losses = tf.where(
        tf.stop_gradient(losses < losses.dtype.max), losses,
        tf.zeros_like(losses))
    num_nonzero_losses = tf.math.count_nonzero(losses)
    loss = tf.math.reduce_mean(losses)
    return loss, num_nonzero_losses

  loss, num_active_triplets = compute_triplet_loss(anchor_positive_distances,
                                                   anchor_negative_distances)
