
import inspect
import unittest

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

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 SwinaSRForImageSuperResolution, SwinaSRModel
					from transformers.models.swinasr.modeling_swinasr import SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
					from PIL import Image

					from transformers import SwinaSRImageProcessor







class 			UpperCamelCase__		:







	'''simple docstring'''





	def __init__(      self					,							UpperCamelCase__					,							UpperCamelCase__=13					,							UpperCamelCase__=32					,							UpperCamelCase__=1					,							UpperCamelCase__=3					,							UpperCamelCase__=16					,							UpperCamelCase__=[1, 2, 1]					,							UpperCamelCase__=[2, 2, 4]					,							UpperCamelCase__=2					,							UpperCamelCase__=2.0					,							UpperCamelCase__=True					,							UpperCamelCase__=0.0					,							UpperCamelCase__=0.0					,							UpperCamelCase__=0.1					,							UpperCamelCase__="gelu"					,							UpperCamelCase__=False					,							UpperCamelCase__=True					,							UpperCamelCase__=0.0_2					,							UpperCamelCase__=1e-5					,							UpperCamelCase__=True					,							UpperCamelCase__=None					,							UpperCamelCase__=False					,							UpperCamelCase__=2					,							):
					A__	:						Any								=				parent
					A__	:						str								=				batch_size
					A__	:						Tuple								=				image_size
					A__	:						List[str]								=				patch_size
					A__	:						Dict								=				num_channels
					A__	:						List[str]								=				embed_dim
					A__	:						Optional[int]								=				depths
					A__	:						str								=				num_heads
					A__	:						Optional[Any]								=				window_size
					A__	:						Tuple								=				mlp_ratio
					A__	:						Dict								=				qkv_bias
					A__	:						Optional[Any]								=				hidden_dropout_prob
					A__	:						Tuple								=				attention_probs_dropout_prob
					A__	:						List[Any]								=				drop_path_rate
					A__	:						Union[str, Any]								=				hidden_act
					A__	:						Optional[int]								=				use_absolute_embeddings
					A__	:						str								=				patch_norm
					A__	:						Optional[int]								=				layer_norm_eps
					A__	:						Dict								=				initializer_range
					A__	:						Optional[Any]								=				is_training
					A__	:						Dict								=				scope
					A__	:						List[str]								=				use_labels
					A__	:						Optional[int]								=				upscale

					# here we set some attributes to make tests pass
					A__	:						Dict								=				len(UpperCamelCase__		)
					A__	:						List[Any]								=				embed_dim
					A__	:						Dict								=				(image_size // patch_size) ** 2





	def 	__snake_case					(      self		):
					A__	:						Tuple								=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

					A__	:						List[str]								=				self.get_config()

					return config, pixel_values, labels





	def 	__snake_case					(      self		):
					return SwinaSRConfig(
					    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					,							upscale=self.upscale					,							)





	def 	__snake_case					(      self					,							UpperCamelCase__					,							UpperCamelCase__					,							UpperCamelCase__		):
					A__	:						Tuple								=				SwinaSRModel(config=UpperCamelCase__		)
					model.to(UpperCamelCase__		)
					model.eval()
					A__	:						int								=				model(UpperCamelCase__		)

					self.parent.assertEqual(
					    result.last_hidden_state.shape					,							(self.batch_size, self.embed_dim, self.image_size, self.image_size)		)





	def 	__snake_case					(      self					,							UpperCamelCase__					,							UpperCamelCase__					,							UpperCamelCase__		):
					A__	:						Tuple								=				SwinaSRForImageSuperResolution(UpperCamelCase__		)
					model.to(UpperCamelCase__		)
					model.eval()
					A__	:						str								=				model(UpperCamelCase__		)

					A__	:						Optional[int]								=				self.image_size * self.upscale
					self.parent.assertEqual(
					    result.reconstruction.shape					,							(self.batch_size, self.num_channels, expected_image_size, expected_image_size)		)





	def 	__snake_case					(      self		):
					A__	:						Union[str, Any]								=				self.prepare_config_and_inputs()
					A__							,				A__							,				A__	:						int								=				config_and_inputs
					A__	:						Optional[int]								=				{'''pixel_values''': pixel_values}
					return config, inputs_dict







@require_torch
class 			UpperCamelCase__		(     SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_,      unittest.TestCase ):







	'''simple docstring'''
	_lowerCAmelCase											=					(SwinaSRModel, SwinaSRForImageSuperResolution) if is_torch_available() else ()
	_lowerCAmelCase											=					{"feature-extraction": SwinaSRModel} if is_torch_available() else {}

	_lowerCAmelCase											=					False
	_lowerCAmelCase											=					False
	_lowerCAmelCase											=					False
	_lowerCAmelCase											=					False
	_lowerCAmelCase											=					False





	def 	__snake_case					(      self		):
					A__	:						Optional[Any]								=				SwinaSRModelTester(self		)
					A__	:						Optional[int]								=				ConfigTester(self					,							config_class=UpperCamelCase__					,							embed_dim=37		)





	def 	__snake_case					(      self		):
					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 	__snake_case					(      self		):
					A__	:						Union[str, Any]								=				self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*UpperCamelCase__		)





	def 	__snake_case					(      self		):
					A__	:						Optional[Any]								=				self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_super_resolution(*UpperCamelCase__		)





	@unittest.skip(reason='''Got `CUDA error: misaligned address` with PyTorch 2.0.0.'''		)
	def 	__snake_case					(      self		):
					pass





	@unittest.skip(reason='''Swin2SR does not use inputs_embeds'''		)
	def 	__snake_case					(      self		):
					pass





	@unittest.skip(reason='''Swin2SR does not support training yet'''		)
	def 	__snake_case					(      self		):
					pass





	@unittest.skip(reason='''Swin2SR does not support training yet'''		)
	def 	__snake_case					(      self		):
					pass





	def 	__snake_case					(      self		):
					A__							,				A__	:						Any								=				self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
									A__	:						Tuple								=				model_class(UpperCamelCase__		)
									self.assertIsInstance(model.get_input_embeddings()					,							(nn.Module)		)
									A__	:						Union[str, Any]								=				model.get_output_embeddings()
									self.assertTrue(x is None or isinstance(UpperCamelCase__					,							nn.Linear		)		)





	def 	__snake_case					(      self		):
					A__							,				A__	:						List[str]								=				self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
									A__	:						str								=				model_class(UpperCamelCase__		)
									A__	:						Union[str, Any]								=				inspect.signature(model.forward		)
									# signature.parameters is an OrderedDict => so arg_names order is deterministic
									A__	:						Tuple								=				[*signature.parameters.keys()]

									A__	:						int								=				['''pixel_values''']
									self.assertListEqual(arg_names[:1]					,							UpperCamelCase__		)





	@slow
	def 	__snake_case					(      self		):
					for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									A__	:						int								=				SwinaSRModel.from_pretrained(UpperCamelCase__		)
									self.assertIsNotNone(UpperCamelCase__		)





	def 	__snake_case					(      self		):
					A__							,				A__	:						Union[str, Any]								=				self.model_tester.prepare_config_and_inputs_for_common()

					A__	:						Any								=				_config_zero_init(UpperCamelCase__		)
					for model_class in self.all_model_classes:
									A__	:						Dict								=				model_class(config=UpperCamelCase__		)
									for name, param in model.named_parameters():
													if "logit_scale" in name:
																	continue
													if 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"					,							)





	def 	__snake_case					(      self		):
					A__							,				A__	:						int								=				self.model_tester.prepare_config_and_inputs_for_common()
					A__	:						Optional[int]								=				True

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

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

									self.assertListEqual(
									    list(attentions[0].shape[-3:]		)					,							[self.model_tester.num_heads[0], window_size_squared, window_size_squared]					,							)
									A__	:						Optional[int]								=				len(UpperCamelCase__		)

									# Check attention is always last and order is fine
									A__	:						Tuple								=				True
									A__	:						Optional[Any]								=				True
									A__	:						Optional[int]								=				model_class(UpperCamelCase__		)
									model.to(UpperCamelCase__		)
									model.eval()
									with torch.no_grad():
													A__	:						Optional[int]								=				model(**self._prepare_for_class(UpperCamelCase__					,							UpperCamelCase__		)		)

									self.assertEqual(out_len + 1					,							len(UpperCamelCase__		)		)

									A__	:						Optional[int]								=				outputs.attentions

									self.assertEqual(len(UpperCamelCase__		)					,							UpperCamelCase__		)

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







@require_vision
@require_torch
@slow
class 			UpperCamelCase__		(     unittest.TestCase ):







	'''simple docstring'''





	def 	__snake_case					(      self		):
					A__	:						List[Any]								=				SwinaSRImageProcessor()
					A__	:						Union[str, Any]								=				SwinaSRForImageSuperResolution.from_pretrained('''caidas/swin2SR-classical-sr-x2-64'''		).to(UpperCamelCase__		)

					A__	:						int								=				Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''		)
					A__	:						Dict								=				processor(images=UpperCamelCase__					,							return_tensors='''pt'''		).to(UpperCamelCase__		)

					# forward pass
					with torch.no_grad():
									A__	:						int								=				model(**UpperCamelCase__		)

					# verify the logits
					A__	:						Any								=				torch.Size([1, 3, 976, 1296]		)
					self.assertEqual(outputs.reconstruction.shape					,							UpperCamelCase__		)
					A__	:						List[Any]								=				torch.tensor(
					    [[0.5_4_5_8, 0.5_5_4_6, 0.5_6_3_8], [0.5_5_2_6, 0.5_5_6_5, 0.5_6_5_1], [0.5_3_9_6, 0.5_4_2_6, 0.5_6_2_1]]		).to(UpperCamelCase__		)
					self.assertTrue(torch.allclose(outputs.reconstruction[0, 0, :3, :3]					,							UpperCamelCase__					,							atol=1e-4		)		)

import unittest
from pathlib import Path

from transformers import is_vision_available, load_tool
from transformers.testing_utils import get_tests_dir

from .test_tools_common import ToolTesterMixin


if is_vision_available():
					from PIL import Image







class 			UpperCamelCase__		(     unittest.TestCase,      SCREAMING_SNAKE_CASE_ ):







	'''simple docstring'''





	def 	__snake_case					(      self		):
					A__	:						Dict								=				load_tool('''image-question-answering'''		)
					self.tool.setup()
					A__	:						List[Any]								=				load_tool('''image-question-answering'''					,							remote=UpperCamelCase__		)





	def 	__snake_case					(      self		):
					A__	:						str								=				Image.open(Path(get_tests_dir('''fixtures/tests_samples/COCO'''		)		) / '''000000039769.png'''		)
					A__	:						List[str]								=				self.tool(UpperCamelCase__					,							'''How many cats are sleeping on the couch?'''		)
					self.assertEqual(UpperCamelCase__					,							'''2'''		)





	def 	__snake_case					(      self		):
					A__	:						Tuple								=				Image.open(Path(get_tests_dir('''fixtures/tests_samples/COCO'''		)		) / '''000000039769.png'''		)
					A__	:						Dict								=				self.remote_tool(UpperCamelCase__					,							'''How many cats are sleeping on the couch?'''		)
					self.assertEqual(UpperCamelCase__					,							'''2'''		)





	def 	__snake_case					(      self		):
					A__	:						Dict								=				Image.open(Path(get_tests_dir('''fixtures/tests_samples/COCO'''		)		) / '''000000039769.png'''		)
					A__	:						int								=				self.tool(image=UpperCamelCase__					,							question='''How many cats are sleeping on the couch?'''		)
					self.assertEqual(UpperCamelCase__					,							'''2'''		)





	def 	__snake_case					(      self		):
					A__	:						Tuple								=				Image.open(Path(get_tests_dir('''fixtures/tests_samples/COCO'''		)		) / '''000000039769.png'''		)
					A__	:						str								=				self.remote_tool(image=UpperCamelCase__					,							question='''How many cats are sleeping on the couch?'''		)
					self.assertEqual(UpperCamelCase__					,							'''2'''		)