code: def _get_device_index(num_devices: int, device_name: str) -> int:
      assert num_devices > 0
  
      # We use the `LOCAL_RANK` environment variable to determine which GPU to
      # pick in case the process has more than one GPU available.
      device_idx = _get_int_from_env("LOCAL_RANK")
      if device_idx is None:
          if num_devices > 1:
              raise RuntimeError(
                  f"The default {device_name} device cannot be determined. There are {num_devices} {device_name} devices available, but the `LOCAL_RANK` environment variable is not set."
              )
  
          return 0
  
      if device_idx < 0:
          raise RuntimeError(
              f"The value of the `LOCAL_RANK` environment variable must be greater than or equal to 0, but is {device_idx} instead."
          )
  
      if device_idx >= num_devices:
          raise RuntimeError(
              f"The value of the `LOCAL_RANK` environment variable must be less than the number of available {device_name} devices ({num_devices}), but is {device_idx} instead."
          )
  
      return device_idx
  
imports: import logging
  import os
  from abc import ABC, abstractmethod
  from datetime import timedelta
  from enum import Enum
  from typing import Optional, final
  import torch
  import torch.distributed
  from torch import Tensor
  from torch.distributed import ProcessGroup, ReduceOp
  from fairseq2.typing import CPU, Device, finaloverride
label_desc: Use image node_id 4 for calling a global function with example usage: _get_device_index(num_devices, device_name) and returns: device_idx, int