


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     __lowerCamelCase						(			UpperCAmelCase_						:		List[str]			,  UpperCAmelCase_						:		Dict=False						):




      """simple docstring"""





      try:
            a						:Union[str, Any]										=	os.environ[key]
      except KeyError:
            # KEY isn't set, default to `default`.
            a						:Optional[int]										=	default
      else:
            # KEY is set, convert it to True or False.
            try:
                  a						:List[str]										=	strtobool(lowerCamelCase__						)
            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


snake_case    :   List[Any]	    =					parse_flag_from_env('''RUN_SLOW''', default=False)
def     __lowerCamelCase						(			UpperCAmelCase_						:		Optional[int]						):




      """simple docstring"""





      return unittest.skip('''Test was skipped'''						)(lowerCamelCase__						)
def     __lowerCamelCase						(			UpperCAmelCase_						:		Dict						):




      """simple docstring"""





      return unittest.skipUnless(_run_slow_tests			,  '''test is slow'''						)(lowerCamelCase__						)
def     __lowerCamelCase						(			UpperCAmelCase_						:		Any						):




      """simple docstring"""





      return unittest.skipUnless(not torch.cuda.is_available()			,  '''test requires only a CPU'''						)(lowerCamelCase__						)
def     __lowerCamelCase						(			UpperCAmelCase_						:		int						):




      """simple docstring"""





      return unittest.skipUnless(torch.cuda.is_available()			,  '''test requires a GPU'''						)(lowerCamelCase__						)
def     __lowerCamelCase						(			UpperCAmelCase_						:		Optional[Any]						):




      """simple docstring"""





      return unittest.skipUnless(is_xpu_available()			,  '''test requires a XPU'''						)(lowerCamelCase__						)
def     __lowerCamelCase						(			UpperCAmelCase_						:		int						):




      """simple docstring"""





      return unittest.skipUnless(is_mps_available()			,  '''test requires a `mps` backend support in `torch`'''						)(lowerCamelCase__						)
def     __lowerCamelCase						(			UpperCAmelCase_						:		Union[str, Any]						):




      """simple docstring"""





      return unittest.skipUnless(
          is_transformers_available() and is_datasets_available()			,  '''test requires the Hugging Face suite'''						)(lowerCamelCase__						)
def     __lowerCamelCase						(			UpperCAmelCase_						:		Dict						):




      """simple docstring"""





      return unittest.skipUnless(is_bnb_available()			,  '''test requires the bitsandbytes library'''						)(lowerCamelCase__						)
def     __lowerCamelCase						(			UpperCAmelCase_						:		Any						):




      """simple docstring"""





      return unittest.skipUnless(is_tpu_available()			,  '''test requires TPU'''						)(lowerCamelCase__						)
def     __lowerCamelCase						(			UpperCAmelCase_						:		Optional[Any]						):




      """simple docstring"""





      return unittest.skipUnless(torch.cuda.device_count() == 1			,  '''test requires a GPU'''						)(lowerCamelCase__						)
def     __lowerCamelCase						(			UpperCAmelCase_						:		int						):




      """simple docstring"""





      return unittest.skipUnless(torch.xpu.device_count() == 1			,  '''test requires a XPU'''						)(lowerCamelCase__						)
def     __lowerCamelCase						(			UpperCAmelCase_						:		Any						):




      """simple docstring"""





      return unittest.skipUnless(torch.cuda.device_count() > 1			,  '''test requires multiple GPUs'''						)(lowerCamelCase__						)
def     __lowerCamelCase						(			UpperCAmelCase_						:		Optional[int]						):




      """simple docstring"""





      return unittest.skipUnless(torch.xpu.device_count() > 1			,  '''test requires multiple XPUs'''						)(lowerCamelCase__						)
def     __lowerCamelCase						(			UpperCAmelCase_						:		Dict						):




      """simple docstring"""





      return unittest.skipUnless(is_safetensors_available()			,  '''test requires safetensors'''						)(lowerCamelCase__						)
def     __lowerCamelCase						(			UpperCAmelCase_						:		List[str]						):




      """simple docstring"""





      return unittest.skipUnless(is_deepspeed_available()			,  '''test requires DeepSpeed'''						)(lowerCamelCase__						)
def     __lowerCamelCase						(			UpperCAmelCase_						:		Union[str, Any]						):




      """simple docstring"""





      return unittest.skipUnless(is_torch_version('''>='''			,  '''1.12.0'''						)			,  '''test requires torch version >= 1.12.0'''						)(lowerCamelCase__						)
def     __lowerCamelCase						(			UpperCAmelCase_						:		List[Any]=None			,  UpperCAmelCase_						:		int=None						):




      """simple docstring"""





      if test_case is None:
            return partial(lowerCamelCase__			,  version=lowerCamelCase__						)
      return unittest.skipUnless(is_torch_version('''>='''			,  lowerCamelCase__						)			,  F'''test requires torch version >= {version}'''						)(lowerCamelCase__						)
def     __lowerCamelCase						(			UpperCAmelCase_						:		List[str]						):




      """simple docstring"""





      return unittest.skipUnless(is_tensorboard_available()			,  '''test requires Tensorboard'''						)(lowerCamelCase__						)
def     __lowerCamelCase						(			UpperCAmelCase_						:		Optional[Any]						):




      """simple docstring"""





      return unittest.skipUnless(is_wandb_available()			,  '''test requires wandb'''						)(lowerCamelCase__						)
def     __lowerCamelCase						(			UpperCAmelCase_						:		Optional[int]						):




      """simple docstring"""





      return unittest.skipUnless(is_comet_ml_available()			,  '''test requires comet_ml'''						)(lowerCamelCase__						)


snake_case    :   Optional[int]	    =					(
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)
def     __lowerCamelCase						(			UpperCAmelCase_						:		List[Any]						):




      """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'''			,  )(lowerCamelCase__						)







class 		_snake_case  (				unittest.TestCase							):
 SCREAMING_SNAKE_CASE__				=	True




 @classmethod
 def 	SCREAMING_SNAKE_CASE__    (		cls   ):
       a						:int										=	tempfile.mkdtemp()




 @classmethod
 def 	SCREAMING_SNAKE_CASE__    (		cls   ):







       if os.path.exists(cls.tmpdir   ):
             shutil.rmtree(cls.tmpdir   )




 def 	SCREAMING_SNAKE_CASE__    (		self   ):







       if self.clear_on_setup:
             for path in Path(self.tmpdir   ).glob('''**/*'''   ):
                   if path.is_file():
                         path.unlink()
                   elif path.is_dir():
                         shutil.rmtree(_lowerCamelCase   )







class 		_snake_case  (				unittest.TestCase							):




 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       super().tearDown()
       # Reset the state of the AcceleratorState singleton.
       AcceleratorState._reset_state()
       PartialState._reset_state()







class 		_snake_case  (				unittest.TestCase							):




 def 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase   ):
       a						:List[Any]										=	mocks if isinstance(_lowerCamelCase ,  (tuple, list)   ) else [mocks]
       for m in self.mocks:
             m.start()
             self.addCleanup(m.stop   )







def     __lowerCamelCase						(			UpperCAmelCase_						:		Optional[Any]						):




      """simple docstring"""





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







class 		_snake_case  :




 def __init__(		self ,  _lowerCamelCase ,  _lowerCamelCase ,  _lowerCamelCase   ):
       a						:Any										=	returncode
       a						:str										=	stdout
       a						:Union[str, Any]										=	stderr







async def     __lowerCamelCase						(			UpperCAmelCase_						:		Dict			,  UpperCAmelCase_						:		List[Any]						):




      """simple docstring"""





      while True:
            a						:List[Any]										=	await stream.readline()
            if line:
                  callback(lowerCamelCase__						)
            else:
                  break
async def     __lowerCamelCase						(			UpperCAmelCase_						:		str			,  UpperCAmelCase_						:		Union[str, Any]=None			,  UpperCAmelCase_						:		Optional[int]=None			,  UpperCAmelCase_						:		Optional[Any]=None			,  UpperCAmelCase_						:		int=False			,  UpperCAmelCase_						:		str=False						):




      """simple docstring"""





      if echo:
            print('''\nRunning: '''			,  ''' '''.join(lowerCamelCase__						)						)

      a						:Union[str, Any]										=	await asyncio.create_subprocess_exec(
          cmd[0]			,  *cmd[1:]			,  stdin=lowerCamelCase__			,  stdout=asyncio.subprocess.PIPE			,  stderr=asyncio.subprocess.PIPE			,  env=lowerCamelCase__			,  )

      # 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)

      a						:Union[str, Any]										=	[]
      a						:str										=	[]

      def tee(UpperCAmelCase_						:		Optional[int]			,  UpperCAmelCase_						:		Optional[Any]			,  UpperCAmelCase_						:		int			,  UpperCAmelCase_						:		Union[str, Any]=""						):
            a						:int										=	line.decode('''utf-8'''						).rstrip()
            sink.append(lowerCamelCase__						)
            if not quiet:
                  print(lowerCamelCase__			,  lowerCamelCase__			,  file=lowerCamelCase__						)

    # XXX: the timeout doesn't seem to make any difference here
      await asyncio.wait(
          [
              asyncio.create_task(_read_stream(p.stdout			,  lambda UpperCAmelCase_						: tee(lowerCamelCase__			,  lowerCamelCase__			,  sys.stdout			,  label='''stdout:'''						)						)						),
              asyncio.create_task(_read_stream(p.stderr			,  lambda UpperCAmelCase_						: tee(lowerCamelCase__			,  lowerCamelCase__			,  sys.stderr			,  label='''stderr:'''						)						)						),
          ]			,  timeout=lowerCamelCase__			,  )
      return _RunOutput(await p.wait()			,  lowerCamelCase__			,  lowerCamelCase__						)
def     __lowerCamelCase						(			UpperCAmelCase_						:		Dict			,  UpperCAmelCase_						:		List[str]=None			,  UpperCAmelCase_						:		Optional[int]=None			,  UpperCAmelCase_						:		str=180			,  UpperCAmelCase_						:		Union[str, Any]=False			,  UpperCAmelCase_						:		List[str]=True						):




      """simple docstring"""





      a						:str										=	asyncio.get_event_loop()
      a						:Dict										=	loop.run_until_complete(
          _stream_subprocess(lowerCamelCase__			,  env=lowerCamelCase__			,  stdin=lowerCamelCase__			,  timeout=lowerCamelCase__			,  quiet=lowerCamelCase__			,  echo=lowerCamelCase__						)						)

      a						:Optional[int]										=	''' '''.join(lowerCamelCase__						)
      if result.returncode > 0:
            a						:Tuple										=	'''\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 		_snake_case  (				a__							):
 pass







def     __lowerCamelCase						(			UpperCAmelCase_						:		List[str]			,  UpperCAmelCase_						:		Optional[Any]=False						):




      """simple docstring"""





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









import numpy as np
from matplotlib import pyplot as plt
from sklearn.datasets import load_iris
from sklearn.metrics import ConfusionMatrixDisplay
from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier
def     __lowerCamelCase						(			UpperCAmelCase_						:		dict						):




      """simple docstring"""





      return (data["data"], data["target"])
def     __lowerCamelCase						(			UpperCAmelCase_						:		np.ndarray			,  UpperCAmelCase_						:		np.ndarray						):




      """simple docstring"""





      a						:Optional[Any]										=	XGBClassifier()
      classifier.fit(UpperCAmelCase_			,  UpperCAmelCase_						)
      return classifier
def     __lowerCamelCase						(			):




      """simple docstring"""





      a						:List[Any]										=	load_iris()
      a							,    a						:Any										=	data_handling(UpperCAmelCase_						)
      a							,    a							,    a							,    a						:Tuple										=	train_test_split(
          UpperCAmelCase_			,  UpperCAmelCase_			,  test_size=0.25						)

      a						:List[Any]										=	iris['''target_names''']

      # Create an XGBoost Classifier from the training data
      a						:Optional[int]										=	xgboost(UpperCAmelCase_			,  UpperCAmelCase_						)

      # Display the confusion matrix of the classifier with both training and test sets
      ConfusionMatrixDisplay.from_estimator(
          UpperCAmelCase_			,  UpperCAmelCase_			,  UpperCAmelCase_			,  display_labels=UpperCAmelCase_			,  cmap='''Blues'''			,  normalize='''true'''			,  )
      plt.title('''Normalized Confusion Matrix - IRIS Dataset'''						)
      plt.show()


if __name__ == "__main__":
     import doctest

     doctest.testmod(verbose=True)
     main()





