code: def ref_lambda_rank_loss(
      self, y, r, use_ndcg_as_loss, use_idcg_normalization, use_exp_gain
  ):
      n = len(y)
  
      def get_discounts(v):
          x = np.argsort(v)
          d = [0 for _ in range(n)]
          for i in range(n):
              d[x[i]] = 1.0 / np.log2(n - i + 1.0)
          return d
  
      def sigm(x):
          return 1 / (1 + np.exp(-x))
  
      def log_sigm(x):
          return -np.log(1 + np.exp(-x))
  
      dy = np.zeros(n)
      loss = 0
      if np.sum(np.abs(r)) < 1e-6:
          return loss, dy
      if use_ndcg_as_loss and (not use_exp_gain):
          g = [r[i] for i in range(n)]
      else:
          g = [2 ** r[i] for i in range(n)]
      d = get_discounts(r)
      idcg = sum([g[i] * d[i] for i in range(n)])
  
      if use_idcg_normalization:
          session_weight = max(idcg, 1e-5)
      else:
          session_weight = 1
  
      d = get_discounts(y)
  
      if use_ndcg_as_loss:
          dcg = sum(g[i] * d[i] for i in range(n))
          loss = (idcg - dcg) / session_weight
      for i in range(n):
          for j in range(n):
              if i == j:
                  continue
              lambda_weight = np.abs((g[i] - g[j]) * (d[i] - d[j]))
              rank_loss = -log_sigm(
                  y[i] - y[j] if r[i] > r[j] else y[j] - y[i]
              )
              rank_dy = (0.0 if r[i] > r[j] else 1.0) - sigm(
                  -y[i] + y[j]
              )
              if not use_ndcg_as_loss:
                  loss += lambda_weight * rank_loss / session_weight
              dy[i] += lambda_weight * rank_dy / session_weight
  
      return loss, dy
  
file_path: pytorch/caffe2/python/operator_test/listwise_l2r_operator_test.py
imports: import caffe2.python.hypothesis_test_util
  import hypothesis.strategies
  import numpy
  from caffe2.python import core, workspace
  from hypothesis import given
label_desc: Use image node_id 1 for calling the TestListwiseL2rOps obj's underlying member method code with example usage: obj.ref_lambda_rank_loss(y, r, use_ndcg_as_loss, use_idcg_normalization, use_exp_gain) and returns: loss,  dy, d, unknown, unknown, loss,  dy