code: def _set_avg_session_metrics(session_group):
      """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.
      """
      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 metric_stats.items():
          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,
          )
  
imports: import collections
  import dataclasses
  import operator
  import re
  from typing import Optional
  from google.protobuf import struct_pb2
  from tensorboard.data import provider
  from tensorboard.plugins.hparams import api_pb2
  from tensorboard.plugins.hparams import backend_context
  from tensorboard.plugins.hparams import error
  from tensorboard.plugins.hparams import json_format_compat
  from tensorboard.plugins.hparams import metadata
  from tensorboard.plugins.hparams import metrics
  from tensorboard.plugins.hparams import plugin_data_pb2
label_desc: Use image node_id 13 for calling a global function with example usage: _set_avg_session_metrics(session_group) without return types