



'''simple docstring'''




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 						_UpperCamelCase  :


			'''simple docstring'''

			def __init__(							self					:			Dict							,					lowerCAmelCase__					:			List[str]							,					lowerCAmelCase__					:			Tuple=1_3							,					lowerCAmelCase__					:			Tuple=3_2							,					lowerCAmelCase__					:			Optional[int]=2							,					lowerCAmelCase__					:			str=3							,					lowerCAmelCase__					:			Optional[int]=1_6							,					lowerCAmelCase__					:			List[str]=[1, 2, 1]							,					lowerCAmelCase__					:			Dict=[2, 2, 4]							,					lowerCAmelCase__					:			Any=2							,					lowerCAmelCase__					:			str=2.0							,					lowerCAmelCase__					:			List[Any]=True							,					lowerCAmelCase__					:			Any=0.0							,					lowerCAmelCase__					:			List[Any]=0.0							,					lowerCAmelCase__					:			Optional[Any]=0.1							,					lowerCAmelCase__					:			Optional[int]="gelu"							,					lowerCAmelCase__					:			Dict=False							,					lowerCAmelCase__					:			Union[str, Any]=True							,					lowerCAmelCase__					:			Any=0.02							,					lowerCAmelCase__					:			List[str]=1E-5							,					lowerCAmelCase__					:			Union[str, Any]=True							,					lowerCAmelCase__					:			int=None							,					lowerCAmelCase__					:			Optional[Any]=True							,					lowerCAmelCase__					:			int=1_0							,					lowerCAmelCase__					:			List[Any]=8							,					lowerCAmelCase__					:			Union[str, Any]=["stage1", "stage2"]							,					lowerCAmelCase__					:			Any=[1, 2]							,					):





					"""simple docstring"""






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

			def UpperCamelCase__ (							self					:			Union[str, Any]						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		List[str]   	=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

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

					__SCREAMING_SNAKE_CASE	:		Tuple   	=		self.get_config()

					return config, pixel_values, labels

			def UpperCamelCase__ (							self					:			Optional[Any]						):





					"""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					:			Optional[int]							,					lowerCAmelCase__					:			Tuple							,					lowerCAmelCase__					:			Tuple							,					lowerCAmelCase__					:			int						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		Optional[int]   	=		SwinModel(config=lowerCAmelCase__						)
					model.to(lowerCAmelCase__						)
					model.eval()
					__SCREAMING_SNAKE_CASE	:		List[str]   	=		model(lowerCAmelCase__						)

					__SCREAMING_SNAKE_CASE	:		List[str]   	=		((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths						) - 1))
					__SCREAMING_SNAKE_CASE	:		Dict   	=		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					:			List[Any]							,					lowerCAmelCase__					:			Dict							,					lowerCAmelCase__					:			int							,					lowerCAmelCase__					:			Tuple						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		Tuple   	=		SwinBackbone(config=lowerCAmelCase__						)
					model.to(lowerCAmelCase__						)
					model.eval()
					__SCREAMING_SNAKE_CASE	:		Any   	=		model(lowerCAmelCase__						)

					# 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], 1_6, 1_6]						)

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

					# verify backbone works with out_features=None
					__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		None
					__SCREAMING_SNAKE_CASE	:		str   	=		SwinBackbone(config=lowerCAmelCase__						)
					model.to(lowerCAmelCase__						)
					model.eval()
					__SCREAMING_SNAKE_CASE	:		List[Any]   	=		model(lowerCAmelCase__						)

					# 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					:			Tuple							,					lowerCAmelCase__					:			Dict							,					lowerCAmelCase__					:			Optional[Any]							,					lowerCAmelCase__					:			List[Any]						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		Any   	=		SwinForMaskedImageModeling(config=lowerCAmelCase__						)
					model.to(lowerCAmelCase__						)
					model.eval()
					__SCREAMING_SNAKE_CASE	:		List[str]   	=		model(lowerCAmelCase__						)
					self.parent.assertEqual(
					    result.logits.shape							,					(self.batch_size, self.num_channels, self.image_size, self.image_size)						)

					# test greyscale images
					__SCREAMING_SNAKE_CASE	:		Union[str, Any]   	=		1
					__SCREAMING_SNAKE_CASE	:		Dict   	=		SwinForMaskedImageModeling(lowerCAmelCase__						)
					model.to(lowerCAmelCase__						)
					model.eval()

					__SCREAMING_SNAKE_CASE	:		List[Any]   	=		floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
					__SCREAMING_SNAKE_CASE	:		Optional[int]   	=		model(lowerCAmelCase__						)
					self.parent.assertEqual(result.logits.shape							,					(self.batch_size, 1, self.image_size, self.image_size)						)

			def UpperCamelCase__ (							self					:			Dict							,					lowerCAmelCase__					:			Any							,					lowerCAmelCase__					:			Any							,					lowerCAmelCase__					:			Dict						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		List[Any]   	=		self.type_sequence_label_size
					__SCREAMING_SNAKE_CASE	:		Dict   	=		SwinForImageClassification(lowerCAmelCase__						)
					model.to(lowerCAmelCase__						)
					model.eval()
					__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		model(lowerCAmelCase__							,					labels=lowerCAmelCase__						)
					self.parent.assertEqual(result.logits.shape							,					(self.batch_size, self.type_sequence_label_size)						)

					# test greyscale images
					__SCREAMING_SNAKE_CASE	:		Dict   	=		1
					__SCREAMING_SNAKE_CASE	:		Union[str, Any]   	=		SwinForImageClassification(lowerCAmelCase__						)
					model.to(lowerCAmelCase__						)
					model.eval()

					__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
					__SCREAMING_SNAKE_CASE	:		Dict   	=		model(lowerCAmelCase__						)
					self.parent.assertEqual(result.logits.shape							,					(self.batch_size, self.type_sequence_label_size)						)



			def UpperCamelCase__ (							self					:			Union[str, Any]						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		str   	=		self.prepare_config_and_inputs()
					(
					    (
					    __SCREAMING_SNAKE_CASE
					)	,						(
					    __SCREAMING_SNAKE_CASE
					)	,						(
					    __SCREAMING_SNAKE_CASE
					)	,						
					)	:		Union[str, Any]   	=		config_and_inputs
					__SCREAMING_SNAKE_CASE	:		Any   	=		{"""pixel_values""": pixel_values}
					return config, inputs_dict






@require_torch
class 						_UpperCamelCase  (							lowerCamelCase__   , lowerCamelCase__   , unittest.TestCase   ):


			'''simple docstring'''

			_A				:		Dict         =		(
			    (
			        SwinModel,
			        SwinBackbone,
			        SwinForImageClassification,
			        SwinForMaskedImageModeling,
			    )
			    if is_torch_available()
			    else ()
			)
			_A				:		List[str]         =		(
			    {'''feature-extraction''': SwinModel, '''image-classification''': SwinForImageClassification}
			    if is_torch_available()
			    else {}
			)
			_A				:		int         =		True

			_A				:		str         =		False
			_A				:		str         =		False
			_A				:		Optional[int]         =		False

			def UpperCamelCase__ (							self					:			str						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		List[str]   	=		SwinModelTester(self						)
					__SCREAMING_SNAKE_CASE	:		Dict   	=		ConfigTester(self							,					config_class=lowerCAmelCase__							,					embed_dim=3_7						)

			def UpperCamelCase__ (							self					:			Any						):





					"""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						):





					"""simple docstring"""






					return

			def UpperCamelCase__ (							self					:			Optional[Any]						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		Dict   	=		self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*lowerCAmelCase__						)

			@unittest.skip(reason="""Got `CUDA error: misaligned address` with PyTorch 2.0.0."""						)
			def UpperCamelCase__ (							self					:			Optional[int]						):





					"""simple docstring"""






					pass

			def UpperCamelCase__ (							self					:			int						):





					"""simple docstring"""






					super().test_training_gradient_checkpointing()

			def UpperCamelCase__ (							self					:			Tuple						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		int   	=		self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_backbone(*lowerCAmelCase__						)

			def UpperCamelCase__ (							self					:			Dict						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		Union[str, Any]   	=		self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_masked_image_modeling(*lowerCAmelCase__						)

			def UpperCamelCase__ (							self					:			List[Any]						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		str   	=		self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__						)

			@unittest.skip(reason="""Swin does not use inputs_embeds"""						)
			def UpperCamelCase__ (							self					:			List[Any]						):





					"""simple docstring"""






					pass

			@unittest.skip(reason="""Swin Transformer does not use feedforward chunking"""						)
			def UpperCamelCase__ (							self					:			str						):





					"""simple docstring"""






					pass

			def UpperCamelCase__ (							self					:			int						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	:		Tuple   	=		self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
							__SCREAMING_SNAKE_CASE	:		List[Any]   	=		model_class(lowerCAmelCase__						)
							self.assertIsInstance(model.get_input_embeddings()							,					(nn.Module)						)
							__SCREAMING_SNAKE_CASE	:		Optional[int]   	=		model.get_output_embeddings()
							self.assertTrue(x is None or isinstance(lowerCAmelCase__							,					nn.Linear						)						)

			def UpperCamelCase__ (							self					:			Optional[int]						):





					"""simple docstring"""






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

					for model_class in self.all_model_classes:
							__SCREAMING_SNAKE_CASE	:		Any   	=		model_class(lowerCAmelCase__						)
							__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		inspect.signature(model.forward						)
							# signature.parameters is an OrderedDict => so arg_names order is deterministic
							__SCREAMING_SNAKE_CASE	:		str   	=		[*signature.parameters.keys()]

							__SCREAMING_SNAKE_CASE	:		List[Any]   	=		["""pixel_values"""]
							self.assertListEqual(arg_names[:1]							,					lowerCAmelCase__						)

			def UpperCamelCase__ (							self					:			List[Any]						):





					"""simple docstring"""






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

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

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

							self.assertListEqual(
							    list(attentions[0].shape[-3:]						)							,					[self.model_tester.num_heads[0], window_size_squared, window_size_squared]							,					)
							__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		len(lowerCAmelCase__						)

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

							# also another +1 for reshaped_hidden_states
							__SCREAMING_SNAKE_CASE	:		List[str]   	=		1 if model_class.__name__ == """SwinBackbone""" else 2
							self.assertEqual(out_len + added_hidden_states							,					len(lowerCAmelCase__						)						)

							__SCREAMING_SNAKE_CASE	:		Optional[int]   	=		outputs.attentions

							self.assertEqual(len(lowerCAmelCase__						)							,					lowerCAmelCase__						)

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

			def UpperCamelCase__ (							self					:			Optional[int]							,					lowerCAmelCase__					:			int							,					lowerCAmelCase__					:			Tuple							,					lowerCAmelCase__					:			str							,					lowerCAmelCase__					:			Optional[Any]						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		Optional[int]   	=		model_class(lowerCAmelCase__						)
					model.to(lowerCAmelCase__						)
					model.eval()

					with torch.no_grad():
							__SCREAMING_SNAKE_CASE	:		Tuple   	=		model(**self._prepare_for_class(lowerCAmelCase__							,					lowerCAmelCase__						)						)

					__SCREAMING_SNAKE_CASE	:		List[str]   	=		outputs.hidden_states

					__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		getattr(
					    self.model_tester							,					"""expected_num_hidden_layers"""							,					len(self.model_tester.depths						) + 1						)
					self.assertEqual(len(lowerCAmelCase__						)							,					lowerCAmelCase__						)

					# Swin has a different seq_length
					__SCREAMING_SNAKE_CASE	:		List[str]   	=		(
					    config.patch_size
					    if isinstance(config.patch_size							,					collections.abc.Iterable						)
					    else (config.patch_size, config.patch_size)
					)

					__SCREAMING_SNAKE_CASE	:		Any   	=		(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":
							__SCREAMING_SNAKE_CASE	:		int   	=		outputs.reshaped_hidden_states
							self.assertEqual(len(lowerCAmelCase__						)							,					lowerCAmelCase__						)

							__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	:		int   	=		reshaped_hidden_states[0].shape
							__SCREAMING_SNAKE_CASE	:		List[Any]   	=		(
							    reshaped_hidden_states[0].view(lowerCAmelCase__							,					lowerCAmelCase__							,					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[Any]						):





					"""simple docstring"""






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

					__SCREAMING_SNAKE_CASE	:		List[str]   	=		(
					    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:
							__SCREAMING_SNAKE_CASE	:		Optional[int]   	=		True
							self.check_hidden_states_output(lowerCAmelCase__							,					lowerCAmelCase__							,					lowerCAmelCase__							,					lowerCAmelCase__						)

							# check that output_hidden_states also work using config
							del inputs_dict["output_hidden_states"]
							__SCREAMING_SNAKE_CASE	:		Optional[int]   	=		True

							self.check_hidden_states_output(lowerCAmelCase__							,					lowerCAmelCase__							,					lowerCAmelCase__							,					lowerCAmelCase__						)

			def UpperCamelCase__ (							self					:			Tuple						):





					"""simple docstring"""






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

					__SCREAMING_SNAKE_CASE	:		Any   	=		(
					    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)
					)
					__SCREAMING_SNAKE_CASE	:		List[Any]   	=		(
					    config.patch_size
					    if isinstance(config.patch_size							,					collections.abc.Iterable						)
					    else (config.patch_size, config.patch_size)
					)

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

					for model_class in self.all_model_classes:
							__SCREAMING_SNAKE_CASE	:		int   	=		True
							self.check_hidden_states_output(lowerCAmelCase__							,					lowerCAmelCase__							,					lowerCAmelCase__							,					(padded_height, padded_width)						)

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

			@slow
			def UpperCamelCase__ (							self					:			Optional[int]						):





					"""simple docstring"""






					for model_name in SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							__SCREAMING_SNAKE_CASE	:		Optional[int]   	=		SwinModel.from_pretrained(lowerCAmelCase__						)
							self.assertIsNotNone(lowerCAmelCase__						)



			def UpperCamelCase__ (							self					:			Union[str, Any]						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		self.model_tester.prepare_config_and_inputs_for_common()

					__SCREAMING_SNAKE_CASE	:		Any   	=		_config_zero_init(lowerCAmelCase__						)
					for model_class in self.all_model_classes:
							__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		model_class(config=lowerCAmelCase__						)
							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 						_UpperCamelCase  (							unittest.TestCase   ):


			'''simple docstring'''

			@cached_property
			def UpperCamelCase__ (							self					:			Optional[int]						):





					"""simple docstring"""






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



			@slow
			def UpperCamelCase__ (							self					:			Optional[int]						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		List[Any]   	=		SwinForImageClassification.from_pretrained("""microsoft/swin-tiny-patch4-window7-224"""						).to(lowerCAmelCase__						)
					__SCREAMING_SNAKE_CASE	:		Union[str, Any]   	=		self.default_image_processor

					__SCREAMING_SNAKE_CASE	:		Dict   	=		Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""						)
					__SCREAMING_SNAKE_CASE	:		Optional[int]   	=		image_processor(images=lowerCAmelCase__							,					return_tensors="""pt"""						).to(lowerCAmelCase__						)

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

					# verify the logits
					__SCREAMING_SNAKE_CASE	:		List[str]   	=		torch.Size((1, 1_0_0_0)						)
					self.assertEqual(outputs.logits.shape							,					lowerCAmelCase__						)
					__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		torch.tensor([-0.09_48, -0.64_54, -0.09_21]						).to(lowerCAmelCase__						)
					self.assertTrue(torch.allclose(outputs.logits[0, :3]							,					lowerCAmelCase__							,					atol=1E-4						)						)






@require_torch
class 						_UpperCamelCase  (							unittest.TestCase   , lowerCamelCase__   ):


			'''simple docstring'''

			_A				:		Tuple         =		(SwinBackbone,) if is_torch_available() else ()
			_A				:		Optional[int]         =		SwinConfig

			def UpperCamelCase__ (							self					:			Optional[int]						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		Tuple   	=		SwinModelTester(self						)




'''simple docstring'''




import math
from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPTextModelWithProjection, CLIPTokenizer

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


UpperCamelCase__	:     List[str]    =			logging.get_logger(__name__)  # pylint: disable=invalid-name

UpperCamelCase__	:     Tuple    =			'''
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import DiffusionPipeline
        >>> from diffusers.utils import export_to_gif

        >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

        >>> repo = "openai/shap-e"
        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)
        >>> pipe = pipe.to(device)

        >>> guidance_scale = 15.0
        >>> prompt = "a shark"

        >>> images = pipe(
        ...     prompt,
        ...     guidance_scale=guidance_scale,
        ...     num_inference_steps=64,
        ...     frame_size=256,
        ... ).images

        >>> gif_path = export_to_gif(images[0], "shark_3d.gif")
        ```
'''






@dataclass
class 						_UpperCamelCase  (							lowerCamelCase__   ):


			'''simple docstring'''

			_A				:		Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]






class 						_UpperCamelCase  (							lowerCamelCase__   ):


			'''simple docstring'''

			def __init__(							self					:			List[str]							,					lowerCAmelCase__					:			PriorTransformer							,					lowerCAmelCase__					:			CLIPTextModelWithProjection							,					lowerCAmelCase__					:			CLIPTokenizer							,					lowerCAmelCase__					:			HeunDiscreteScheduler							,					lowerCAmelCase__					:			ShapERenderer							,					):





					"""simple docstring"""






					super().__init__()

					self.register_modules(
					    prior=lowerCAmelCase__							,					text_encoder=lowerCAmelCase__							,					tokenizer=lowerCAmelCase__							,					scheduler=lowerCAmelCase__							,					renderer=lowerCAmelCase__							,					)

			def UpperCamelCase__ (							self					:			Tuple							,					lowerCAmelCase__					:			List[Any]							,					lowerCAmelCase__					:			List[str]							,					lowerCAmelCase__					:			Any							,					lowerCAmelCase__					:			Dict							,					lowerCAmelCase__					:			List[Any]							,					lowerCAmelCase__					:			int						):





					"""simple docstring"""






					if latents is None:
							__SCREAMING_SNAKE_CASE	:		Optional[int]   	=		randn_tensor(lowerCAmelCase__							,					generator=lowerCAmelCase__							,					device=lowerCAmelCase__							,					dtype=lowerCAmelCase__						)
					else:
							if latents.shape != shape:
									raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {shape}"						)
							__SCREAMING_SNAKE_CASE	:		Any   	=		latents.to(lowerCAmelCase__						)

					__SCREAMING_SNAKE_CASE	:		Dict   	=		latents * scheduler.init_noise_sigma
					return latents

			def UpperCamelCase__ (							self					:			str							,					lowerCAmelCase__					:			int=0						):





					"""simple docstring"""






					if is_accelerate_available():
							from accelerate import cpu_offload
					else:
							raise ImportError("""Please install accelerate via `pip install accelerate`"""						)

					__SCREAMING_SNAKE_CASE	:		List[str]   	=		torch.device(F"cuda:{gpu_id}"						)

					__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		[self.text_encoder, self.prior]
					for cpu_offloaded_model in models:
							if cpu_offloaded_model is not None:
									cpu_offload(lowerCAmelCase__							,					lowerCAmelCase__						)

			def UpperCamelCase__ (							self					:			int							,					lowerCAmelCase__					:			str=0						):





					"""simple docstring"""






					if is_accelerate_available() and is_accelerate_version(""">="""							,					"""0.17.0.dev0"""						):
							from accelerate import cpu_offload_with_hook
					else:
							raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher."""						)

					__SCREAMING_SNAKE_CASE	:		List[str]   	=		torch.device(F"cuda:{gpu_id}"						)

					if self.device.type != "cpu":
							self.to("""cpu"""							,					silence_dtype_warnings=lowerCAmelCase__						)
							torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

					__SCREAMING_SNAKE_CASE	:		List[str]   	=		None
					for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
							__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	:		Dict   	=		cpu_offload_with_hook(lowerCAmelCase__							,					lowerCAmelCase__							,					prev_module_hook=lowerCAmelCase__						)

					if self.safety_checker is not None:
							__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	:		List[str]   	=		cpu_offload_with_hook(self.safety_checker							,					lowerCAmelCase__							,					prev_module_hook=lowerCAmelCase__						)

					# We'll offload the last model manually.
					__SCREAMING_SNAKE_CASE	:		str   	=		hook

			@property
			def UpperCamelCase__ (							self					:			List[str]						):





					"""simple docstring"""






					if self.device != torch.device("""meta"""						) or not hasattr(self.text_encoder							,					"""_hf_hook"""						):
							return self.device
					for module in self.text_encoder.modules():
							if (
							    hasattr(lowerCAmelCase__							,					"""_hf_hook"""						)
							    and hasattr(module._hf_hook							,					"""execution_device"""						)
							    and module._hf_hook.execution_device is not None
							):
									return torch.device(module._hf_hook.execution_device						)
					return self.device

			def UpperCamelCase__ (							self					:			Optional[int]							,					lowerCAmelCase__					:			Any							,					lowerCAmelCase__					:			Any							,					lowerCAmelCase__					:			Any							,					lowerCAmelCase__					:			Tuple							,					):





					"""simple docstring"""






					len(lowerCAmelCase__						) if isinstance(lowerCAmelCase__							,					lowerCAmelCase__						) else 1

					# YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
					__SCREAMING_SNAKE_CASE	:		Union[str, Any]   	=		0
					# get prompt text embeddings
					__SCREAMING_SNAKE_CASE	:		Tuple   	=		self.tokenizer(
					    lowerCAmelCase__							,					padding="""max_length"""							,					max_length=self.tokenizer.model_max_length							,					truncation=lowerCAmelCase__							,					return_tensors="""pt"""							,					)
					__SCREAMING_SNAKE_CASE	:		str   	=		text_inputs.input_ids
					__SCREAMING_SNAKE_CASE	:		Dict   	=		self.tokenizer(lowerCAmelCase__							,					padding="""longest"""							,					return_tensors="""pt"""						).input_ids

					if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(lowerCAmelCase__							,					lowerCAmelCase__						):
							__SCREAMING_SNAKE_CASE	:		Dict   	=		self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]						)
							logger.warning(
							    """The following part of your input was truncated because CLIP can only handle sequences up to"""
							    F" {self.tokenizer.model_max_length} tokens: {removed_text}"						)

					__SCREAMING_SNAKE_CASE	:		Any   	=		self.text_encoder(text_input_ids.to(lowerCAmelCase__						)						)
					__SCREAMING_SNAKE_CASE	:		Any   	=		text_encoder_output.text_embeds

					__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		prompt_embeds.repeat_interleave(lowerCAmelCase__							,					dim=0						)
					# in Shap-E it normalize the prompt_embeds and then later rescale it
					__SCREAMING_SNAKE_CASE	:		Optional[int]   	=		prompt_embeds / torch.linalg.norm(lowerCAmelCase__							,					dim=-1							,					keepdim=lowerCAmelCase__						)

					if do_classifier_free_guidance:
							__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		torch.zeros_like(lowerCAmelCase__						)

							# For classifier free guidance, we need to do two forward passes.
							# Here we concatenate the unconditional and text embeddings into a single batch
							# to avoid doing two forward passes
							__SCREAMING_SNAKE_CASE	:		List[str]   	=		torch.cat([negative_prompt_embeds, prompt_embeds]						)

					# Rescale the features to have unit variance
					__SCREAMING_SNAKE_CASE	:		Tuple   	=		math.sqrt(prompt_embeds.shape[1]						) * prompt_embeds

					return prompt_embeds



			@torch.no_grad()
			@replace_example_docstring(lowerCAmelCase__						)
			def __call__(							self					:			Union[str, Any]							,					lowerCAmelCase__					:			str							,					lowerCAmelCase__					:			int = 1							,					lowerCAmelCase__					:			int = 2_5							,					lowerCAmelCase__					:			Optional[Union[torch.Generator, List[torch.Generator]]] = None							,					lowerCAmelCase__					:			Optional[torch.FloatTensor] = None							,					lowerCAmelCase__					:			float = 4.0							,					lowerCAmelCase__					:			int = 6_4							,					lowerCAmelCase__					:			Optional[str] = "pil"							,					lowerCAmelCase__					:			bool = True							,					):





					"""simple docstring"""






					if isinstance(lowerCAmelCase__							,					lowerCAmelCase__						):
							__SCREAMING_SNAKE_CASE	:		str   	=		1
					elif isinstance(lowerCAmelCase__							,					lowerCAmelCase__						):
							__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		len(lowerCAmelCase__						)
					else:
							raise ValueError(F"`prompt` has to be of type `str` or `list` but is {type(lowerCAmelCase__						)}"						)

					__SCREAMING_SNAKE_CASE	:		Dict   	=		self._execution_device

					__SCREAMING_SNAKE_CASE	:		str   	=		batch_size * num_images_per_prompt

					__SCREAMING_SNAKE_CASE	:		str   	=		guidance_scale > 1.0
					__SCREAMING_SNAKE_CASE	:		int   	=		self._encode_prompt(lowerCAmelCase__							,					lowerCAmelCase__							,					lowerCAmelCase__							,					lowerCAmelCase__						)

					# prior

					self.scheduler.set_timesteps(lowerCAmelCase__							,					device=lowerCAmelCase__						)
					__SCREAMING_SNAKE_CASE	:		Union[str, Any]   	=		self.scheduler.timesteps

					__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		self.prior.config.num_embeddings
					__SCREAMING_SNAKE_CASE	:		int   	=		self.prior.config.embedding_dim

					__SCREAMING_SNAKE_CASE	:		str   	=		self.prepare_latents(
					    (batch_size, num_embeddings * embedding_dim)							,					prompt_embeds.dtype							,					lowerCAmelCase__							,					lowerCAmelCase__							,					lowerCAmelCase__							,					self.scheduler							,					)

					# YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim
					__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		latents.reshape(latents.shape[0]							,					lowerCAmelCase__							,					lowerCAmelCase__						)

					for i, t in enumerate(self.progress_bar(lowerCAmelCase__						)						):
							# expand the latents if we are doing classifier free guidance
							__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		torch.cat([latents] * 2						) if do_classifier_free_guidance else latents
							__SCREAMING_SNAKE_CASE	:		str   	=		self.scheduler.scale_model_input(lowerCAmelCase__							,					lowerCAmelCase__						)

							__SCREAMING_SNAKE_CASE	:		str   	=		self.prior(
							    lowerCAmelCase__							,					timestep=lowerCAmelCase__							,					proj_embedding=lowerCAmelCase__							,					).predicted_image_embedding

							# remove the variance
							__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	:		List[Any]   	=		noise_pred.split(
							    scaled_model_input.shape[2]							,					dim=2						)  # batch_size, num_embeddings, embedding_dim

							if do_classifier_free_guidance is not None:
									__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	:		Any   	=		noise_pred.chunk(2						)
									__SCREAMING_SNAKE_CASE	:		str   	=		noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

							__SCREAMING_SNAKE_CASE	:		str   	=		self.scheduler.step(
							    lowerCAmelCase__							,					timestep=lowerCAmelCase__							,					sample=lowerCAmelCase__							,					).prev_sample

					if output_type == "latent":
							return ShapEPipelineOutput(images=lowerCAmelCase__						)

					__SCREAMING_SNAKE_CASE	:		Dict   	=		[]
					for i, latent in enumerate(lowerCAmelCase__						):
							__SCREAMING_SNAKE_CASE	:		List[Any]   	=		self.renderer.decode(
							    latent[None, :]							,					lowerCAmelCase__							,					size=lowerCAmelCase__							,					ray_batch_size=4_0_9_6							,					n_coarse_samples=6_4							,					n_fine_samples=1_2_8							,					)
							images.append(lowerCAmelCase__						)

					__SCREAMING_SNAKE_CASE	:		Dict   	=		torch.stack(lowerCAmelCase__						)

					if output_type not in ["np", "pil"]:
							raise ValueError(F"Only the output types `pil` and `np` are supported not output_type={output_type}"						)

					__SCREAMING_SNAKE_CASE	:		str   	=		images.cpu().numpy()

					if output_type == "pil":
							__SCREAMING_SNAKE_CASE	:		int   	=		[self.numpy_to_pil(lowerCAmelCase__						) for image in images]

					# Offload last model to CPU
					if hasattr(self							,					"""final_offload_hook"""						) and self.final_offload_hook is not None:
							self.final_offload_hook.offload()

					if not return_dict:
							return (images,)

					return ShapEPipelineOutput(images=lowerCAmelCase__						)