code: def convert_to_torch(
      stats: Any,
      device: Union[str, None],
      cast: Union[torch.dtype, None],
      in_place: Union[bool, str],
  ) -> Any:
      """Converts any struct to torch.Tensors.
  
      :param stats: Any (possibly nested) struct, the values in which will be
          converted and returned as a new struct with all leaves converted
          to torch tensors.
      :param device: 'cpu' or 'cuda', or None if it should stay the same
      :param cast: the type the element should be cast to, or None if it should stay the same
      :param in_place: specify if the operation should be done in_place, can be bool or 'try'
  
      :return: A new struct with the same structure as `stats`, but with all
              values converted to torch Tensor types.
  
      """
  
      def mapping(item):
          """Define mapping"""
          if torch.is_tensor(item):
              tensor = item
          else:
              tensor = torch.from_numpy(np.asarray(item))
          if tensor.dtype != cast and cast is not None:
              tensor = tensor.to(cast)
          if tensor.device != device and device is not None:
              tensor = tensor.to(device)
          return tensor
  
      assert in_place in [True, False, "try"]
      if in_place == "try":
          return map_nested_structure(stats, mapping, in_place, 1)
      else:
          return map_nested_structure(stats, mapping, in_place)
  
file_path: maze/maze/perception/perception_utils.py
imports: import collections
  from collections import defaultdict
  from typing import Union, Dict, Any, Callable, Sequence, Iterable
  import gym
  import numpy
  import torch
  from gym import spaces
  from maze.core.env.structured_env import StepKeyType
  from maze.core.utils.structured_env_utils import flat_structured_space
label_desc: Use image node_id 4 for calling a global function with example usage: convert_to_torch(stats, device, cast, in_place) and returns: tensor, map_nested_structure, map_nested_structure