'''simple docstring'''


from ...configuration_utils import PretrainedConfig
from ...utils import logging


__lowerCAmelCase	:       Tuple						       =	logging.get_logger(__name__)

__lowerCAmelCase	:       Any						       =	{
    "caidas/swin2sr-classicalsr-x2-64": (
        "https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json"
    ),
}






class 						A   (   UpperCAmelCase   ):
							a_        =      '''swin2sr'''

							a_        =      {
							    '''hidden_size''': '''embed_dim''',
							    '''num_attention_heads''': '''num_heads''',
							    '''num_hidden_layers''': '''num_layers''',
							}





							def __init__(      self				:							int     ,		__a				:							str=6_4     ,		__a				:							Optional[int]=1     ,		__a				:							List[str]=3     ,		__a				:							Optional[Any]=1_8_0     ,		__a				:							Optional[int]=[6, 6, 6, 6, 6, 6]     ,		__a				:							Dict=[6, 6, 6, 6, 6, 6]     ,		__a				:							Optional[Any]=8     ,		__a				:							Dict=2.0     ,		__a				:							str=True     ,		__a				:							Any=0.0     ,		__a				:							Any=0.0     ,		__a				:							Union[str, Any]=0.1     ,		__a				:							List[Any]="gelu"     ,		__a				:							int=False     ,		__a				:							Dict=0.0_2     ,		__a				:							Union[str, Any]=1e-5     ,		__a				:							int=2     ,		__a				:							Optional[Any]=1.0     ,		__a				:							Optional[Any]="1conv"     ,		__a				:							int="pixelshuffle"     ,		**__a				:							List[Any]     ,		)							->	Any:
								super().__init__(**__a	)

								__UpperCAmelCase							=			image_size
								__UpperCAmelCase							=			patch_size
								__UpperCAmelCase							=			num_channels
								__UpperCAmelCase							=			embed_dim
								__UpperCAmelCase							=			depths
								__UpperCAmelCase							=			len(__a	)
								__UpperCAmelCase							=			num_heads
								__UpperCAmelCase							=			window_size
								__UpperCAmelCase							=			mlp_ratio
								__UpperCAmelCase							=			qkv_bias
								__UpperCAmelCase							=			hidden_dropout_prob
								__UpperCAmelCase							=			attention_probs_dropout_prob
								__UpperCAmelCase							=			drop_path_rate
								__UpperCAmelCase							=			hidden_act
								__UpperCAmelCase							=			use_absolute_embeddings
								__UpperCAmelCase							=			layer_norm_eps
								__UpperCAmelCase							=			initializer_range
								__UpperCAmelCase							=			upscale
								__UpperCAmelCase							=			img_range
								__UpperCAmelCase							=			resi_connection
								__UpperCAmelCase							=			upsampler

'''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	:       Optional[int]						       =	[
    "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 						A   (   unittest.TestCase   ):





							def       snake_case__						(      self				:							Any     ,		__a				:							str     ,		__a				:							bool     ,		__a				:							str = None     ,		__a				:							list = None	)							->	Tuple:
								__UpperCAmelCase							=			None
								__UpperCAmelCase							=			os.path.abspath(os.path.join('''examples'''     ,		'''by_feature'''	)	)
								__UpperCAmelCase							=			os.path.abspath('''examples'''	)
								for item in os.listdir(__a	):
									if item not in EXCLUDE_EXAMPLES:
										__UpperCAmelCase							=			os.path.join(__a     ,		__a	)
										if os.path.isfile(__a	) and ".py" in item_path:
											with self.subTest(
											    tested_script=__a     ,		feature_script=__a     ,		tested_section='''main()''' if parser_only else '''training_function()'''     ,		):
												__UpperCAmelCase							=			compare_against_test(
												    os.path.join(__a     ,		__a	)     ,		__a     ,		__a     ,		__a	)
												__UpperCAmelCase							=			'''\n'''.join(__a	)
												if special_strings is not None:
													for string in special_strings:
														__UpperCAmelCase							=			diff.replace(__a     ,		''''''	)
												self.assertEqual(__a     ,		''''''	)





							def       snake_case__						(      self				:							Optional[Any]	)							->	str:
								self.one_complete_example('''complete_nlp_example.py'''     ,		__a	)
								self.one_complete_example('''complete_nlp_example.py'''     ,		__a	)






							def       snake_case__						(      self				:							List[str]	)							->	Tuple:
								__UpperCAmelCase							=			os.path.abspath(os.path.join('''examples'''     ,		'''cv_example.py'''	)	)
								__UpperCAmelCase							=			[
								    ''' ''' * 1_6 + '''{\n\n''',
								    ''' ''' * 2_0 + '''"accuracy": eval_metric["accuracy"],\n\n''',
								    ''' ''' * 2_0 + '''"f1": eval_metric["f1"],\n\n''',
								    ''' ''' * 2_0 + '''"train_loss": total_loss.item() / len(train_dataloader),\n\n''',
								    ''' ''' * 2_0 + '''"epoch": epoch,\n\n''',
								    ''' ''' * 1_6 + '''},\n\n''',
								    ''' ''' * 1_6 + '''step=epoch,\n''',
								    ''' ''' * 1_2,
								    ''' ''' * 8 + '''for step, batch in enumerate(active_dataloader):\n''',
								]
								self.one_complete_example('''complete_cv_example.py'''     ,		__a     ,		__a     ,		__a	)
								self.one_complete_example('''complete_cv_example.py'''     ,		__a     ,		__a     ,		__a	)






@mock.patch.dict(os.environ       ,	{'''TESTING_MOCKED_DATALOADERS''': '''1'''}   )
class 						A   (   UpperCAmelCase   ):
							a_        =      False





							@classmethod
							def       snake_case__						(      cls				:							Tuple	)							->	str:
								super().setUpClass()
								__UpperCAmelCase							=			tempfile.mkdtemp()
								__UpperCAmelCase							=			os.path.join(cls._tmpdir     ,		'''default_config.yml'''	)

								write_basic_config(save_location=cls.configPath	)
								__UpperCAmelCase							=			['''accelerate''', '''launch''', '''--config_file''', cls.configPath]





							@classmethod
							def       snake_case__						(      cls				:							Dict	)							->	int:
								super().tearDownClass()
								shutil.rmtree(cls._tmpdir	)





							def       snake_case__						(      self				:							Tuple	)							->	Dict:
								__UpperCAmelCase							=			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       snake_case__						(      self				:							str	)							->	int:
								__UpperCAmelCase							=			f"""
        examples/by_feature/checkpointing.py
        --checkpointing_steps 1
        --output_dir {self.tmpdir}
        """.split()
								__UpperCAmelCase							=			run_command(self._launch_args + testargs	)
								self.assertTrue(os.path.exists(os.path.join(self.tmpdir     ,		'''step_2'''	)	)	)





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





							def       snake_case__						(      self				:							Tuple	)							->	Optional[int]:
								__UpperCAmelCase							=			f"""
        examples/by_feature/checkpointing.py
        --resume_from_checkpoint {os.path.join(self.tmpdir     ,		'step_2'	)}
        """.split()
								__UpperCAmelCase							=			run_command(self._launch_args + testargs     ,		return_stdout=__a	)
								if torch.cuda.is_available():
									__UpperCAmelCase							=			torch.cuda.device_count()
								else:
									__UpperCAmelCase							=			1
								if num_processes > 1:
									self.assertNotIn('''epoch 0:'''     ,		__a	)
									self.assertIn('''epoch 1:'''     ,		__a	)
								else:
									self.assertIn('''epoch 0:'''     ,		__a	)
									self.assertIn('''epoch 1:'''     ,		__a	)





							@slow
							def       snake_case__						(      self				:							Any	)							->	Optional[Any]:
								__UpperCAmelCase							=			'''
        examples/by_feature/cross_validation.py
        --num_folds 2
        '''.split()
								with mock.patch.dict(os.environ     ,		{'''TESTING_MOCKED_DATALOADERS''': '''0'''}	):
									__UpperCAmelCase							=			run_command(self._launch_args + testargs     ,		return_stdout=__a	)
									__UpperCAmelCase							=			re.findall('''({.+})'''     ,		__a	)
									__UpperCAmelCase							=			[r for r in results if '''accuracy''' in r][-1]
									__UpperCAmelCase							=			ast.literal_eval(__a	)
									self.assertGreaterEqual(results['''accuracy''']     ,		0.7_5	)





							def       snake_case__						(      self				:							Dict	)							->	int:
								__UpperCAmelCase							=			['''examples/by_feature/multi_process_metrics.py''']
								run_command(self._launch_args + testargs	)





							@require_trackers
							@mock.patch.dict(os.environ     ,		{'''WANDB_MODE''': '''offline'''}	)
							def       snake_case__						(      self				:							Optional[Any]	)							->	Optional[int]:
								with tempfile.TemporaryDirectory() as tmpdir:
									__UpperCAmelCase							=			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(__a     ,		'''tracking'''	)	)	)





							def       snake_case__						(      self				:							Optional[int]	)							->	List[Any]:
								__UpperCAmelCase							=			['''examples/by_feature/gradient_accumulation.py''']
								run_command(self._launch_args + testargs	)






							def       snake_case__						(      self				:							Tuple	)							->	Optional[Any]:
								__UpperCAmelCase							=			['''examples/by_feature/local_sgd.py''']
								run_command(self._launch_args + testargs	)
