

"""simple docstring"""





import asyncio
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from distutils.util import strtobool
from functools import partial
from pathlib import Path
from typing import List, Union
from unittest import mock

import torch

from ..state import AcceleratorState, PartialState
from ..utils import (
    gather,
    is_bnb_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_mps_available,
    is_safetensors_available,
    is_tensorboard_available,
    is_torch_version,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)




def   _A  (  UpperCamelCase_     :       List[Any],			UpperCamelCase_     :       Tuple=False)	->						int:
   '''simple docstring'''


   try:
      __lowercase								=						os.environ[key]
   except KeyError:
      # KEY isn't set, default to `default`.
      __lowercase								=						default
   else:
      # KEY is set, convert it to True or False.
      try:
         __lowercase								=						strtobool(UpperCamelCase_)
      except ValueError:
         # More values are supported, but let's keep the message simple.
         raise ValueError(F"""If set, {key} must be yes or no.""")
   return _value


_a       =							parse_flag_from_env('RUN_SLOW', default=False)




def   _A  (  UpperCamelCase_     :       int)	->						Optional[int]:
   '''simple docstring'''


   return unittest.skip("Test was skipped")(UpperCamelCase_)




def   _A  (  UpperCamelCase_     :       Any)	->						Optional[int]:
   '''simple docstring'''


   return unittest.skipUnless(_run_slow_tests,			"test is slow")(UpperCamelCase_)




def   _A  (  UpperCamelCase_     :       Tuple)	->						List[Any]:
   '''simple docstring'''


   return unittest.skipUnless(not torch.cuda.is_available(),			"test requires only a CPU")(UpperCamelCase_)




def   _A  (  UpperCamelCase_     :       int)	->						Any:
   '''simple docstring'''


   return unittest.skipUnless(torch.cuda.is_available(),			"test requires a GPU")(UpperCamelCase_)




def   _A  (  UpperCamelCase_     :       Optional[int])	->						Tuple:
   '''simple docstring'''


   return unittest.skipUnless(is_xpu_available(),			"test requires a XPU")(UpperCamelCase_)




def   _A  (  UpperCamelCase_     :       Optional[int])	->						Dict:
   '''simple docstring'''


   return unittest.skipUnless(is_mps_available(),			"test requires a `mps` backend support in `torch`")(UpperCamelCase_)




def   _A  (  UpperCamelCase_     :       int)	->						List[Any]:
   '''simple docstring'''


   return unittest.skipUnless(
       is_transformers_available() and is_datasets_available(),			"test requires the Hugging Face suite")(UpperCamelCase_)




def   _A  (  UpperCamelCase_     :       Union[str, Any])	->						Tuple:
   '''simple docstring'''


   return unittest.skipUnless(is_bnb_available(),			"test requires the bitsandbytes library")(UpperCamelCase_)




def   _A  (  UpperCamelCase_     :       Optional[Any])	->						int:
   '''simple docstring'''


   return unittest.skipUnless(is_tpu_available(),			"test requires TPU")(UpperCamelCase_)




def   _A  (  UpperCamelCase_     :       str)	->						List[Any]:
   '''simple docstring'''


   return unittest.skipUnless(torch.cuda.device_count() == 1,			"test requires a GPU")(UpperCamelCase_)




def   _A  (  UpperCamelCase_     :       Union[str, Any])	->						List[str]:
   '''simple docstring'''


   return unittest.skipUnless(torch.xpu.device_count() == 1,			"test requires a XPU")(UpperCamelCase_)




def   _A  (  UpperCamelCase_     :       List[Any])	->						str:
   '''simple docstring'''


   return unittest.skipUnless(torch.cuda.device_count() > 1,			"test requires multiple GPUs")(UpperCamelCase_)




def   _A  (  UpperCamelCase_     :       Optional[int])	->						str:
   '''simple docstring'''


   return unittest.skipUnless(torch.xpu.device_count() > 1,			"test requires multiple XPUs")(UpperCamelCase_)




def   _A  (  UpperCamelCase_     :       str)	->						int:
   '''simple docstring'''


   return unittest.skipUnless(is_safetensors_available(),			"test requires safetensors")(UpperCamelCase_)




def   _A  (  UpperCamelCase_     :       Dict)	->						str:
   '''simple docstring'''


   return unittest.skipUnless(is_deepspeed_available(),			"test requires DeepSpeed")(UpperCamelCase_)




def   _A  (  UpperCamelCase_     :       List[str])	->						Dict:
   '''simple docstring'''


   return unittest.skipUnless(is_torch_version(">=",			"1.12.0"),			"test requires torch version >= 1.12.0")(UpperCamelCase_)




def   _A  (  UpperCamelCase_     :       Dict=None,			UpperCamelCase_     :       int=None)	->						int:
   '''simple docstring'''


   if test_case is None:
      return partial(UpperCamelCase_,			version=UpperCamelCase_)
   return unittest.skipUnless(is_torch_version(">=",			UpperCamelCase_),			F"""test requires torch version >= {version}""")(UpperCamelCase_)




def   _A  (  UpperCamelCase_     :       List[Any])	->						Any:
   '''simple docstring'''


   return unittest.skipUnless(is_tensorboard_available(),			"test requires Tensorboard")(UpperCamelCase_)




def   _A  (  UpperCamelCase_     :       Optional[Any])	->						Union[str, Any]:
   '''simple docstring'''


   return unittest.skipUnless(is_wandb_available(),			"test requires wandb")(UpperCamelCase_)




def   _A  (  UpperCamelCase_     :       Optional[int])	->						Tuple:
   '''simple docstring'''


   return unittest.skipUnless(is_comet_ml_available(),			"test requires comet_ml")(UpperCamelCase_)


_a       =							(
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)




def   _A  (  UpperCamelCase_     :       List[str])	->						str:
   '''simple docstring'''


   return unittest.skipUnless(
       _atleast_one_tracker_available,			"test requires at least one tracker to be available and for `comet_ml` to not be installed",			)(UpperCamelCase_)




class 					_lowerCAmelCase  (	unittest.TestCase   ):







 """simple docstring"""







 __UpperCAmelCase	:					Tuple   		=	True


 @classmethod
 def 					_lowercase (			cls							:			Dict	):
    __lowercase								=						tempfile.mkdtemp()


 @classmethod
 def 					_lowercase (			cls							:			List[str]	):
    if os.path.exists(cls.tmpdir	):
       shutil.rmtree(cls.tmpdir	)



 def 					_lowercase (			self							:			Union[str, Any]	):
    if self.clear_on_setup:
       for path in Path(self.tmpdir	).glob("**/*"	):
          if path.is_file():
             path.unlink()
          elif path.is_dir():
             shutil.rmtree(UpperCAmelCase__	)







class 					_lowerCAmelCase  (	unittest.TestCase   ):







 """simple docstring"""







 def 					_lowercase (			self							:			Optional[Any]	):
    super().tearDown()
    # Reset the state of the AcceleratorState singleton.
    AcceleratorState._reset_state()
    PartialState._reset_state()







class 					_lowerCAmelCase  (	unittest.TestCase   ):







 """simple docstring"""







 def 					_lowercase (			self							:			Optional[int],					UpperCAmelCase__							:			Union[mock.Mock, List[mock.Mock]]	):
    __lowercase								=						mocks if isinstance(UpperCAmelCase__,					(tuple, list)	) else [mocks]
    for m in self.mocks:
       m.start()
       self.addCleanup(m.stop	)







def   _A  (  UpperCamelCase_     :       int)	->						int:
   '''simple docstring'''


   __lowercase								=						AcceleratorState()
   __lowercase								=						tensor[None].clone().to(state.device)
   __lowercase								=						gather(UpperCamelCase_).cpu()
   __lowercase								=						tensor[0].cpu()
   for i in range(tensors.shape[0]):
      if not torch.equal(tensors[i],			UpperCamelCase_):
         return False
   return True




class 					_lowerCAmelCase  :







 """simple docstring"""







 def __init__(			self							:			Union[str, Any],					UpperCAmelCase__							:			List[Any],					UpperCAmelCase__							:			List[str],					UpperCAmelCase__							:			Tuple	):
    __lowercase								=						returncode
    __lowercase								=						stdout
    __lowercase								=						stderr







async def   _A  (  UpperCamelCase_     :       int,			UpperCamelCase_     :       List[str])	->						Any:
   '''simple docstring'''


   while True:
      __lowercase								=						await stream.readline()
      if line:
         callback(UpperCamelCase_)
      else:
         break




async def   _A  (  UpperCamelCase_     :       Optional[int],			UpperCamelCase_     :       List[str]=None,			UpperCamelCase_     :       Optional[Any]=None,			UpperCamelCase_     :       List[str]=None,			UpperCamelCase_     :       Dict=False,			UpperCamelCase_     :       int=False)	->						_RunOutput:
   '''simple docstring'''


   if echo:
      print("\nRunning: ",			" ".join(UpperCamelCase_))

   __lowercase								=						await asyncio.create_subprocess_exec(
       cmd[0],			*cmd[1:],			stdin=UpperCamelCase_,			stdout=asyncio.subprocess.PIPE,			stderr=asyncio.subprocess.PIPE,			env=UpperCamelCase_,			)

   # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
   # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
   #
   # If it starts hanging, will need to switch to the following code. The problem is that no data
   # will be seen until it's done and if it hangs for example there will be no debug info.
   # out, err = await p.communicate()
   # return _RunOutput(p.returncode, out, err)

   __lowercase								=						[]
   __lowercase								=						[]

   def tee(UpperCamelCase_     :       Any,			UpperCamelCase_     :       List[Any],			UpperCamelCase_     :       Dict,			UpperCamelCase_     :       int=""):
      __lowercase								=						line.decode("utf-8").rstrip()
      sink.append(UpperCamelCase_)
      if not quiet:
         print(UpperCamelCase_,			UpperCamelCase_,			file=UpperCamelCase_)

    # XXX: the timeout doesn't seem to make any difference here
   await asyncio.wait(
       [
           asyncio.create_task(_read_stream(p.stdout,			lambda UpperCamelCase_: tee(UpperCamelCase_,			UpperCamelCase_,			sys.stdout,			label="stdout:"))),
           asyncio.create_task(_read_stream(p.stderr,			lambda UpperCamelCase_: tee(UpperCamelCase_,			UpperCamelCase_,			sys.stderr,			label="stderr:"))),
       ],			timeout=UpperCamelCase_,			)
   return _RunOutput(await p.wait(),			UpperCamelCase_,			UpperCamelCase_)




def   _A  (  UpperCamelCase_     :       str,			UpperCamelCase_     :       Optional[Any]=None,			UpperCamelCase_     :       Dict=None,			UpperCamelCase_     :       str=180,			UpperCamelCase_     :       Optional[int]=False,			UpperCamelCase_     :       int=True)	->						_RunOutput:
   '''simple docstring'''


   __lowercase								=						asyncio.get_event_loop()
   __lowercase								=						loop.run_until_complete(
       _stream_subprocess(UpperCamelCase_,			env=UpperCamelCase_,			stdin=UpperCamelCase_,			timeout=UpperCamelCase_,			quiet=UpperCamelCase_,			echo=UpperCamelCase_))

   __lowercase								=						" ".join(UpperCamelCase_)
   if result.returncode > 0:
      __lowercase								=						"\n".join(result.stderr)
      raise RuntimeError(
          F"""'{cmd_str}' failed with returncode {result.returncode}\n\n"""
          F"""The combined stderr from workers follows:\n{stderr}""")

   return result




class 					_lowerCAmelCase  (	lowercase   ):







 """simple docstring"""







 pass







def   _A  (  UpperCamelCase_     :       List[str],			UpperCamelCase_     :       Optional[int]=False)	->						Union[str, Any]:
   '''simple docstring'''


   try:
      __lowercase								=						subprocess.check_output(UpperCamelCase_,			stderr=subprocess.STDOUT)
      if return_stdout:
         if hasattr(UpperCamelCase_,			"decode"):
            __lowercase								=						output.decode("utf-8")
         return output
   except subprocess.CalledProcessError as e:
      raise SubprocessCallException(
          F"""Command `{" ".join(UpperCamelCase_)}` failed with the following error:\n\n{e.output.decode()}""") from e







"""simple docstring"""





from __future__ import annotations

from typing import Any




class 					_lowerCAmelCase  :







 """simple docstring"""







 def __init__(			self							:			Any,					UpperCAmelCase__							:			int	):
    __lowercase								=						num_of_nodes
    __lowercase								=						[]
    __lowercase								=						{}


 def 					_lowercase (			self							:			Optional[Any],					UpperCAmelCase__							:			int,					UpperCAmelCase__							:			int,					UpperCAmelCase__							:			int	):
    self.m_edges.append([u_node, v_node, weight]	)


 def 					_lowercase (			self							:			Union[str, Any],					UpperCAmelCase__							:			int	):

    if self.m_component[u_node] == u_node:
       return u_node
    return self.find_component(self.m_component[u_node]	)


 def 					_lowercase (			self							:			List[Any],					UpperCAmelCase__							:			int	):

    if self.m_component[u_node] != u_node:
       for k in self.m_component:
          __lowercase								=						self.find_component(UpperCAmelCase__	)


 def 					_lowercase (			self							:			Union[str, Any],					UpperCAmelCase__							:			list[int],					UpperCAmelCase__							:			int,					UpperCAmelCase__							:			int	):

    if component_size[u_node] <= component_size[v_node]:
       __lowercase								=						v_node
       component_size[v_node] += component_size[u_node]
       self.set_component(UpperCAmelCase__	)

    elif component_size[u_node] >= component_size[v_node]:
       __lowercase								=						self.find_component(UpperCAmelCase__	)
       component_size[u_node] += component_size[v_node]
       self.set_component(UpperCAmelCase__	)



 def 					_lowercase (			self							:			Any	):
    __lowercase								=						[]
    __lowercase								=						0

    __lowercase								=						[-1] * self.m_num_of_nodes

    # A list of components (initialized to all of the nodes)
    for node in range(self.m_num_of_nodes	):
       self.m_component.update({node: node}	)
       component_size.append(1	)

    __lowercase								=						self.m_num_of_nodes

    while num_of_components > 1:
       for edge in self.m_edges:
          __lowercase		,__lowercase		,__lowercase								=						edge

          __lowercase								=						self.m_component[u]
          __lowercase								=						self.m_component[v]

          if u_component != v_component:

             for component in (u_component, v_component):
                if (
                    minimum_weight_edge[component] == -1
                    or minimum_weight_edge[component][2] > w
                ):
                   __lowercase								=						[u, v, w]

       for edge in minimum_weight_edge:
          if isinstance(UpperCAmelCase__,					UpperCAmelCase__	):
             __lowercase		,__lowercase		,__lowercase								=						edge

             __lowercase								=						self.m_component[u]
             __lowercase								=						self.m_component[v]

             if u_component != v_component:
                mst_weight += w
                self.union(UpperCAmelCase__,					UpperCAmelCase__,					UpperCAmelCase__	)
                print(F"""Added edge [{u} - {v}]\nAdded weight: {w}\n"""	)
                num_of_components -= 1

       __lowercase								=						[-1] * self.m_num_of_nodes
    print(F"""The total weight of the minimal spanning tree is: {mst_weight}"""	)







def   _A  (  )	->						None:
   '''simple docstring'''




if __name__ == "__main__":
   import doctest

   doctest.testmod()




