code: def _set_avg_session_metrics(session_group):
    
    assert session_group.sessions, 'SessionGroup cannot be empty.'
    # Algorithm: Iterate over all (session, metric) pairs and maintain a
    # dict from _MetricIdentifier to _MetricStats objects.
    # Then use the final dict state to compute the average for each metric.
    metric_stats = collections.defaultdict(_MetricStats)
    for session in session_group.sessions:
      for metric_value in session.metric_values:
        metric_name = _MetricIdentifier(group=metric_value.name.group,
                                        tag=metric_value.name.tag)
        stats = metric_stats[metric_name]
        stats.total += metric_value.value
        stats.count += 1
        stats.total_step += metric_value.training_step
        stats.total_wall_time_secs += metric_value.wall_time_secs
  
    del session_group.metric_values[:]
    for (metric_name, stats) in six.iteritems(metric_stats):
      session_group.metric_values.add(
          name=api_pb2.MetricName(group=metric_name.group, tag=metric_name.tag),
          value=float(stats.total)/float(stats.count),
          training_step=stats.total_step // stats.count,
          wall_time_secs=stats.total_wall_time_secs / stats.count)
docs: Sets the metrics for the group to be the average of its sessions.
  
    The resulting session group metrics consist of the union of metrics across
    the group's sessions. The value of each session group metric is the average
    of that metric values across the sessions in the group. The 'step' and
    'wall_time_secs' fields of the resulting MetricValue field in the session
    group are populated with the corresponding averages (truncated for 'step')
    as well.
  
    Args:
      session_group: A SessionGroup protobuffer.