






"""simple docstring"""
import ast
import os
import re
import shutil
import tempfile
import unittest
from unittest import mock

import torch

from accelerate.test_utils.examples import compare_against_test
from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow
from accelerate.utils import write_basic_config


# DataLoaders built from `test_samples/MRPC` for quick testing
# Should mock `{script_name}.get_dataloaders` via:
# @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders)

_lowerCAmelCase       =				[
    "cross_validation.py",
    "gradient_accumulation.py",
    "local_sgd.py",
    "multi_process_metrics.py",
    "memory.py",
    "automatic_gradient_accumulation.py",
    "fsdp_with_peak_mem_tracking.py",
    "deepspeed_with_config_support.py",
    "megatron_lm_gpt_pretraining.py",
]



class   SCREAMING_SNAKE_CASE	(					unittest.TestCase    ):





	"""simple docstring"""




	def  lowerCamelCase(self  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  lowerCAmelCase_ = None  ,  lowerCAmelCase_ = None				):
		A_		:    List[str]						     = None
		A_		:    Union[str, Any]						     = os.path.abspath(os.path.join("""examples"""  ,  """by_feature"""				)				)
		A_		:    int						     = os.path.abspath("""examples"""				)
		for item in os.listdir(lowerCAmelCase_				):
			if item not in EXCLUDE_EXAMPLES:
				A_		:    Union[str, Any]						     = os.path.join(lowerCAmelCase_  ,  lowerCAmelCase_				)
				if os.path.isfile(lowerCAmelCase_				) and ".py" in item_path:
					with self.subTest(
					    tested_script=lowerCAmelCase_  ,  feature_script=lowerCAmelCase_  ,  tested_section="""main()""" if parser_only else """training_function()"""  ,  ):
						A_		:    Any						     = compare_against_test(
						    os.path.join(lowerCAmelCase_  ,  lowerCAmelCase_				)  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  lowerCAmelCase_				)
						A_		:    List[Any]						     = """\n""".join(lowerCAmelCase_				)
						if special_strings is not None:
							for string in special_strings:
								A_		:    Union[str, Any]						     = diff.replace(lowerCAmelCase_  ,  """"""				)
						self.assertEqual(lowerCAmelCase_  ,  """"""				)





	def  lowerCamelCase(self				):
		self.one_complete_example("""complete_nlp_example.py"""  ,  lowerCAmelCase_				)
		self.one_complete_example("""complete_nlp_example.py"""  ,  lowerCAmelCase_				)





	def  lowerCamelCase(self				):
		A_		:    Union[str, Any]						     = os.path.abspath(os.path.join("""examples"""  ,  """cv_example.py"""				)				)
		A_		:    Union[str, Any]						     = [
		    """ """ * 16 + """{\n\n""",
		    """ """ * 20 + """\"accuracy\": eval_metric[\"accuracy\"],\n\n""",
		    """ """ * 20 + """\"f1\": eval_metric[\"f1\"],\n\n""",
		    """ """ * 20 + """\"train_loss\": total_loss.item() / len(train_dataloader),\n\n""",
		    """ """ * 20 + """\"epoch\": epoch,\n\n""",
		    """ """ * 16 + """},\n\n""",
		    """ """ * 16 + """step=epoch,\n""",
		    """ """ * 12,
		    """ """ * 8 + """for step, batch in enumerate(active_dataloader):\n""",
		]
		self.one_complete_example("""complete_cv_example.py"""  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  lowerCAmelCase_				)
		self.one_complete_example("""complete_cv_example.py"""  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  lowerCAmelCase_				)






@mock.patch.dict(os.environ							,							{"""TESTING_MOCKED_DATALOADERS""": """1"""}    )
class   SCREAMING_SNAKE_CASE	(					_SCREAMING_SNAKE_CASE    ):





	"""simple docstring"""




	_A							:					int 			=					False





	@classmethod
	def  lowerCamelCase(cls				):
		super().setUpClass()
		A_		:    Union[str, Any]						     = tempfile.mkdtemp()
		A_		:    Any						     = os.path.join(cls._tmpdir  ,  """default_config.yml"""				)

		write_basic_config(save_location=cls.configPath				)
		A_		:    Tuple						     = ["""accelerate""", """launch""", """--config_file""", cls.configPath]





	@classmethod
	def  lowerCamelCase(cls				):
		super().tearDownClass()
		shutil.rmtree(cls._tmpdir				)





	def  lowerCamelCase(self				):
		A_		:    Union[str, Any]						     = f"""
        examples/by_feature/checkpointing.py
        --checkpointing_steps epoch
        --output_dir {self.tmpdir}
        """.split()
		run_command(self._launch_args + testargs				)
		self.assertTrue(os.path.exists(os.path.join(self.tmpdir  ,  """epoch_0"""				)				)				)





	def  lowerCamelCase(self				):
		A_		:    Dict						     = f"""
        examples/by_feature/checkpointing.py
        --checkpointing_steps 1
        --output_dir {self.tmpdir}
        """.split()
		A_		:    Any						     = run_command(self._launch_args + testargs				)
		self.assertTrue(os.path.exists(os.path.join(self.tmpdir  ,  """step_2"""				)				)				)





	def  lowerCamelCase(self				):
		A_		:    Any						     = f"""
        examples/by_feature/checkpointing.py
        --resume_from_checkpoint {os.path.join(self.tmpdir  ,  "epoch_0"				)}
        """.split()
		A_		:    str						     = run_command(self._launch_args + testargs  ,  return_stdout=lowerCAmelCase_				)
		self.assertNotIn("""epoch 0:"""  ,  lowerCAmelCase_				)
		self.assertIn("""epoch 1:"""  ,  lowerCAmelCase_				)





	def  lowerCamelCase(self				):
		A_		:    Optional[Any]						     = f"""
        examples/by_feature/checkpointing.py
        --resume_from_checkpoint {os.path.join(self.tmpdir  ,  "step_2"				)}
        """.split()
		A_		:    Optional[Any]						     = run_command(self._launch_args + testargs  ,  return_stdout=lowerCAmelCase_				)
		if torch.cuda.is_available():
			A_		:    Any						     = torch.cuda.device_count()
		else:
			A_		:    List[str]						     = 1
		if num_processes > 1:
			self.assertNotIn("""epoch 0:"""  ,  lowerCAmelCase_				)
			self.assertIn("""epoch 1:"""  ,  lowerCAmelCase_				)
		else:
			self.assertIn("""epoch 0:"""  ,  lowerCAmelCase_				)
			self.assertIn("""epoch 1:"""  ,  lowerCAmelCase_				)





	@slow
	def  lowerCamelCase(self				):
		A_		:    int						     = """
        examples/by_feature/cross_validation.py
        --num_folds 2
        """.split()
		with mock.patch.dict(os.environ  ,  {"""TESTING_MOCKED_DATALOADERS""": """0"""}				):
			A_		:    Optional[Any]						     = run_command(self._launch_args + testargs  ,  return_stdout=lowerCAmelCase_				)
			A_		:    str						     = re.findall("""({.+})"""  ,  lowerCAmelCase_				)
			A_		:    int						     = [r for r in results if """accuracy""" in r][-1]
			A_		:    Tuple						     = ast.literal_eval(lowerCAmelCase_				)
			self.assertGreaterEqual(results["""accuracy"""]  ,  0.75				)





	def  lowerCamelCase(self				):
		A_		:    Any						     = ["""examples/by_feature/multi_process_metrics.py"""]
		run_command(self._launch_args + testargs				)





	@require_trackers
	@mock.patch.dict(os.environ  ,  {"""WANDB_MODE""": """offline"""}				)
	def  lowerCamelCase(self				):
		with tempfile.TemporaryDirectory() as tmpdir:
			A_		:    Tuple						     = f"""
            examples/by_feature/tracking.py
            --with_tracking
            --project_dir {tmpdir}
            """.split()
			run_command(self._launch_args + testargs				)
			self.assertTrue(os.path.exists(os.path.join(lowerCAmelCase_  ,  """tracking"""				)				)				)





	def  lowerCamelCase(self				):
		A_		:    Dict						     = ["""examples/by_feature/gradient_accumulation.py"""]
		run_command(self._launch_args + testargs				)





	def  lowerCamelCase(self				):
		A_		:    List[Any]						     = ["""examples/by_feature/local_sgd.py"""]
		run_command(self._launch_args + testargs				)









"""simple docstring"""
import numpy as np






def       __UpperCamelCase						(		snake_case__ , snake_case__ , snake_case__ = 1E-12 , snake_case__ = 100 , ):
	assert np.shape(snake_case__       )[0] == np.shape(snake_case__       )[1]
	# Ensure proper dimensionality.
	assert np.shape(snake_case__       )[0] == np.shape(snake_case__       )[0]
	# Ensure inputs are either both complex or both real
	assert np.iscomplexobj(snake_case__       ) == np.iscomplexobj(snake_case__       )
	A_		:    Union[str, Any]						     = np.iscomplexobj(snake_case__       )
	if is_complex:
		# Ensure complex input_matrix is Hermitian
		assert np.array_equal(snake_case__ , input_matrix.conj().T       )

	# Set convergence to False. Will define convergence when we exceed max_iterations
	# or when we have small changes from one iteration to next.

	A_		:    List[str]						     = False
	A_		:    int						     = 0
	A_		:    List[Any]						     = 0
	A_		:    Tuple						     = 1E12

	while not convergence:
		# Multiple matrix by the vector.
		A_		:    Dict						     = np.dot(snake_case__ , snake_case__       )
		# Normalize the resulting output vector.
		A_		:    str						     = w / np.linalg.norm(snake_case__       )
		# Find rayleigh quotient
		# (faster than usual b/c we know vector is normalized already)
		A_		:    str						     = vector.conj().T if is_complex else vector.T
		A_		:    Optional[Any]						     = np.dot(snake_case__ , np.dot(snake_case__ , snake_case__       )       )

		# Check convergence.
		A_		:    Any						     = np.abs(lambda_ - lambda_previous       ) / lambda_
		iterations += 1

		if error <= error_tol or iterations >= max_iterations:
			A_		:    Optional[Any]						     = True

		A_		:    Union[str, Any]						     = lambda_

	if is_complex:
		A_		:    str						     = np.real(lambda_       )

	return lambda_, vector






def       __UpperCamelCase						(		):
	A_		:    Optional[int]						     = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]]       )
	A_		:    Tuple						     = np.array([41, 4, 20]       )
	A_		:    Tuple						     = real_input_matrix.astype(np.complexaaa       )
	A_		:    List[Any]						     = np.triu(1J * complex_input_matrix , 1       )
	complex_input_matrix += imag_matrix
	complex_input_matrix += -1 * imag_matrix.T
	A_		:    Any						     = np.array([41, 4, 20]       ).astype(np.complexaaa       )

	for problem_type in ["real", "complex"]:
		if problem_type == "real":
			A_		:    Optional[int]						     = real_input_matrix
			A_		:    List[str]						     = real_vector
		elif problem_type == "complex":
			A_		:    List[Any]						     = complex_input_matrix
			A_		:    str						     = complex_vector

		# Our implementation.
		A_     ,  A_		:    Dict						     = power_iteration(snake_case__ , snake_case__       )

		# Numpy implementation.

		# Get eigenvalues and eigenvectors using built-in numpy
		# eigh (eigh used for symmetric or hermetian matrices).
		A_     ,  A_		:    Optional[Any]						     = np.linalg.eigh(snake_case__       )
		# Last eigenvalue is the maximum one.
		A_		:    List[Any]						     = eigen_values[-1]
		# Last column in this matrix is eigenvector corresponding to largest eigenvalue.
		A_		:    Optional[Any]						     = eigen_vectors[:, -1]

		# Check our implementation and numpy gives close answers.
		assert np.abs(eigen_value - eigen_value_max       ) <= 1E-6
		# Take absolute values element wise of each eigenvector.
		# as they are only unique to a minus sign.
		assert np.linalg.norm(np.abs(snake_case__       ) - np.abs(snake_case__       )       ) <= 1E-6


if __name__ == "__main__":
							import doctest

							doctest.testmod()
							test_power_iteration()

