code: def avg_and_save_k_checkpoints(
      model_state: Dict,
      best_metric: float,
      k_best_checkpoints: int,
      max_ckpt_metric: bool,
      ckpt_str: str,
  ) -> None:
      """Save top-k checkpoints and their average.
  
      Args:
          model_state: `state_dict` containing model parameters.
          best_metric: Best observed value of the tracking validation metric. For example, best top-1 validation accuracy
              that is observed until the current iteration.
          k_best_checkpoints: An integer k determining number of top (based on validation metric) checkpoints to keep.
              If `k_best_checkpoints` is smaller than 1, only best checkpoint is stored.
          max_ckpt_metric: A boolean demonstrating whether the tracking validation metric is higher the better, or lower
              the better.
          ckpt_str: String determining path prefix for checkpoints to be saved.
      """
      try:
          ckpt_fname = "{}_score_{:.4f}.{}".format(
              ckpt_str, best_metric, CHECKPOINT_EXTN
          )
          torch.save(model_state, ckpt_fname)
  
          best_fnames = glob.glob("{}_score_*".format(ckpt_str))
          best_scores = [
              float(
                  f.split("_score_")[-1].replace(
                      ".{}".format(CHECKPOINT_EXTN), ""
                  )
              )
              for f in best_fnames
          ]
  
          best_scores_keep = []
          if len(best_scores) > k_best_checkpoints:
              best_scores = sorted(best_scores)
              if not max_ckpt_metric:
                  best_scores = best_scores[::-1]
              best_scores_keep = best_scores[-k_best_checkpoints:]
              for k in best_scores:
                  if k in best_scores_keep:
                      continue
                  rm_ckpt = "{}_score_{:.4f}.{}".format(
                      ckpt_str, k, CHECKPOINT_EXTN
                  )
                  os.remove(rm_ckpt)
                  logger.log("Deleting checkpoint: {}".format(rm_ckpt))
          #
          if len(best_scores_keep) > 1:
              avg_fnames = [
                  "{}_score_{:.4f}.{}".format(
                      ckpt_str, k, CHECKPOINT_EXTN
                  )
                  for k in best_scores_keep
              ]
              logger.log(
                  "Averaging checkpoints: {}".format(
                      [f.split("/")[-1] for f in avg_fnames]
                  )
              )
              # save the average model
              avg_model_state = average_ckpts(ckpt_loc_list=avg_fnames)
              ckpt_fname = "{}_avg.{}".format(ckpt_str, CHECKPOINT_EXTN)
              if avg_model_state:
                  torch.save(avg_model_state, ckpt_fname)
                  logger.log(
                      "Averaged checkpoint saved at: {}".format(
                          ckpt_fname
                      )
                  )
      except Exception as e:
          logger.log("Error in k-best-checkpoint")
          print(e)
  
imports: import argparse
  import glob
  import math
  import os
  from typing import Dict, List, Optional, Tuple, Union
  import torch
  from cvnets import EMA
  from optim import BaseOptim
  from utils import logger
  from utils.common_utils import unwrap_model_fn
  from utils.ddp_utils import is_master
  from utils.download_utils import get_local_path
label_desc: Use image node_id 4 for calling a global function with example usage: avg_and_save_k_checkpoints(model_state, best_metric, k_best_checkpoints, max_ckpt_metric, ckpt_str) without return types