





import collections
import inspect
import unittest

from transformers import SwinConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
						import torch
						from torch import nn

						from transformers import SwinBackbone, SwinForImageClassification, SwinForMaskedImageModeling, SwinModel
						from transformers.models.swin.modeling_swin import SWIN_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
						from PIL import Image

						from transformers import AutoImageProcessor
class SCREAMING_SNAKE_CASE_    :






						def __init__(   self   :   Dict		, _A   :   Tuple		, _A   :   List[str]=13		, _A   :   Union[str, Any]=32		, _A   :   List[str]=2		, _A   :   Optional[Any]=3		, _A   :   List[str]=16		, _A   :   Optional[Any]=[1, 2, 1]		, _A   :   Dict=[2, 2, 4]		, _A   :   Optional[int]=2		, _A   :   Any=2.0		, _A   :   int=True		, _A   :   Union[str, Any]=0.0		, _A   :   Tuple=0.0		, _A   :   Optional[int]=0.1		, _A   :   Union[str, Any]="gelu"		, _A   :   List[Any]=False		, _A   :   Tuple=True		, _A   :   List[str]=0.0_2		, _A   :   Optional[Any]=1E-5		, _A   :   Any=True		, _A   :   Optional[Any]=None		, _A   :   Optional[int]=True		, _A   :   str=10		, _A   :   Any=8		, _A   :   List[str]=["stage1", "stage2"]		, _A   :   Optional[Any]=[1, 2]		, )				->     Optional[Any]:







							"""simple docstring"""


							snake_case_		:      Any           =						parent
							snake_case_		:      Optional[int]           =						batch_size
							snake_case_		:      Dict           =						image_size
							snake_case_		:      Union[str, Any]           =						patch_size
							snake_case_		:      Optional[Any]           =						num_channels
							snake_case_		:      int           =						embed_dim
							snake_case_		:      Optional[Any]           =						depths
							snake_case_		:      Optional[int]           =						num_heads
							snake_case_		:      Dict           =						window_size
							snake_case_		:      Any           =						mlp_ratio
							snake_case_		:      int           =						qkv_bias
							snake_case_		:      Tuple           =						hidden_dropout_prob
							snake_case_		:      Tuple           =						attention_probs_dropout_prob
							snake_case_		:      Optional[Any]           =						drop_path_rate
							snake_case_		:      int           =						hidden_act
							snake_case_		:      List[str]           =						use_absolute_embeddings
							snake_case_		:      List[Any]           =						patch_norm
							snake_case_		:      List[Any]           =						layer_norm_eps
							snake_case_		:      int           =						initializer_range
							snake_case_		:      Optional[int]           =						is_training
							snake_case_		:      Dict           =						scope
							snake_case_		:      Dict           =						use_labels
							snake_case_		:      List[str]           =						type_sequence_label_size
							snake_case_		:      int           =						encoder_stride
							snake_case_		:      Optional[Any]           =						out_features
							snake_case_		:      List[str]           =						out_indices






						def UpperCAmelCase_					(   self   :   List[Any]						)				->     Optional[int]:







							"""simple docstring"""


							snake_case_		:      Optional[Any]           =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

							snake_case_		:      str           =						None
							if self.use_labels:
								snake_case_		:      Tuple           =						ids_tensor([self.batch_size]		, self.type_sequence_label_size						)

							snake_case_		:      List[Any]           =						self.get_config()

							return config, pixel_values, labels






						def UpperCAmelCase_					(   self   :   Tuple						)				->     Tuple:







							"""simple docstring"""


							return SwinConfig(
							    image_size=self.image_size		, patch_size=self.patch_size		, num_channels=self.num_channels		, embed_dim=self.embed_dim		, depths=self.depths		, num_heads=self.num_heads		, window_size=self.window_size		, mlp_ratio=self.mlp_ratio		, qkv_bias=self.qkv_bias		, hidden_dropout_prob=self.hidden_dropout_prob		, attention_probs_dropout_prob=self.attention_probs_dropout_prob		, drop_path_rate=self.drop_path_rate		, hidden_act=self.hidden_act		, use_absolute_embeddings=self.use_absolute_embeddings		, path_norm=self.patch_norm		, layer_norm_eps=self.layer_norm_eps		, initializer_range=self.initializer_range		, encoder_stride=self.encoder_stride		, out_features=self.out_features		, out_indices=self.out_indices		, )






						def UpperCAmelCase_					(   self   :   List[Any]		, _A   :   Dict		, _A   :   Tuple		, _A   :   List[Any]						)				->     Dict:







							"""simple docstring"""


							snake_case_		:      List[Any]           =						SwinModel(config=_A						)
							model.to(_A						)
							model.eval()
							snake_case_		:      List[str]           =						model(_A						)

							snake_case_		:      str           =						((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths						) - 1))
							snake_case_		:      str           =						int(config.embed_dim * 2 ** (len(config.depths						) - 1)						)

							self.parent.assertEqual(result.last_hidden_state.shape		, (self.batch_size, expected_seq_len, expected_dim)						)






						def UpperCAmelCase_					(   self   :   Any		, _A   :   Tuple		, _A   :   str		, _A   :   Union[str, Any]						)				->     List[Any]:







							"""simple docstring"""


							snake_case_		:      Optional[Any]           =						SwinBackbone(config=_A						)
							model.to(_A						)
							model.eval()
							snake_case_		:      str           =						model(_A						)

							# verify hidden states
							self.parent.assertEqual(len(result.feature_maps						)		, len(config.out_features						)						)
							self.parent.assertListEqual(list(result.feature_maps[0].shape						)		, [self.batch_size, model.channels[0], 16, 16]						)

							# verify channels
							self.parent.assertEqual(len(model.channels						)		, len(config.out_features						)						)

							# verify backbone works with out_features=None
							snake_case_		:      Tuple           =						None
							snake_case_		:      List[str]           =						SwinBackbone(config=_A						)
							model.to(_A						)
							model.eval()
							snake_case_		:      int           =						model(_A						)

							# verify feature maps
							self.parent.assertEqual(len(result.feature_maps						)		, 1						)
							self.parent.assertListEqual(list(result.feature_maps[0].shape						)		, [self.batch_size, model.channels[-1], 4, 4]						)

							# verify channels
							self.parent.assertEqual(len(model.channels						)		, 1						)






						def UpperCAmelCase_					(   self   :   Dict		, _A   :   Optional[int]		, _A   :   Union[str, Any]		, _A   :   List[Any]						)				->     List[Any]:







							"""simple docstring"""


							snake_case_		:      str           =						SwinForMaskedImageModeling(config=_A						)
							model.to(_A						)
							model.eval()
							snake_case_		:      Optional[int]           =						model(_A						)
							self.parent.assertEqual(
							    result.logits.shape		, (self.batch_size, self.num_channels, self.image_size, self.image_size)						)

							# test greyscale images
							snake_case_		:      Optional[Any]           =						1
							snake_case_		:      Optional[int]           =						SwinForMaskedImageModeling(_A						)
							model.to(_A						)
							model.eval()

							snake_case_		:      Tuple           =						floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
							snake_case_		:      str           =						model(_A						)
							self.parent.assertEqual(result.logits.shape		, (self.batch_size, 1, self.image_size, self.image_size)						)






						def UpperCAmelCase_					(   self   :   List[str]		, _A   :   int		, _A   :   List[str]		, _A   :   Optional[Any]						)				->     List[str]:







							"""simple docstring"""


							snake_case_		:      Dict           =						self.type_sequence_label_size
							snake_case_		:      Any           =						SwinForImageClassification(_A						)
							model.to(_A						)
							model.eval()
							snake_case_		:      int           =						model(_A		, labels=_A						)
							self.parent.assertEqual(result.logits.shape		, (self.batch_size, self.type_sequence_label_size)						)

							# test greyscale images
							snake_case_		:      str           =						1
							snake_case_		:      Optional[int]           =						SwinForImageClassification(_A						)
							model.to(_A						)
							model.eval()

							snake_case_		:      str           =						floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
							snake_case_		:      Optional[Any]           =						model(_A						)
							self.parent.assertEqual(result.logits.shape		, (self.batch_size, self.type_sequence_label_size)						)






						def UpperCAmelCase_					(   self   :   Dict						)				->     str:







							"""simple docstring"""


							snake_case_		:      Dict           =						self.prepare_config_and_inputs()
							(
							    (
							    snake_case_
							)    ,(
							    snake_case_
							)    ,(
							    snake_case_
							)    ,
							)		:      List[Any]           =						config_and_inputs
							snake_case_		:      int           =						{'pixel_values': pixel_values}
							return config, inputs_dict
@require_torch
class SCREAMING_SNAKE_CASE_    (       snake_case_							,					snake_case_							,					unittest.TestCase       ):
						__magic_name__:      Any			   =							(
						    (
						        SwinModel,
						        SwinBackbone,
						        SwinForImageClassification,
						        SwinForMaskedImageModeling,
						    )
						    if is_torch_available()
						    else ()
						)
						__magic_name__:      List[Any]			   =							(
						    {"feature-extraction": SwinModel, "image-classification": SwinForImageClassification}
						    if is_torch_available()
						    else {}
						)
						__magic_name__:      int			   =							True

						__magic_name__:      Optional[int]			   =							False
						__magic_name__:      Dict			   =							False
						__magic_name__:      List[str]			   =							False






						def UpperCAmelCase_					(   self   :   List[str]						)				->     Optional[Any]:







							"""simple docstring"""


							snake_case_		:      Tuple           =						SwinModelTester(self						)
							snake_case_		:      Optional[Any]           =						ConfigTester(self		, config_class=_A		, embed_dim=37						)






						def UpperCAmelCase_					(   self   :   Union[str, Any]						)				->     Dict:







							"""simple docstring"""


							self.create_and_test_config_common_properties()
							self.config_tester.create_and_test_config_to_json_string()
							self.config_tester.create_and_test_config_to_json_file()
							self.config_tester.create_and_test_config_from_and_save_pretrained()
							self.config_tester.create_and_test_config_with_num_labels()
							self.config_tester.check_config_can_be_init_without_params()
							self.config_tester.check_config_arguments_init()






						def UpperCAmelCase_					(   self   :   Dict						)				->     str:







							"""simple docstring"""


							return






						def UpperCAmelCase_					(   self   :   Optional[int]						)				->     Optional[int]:







							"""simple docstring"""


							snake_case_		:      List[Any]           =						self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*_A						)






						@unittest.skip(reason='Got `CUDA error: misaligned address` with PyTorch 2.0.0.'						)
						def UpperCAmelCase_					(   self   :   Tuple						)				->     Optional[Any]:







							"""simple docstring"""


							pass






						def UpperCAmelCase_					(   self   :   Tuple						)				->     List[Any]:







							"""simple docstring"""


							super().test_training_gradient_checkpointing()






						def UpperCAmelCase_					(   self   :   Any						)				->     Tuple:







							"""simple docstring"""


							snake_case_		:      str           =						self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_backbone(*_A						)






						def UpperCAmelCase_					(   self   :   Any						)				->     int:







							"""simple docstring"""


							snake_case_		:      Dict           =						self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_masked_image_modeling(*_A						)






						def UpperCAmelCase_					(   self   :   Optional[Any]						)				->     str:







							"""simple docstring"""


							snake_case_		:      Union[str, Any]           =						self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*_A						)






						@unittest.skip(reason='Swin does not use inputs_embeds'						)
						def UpperCAmelCase_					(   self   :   List[Any]						)				->     Dict:







							"""simple docstring"""


							pass






						@unittest.skip(reason='Swin Transformer does not use feedforward chunking'						)
						def UpperCAmelCase_					(   self   :   List[str]						)				->     Optional[Any]:







							"""simple docstring"""


							pass






						def UpperCAmelCase_					(   self   :   Optional[int]						)				->     Dict:







							"""simple docstring"""


							snake_case_    ,snake_case_		:      Optional[int]           =						self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
								snake_case_		:      str           =						model_class(_A						)
								self.assertIsInstance(model.get_input_embeddings()		, (nn.Module)						)
								snake_case_		:      str           =						model.get_output_embeddings()
								self.assertTrue(x is None or isinstance(_A		, nn.Linear						)						)






						def UpperCAmelCase_					(   self   :   Optional[Any]						)				->     Tuple:







							"""simple docstring"""


							snake_case_    ,snake_case_		:      int           =						self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
								snake_case_		:      Tuple           =						model_class(_A						)
								snake_case_		:      str           =						inspect.signature(model.forward						)
								# signature.parameters is an OrderedDict => so arg_names order is deterministic
								snake_case_		:      Dict           =						[*signature.parameters.keys()]

								snake_case_		:      Tuple           =						['pixel_values']
								self.assertListEqual(arg_names[:1]		, _A						)






						def UpperCAmelCase_					(   self   :   Optional[int]						)				->     Any:







							"""simple docstring"""


							snake_case_    ,snake_case_		:      Any           =						self.model_tester.prepare_config_and_inputs_for_common()
							snake_case_		:      Tuple           =						True

							for model_class in self.all_model_classes:
								snake_case_		:      Optional[int]           =						True
								snake_case_		:      Union[str, Any]           =						False
								snake_case_		:      Any           =						True
								snake_case_		:      Union[str, Any]           =						model_class(_A						)
								model.to(_A						)
								model.eval()
								with torch.no_grad():
									snake_case_		:      Optional[Any]           =						model(**self._prepare_for_class(_A		, _A						)						)
								snake_case_		:      Tuple           =						outputs.attentions
								snake_case_		:      str           =						len(self.model_tester.depths						)
								self.assertEqual(len(_A						)		, _A						)

								# check that output_attentions also work using config
								del inputs_dict["output_attentions"]
								snake_case_		:      Optional[Any]           =						True
								snake_case_		:      Tuple           =						config.window_size**2
								snake_case_		:      List[Any]           =						model_class(_A						)
								model.to(_A						)
								model.eval()
								with torch.no_grad():
									snake_case_		:      Union[str, Any]           =						model(**self._prepare_for_class(_A		, _A						)						)
								snake_case_		:      List[str]           =						outputs.attentions
								self.assertEqual(len(_A						)		, _A						)

								self.assertListEqual(
								    list(attentions[0].shape[-3:]						)		, [self.model_tester.num_heads[0], window_size_squared, window_size_squared]		, )
								snake_case_		:      List[str]           =						len(_A						)

								# Check attention is always last and order is fine
								snake_case_		:      Dict           =						True
								snake_case_		:      List[str]           =						True
								snake_case_		:      List[Any]           =						model_class(_A						)
								model.to(_A						)
								model.eval()
								with torch.no_grad():
									snake_case_		:      Tuple           =						model(**self._prepare_for_class(_A		, _A						)						)

								# also another +1 for reshaped_hidden_states
								snake_case_		:      int           =						1 if model_class.__name__ == 'SwinBackbone' else 2
								self.assertEqual(out_len + added_hidden_states		, len(_A						)						)

								snake_case_		:      str           =						outputs.attentions

								self.assertEqual(len(_A						)		, _A						)

								self.assertListEqual(
								    list(self_attentions[0].shape[-3:]						)		, [self.model_tester.num_heads[0], window_size_squared, window_size_squared]		, )






						def UpperCAmelCase_					(   self   :   Tuple		, _A   :   Union[str, Any]		, _A   :   Any		, _A   :   Any		, _A   :   str						)				->     Tuple:







							"""simple docstring"""


							snake_case_		:      List[Any]           =						model_class(_A						)
							model.to(_A						)
							model.eval()

							with torch.no_grad():
								snake_case_		:      List[Any]           =						model(**self._prepare_for_class(_A		, _A						)						)

							snake_case_		:      Optional[Any]           =						outputs.hidden_states

							snake_case_		:      str           =						getattr(
							    self.model_tester		, 'expected_num_hidden_layers'		, len(self.model_tester.depths						) + 1						)
							self.assertEqual(len(_A						)		, _A						)

							# Swin has a different seq_length
							snake_case_		:      Optional[int]           =						(
							    config.patch_size
							    if isinstance(config.patch_size		, collections.abc.Iterable						)
							    else (config.patch_size, config.patch_size)
							)

							snake_case_		:      List[str]           =						(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

							self.assertListEqual(
							    list(hidden_states[0].shape[-2:]						)		, [num_patches, self.model_tester.embed_dim]		, )

							if not model_class.__name__ == "SwinBackbone":
								snake_case_		:      Optional[Any]           =						outputs.reshaped_hidden_states
								self.assertEqual(len(_A						)		, _A						)

								snake_case_    ,snake_case_    ,snake_case_    ,snake_case_		:      Union[str, Any]           =						reshaped_hidden_states[0].shape
								snake_case_		:      str           =						(
								    reshaped_hidden_states[0].view(_A		, _A		, height * width						).permute(0		, 2		, 1						)
								)
								self.assertListEqual(
								    list(reshaped_hidden_states.shape[-2:]						)		, [num_patches, self.model_tester.embed_dim]		, )






						def UpperCAmelCase_					(   self   :   Optional[int]						)				->     List[Any]:







							"""simple docstring"""


							snake_case_    ,snake_case_		:      Dict           =						self.model_tester.prepare_config_and_inputs_for_common()

							snake_case_		:      Optional[int]           =						(
							    self.model_tester.image_size
							    if isinstance(self.model_tester.image_size		, collections.abc.Iterable						)
							    else (self.model_tester.image_size, self.model_tester.image_size)
							)

							for model_class in self.all_model_classes:
								snake_case_		:      List[str]           =						True
								self.check_hidden_states_output(_A		, _A		, _A		, _A						)

								# check that output_hidden_states also work using config
								del inputs_dict["output_hidden_states"]
								snake_case_		:      str           =						True

								self.check_hidden_states_output(_A		, _A		, _A		, _A						)






						def UpperCAmelCase_					(   self   :   Optional[Any]						)				->     Union[str, Any]:







							"""simple docstring"""


							snake_case_    ,snake_case_		:      List[str]           =						self.model_tester.prepare_config_and_inputs_for_common()
							snake_case_		:      Any           =						3

							snake_case_		:      Optional[int]           =						(
							    self.model_tester.image_size
							    if isinstance(self.model_tester.image_size		, collections.abc.Iterable						)
							    else (self.model_tester.image_size, self.model_tester.image_size)
							)
							snake_case_		:      Dict           =						(
							    config.patch_size
							    if isinstance(config.patch_size		, collections.abc.Iterable						)
							    else (config.patch_size, config.patch_size)
							)

							snake_case_		:      Union[str, Any]           =						image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
							snake_case_		:      str           =						image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

							for model_class in self.all_model_classes:
								snake_case_		:      str           =						True
								self.check_hidden_states_output(_A		, _A		, _A		, (padded_height, padded_width)						)

								# check that output_hidden_states also work using config
								del inputs_dict["output_hidden_states"]
								snake_case_		:      List[str]           =						True
								self.check_hidden_states_output(_A		, _A		, _A		, (padded_height, padded_width)						)






						@slow
						def UpperCAmelCase_					(   self   :   int						)				->     Optional[Any]:







							"""simple docstring"""


							for model_name in SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
								snake_case_		:      Union[str, Any]           =						SwinModel.from_pretrained(_A						)
								self.assertIsNotNone(_A						)






						def UpperCAmelCase_					(   self   :   Optional[Any]						)				->     Union[str, Any]:







							"""simple docstring"""


							snake_case_    ,snake_case_		:      List[str]           =						self.model_tester.prepare_config_and_inputs_for_common()

							snake_case_		:      Optional[Any]           =						_config_zero_init(_A						)
							for model_class in self.all_model_classes:
								snake_case_		:      Tuple           =						model_class(config=_A						)
								for name, param in model.named_parameters():
									if "embeddings" not in name and param.requires_grad:
										self.assertIn(
										    ((param.data.mean() * 1E9).round() / 1E9).item()		, [0.0, 1.0]		, msg=F"""Parameter {name} of model {model_class} seems not properly initialized"""		, )
@require_vision
@require_torch
class SCREAMING_SNAKE_CASE_    (       unittest.TestCase       ):






						@cached_property
						def UpperCAmelCase_					(   self   :   List[Any]						)				->     List[str]:







							"""simple docstring"""


							return (
							    AutoImageProcessor.from_pretrained('microsoft/swin-tiny-patch4-window7-224'						)
							    if is_vision_available()
							    else None
							)






						@slow
						def UpperCAmelCase_					(   self   :   List[Any]						)				->     Tuple:







							"""simple docstring"""


							snake_case_		:      Optional[Any]           =						SwinForImageClassification.from_pretrained('microsoft/swin-tiny-patch4-window7-224'						).to(_A						)
							snake_case_		:      List[str]           =						self.default_image_processor

							snake_case_		:      Optional[Any]           =						Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
							snake_case_		:      Optional[int]           =						image_processor(images=_A		, return_tensors='pt'						).to(_A						)

							# forward pass
							with torch.no_grad():
								snake_case_		:      Union[str, Any]           =						model(**_A						)

							# verify the logits
							snake_case_		:      str           =						torch.Size((1, 1000)						)
							self.assertEqual(outputs.logits.shape		, _A						)
							snake_case_		:      Any           =						torch.tensor([-0.0_9_4_8, -0.6_4_5_4, -0.0_9_2_1]						).to(_A						)
							self.assertTrue(torch.allclose(outputs.logits[0, :3]		, _A		, atol=1E-4						)						)
@require_torch
class SCREAMING_SNAKE_CASE_    (       unittest.TestCase							,					snake_case_       ):
						__magic_name__:      int			   =							(SwinBackbone,) if is_torch_available() else ()
						__magic_name__:      Optional[int]			   =							SwinConfig






						def UpperCAmelCase_					(   self   :   List[Any]						)				->     Any:







							"""simple docstring"""


							snake_case_		:      int           =						SwinModelTester(self						)






'''simple docstring'''



def 							__UpperCAmelCase				(				UpperCamelCase__				:int			)		->						Any:
				snake_case__      :   Dict      =    len(UpperCamelCase__			)
				for _ in range(
				    0   ,				int(((no_of_elements - 1) / 2) + 1			)			):  # we don't need to traverse to end of list as
								for j in range(0   ,				no_of_elements - 1			):
												if (
												    lst[j + 1] < lst[j]
												):  # applying bubble sort algorithm from left to right (or forwards)
																snake_case__      :   int      =    lst[j + 1]
																snake_case__      :   Tuple      =    lst[j]
																snake_case__      :   Tuple      =    temp
												if (
												    lst[no_of_elements - 1 - j] < lst[no_of_elements - 2 - j]
												):  # applying bubble sort algorithm from right to left (or backwards)
																snake_case__      :   Optional[Any]      =    lst[no_of_elements - 1 - j]
																snake_case__      :   Tuple      =    lst[no_of_elements - 2 - j]
																snake_case__      :   Any      =    temp
				return lst


if __name__ == "__main__":
				print("enter the list to be sorted")
				_lowercase       :						Any						=[int(x) for x in input().split()]  # inputing elements of the list in one line
				_lowercase       :						Tuple						=double_sort(lst)
				print("the sorted list is")
				print(sorted_lst)




