

import copy
import fnmatch
import json
import os
import pickle as pkl
import shutil
import sys
import tarfile
import tempfile
from collections import OrderedDict
from contextlib import contextmanager
from functools import partial
from hashlib import shaaaa
from io import BytesIO
from pathlib import Path
from urllib.parse import urlparse
from zipfile import ZipFile, is_zipfile

import cva
import numpy as np
import requests
import wget
from filelock import FileLock
from PIL import Image
from tqdm.auto import tqdm
from yaml import Loader, dump, load


try:
 import torch

 _UpperCamelCase			       =			True
except ImportError:
 _UpperCamelCase			       =			False


try:
 from torch.hub import _get_torch_home

 _UpperCamelCase			       =			_get_torch_home()
except ImportError:
 _UpperCamelCase			       =			os.path.expanduser(
     os.getenv('''TORCH_HOME''', os.path.join(os.getenv('''XDG_CACHE_HOME''', '''~/.cache'''), '''torch'''))
 )

_UpperCamelCase			       =			os.path.join(torch_cache_home, '''transformers''')

_UpperCamelCase			       =			'''https://cdn.huggingface.co'''
_UpperCamelCase			       =			'''https://s3.amazonaws.com/models.huggingface.co/bert'''
_UpperCamelCase			       =			'''/'''.join(str(Path(__file__).resolve()).split('''/''')[:-1])
_UpperCamelCase			       =			os.path.join(PATH, '''config.yaml''')
_UpperCamelCase			       =			os.path.join(PATH, '''attributes.txt''')
_UpperCamelCase			       =			os.path.join(PATH, '''objects.txt''')
_UpperCamelCase			       =			os.getenv('''PYTORCH_PRETRAINED_BERT_CACHE''', default_cache_path)
_UpperCamelCase			       =			os.getenv('''PYTORCH_TRANSFORMERS_CACHE''', PYTORCH_PRETRAINED_BERT_CACHE)
_UpperCamelCase			       =			os.getenv('''TRANSFORMERS_CACHE''', PYTORCH_TRANSFORMERS_CACHE)
_UpperCamelCase			       =			'''pytorch_model.bin'''
_UpperCamelCase			       =			'''config.yaml'''
def 						UpperCamelCase_(			snake_case__:  Union[str, Any]=OBJECTS  ,    snake_case__:  Optional[int]=ATTRIBUTES   )       -> int:
 UpperCAmelCase__							=				[]
 with open(snake_case__   ) as f:
  for object in f.readlines():
   vg_classes.append(object.split(','   )[0].lower().strip()   )

 UpperCAmelCase__							=				[]
 with open(snake_case__   ) as f:
  for object in f.readlines():
   vg_attrs.append(object.split(','   )[0].lower().strip()   )
 return vg_classes, vg_attrs
def 						UpperCamelCase_(			snake_case__:  Dict   )       -> Optional[int]:
 UpperCAmelCase__							=				OrderedDict()
 with open(snake_case__  ,    'rb'   ) as f:
  UpperCAmelCase__							=				pkl.load(snake_case__   )['model']
 for k in copy.deepcopy(list(ckp.keys()   )   ):
  UpperCAmelCase__							=				ckp.pop(snake_case__   )
  if isinstance(snake_case__  ,    np.ndarray   ):
   UpperCAmelCase__							=				torch.tensor(snake_case__   )
  else:
   assert isinstance(snake_case__  ,    torch.tensor   ), type(snake_case__   )
  UpperCAmelCase__							=				v
 return r



class     lowercase						:



 '''simple docstring'''


 __SCREAMING_SNAKE_CASE												=				{}




 def __init__(self       ,       __a       ,       __a = "root"       ,       __a=0 ) ->					Optional[Any]:






  """simple docstring"""





  UpperCAmelCase__							=				name
  UpperCAmelCase__							=				level
  UpperCAmelCase__							=				{}
  for k, v in dictionary.items():
   if v is None:
    raise ValueError()
   UpperCAmelCase__							=				copy.deepcopy(__a )
   UpperCAmelCase__							=				copy.deepcopy(__a )
   if isinstance(__a       ,       __a ):
    UpperCAmelCase__							=				Config(__a       ,       name=__a       ,       level=level + 1 )
   UpperCAmelCase__							=				v
   setattr(self       ,       __a       ,       __a )

  UpperCAmelCase__							=				d




 def __repr__(self ) ->					Union[str, Any]:






  """simple docstring"""





  return str(list((self._pointer.keys()) ) )




 def __setattr__(self       ,       __a       ,       __a ) ->					List[str]:






  """simple docstring"""





  UpperCAmelCase__							=				val
  UpperCAmelCase__							=				val
  UpperCAmelCase__							=				key.split('.' )
  UpperCAmelCase__							=				len(__a ) - 1
  UpperCAmelCase__							=				self._pointer
  if len(__a ) > 1:
   for i, l in enumerate(__a ):
    if hasattr(self       ,       __a ) and isinstance(getattr(self       ,       __a )       ,       __a ):
     setattr(getattr(self       ,       __a )       ,       '.'.join(levels[i:] )       ,       __a )
    if l == last_level:
     UpperCAmelCase__							=				val
    else:
     UpperCAmelCase__							=				pointer[l]




 def   UpperCamelCase__							(self ) ->					Optional[int]:






  """simple docstring"""





  return self._pointer




 def   UpperCamelCase__							(self       ,       __a       ,       __a ) ->					Optional[int]:






  """simple docstring"""





  with open(F"{file_name}"       ,       'w' ) as stream:
   dump(__a       ,       __a )




 def   UpperCamelCase__							(self       ,       __a       ,       __a ) ->					int:






  """simple docstring"""





  with open(F"{file_name}"       ,       'w' ) as stream:
   json.dump(__a       ,       __a )




 @staticmethod
 def   UpperCamelCase__							(__a ) ->					Dict:






  """simple docstring"""





  with open(__a ) as stream:
   UpperCAmelCase__							=				load(__a       ,       Loader=__a )
  return data




 def __str__(self ) ->					str:






  """simple docstring"""





  UpperCAmelCase__							=				'    '
  if self._name != "root":
   UpperCAmelCase__							=				F"{t * (self._level-1)}{self._name}:\n"
  else:
   UpperCAmelCase__							=				''
  UpperCAmelCase__							=				self._level
  for i, (k, v) in enumerate(self._pointer.items() ):
   if isinstance(__a       ,       __a ):
    r += F"{t * (self._level)}{v}\n"
    self._level += 1
   else:
    r += F"{t * (self._level)}{k}: {v} ({type(__a ).__name__})\n"
   UpperCAmelCase__							=				level
  return r[:-1]




 @classmethod
 def   UpperCamelCase__							(cls       ,       __a       ,       **__a ) ->					List[str]:






  """simple docstring"""





  UpperCAmelCase__				,    UpperCAmelCase__							=				cls.get_config_dict(__a       ,       **__a )
  return cls(__a )




 @classmethod
 def   UpperCamelCase__							(cls       ,       __a       ,       **__a ) ->					Optional[int]:






  """simple docstring"""





  UpperCAmelCase__							=				kwargs.pop('cache_dir'       ,       __a )
  UpperCAmelCase__							=				kwargs.pop('force_download'       ,       __a )
  UpperCAmelCase__							=				kwargs.pop('resume_download'       ,       __a )
  UpperCAmelCase__							=				kwargs.pop('proxies'       ,       __a )
  UpperCAmelCase__							=				kwargs.pop('local_files_only'       ,       __a )

  if os.path.isdir(__a ):
   UpperCAmelCase__							=				os.path.join(__a       ,       __a )
  elif os.path.isfile(__a ) or is_remote_url(__a ):
   UpperCAmelCase__							=				pretrained_model_name_or_path
  else:
   UpperCAmelCase__							=				hf_bucket_url(__a       ,       filename=__a       ,       use_cdn=__a )

  try:
   # Load from URL or cache if already cached
   UpperCAmelCase__							=				cached_path(
       __a       ,       cache_dir=__a       ,       force_download=__a       ,       proxies=__a       ,       resume_download=__a       ,       local_files_only=__a       ,       )
   # Load config dict
   if resolved_config_file is None:
    raise EnvironmentError

   UpperCAmelCase__							=				Config.load_yaml(__a )

  except EnvironmentError:
   UpperCAmelCase__							=				'Can\'t load config for'
   raise EnvironmentError(__a )

  if resolved_config_file == config_file:
   print('loading configuration file from path' )
  else:
   print('loading configuration file cache' )

  return Config.load_yaml(__a ), kwargs







def 						UpperCamelCase_(			snake_case__:  Optional[Any]   )       -> List[str]:
 UpperCAmelCase__							=				torch.load('dump.pt'  ,    map_location=in_tensor.device   )
 UpperCAmelCase__							=				in_tensor.numpy()
 UpperCAmelCase__							=				out_tensor.numpy()[0]
 print(na.shape  ,    na[0, 0, :5]   )
 print(na.shape  ,    na[0, 0, :5]   )
 assert np.allclose(snake_case__  ,    snake_case__  ,    rtol=0.0_1  ,    atol=0.1   ), (
     f"{sum([1 for x in np.isclose(snake_case__  ,    snake_case__  ,    rtol=0.0_1  ,    atol=0.1   ).flatten() if x is False]   )/len(na.flatten()   )*1_00:.4f} %"
     " element-wise mismatch"
 )
 raise Exception('tensors are all good'   )

 # Hugging face functions below
def 						UpperCamelCase_(			snake_case__:  Dict   )       -> Tuple:
 UpperCAmelCase__							=				urlparse(snake_case__   )
 return parsed.scheme in ("http", "https")
def 						UpperCamelCase_(			snake_case__:  str  ,    snake_case__:  str  ,    snake_case__:  List[Any]=True   )       -> str:
 UpperCAmelCase__							=				CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
 UpperCAmelCase__							=				'/' not in model_id
 if legacy_format:
  return f"{endpoint}/{model_id}-{filename}"
 else:
  return f"{endpoint}/{model_id}/{filename}"
def 						UpperCamelCase_(			snake_case__:  List[Any]  ,    snake_case__:  List[Any]  ,    snake_case__:  Optional[Any]=None  ,    snake_case__:  List[Any]=0  ,    snake_case__:  str=None  ,    )       -> Dict:
 UpperCAmelCase__							=				'python/{}'.format(sys.version.split()[0]   )
 if _torch_available:
  ua += "; torch/{}".format(torch.__version__   )
 if isinstance(snake_case__  ,    snake_case__   ):
  ua += "; " + "; ".join('{}/{}'.format(snake_case__  ,    snake_case__   ) for k, v in user_agent.items()   )
 elif isinstance(snake_case__  ,    snake_case__   ):
  ua += "; " + user_agent
 UpperCAmelCase__							=				{'user-agent': ua}
 if resume_size > 0:
  UpperCAmelCase__							=				'bytes=%d-' % (resume_size,)
 UpperCAmelCase__							=				requests.get(snake_case__  ,    stream=snake_case__  ,    proxies=snake_case__  ,    headers=snake_case__   )
 if response.status_code == 4_16:  # Range not satisfiable
  return
 UpperCAmelCase__							=				response.headers.get('Content-Length'   )
 UpperCAmelCase__							=				resume_size + int(snake_case__   ) if content_length is not None else None
 UpperCAmelCase__							=				tqdm(
     unit='B'  ,    unit_scale=snake_case__  ,    total=snake_case__  ,    initial=snake_case__  ,    desc='Downloading'  ,    )
 for chunk in response.iter_content(chunk_size=10_24   ):
  if chunk:  # filter out keep-alive new chunks
   progress.update(len(snake_case__   )   )
   temp_file.write(snake_case__   )
 progress.close()
def 						UpperCamelCase_(			snake_case__:  str  ,    snake_case__:  Dict=None  ,    snake_case__:  List[Any]=False  ,    snake_case__:  str=None  ,    snake_case__:  List[str]=10  ,    snake_case__:  List[str]=False  ,    snake_case__:  List[str]=None  ,    snake_case__:  Dict=False  ,    )       -> Any:
 if cache_dir is None:
  UpperCAmelCase__							=				TRANSFORMERS_CACHE
 if isinstance(snake_case__  ,    snake_case__   ):
  UpperCAmelCase__							=				str(snake_case__   )

 os.makedirs(snake_case__  ,    exist_ok=snake_case__   )

 UpperCAmelCase__							=				None
 if not local_files_only:
  try:
   UpperCAmelCase__							=				requests.head(snake_case__  ,    allow_redirects=snake_case__  ,    proxies=snake_case__  ,    timeout=snake_case__   )
   if response.status_code == 2_00:
    UpperCAmelCase__							=				response.headers.get('ETag'   )
  except (EnvironmentError, requests.exceptions.Timeout):
   # etag is already None
   pass

 UpperCAmelCase__							=				url_to_filename(snake_case__  ,    snake_case__   )

 # get cache path to put the file
 UpperCAmelCase__							=				os.path.join(snake_case__  ,    snake_case__   )

 # etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible.
 # try to get the last downloaded one
 if etag is None:
  if os.path.exists(snake_case__   ):
   return cache_path
  else:
   UpperCAmelCase__							=				[
       file
       for file in fnmatch.filter(os.listdir(snake_case__   )  ,    filename + '.*'   )
       if not file.endswith('.json'   ) and not file.endswith('.lock'   )
   ]
   if len(snake_case__   ) > 0:
    return os.path.join(snake_case__  ,    matching_files[-1]   )
   else:
    # If files cannot be found and local_files_only=True,
    # the models might've been found if local_files_only=False
    # Notify the user about that
    if local_files_only:
     raise ValueError(
         'Cannot find the requested files in the cached path and outgoing traffic has been'
         ' disabled. To enable model look-ups and downloads online, set \'local_files_only\''
         ' to False.'   )
    return None

    # From now on, etag is not None.
 if os.path.exists(snake_case__   ) and not force_download:
  return cache_path

 # Prevent parallel downloads of the same file with a lock.
 UpperCAmelCase__							=				cache_path + '.lock'
 with FileLock(snake_case__   ):
  # If the download just completed while the lock was activated.
  if os.path.exists(snake_case__   ) and not force_download:
   # Even if returning early like here, the lock will be released.
   return cache_path

  if resume_download:
   UpperCAmelCase__							=				cache_path + '.incomplete'

   @contextmanager
   def _resumable_file_manager():
    with open(snake_case__  ,    'a+b'   ) as f:
     yield f

   UpperCAmelCase__							=				_resumable_file_manager
   if os.path.exists(snake_case__   ):
    UpperCAmelCase__							=				os.stat(snake_case__   ).st_size
   else:
    UpperCAmelCase__							=				0
  else:
   UpperCAmelCase__							=				partial(tempfile.NamedTemporaryFile  ,    dir=snake_case__  ,    delete=snake_case__   )
   UpperCAmelCase__							=				0

  # Download to temporary file, then copy to cache dir once finished.
  # Otherwise you get corrupt cache entries if the download gets interrupted.
  with temp_file_manager() as temp_file:
   print(
       '%s not found in cache or force_download set to True, downloading to %s'  ,    snake_case__  ,    temp_file.name  ,    )

   http_get(
       snake_case__  ,    snake_case__  ,    proxies=snake_case__  ,    resume_size=snake_case__  ,    user_agent=snake_case__  ,    )

  os.replace(temp_file.name  ,    snake_case__   )

  UpperCAmelCase__							=				{'url': url, 'etag': etag}
  UpperCAmelCase__							=				cache_path + '.json'
  with open(snake_case__  ,    'w'   ) as meta_file:
   json.dump(snake_case__  ,    snake_case__   )

 return cache_path
def 						UpperCamelCase_(			snake_case__:  int  ,    snake_case__:  int=None   )       -> Union[str, Any]:
 UpperCAmelCase__							=				url.encode('utf-8'   )
 UpperCAmelCase__							=				shaaaa(snake_case__   )
 UpperCAmelCase__							=				url_hash.hexdigest()

 if etag:
  UpperCAmelCase__							=				etag.encode('utf-8'   )
  UpperCAmelCase__							=				shaaaa(snake_case__   )
  filename += "." + etag_hash.hexdigest()

 if url.endswith('.h5'   ):
  filename += ".h5"

 return filename
def 						UpperCamelCase_(			snake_case__:  Optional[Any]  ,    snake_case__:  Tuple=None  ,    snake_case__:  Optional[int]=False  ,    snake_case__:  int=None  ,    snake_case__:  List[Any]=False  ,    snake_case__:  int=None  ,    snake_case__:  int=False  ,    snake_case__:  List[Any]=False  ,    snake_case__:  int=False  ,    )       -> Optional[Any]:
 if cache_dir is None:
  UpperCAmelCase__							=				TRANSFORMERS_CACHE
 if isinstance(snake_case__  ,    snake_case__   ):
  UpperCAmelCase__							=				str(snake_case__   )
 if isinstance(snake_case__  ,    snake_case__   ):
  UpperCAmelCase__							=				str(snake_case__   )

 if is_remote_url(snake_case__   ):
  # URL, so get it from the cache (downloading if necessary)
  UpperCAmelCase__							=				get_from_cache(
      snake_case__  ,    cache_dir=snake_case__  ,    force_download=snake_case__  ,    proxies=snake_case__  ,    resume_download=snake_case__  ,    user_agent=snake_case__  ,    local_files_only=snake_case__  ,    )
 elif os.path.exists(snake_case__   ):
  # File, and it exists.
  UpperCAmelCase__							=				url_or_filename
 elif urlparse(snake_case__   ).scheme == "":
  # File, but it doesn't exist.
  raise EnvironmentError('file {} not found'.format(snake_case__   )   )
 else:
  # Something unknown
  raise ValueError('unable to parse {} as a URL or as a local path'.format(snake_case__   )   )

 if extract_compressed_file:
  if not is_zipfile(snake_case__   ) and not tarfile.is_tarfile(snake_case__   ):
   return output_path

  # Path where we extract compressed archives
  # We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/"
  UpperCAmelCase__				,    UpperCAmelCase__							=				os.path.split(snake_case__   )
  UpperCAmelCase__							=				output_file.replace('.'  ,    '-'   ) + '-extracted'
  UpperCAmelCase__							=				os.path.join(snake_case__  ,    snake_case__   )

  if os.path.isdir(snake_case__   ) and os.listdir(snake_case__   ) and not force_extract:
   return output_path_extracted

  # Prevent parallel extractions
  UpperCAmelCase__							=				output_path + '.lock'
  with FileLock(snake_case__   ):
   shutil.rmtree(snake_case__  ,    ignore_errors=snake_case__   )
   os.makedirs(snake_case__   )
   if is_zipfile(snake_case__   ):
    with ZipFile(snake_case__  ,    'r'   ) as zip_file:
     zip_file.extractall(snake_case__   )
     zip_file.close()
   elif tarfile.is_tarfile(snake_case__   ):
    UpperCAmelCase__							=				tarfile.open(snake_case__   )
    tar_file.extractall(snake_case__   )
    tar_file.close()
   else:
    raise EnvironmentError('Archive format of {} could not be identified'.format(snake_case__   )   )

  return output_path_extracted

 return output_path
def 						UpperCamelCase_(			snake_case__:  Dict  ,    snake_case__:  Optional[int]=","   )       -> str:
 assert isinstance(snake_case__  ,    snake_case__   )
 if os.path.isfile(snake_case__   ):
  with open(snake_case__   ) as f:
   UpperCAmelCase__							=				eval(f.read()   )
 else:
  UpperCAmelCase__							=				requests.get(snake_case__   )
  try:
   UpperCAmelCase__							=				requests.json()
  except Exception:
   UpperCAmelCase__							=				req.content.decode()
   assert data is not None, "could not connect"
   try:
    UpperCAmelCase__							=				eval(snake_case__   )
   except Exception:
    UpperCAmelCase__							=				data.split('\n'   )
  req.close()
 return data
def 						UpperCamelCase_(			snake_case__:  List[Any]   )       -> List[str]:
 UpperCAmelCase__							=				requests.get(snake_case__   )
 UpperCAmelCase__							=				np.array(Image.open(BytesIO(response.content   )   )   )
 return img
def 						UpperCamelCase_(			snake_case__:  List[Any]   )       -> Union[str, Any]:
 UpperCAmelCase__							=				url.split('/'   )[-1]
 if fn not in os.listdir(os.getcwd()   ):
  wget.download(snake_case__   )
 with open(snake_case__  ,    'rb'   ) as stream:
  UpperCAmelCase__							=				pkl.load(snake_case__   )
 UpperCAmelCase__							=				weights.pop('model'   )
 UpperCAmelCase__							=				{}
 for k, v in model.items():
  UpperCAmelCase__							=				torch.from_numpy(snake_case__   )
  if "running_var" in k:
   UpperCAmelCase__							=				torch.tensor([0]   )
   UpperCAmelCase__							=				k.replace('running_var'  ,    'num_batches_tracked'   )
   UpperCAmelCase__							=				zero
 return new
def 						UpperCamelCase_(			)       -> Dict:
 print(f"{os.path.abspath(os.path.join(snake_case__  ,    os.pardir   )   )}/demo.ipynb"   )
def 						UpperCamelCase_(			snake_case__:  Dict  ,    snake_case__:  Dict="RGB"   )       -> List[str]:
 assert isinstance(snake_case__  ,    snake_case__   )
 if os.path.isfile(snake_case__   ):
  UpperCAmelCase__							=				cva.imread(snake_case__   )
 else:
  UpperCAmelCase__							=				get_image_from_url(snake_case__   )
  assert img is not None, f"could not connect to: {im}"
 UpperCAmelCase__							=				cva.cvtColor(snake_case__  ,    cva.COLOR_BGR2RGB   )
 if input_format == "RGB":
  UpperCAmelCase__							=				img[:, :, ::-1]
 return img







def 						UpperCamelCase_(			snake_case__:  Tuple  ,    snake_case__:  List[str]=1   )       -> Any:
 return (images[i : i + batch] for i in range(0  ,    len(snake_case__   )  ,    snake_case__   ))






import os
import pickle
import unittest
from collections import UserDict, namedtuple

import torch

from accelerate.test_utils.testing import require_cuda, require_torch_min_version
from accelerate.test_utils.training import RegressionModel
from accelerate.utils import (
    convert_outputs_to_fpaa,
    extract_model_from_parallel,
    find_device,
    listify,
    patch_environment,
    recursively_apply,
    send_to_device,
)


_UpperCamelCase			       =			namedtuple('''ExampleNamedTuple''', '''a b c''')



class     lowercase						(       unittest.TestCase					):



 '''simple docstring'''


 def   UpperCamelCase__							(self ) ->					Tuple:






  """simple docstring"""





  UpperCAmelCase__							=				torch.randn(5       ,       2 )
  UpperCAmelCase__							=				torch.device('cuda' ) if torch.cuda.is_available() else torch.device('cpu' )

  UpperCAmelCase__							=				send_to_device(__a       ,       __a )
  self.assertTrue(torch.equal(resulta.cpu()       ,       __a ) )

  UpperCAmelCase__							=				send_to_device((tensor, [tensor, tensor], 1)       ,       __a )
  self.assertIsInstance(__a       ,       __a )
  self.assertTrue(torch.equal(resulta[0].cpu()       ,       __a ) )
  self.assertIsInstance(resulta[1]       ,       __a )
  self.assertTrue(torch.equal(resulta[1][0].cpu()       ,       __a ) )
  self.assertTrue(torch.equal(resulta[1][1].cpu()       ,       __a ) )
  self.assertEqual(resulta[2]       ,       1 )

  UpperCAmelCase__							=				send_to_device({'a': tensor, 'b': [tensor, tensor], 'c': 1}       ,       __a )
  self.assertIsInstance(__a       ,       __a )
  self.assertTrue(torch.equal(resulta['a'].cpu()       ,       __a ) )
  self.assertIsInstance(resulta['b']       ,       __a )
  self.assertTrue(torch.equal(resulta['b'][0].cpu()       ,       __a ) )
  self.assertTrue(torch.equal(resulta['b'][1].cpu()       ,       __a ) )
  self.assertEqual(resulta['c']       ,       1 )

  UpperCAmelCase__							=				send_to_device(ExampleNamedTuple(a=__a       ,       b=[tensor, tensor]       ,       c=1 )       ,       __a )
  self.assertIsInstance(__a       ,       __a )
  self.assertTrue(torch.equal(resulta.a.cpu()       ,       __a ) )
  self.assertIsInstance(resulta.b       ,       __a )
  self.assertTrue(torch.equal(resulta.b[0].cpu()       ,       __a ) )
  self.assertTrue(torch.equal(resulta.b[1].cpu()       ,       __a ) )
  self.assertEqual(resulta.c       ,       1 )

  UpperCAmelCase__							=				send_to_device(UserDict({'a': tensor, 'b': [tensor, tensor], 'c': 1} )       ,       __a )
  self.assertIsInstance(__a       ,       __a )
  self.assertTrue(torch.equal(resulta['a'].cpu()       ,       __a ) )
  self.assertIsInstance(resulta['b']       ,       __a )
  self.assertTrue(torch.equal(resulta['b'][0].cpu()       ,       __a ) )
  self.assertTrue(torch.equal(resulta['b'][1].cpu()       ,       __a ) )
  self.assertEqual(resulta['c']       ,       1 )




 def   UpperCamelCase__							(self ) ->					List[str]:






  """simple docstring"""





  with self.assertRaises(__a ) as cm:
   UpperCAmelCase__							=				recursively_apply(torch.tensor       ,       (torch.tensor(1 ), 1)       ,       error_on_other_type=__a )
  self.assertEqual(
      str(cm.exception )       ,       'Unsupported types (<class \'int\'>) passed to `tensor`. Only nested list/tuple/dicts of objects that are valid for `is_torch_tensor` should be passed.'       ,       )




 def   UpperCamelCase__							(self ) ->					List[str]:






  """simple docstring"""





  UpperCAmelCase__							=				torch.tensor([1, 2, 3, 4, 5] )
  self.assertEqual(listify(__a )       ,       [1, 2, 3, 4, 5] )

  UpperCAmelCase__							=				torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] )
  self.assertEqual(listify(__a )       ,       [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] )

  UpperCAmelCase__							=				torch.tensor([[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], [[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]] )
  self.assertEqual(
      listify(__a )       ,       [[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], [[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]] )




 def   UpperCamelCase__							(self ) ->					int:






  """simple docstring"""





  with patch_environment(aa=1       ,       BB=2 ):
   self.assertEqual(os.environ.get('AA' )       ,       '1' )
   self.assertEqual(os.environ.get('BB' )       ,       '2' )

  self.assertNotIn('AA'       ,       os.environ )
  self.assertNotIn('BB'       ,       os.environ )




 def   UpperCamelCase__							(self ) ->					Dict:






  """simple docstring"""





  UpperCAmelCase__							=				RegressionModel()
  UpperCAmelCase__							=				model.forward
  UpperCAmelCase__							=				convert_outputs_to_fpaa(model.forward )
  UpperCAmelCase__							=				extract_model_from_parallel(__a       ,       keep_fpaa_wrapper=__a )
  UpperCAmelCase__							=				pickle.dumps(__a )




 @require_cuda
 def   UpperCamelCase__							(self ) ->					Tuple:






  """simple docstring"""





  UpperCAmelCase__							=				RegressionModel()
  UpperCAmelCase__							=				model.forward
  UpperCAmelCase__							=				torch.cuda.amp.autocast(dtype=torch.floataa )(model.forward )
  UpperCAmelCase__							=				convert_outputs_to_fpaa(model.forward )
  UpperCAmelCase__							=				extract_model_from_parallel(__a       ,       keep_fpaa_wrapper=__a )
  UpperCAmelCase__							=				pickle.dumps(__a )




 @require_cuda
 @require_torch_min_version(version='2.0' )
 def   UpperCamelCase__							(self ) ->					List[str]:






  """simple docstring"""





  UpperCAmelCase__							=				RegressionModel()
  UpperCAmelCase__							=				model.forward
  UpperCAmelCase__							=				torch.cuda.amp.autocast(dtype=torch.floataa )(model.forward )
  UpperCAmelCase__							=				convert_outputs_to_fpaa(model.forward )
  UpperCAmelCase__							=				torch.compile(model.forward       ,       backend='inductor' )
  UpperCAmelCase__							=				torch.randn(4       ,       10 ).cuda()
  UpperCAmelCase__							=				model(__a )




 def   UpperCamelCase__							(self ) ->					Optional[Any]:






  """simple docstring"""





  UpperCAmelCase__							=				RegressionModel()
  # could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU
  UpperCAmelCase__							=				torch.nn.parallel.DataParallel(__a )
  UpperCAmelCase__							=				extract_model_from_parallel(__a )

  self.assertEqual(__a       ,       __a )




 @require_torch_min_version(version='2.0' )
 def   UpperCamelCase__							(self ) ->					Optional[Any]:






  """simple docstring"""





  UpperCAmelCase__							=				RegressionModel()
  UpperCAmelCase__							=				torch.compile(__a )

  # could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU
  UpperCAmelCase__							=				torch.nn.parallel.DataParallel(__a )
  UpperCAmelCase__							=				torch.compile(__a )
  UpperCAmelCase__							=				extract_model_from_parallel(__a )

  self.assertEqual(compiled_model._orig_mod       ,       compiled_model_unwrapped._orig_mod )




 def   UpperCamelCase__							(self ) ->					str:






  """simple docstring"""





  self.assertEqual(find_device([1, 'a', torch.tensor([1, 2, 3] )] )       ,       torch.device('cpu' ) )
  self.assertEqual(find_device({'a': 1, 'b': torch.tensor([1, 2, 3] )} )       ,       torch.device('cpu' ) )
  self.assertIsNone(find_device([1, 'a'] ) )



