code: def ranking_within_session(
      predictions: torch.Tensor,
      session: torch.Tensor,
  ) -> torch.Tensor:
      # rank predictions that belong to the same session
  
      #  Example:
      #  predictions = [1.0, 0.0, 0.51, 0.8, 1.0, 0.0, 0.51, 0.8, 1.0, 0.0, 0.51, 0.8]
      #  sessions =    [1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1]
      #  return =      [0, 5, 3, 2, 1, 6, 4, 1, 0, 4, 3, 2]
      n_tasks = predictions.size(0)
      matching_session_id = session.view(-1, n_tasks) == session.view(
          n_tasks, -1
      )
      predictions_relation = predictions.view(
          -1, n_tasks
      ) >= predictions.view(n_tasks, -1)
      relation_within_session = (
          matching_session_id & predictions_relation
      )
      rank_within_session = torch.sum(
          matching_session_id, dim=-1
      ) - torch.sum(relation_within_session, dim=-1)
      return rank_within_session
  
imports: import logging
  from typing import Any, cast, Dict, List, Optional, Set, Type, Union
  import torch
  from torch import distributed
  from torchrec.metrics.metrics_config import RecTaskInfo, SessionMetricDef
  from torchrec.metrics.metrics_namespace import MetricName, MetricNamespace, MetricPrefix
  from torchrec.metrics.rec_metric import MetricComputationReport, RecComputeMode, RecMetric, RecMetricComputation, RecMetricException
label_desc: Use image node_id 2 for calling a global function with example usage: ranking_within_session(predictions, session) and returns: rank_within_session