code: def _test_setup_common_training_handlers(
      dirname,
      device,
      rank=0,
      local_rank=0,
      distributed=False,
      lr_scheduler=None,
      save_handler=None,
      output_transform=lambda loss: loss,
  ):
      lr = 0.01
      step_size = 100
      gamma = 0.5
      num_iters = 100
      num_epochs = 10
  
      model = DummyModel().to(device)
      if distributed and "cuda" in torch.device(device).type:
          model = torch.nn.parallel.DistributedDataParallel(
              model, device_ids=[local_rank], output_device=local_rank
          )
      optimizer = torch.optim.SGD(model.parameters(), lr=lr)
  
      if lr_scheduler is None:
          lr_scheduler = torch.optim.lr_scheduler.StepLR(
              optimizer, step_size=step_size, gamma=gamma
          )
      elif (
          isinstance(lr_scheduler, str)
          and lr_scheduler == "ignite|LRScheduler"
      ):
          from ignite.contrib.handlers import LRScheduler
  
          lr_scheduler = LRScheduler(
              torch.optim.lr_scheduler.StepLR(
                  optimizer, step_size=step_size, gamma=gamma
              )
          )
      elif isinstance(lr_scheduler, str) and lr_scheduler == "ignite":
          from ignite.contrib.handlers import PiecewiseLinear
  
          milestones_values = [
              (0, 0.0),
              (step_size, lr),
              (num_iters * (num_epochs - 1), 0.0),
          ]
          lr_scheduler = PiecewiseLinear(
              optimizer,
              param_name="lr",
              milestones_values=milestones_values,
          )
      else:
          raise ValueError(f"Unknown lr_scheduler: {lr_scheduler}")
  
      def update_fn(engine, batch):
          optimizer.zero_grad()
          x = torch.tensor([batch], requires_grad=True, device=device)
          y_pred = model(x)
          loss = y_pred.mean()
          loss.backward()
          optimizer.step()
          return output_transform(loss)
  
      train_sampler = None
      if distributed and idist.get_world_size() > 1:
          train_sampler = MagicMock(spec=DistributedSampler)
          train_sampler.set_epoch = MagicMock()
  
      trainer = Engine(update_fn)
      setup_common_training_handlers(
          trainer,
          train_sampler=train_sampler,
          to_save={"model": model, "optimizer": optimizer},
          save_every_iters=75,
          output_path=dirname,
          save_handler=save_handler,
          lr_scheduler=lr_scheduler,
          with_gpu_stats=False,
          output_names=["batch_loss"],
          with_pbars=True,
          with_pbar_on_iters=True,
          log_every_iters=50,
      )
  
      data = [i * 0.1 for i in range(num_iters)]
      trainer.run(data, max_epochs=num_epochs)
  
      # check handlers
      handlers = trainer._event_handlers[Events.ITERATION_COMPLETED]
      for cls in [
          TerminateOnNan,
      ]:
          assert any(
              [isinstance(h[0], cls) for h in handlers]
          ), f"{handlers}"
      assert "batch_loss" in trainer.state.metrics
  
      # Check saved checkpoint
      if rank == 0:
          if save_handler is not None:
              dirname = save_handler.dirname
          checkpoints = list(os.listdir(dirname))
          assert len(checkpoints) == 1
          for v in [
              "training_checkpoint",
          ]:
              assert any([v in c for c in checkpoints])
  
      # Check LR scheduling
      assert optimizer.param_groups[0]["lr"] <= lr * gamma ** (
          (num_iters * num_epochs - 1) // step_size
      ), f"{optimizer.param_groups[0]['lr']} vs {lr * gamma ** ((num_iters * num_epochs - 1) // step_size)}"
  
imports: import os
  import sys
  from unittest.mock import call, MagicMock
  import pytest
  import torch
  import torch.nn
  from torch.utils.data.distributed import DistributedSampler
  import ignite.contrib.handlers
  import ignite.distributed
  from ignite.contrib.engines.common import _setup_logging, add_early_stopping_by_val_score, gen_save_best_models_by_val_score, save_best_model_by_val_score, setup_any_logging, setup_clearml_logging, setup_common_training_handlers, setup_mlflow_logging, setup_neptune_logging, setup_plx_logging, setup_tb_logging, setup_trains_logging, setup_visdom_logging, setup_wandb_logging
  from ignite.engine import Engine, Events
  from ignite.handlers import DiskSaver, TerminateOnNan
label_desc: Use image node_id 1 for calling a global function with example usage: _test_setup_common_training_handlers(dirname, device, rank, local_rank, distributed, lr_scheduler, save_handler, output_transform) and returns: output_transform