code: def main(args):
      print(args)
  
      if not isinstance(args.workers, int):
          args.workers = min(16, mp.cpu_count())
  
      torch.backends.cudnn.benchmark = True
      system_available_memory = int(
          psutil.virtual_memory().available / 1024**3
      )
  
      # Load docTR model
      model = detection.__dict__[args.arch](
          pretrained=not isinstance(args.resume, str),
          assume_straight_pages=not args.rotation,
      ).eval()
  
      if isinstance(args.size, int):
          input_shape = (args.size, args.size)
      else:
          input_shape = model.cfg["input_shape"][-2:]
      mean, std = model.cfg["mean"], model.cfg["std"]
  
      st = time.time()
      ds = datasets.__dict__[args.dataset](
          train=True,
          download=True,
          use_polygons=args.rotation,
          sample_transforms=T.Resize(input_shape),
      )
      # Monkeypatch
      subfolder = ds.root.split("/")[-2:]
      ds.root = str(Path(ds.root).parent.parent)
      ds.data = [
          (os.path.join(*subfolder, name), target)
          for name, target in ds.data
      ]
      _ds = datasets.__dict__[args.dataset](
          train=False,
          download=True,
          use_polygons=args.rotation,
          sample_transforms=T.Resize(input_shape),
      )
      subfolder = _ds.root.split("/")[-2:]
      ds.data.extend(
          [
              (os.path.join(*subfolder, name), target)
              for name, target in _ds.data
          ]
      )
  
      test_loader = DataLoader(
          ds,
          batch_size=args.batch_size,
          drop_last=False,
          num_workers=args.workers,
          sampler=SequentialSampler(ds),
          pin_memory=torch.cuda.is_available(),
          collate_fn=ds.collate_fn,
      )
      print(
          f"Test set loaded in {time.time() - st:.4}s ({len(ds)} samples in "
          f"{len(test_loader)} batches)"
      )
  
      batch_transforms = Normalize(mean=mean, std=std)
  
      # Resume weights
      if isinstance(args.resume, str):
          print(f"Resuming {args.resume}")
          checkpoint = torch.load(args.resume, map_location="cpu")
          model.load_state_dict(checkpoint)
  
      # GPU
      if isinstance(args.device, int):
          if not torch.cuda.is_available():
              raise AssertionError(
                  "PyTorch cannot access your GPU. Please investigate!"
              )
          if args.device >= torch.cuda.device_count():
              raise ValueError("Invalid device index")
      # Silent default switch to GPU if available
      elif torch.cuda.is_available():
          args.device = 0
      else:
          logging.warning("No accessible GPU, targe device set to CPU.")
      if torch.cuda.is_available():
          torch.cuda.set_device(args.device)
          model = model.cuda()
  
      # Metrics
      metric = LocalizationConfusion(
          use_polygons=args.rotation,
          mask_shape=input_shape,
          use_broadcasting=True
          if system_available_memory > 62
          else False,
      )
  
      print("Running evaluation")
      val_loss, recall, precision, mean_iou = evaluate(
          model, test_loader, batch_transforms, metric, amp=args.amp
      )
      print(
          f"Validation loss: {val_loss:.6} (Recall: {recall:.2%} | Precision: {precision:.2%} | "
          f"Mean IoU: {mean_iou:.2%})"
      )
  
file_path: doctr/references/detection/evaluate_pytorch.py
imports: import os
  from doctr.file_utils import CLASS_NAME
  import logging
  import multiprocessing
  import time
  from pathlib import Path
  import psutil
  import torch
  from torch.utils.data import DataLoader, SequentialSampler
  from torchvision.transforms import Normalize
  from tqdm import tqdm
  from doctr import datasets
  from doctr import transforms
  from doctr.models import detection
  from doctr.utils.metrics import LocalizationConfusion
label_desc: Use image node_id 2 for calling a global function with example usage: main(args) without return types