code: def gen_save_best_models_by_val_score(
      save_handler: Union[Callable, BaseSaveHandler],
      evaluator: Engine,
      models: Union[torch.nn.Module, Dict[str, torch.nn.Module]],
      metric_name: str,
      n_saved: int = 3,
      trainer: Optional[Engine] = None,
      tag: str = "val",
      score_sign: float = 1.0,
      **kwargs: Any,
  ) -> Checkpoint:
      """Method adds a handler to ``evaluator`` to save ``n_saved`` of best models based on the metric
      (named by ``metric_name``) provided by ``evaluator`` (i.e. ``evaluator.state.metrics[metric_name]``).
      Models with highest metric value will be retained. The logic of how to store objects is delegated to
      ``save_handler``.
  
      Args:
          save_handler: Method or callable class to
              use to save engine and other provided objects. Function receives two objects: checkpoint as a dictionary
              and filename. If ``save_handler`` is callable class, it can
              inherit of :class:`~ignite.handlers.checkpoint.BaseSaveHandler` and optionally implement ``remove`` method
              to keep a fixed number of saved checkpoints. In case if user needs to save engine's checkpoint on a disk,
              ``save_handler`` can be defined with :class:`~ignite.handlers.DiskSaver`.
          evaluator: evaluation engine used to provide the score
          models: model or dictionary with the object to save. Objects should have
              implemented ``state_dict`` and ``load_state_dict`` methods.
          metric_name: metric name to use for score evaluation. This metric should be present in
              `evaluator.state.metrics`.
          n_saved: number of best models to store
          trainer: trainer engine to fetch the epoch when saving the best model.
          tag: score name prefix: `{tag}_{metric_name}`. By default, tag is "val".
          score_sign: sign of the score: 1.0 or -1.0. For error-like metrics, e.g. smaller is better,
              a negative score sign should be used (objects with larger score are retained). Default, 1.0.
          kwargs: optional keyword args to be passed to construct :class:`~ignite.handlers.checkpoint.Checkpoint`.
  
      Returns:
          A :class:`~ignite.handlers.checkpoint.Checkpoint` handler.
      """
      global_step_transform = None
      if trainer is not None:
          global_step_transform = global_step_from_engine(trainer)
  
      if isinstance(models, nn.Module):
          to_save: Dict[str, nn.Module] = {"model": models}
      else:
          to_save = models
  
      best_model_handler = Checkpoint(
          to_save,
          save_handler,
          filename_prefix="best",
          n_saved=n_saved,
          global_step_transform=global_step_transform,
          score_name=f"{tag}_{metric_name.lower()}",
          score_function=get_default_score_fn(
              metric_name, score_sign=score_sign
          ),
          **kwargs,
      )
      evaluator.add_event_handler(Events.COMPLETED, best_model_handler)
  
      return best_model_handler
  
imports: import numbers
  import warnings
  from functools import partial
  from typing import Any, Callable, cast, Dict, Iterable, Mapping, Optional, Sequence, Union
  import torch
  import torch.nn
  from torch.optim.optimizer import Optimizer
  from torch.utils.data.distributed import DistributedSampler
  import ignite.distributed
  from ignite.contrib.handlers import ClearMLLogger, global_step_from_engine, MLflowLogger, NeptuneLogger, PolyaxonLogger, ProgressBar, TensorboardLogger, VisdomLogger, WandBLogger
  from ignite.contrib.handlers.base_logger import BaseLogger
  from ignite.contrib.metrics import GpuInfo
  from ignite.engine import Engine, Events
  from ignite.handlers import Checkpoint, DiskSaver, EarlyStopping, TerminateOnNan
  from ignite.handlers.checkpoint import BaseSaveHandler
  from ignite.handlers.param_scheduler import ParamScheduler
  from ignite.metrics import RunningAverage
  from ignite.metrics.metric import RunningBatchWise
  from ignite.utils import deprecated
label_desc: Use image node_id 15 for calling a global function with example usage: gen_save_best_models_by_val_score(save_handler, evaluator, models, metric_name, n_saved, trainer, tag, score_sign) and returns: best_model_handler