code: def _setup_common_training_handlers(
      trainer: Engine,
      to_save: Optional[Mapping] = None,
      save_every_iters: int = 1000,
      output_path: Optional[str] = None,
      lr_scheduler: Optional[
          Union[ParamScheduler, PyTorchLRScheduler]
      ] = None,
      with_gpu_stats: bool = False,
      output_names: Optional[Iterable[str]] = None,
      with_pbars: bool = True,
      with_pbar_on_iters: bool = True,
      log_every_iters: int = 100,
      stop_on_nan: bool = True,
      clear_cuda_cache: bool = True,
      save_handler: Optional[Union[Callable, BaseSaveHandler]] = None,
      **kwargs: Any,
  ) -> None:
      if output_path is not None and save_handler is not None:
          raise ValueError(
              "Arguments output_path and save_handler are mutually exclusive. Please, define only one of them"
          )
  
      if stop_on_nan:
          trainer.add_event_handler(
              Events.ITERATION_COMPLETED, TerminateOnNan()
          )
  
      if lr_scheduler is not None:
          if isinstance(lr_scheduler, PyTorchLRScheduler):
              trainer.add_event_handler(
                  Events.ITERATION_COMPLETED,
                  lambda engine: lr_scheduler.step(),
              )
          else:
              trainer.add_event_handler(
                  Events.ITERATION_STARTED, lr_scheduler
              )
  
      if torch.cuda.is_available() and clear_cuda_cache:
          trainer.add_event_handler(
              Events.EPOCH_COMPLETED, empty_cuda_cache
          )
  
      if to_save is not None:
          if output_path is None and save_handler is None:
              raise ValueError(
                  "If to_save argument is provided then output_path or save_handler arguments should be also defined"
              )
          if output_path is not None:
              save_handler = DiskSaver(
                  dirname=output_path, require_empty=False
              )
  
          checkpoint_handler = Checkpoint(
              to_save,
              cast(Union[Callable, BaseSaveHandler], save_handler),
              filename_prefix="training",
              **kwargs,
          )
          trainer.add_event_handler(
              Events.ITERATION_COMPLETED(every=save_every_iters),
              checkpoint_handler,
          )
  
      if with_gpu_stats:
          GpuInfo().attach(
              trainer, name="gpu", event_name=Events.ITERATION_COMPLETED(every=log_every_iters)  # type: ignore[arg-type]
          )
  
      if output_names is not None:
  
          def output_transform(x: Any, index: int, name: str) -> Any:
              if isinstance(x, Mapping):
                  return x[name]
              elif isinstance(x, Sequence):
                  return x[index]
              elif isinstance(x, (torch.Tensor, numbers.Number)):
                  return x
              else:
                  raise TypeError(
                      "Unhandled type of update_function's output. "
                      f"It should either mapping or sequence, but given {type(x)}"
                  )
  
          for i, n in enumerate(output_names):
              RunningAverage(
                  output_transform=partial(
                      output_transform, index=i, name=n
                  )
              ).attach(trainer, n, usage=RunningBatchWise())
  
      if with_pbars:
          if with_pbar_on_iters:
              ProgressBar(persist=False).attach(
                  trainer,
                  metric_names="all",
                  event_name=Events.ITERATION_COMPLETED(
                      every=log_every_iters
                  ),
              )
  
          ProgressBar(persist=True, bar_format="").attach(
              trainer,
              event_name=Events.EPOCH_STARTED,
              closing_event_name=Events.COMPLETED,
          )
  
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 2 for calling a global function with example usage: _setup_common_training_handlers(trainer, to_save, save_every_iters, output_path, lr_scheduler, with_gpu_stats, output_names, with_pbars, with_pbar_on_iters, log_every_iters, stop_on_nan, clear_cuda_cache, save_handler) and returns: x, x, x