





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       SCREAMING_SNAKE_CASE__  (       _lowercase     : Optional[Any]   ,    _lowercase     : Tuple=False			)   ->							Dict:




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


__UpperCamelCase:	List[Any] = parse_flag_from_env("""RUN_SLOW""", default=False)


def       SCREAMING_SNAKE_CASE__  (       _lowercase     : Tuple			)   ->							Union[str, Any]:




		'''simple docstring'''
		return unittest.skip('Test was skipped'			)(_lowercase			)


def       SCREAMING_SNAKE_CASE__  (       _lowercase     : Dict			)   ->							Optional[Any]:




		'''simple docstring'''
		return unittest.skipUnless(_run_slow_tests   ,    'test is slow'			)(_lowercase			)


def       SCREAMING_SNAKE_CASE__  (       _lowercase     : Dict			)   ->							Optional[Any]:




		'''simple docstring'''
		return unittest.skipUnless(not torch.cuda.is_available()   ,    'test requires only a CPU'			)(_lowercase			)


def       SCREAMING_SNAKE_CASE__  (       _lowercase     : Any			)   ->							Tuple:




		'''simple docstring'''
		return unittest.skipUnless(torch.cuda.is_available()   ,    'test requires a GPU'			)(_lowercase			)


def       SCREAMING_SNAKE_CASE__  (       _lowercase     : str			)   ->							str:




		'''simple docstring'''
		return unittest.skipUnless(is_xpu_available()   ,    'test requires a XPU'			)(_lowercase			)


def       SCREAMING_SNAKE_CASE__  (       _lowercase     : int			)   ->							List[Any]:




		'''simple docstring'''
		return unittest.skipUnless(is_mps_available()   ,    'test requires a `mps` backend support in `torch`'			)(_lowercase			)


def       SCREAMING_SNAKE_CASE__  (       _lowercase     : Any			)   ->							List[str]:




		'''simple docstring'''
		return unittest.skipUnless(
		    is_transformers_available() and is_datasets_available()   ,    'test requires the Hugging Face suite'			)(_lowercase			)


def       SCREAMING_SNAKE_CASE__  (       _lowercase     : List[Any]			)   ->							Any:




		'''simple docstring'''
		return unittest.skipUnless(is_bnb_available()   ,    'test requires the bitsandbytes library'			)(_lowercase			)


def       SCREAMING_SNAKE_CASE__  (       _lowercase     : List[Any]			)   ->							Dict:




		'''simple docstring'''
		return unittest.skipUnless(is_tpu_available()   ,    'test requires TPU'			)(_lowercase			)


def       SCREAMING_SNAKE_CASE__  (       _lowercase     : Tuple			)   ->							Tuple:




		'''simple docstring'''
		return unittest.skipUnless(torch.cuda.device_count() == 1   ,    'test requires a GPU'			)(_lowercase			)


def       SCREAMING_SNAKE_CASE__  (       _lowercase     : str			)   ->							Optional[int]:




		'''simple docstring'''
		return unittest.skipUnless(torch.xpu.device_count() == 1   ,    'test requires a XPU'			)(_lowercase			)


def       SCREAMING_SNAKE_CASE__  (       _lowercase     : str			)   ->							Union[str, Any]:




		'''simple docstring'''
		return unittest.skipUnless(torch.cuda.device_count() > 1   ,    'test requires multiple GPUs'			)(_lowercase			)


def       SCREAMING_SNAKE_CASE__  (       _lowercase     : Any			)   ->							List[Any]:




		'''simple docstring'''
		return unittest.skipUnless(torch.xpu.device_count() > 1   ,    'test requires multiple XPUs'			)(_lowercase			)


def       SCREAMING_SNAKE_CASE__  (       _lowercase     : int			)   ->							Any:




		'''simple docstring'''
		return unittest.skipUnless(is_safetensors_available()   ,    'test requires safetensors'			)(_lowercase			)


def       SCREAMING_SNAKE_CASE__  (       _lowercase     : Optional[int]			)   ->							Optional[Any]:




		'''simple docstring'''
		return unittest.skipUnless(is_deepspeed_available()   ,    'test requires DeepSpeed'			)(_lowercase			)


def       SCREAMING_SNAKE_CASE__  (       _lowercase     : str			)   ->							str:




		'''simple docstring'''
		return unittest.skipUnless(is_torch_version('>='   ,    '1.12.0'			)   ,    'test requires torch version >= 1.12.0'			)(_lowercase			)


def       SCREAMING_SNAKE_CASE__  (       _lowercase     : List[Any]=None   ,    _lowercase     : Tuple=None			)   ->							List[Any]:




		'''simple docstring'''
		if test_case is None:
				return partial(_lowercase   ,    version=_lowercase			)
		return unittest.skipUnless(is_torch_version('>='   ,    _lowercase			)   ,    f"""test requires torch version >= {version}"""			)(_lowercase			)


def       SCREAMING_SNAKE_CASE__  (       _lowercase     : List[Any]			)   ->							Optional[int]:




		'''simple docstring'''
		return unittest.skipUnless(is_tensorboard_available()   ,    'test requires Tensorboard'			)(_lowercase			)


def       SCREAMING_SNAKE_CASE__  (       _lowercase     : List[str]			)   ->							Union[str, Any]:




		'''simple docstring'''
		return unittest.skipUnless(is_wandb_available()   ,    'test requires wandb'			)(_lowercase			)


def       SCREAMING_SNAKE_CASE__  (       _lowercase     : Optional[int]			)   ->							Optional[Any]:




		'''simple docstring'''
		return unittest.skipUnless(is_comet_ml_available()   ,    'test requires comet_ml'			)(_lowercase			)


__UpperCamelCase:	str = (
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)


def       SCREAMING_SNAKE_CASE__  (       _lowercase     : Dict			)   ->							List[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'   ,    )(_lowercase			)


class       __lowerCAmelCase					(       unittest.TestCase      ):


	'''simple docstring'''





	_A													=				True

	@classmethod
	def    snake_case__(						cls:						Optional[int]			):
			lowercase__					:      Dict      =		tempfile.mkdtemp()

	@classmethod
	def    snake_case__(						cls:						Dict			):
			if os.path.exists(cls.tmpdir			):
					shutil.rmtree(cls.tmpdir			)





	def    snake_case__(						self:						Tuple			):
			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       __lowerCAmelCase					(       unittest.TestCase      ):


	'''simple docstring'''





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


class       __lowerCAmelCase					(       unittest.TestCase      ):


	'''simple docstring'''





	def    snake_case__(						self:						List[Any],					lowerCamelCase_:						Union[mock.Mock, List[mock.Mock]]			):
			lowercase__					:      Any      =		mocks if isinstance(lowerCamelCase_,					(tuple, list)			) else [mocks]
			for m in self.mocks:
					m.start()
					self.addCleanup(m.stop			)


def       SCREAMING_SNAKE_CASE__  (       _lowercase     : List[str]			)   ->							Any:




		'''simple docstring'''
		lowercase__					:      Dict      =		AcceleratorState()
		lowercase__					:      List[Any]      =		tensor[None].clone().to(state.device			)
		lowercase__					:      Tuple      =		gather(_lowercase			).cpu()
		lowercase__					:      Dict      =		tensor[0].cpu()
		for i in range(tensors.shape[0]			):
				if not torch.equal(tensors[i]   ,    _lowercase			):
						return False
		return True


class       __lowerCAmelCase					:


	'''simple docstring'''





	def __init__(						self:						List[str],					lowerCamelCase_:						str,					lowerCamelCase_:						Optional[Any],					lowerCamelCase_:						Optional[int]			):
			lowercase__					:      int      =		returncode
			lowercase__					:      Optional[Any]      =		stdout
			lowercase__					:      Optional[Any]      =		stderr


async def       SCREAMING_SNAKE_CASE__  (       _lowercase     : Any   ,    _lowercase     : Any			)   ->							int:




		'''simple docstring'''
		while True:
				lowercase__					:      Any      =		await stream.readline()
				if line:
						callback(_lowercase			)
				else:
						break


async def       SCREAMING_SNAKE_CASE__  (       _lowercase     : List[str]   ,    _lowercase     : List[str]=None   ,    _lowercase     : Union[str, Any]=None   ,    _lowercase     : Optional[int]=None   ,    _lowercase     : Optional[int]=False   ,    _lowercase     : int=False			)   ->							_RunOutput:




		'''simple docstring'''
		if echo:
				print('\nRunning: '   ,    ' '.join(_lowercase			)			)

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

		# 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__					:      Union[str, Any]      =		[]
		lowercase__					:      Union[str, Any]      =		[]

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

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


def       SCREAMING_SNAKE_CASE__  (       _lowercase     : str   ,    _lowercase     : List[str]=None   ,    _lowercase     : Optional[Any]=None   ,    _lowercase     : int=180   ,    _lowercase     : Optional[Any]=False   ,    _lowercase     : List[Any]=True			)   ->							_RunOutput:




		'''simple docstring'''
		lowercase__					:      Optional[Any]      =		asyncio.get_event_loop()
		lowercase__					:      List[str]      =		loop.run_until_complete(
		    _stream_subprocess(_lowercase   ,    env=_lowercase   ,    stdin=_lowercase   ,    timeout=_lowercase   ,    quiet=_lowercase   ,    echo=_lowercase			)			)

		lowercase__					:      Any      =		' '.join(_lowercase			)
		if result.returncode > 0:
				lowercase__					:      Optional[Any]      =		'\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					(       _UpperCamelCase      ):


	'''simple docstring'''





	pass


def       SCREAMING_SNAKE_CASE__  (       _lowercase     : List[str]   ,    _lowercase     : Optional[Any]=False			)   ->							Union[str, Any]:




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









import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.metrics import mean_absolute_error, mean_squared_error
from sklearn.model_selection import train_test_split
from xgboost import XGBRegressor


def       SCREAMING_SNAKE_CASE__  (       _lowercase     : dict			)   ->							tuple:




		'''simple docstring'''
		return (data["data"], data["target"])


def       SCREAMING_SNAKE_CASE__  (       _lowercase     : np.ndarray   ,    _lowercase     : np.ndarray   ,    _lowercase     : np.ndarray			)   ->							np.ndarray:




		'''simple docstring'''
		lowercase__					:      List[str]      =		XGBRegressor(verbosity=0   ,    random_state=42			)
		xgb.fit(_lowercase   ,    _lowercase			)
		# Predict target for test data
		lowercase__					:      Union[str, Any]      =		xgb.predict(_lowercase			)
		lowercase__					:      Tuple      =		predictions.reshape(len(_lowercase			)   ,    1			)
		return predictions


def       SCREAMING_SNAKE_CASE__  (       )   ->							None:




		'''simple docstring'''
		lowercase__					:      List[str]      =		fetch_california_housing()
		lowercase__   ,				lowercase__					:      Optional[int]      =		data_handling(_lowercase			)
		lowercase__   ,				lowercase__   ,				lowercase__   ,				lowercase__					:      Optional[Any]      =		train_test_split(
		    _lowercase   ,    _lowercase   ,    test_size=0.25   ,    random_state=1			)
		lowercase__					:      Any      =		xgboost(_lowercase   ,    _lowercase   ,    _lowercase			)
		# Error printing
		print(f"""Mean Absolute Error : {mean_absolute_error(_lowercase   ,    _lowercase			)}"""			)
		print(f"""Mean Square Error  : {mean_squared_error(_lowercase   ,    _lowercase			)}"""			)


if __name__ == "__main__":
			import doctest

			doctest.testmod(verbose=True)
			main()


