code: 
  
  
  
  
  """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 			lowerCamelCase__    :
  
  
  			def __init__(     self				, SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE=13				, SCREAMING_SNAKE_CASE=32				, SCREAMING_SNAKE_CASE=2				, SCREAMING_SNAKE_CASE=3				, SCREAMING_SNAKE_CASE=16				, SCREAMING_SNAKE_CASE=[1, 2, 1]				, SCREAMING_SNAKE_CASE=[2, 2, 4]				, SCREAMING_SNAKE_CASE=2				, SCREAMING_SNAKE_CASE=2.0				, SCREAMING_SNAKE_CASE=True				, SCREAMING_SNAKE_CASE=0.0				, SCREAMING_SNAKE_CASE=0.0				, SCREAMING_SNAKE_CASE=0.1				, SCREAMING_SNAKE_CASE="gelu"				, SCREAMING_SNAKE_CASE=False				, SCREAMING_SNAKE_CASE=True				, SCREAMING_SNAKE_CASE=0.02				, SCREAMING_SNAKE_CASE=1E-5				, SCREAMING_SNAKE_CASE=True				, SCREAMING_SNAKE_CASE=None				, SCREAMING_SNAKE_CASE=True				, SCREAMING_SNAKE_CASE=10				, SCREAMING_SNAKE_CASE=8				, SCREAMING_SNAKE_CASE=["stage1", "stage2"]				, SCREAMING_SNAKE_CASE=[1, 2]				, ):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					snake_case		:						str								=				parent
  					snake_case		:						Any								=				batch_size
  					snake_case		:						List[str]								=				image_size
  					snake_case		:						Tuple								=				patch_size
  					snake_case		:						Tuple								=				num_channels
  					snake_case		:						List[str]								=				embed_dim
  					snake_case		:						Optional[int]								=				depths
  					snake_case		:						Optional[int]								=				num_heads
  					snake_case		:						int								=				window_size
  					snake_case		:						List[str]								=				mlp_ratio
  					snake_case		:						Dict								=				qkv_bias
  					snake_case		:						int								=				hidden_dropout_prob
  					snake_case		:						Any								=				attention_probs_dropout_prob
  					snake_case		:						str								=				drop_path_rate
  					snake_case		:						Optional[int]								=				hidden_act
  					snake_case		:						Dict								=				use_absolute_embeddings
  					snake_case		:						str								=				patch_norm
  					snake_case		:						int								=				layer_norm_eps
  					snake_case		:						Dict								=				initializer_range
  					snake_case		:						List[Any]								=				is_training
  					snake_case		:						List[Any]								=				scope
  					snake_case		:						Any								=				use_labels
  					snake_case		:						int								=				type_sequence_label_size
  					snake_case		:						Union[str, Any]								=				encoder_stride
  					snake_case		:						Any								=				out_features
  					snake_case		:						str								=				out_indices
  
  
  			def 							lowerCamelCase_				(     self							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					snake_case		:						Optional[int]								=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)
  
  					snake_case		:						Any								=				None
  					if self.use_labels:
  							snake_case		:						List[Any]								=				ids_tensor([self.batch_size]				, self.type_sequence_label_size							)
  
  					snake_case		:						str								=				self.get_config()
  
  					return config, pixel_values, labels
  
  
  			def 							lowerCamelCase_				(     self							):
  
  
  
  					"""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 							lowerCamelCase_				(     self				, SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					snake_case		:						List[Any]								=				SwinModel(config=SCREAMING_SNAKE_CASE							)
  					model.to(SCREAMING_SNAKE_CASE							)
  					model.eval()
  					snake_case		:						List[Any]								=				model(SCREAMING_SNAKE_CASE							)
  
  					snake_case		:						Optional[int]								=				((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths							) - 1))
  					snake_case		:						Tuple								=				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 							lowerCamelCase_				(     self				, SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					snake_case		:						Any								=				SwinBackbone(config=SCREAMING_SNAKE_CASE							)
  					model.to(SCREAMING_SNAKE_CASE							)
  					model.eval()
  					snake_case		:						List[str]								=				model(SCREAMING_SNAKE_CASE							)
  
  					# 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		:						Dict								=				SwinBackbone(config=SCREAMING_SNAKE_CASE							)
  					model.to(SCREAMING_SNAKE_CASE							)
  					model.eval()
  					snake_case		:						Dict								=				model(SCREAMING_SNAKE_CASE							)
  
  					# 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 							lowerCamelCase_				(     self				, SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					snake_case		:						Optional[Any]								=				SwinForMaskedImageModeling(config=SCREAMING_SNAKE_CASE							)
  					model.to(SCREAMING_SNAKE_CASE							)
  					model.eval()
  					snake_case		:						Optional[int]								=				model(SCREAMING_SNAKE_CASE							)
  					self.parent.assertEqual(
  					    result.logits.shape				, (self.batch_size, self.num_channels, self.image_size, self.image_size)							)
  
  					# test greyscale images
  					snake_case		:						List[str]								=				1
  					snake_case		:						str								=				SwinForMaskedImageModeling(SCREAMING_SNAKE_CASE							)
  					model.to(SCREAMING_SNAKE_CASE							)
  					model.eval()
  
  					snake_case		:						List[str]								=				floats_tensor([self.batch_size, 1, self.image_size, self.image_size]							)
  					snake_case		:						List[str]								=				model(SCREAMING_SNAKE_CASE							)
  					self.parent.assertEqual(result.logits.shape				, (self.batch_size, 1, self.image_size, self.image_size)							)
  
  
  			def 							lowerCamelCase_				(     self				, SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					snake_case		:						List[str]								=				self.type_sequence_label_size
  					snake_case		:						Union[str, Any]								=				SwinForImageClassification(SCREAMING_SNAKE_CASE							)
  					model.to(SCREAMING_SNAKE_CASE							)
  					model.eval()
  					snake_case		:						Tuple								=				model(SCREAMING_SNAKE_CASE				, labels=SCREAMING_SNAKE_CASE							)
  					self.parent.assertEqual(result.logits.shape				, (self.batch_size, self.type_sequence_label_size)							)
  
  					# test greyscale images
  					snake_case		:						Tuple								=				1
  					snake_case		:						int								=				SwinForImageClassification(SCREAMING_SNAKE_CASE							)
  					model.to(SCREAMING_SNAKE_CASE							)
  					model.eval()
  
  					snake_case		:						Union[str, Any]								=				floats_tensor([self.batch_size, 1, self.image_size, self.image_size]							)
  					snake_case		:						Tuple								=				model(SCREAMING_SNAKE_CASE							)
  					self.parent.assertEqual(result.logits.shape				, (self.batch_size, self.type_sequence_label_size)							)
  
  
  
  			def 							lowerCamelCase_				(     self							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					snake_case		:						Any								=				self.prepare_config_and_inputs()
  					(
  					    (
  					    snake_case
  					)			,				(
  					    snake_case
  					)			,				(
  					    snake_case
  					)			,				
  					)		:						Dict								=				config_and_inputs
  					snake_case		:						Any								=				{"pixel_values": pixel_values}
  					return config, inputs_dict
  
  
  
  
  
  
  
  @require_torch
  class 			lowerCamelCase__    (  lowerCamelCase_				,  lowerCamelCase_				,  unittest.TestCase			):
  			a__ :      Optional[int]								=     (
  			    (
  			        SwinModel,
  			        SwinBackbone,
  			        SwinForImageClassification,
  			        SwinForMaskedImageModeling,
  			    )
  			    if is_torch_available()
  			    else ()
  			)
  			a__ :      List[str]								=     (
  			    {"""feature-extraction""": SwinModel, """image-classification""": SwinForImageClassification}
  			    if is_torch_available()
  			    else {}
  			)
  			a__ :      Optional[int]								=     True
  
  			a__ :      Optional[Any]								=     False
  			a__ :      Union[str, Any]								=     False
  			a__ :      Union[str, Any]								=     False
  
  
  			def 							lowerCamelCase_				(     self							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					snake_case		:						Optional[int]								=				SwinModelTester(self							)
  					snake_case		:						List[str]								=				ConfigTester(self				, config_class=SCREAMING_SNAKE_CASE				, embed_dim=37							)
  
  
  			def 							lowerCamelCase_				(     self							):
  
  
  
  					"""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 							lowerCamelCase_				(     self							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					return
  
  
  			def 							lowerCamelCase_				(     self							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					snake_case		:						Optional[Any]								=				self.model_tester.prepare_config_and_inputs()
  					self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE							)
  
  
  			@unittest.skip(reason="Got `CUDA error: misaligned address` with PyTorch 2.0.0."							)
  			def 							lowerCamelCase_				(     self							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					pass
  
  
  			def 							lowerCamelCase_				(     self							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					super().test_training_gradient_checkpointing()
  
  
  			def 							lowerCamelCase_				(     self							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					snake_case		:						Union[str, Any]								=				self.model_tester.prepare_config_and_inputs()
  					self.model_tester.create_and_check_backbone(*SCREAMING_SNAKE_CASE							)
  
  
  			def 							lowerCamelCase_				(     self							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					snake_case		:						str								=				self.model_tester.prepare_config_and_inputs()
  					self.model_tester.create_and_check_for_masked_image_modeling(*SCREAMING_SNAKE_CASE							)
  
  
  			def 							lowerCamelCase_				(     self							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					snake_case		:						List[Any]								=				self.model_tester.prepare_config_and_inputs()
  					self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE							)
  
  
  			@unittest.skip(reason="Swin does not use inputs_embeds"							)
  			def 							lowerCamelCase_				(     self							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					pass
  
  
  			@unittest.skip(reason="Swin Transformer does not use feedforward chunking"							)
  			def 							lowerCamelCase_				(     self							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					pass
  
  
  			def 							lowerCamelCase_				(     self							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					snake_case			,				snake_case		:						str								=				self.model_tester.prepare_config_and_inputs_for_common()
  
  					for model_class in self.all_model_classes:
  							snake_case		:						Union[str, Any]								=				model_class(SCREAMING_SNAKE_CASE							)
  							self.assertIsInstance(model.get_input_embeddings()				, (nn.Module)							)
  							snake_case		:						Union[str, Any]								=				model.get_output_embeddings()
  							self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE				, nn.Linear							)							)
  
  
  			def 							lowerCamelCase_				(     self							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					snake_case			,				snake_case		:						Optional[Any]								=				self.model_tester.prepare_config_and_inputs_for_common()
  
  					for model_class in self.all_model_classes:
  							snake_case		:						str								=				model_class(SCREAMING_SNAKE_CASE							)
  							snake_case		:						Optional[int]								=				inspect.signature(model.forward							)
  							# signature.parameters is an OrderedDict => so arg_names order is deterministic
  							snake_case		:						Tuple								=				[*signature.parameters.keys()]
  
  							snake_case		:						Optional[Any]								=				["pixel_values"]
  							self.assertListEqual(arg_names[:1]				, SCREAMING_SNAKE_CASE							)
  
  
  			def 							lowerCamelCase_				(     self							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					snake_case			,				snake_case		:						int								=				self.model_tester.prepare_config_and_inputs_for_common()
  					snake_case		:						List[Any]								=				True
  
  					for model_class in self.all_model_classes:
  							snake_case		:						List[str]								=				True
  							snake_case		:						Optional[int]								=				False
  							snake_case		:						str								=				True
  							snake_case		:						Optional[int]								=				model_class(SCREAMING_SNAKE_CASE							)
  							model.to(SCREAMING_SNAKE_CASE							)
  							model.eval()
  							with torch.no_grad():
  									snake_case		:						Union[str, Any]								=				model(**self._prepare_for_class(SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE							)							)
  							snake_case		:						Union[str, Any]								=				outputs.attentions
  							snake_case		:						Optional[Any]								=				len(self.model_tester.depths							)
  							self.assertEqual(len(SCREAMING_SNAKE_CASE							)				, SCREAMING_SNAKE_CASE							)
  
  							# check that output_attentions also work using config
  							del inputs_dict["output_attentions"]
  							snake_case		:						Any								=				True
  							snake_case		:						int								=				config.window_size**2
  							snake_case		:						Tuple								=				model_class(SCREAMING_SNAKE_CASE							)
  							model.to(SCREAMING_SNAKE_CASE							)
  							model.eval()
  							with torch.no_grad():
  									snake_case		:						int								=				model(**self._prepare_for_class(SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE							)							)
  							snake_case		:						Dict								=				outputs.attentions
  							self.assertEqual(len(SCREAMING_SNAKE_CASE							)				, SCREAMING_SNAKE_CASE							)
  
  							self.assertListEqual(
  							    list(attentions[0].shape[-3:]							)				, [self.model_tester.num_heads[0], window_size_squared, window_size_squared]				, )
  							snake_case		:						Optional[int]								=				len(SCREAMING_SNAKE_CASE							)
  
  							# Check attention is always last and order is fine
  							snake_case		:						str								=				True
  							snake_case		:						Any								=				True
  							snake_case		:						Optional[Any]								=				model_class(SCREAMING_SNAKE_CASE							)
  							model.to(SCREAMING_SNAKE_CASE							)
  							model.eval()
  							with torch.no_grad():
  									snake_case		:						int								=				model(**self._prepare_for_class(SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE							)							)
  
  							# 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(SCREAMING_SNAKE_CASE							)							)
  
  							snake_case		:						Optional[int]								=				outputs.attentions
  
  							self.assertEqual(len(SCREAMING_SNAKE_CASE							)				, SCREAMING_SNAKE_CASE							)
  
  							self.assertListEqual(
  							    list(self_attentions[0].shape[-3:]							)				, [self.model_tester.num_heads[0], window_size_squared, window_size_squared]				, )
  
  
  			def 							lowerCamelCase_				(     self				, SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					snake_case		:						List[str]								=				model_class(SCREAMING_SNAKE_CASE							)
  					model.to(SCREAMING_SNAKE_CASE							)
  					model.eval()
  
  					with torch.no_grad():
  							snake_case		:						int								=				model(**self._prepare_for_class(SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE							)							)
  
  					snake_case		:						Tuple								=				outputs.hidden_states
  
  					snake_case		:						str								=				getattr(
  					    self.model_tester				, "expected_num_hidden_layers"				, len(self.model_tester.depths							) + 1							)
  					self.assertEqual(len(SCREAMING_SNAKE_CASE							)				, SCREAMING_SNAKE_CASE							)
  
  					# Swin has a different seq_length
  					snake_case		:						List[str]								=				(
  					    config.patch_size
  					    if isinstance(config.patch_size				, collections.abc.Iterable							)
  					    else (config.patch_size, config.patch_size)
  					)
  
  					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":
  							snake_case		:						Optional[Any]								=				outputs.reshaped_hidden_states
  							self.assertEqual(len(SCREAMING_SNAKE_CASE							)				, SCREAMING_SNAKE_CASE							)
  
  							snake_case			,				snake_case			,				snake_case			,				snake_case		:						int								=				reshaped_hidden_states[0].shape
  							snake_case		:						Any								=				(
  							    reshaped_hidden_states[0].view(SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE				, height * width							).permute(0				, 2				, 1							)
  							)
  							self.assertListEqual(
  							    list(reshaped_hidden_states.shape[-2:]							)				, [num_patches, self.model_tester.embed_dim]				, )
  
  
  			def 							lowerCamelCase_				(     self							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					snake_case			,				snake_case		:						str								=				self.model_tester.prepare_config_and_inputs_for_common()
  
  					snake_case		:						Tuple								=				(
  					    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(SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE							)
  
  							# check that output_hidden_states also work using config
  							del inputs_dict["output_hidden_states"]
  							snake_case		:						Optional[Any]								=				True
  
  							self.check_hidden_states_output(SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE							)
  
  
  			def 							lowerCamelCase_				(     self							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					snake_case			,				snake_case		:						int								=				self.model_tester.prepare_config_and_inputs_for_common()
  					snake_case		:						Dict								=				3
  
  					snake_case		:						Optional[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)
  					)
  					snake_case		:						int								=				(
  					    config.patch_size
  					    if isinstance(config.patch_size				, collections.abc.Iterable							)
  					    else (config.patch_size, config.patch_size)
  					)
  
  					snake_case		:						Optional[Any]								=				image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
  					snake_case		:						List[str]								=				image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])
  
  					for model_class in self.all_model_classes:
  							snake_case		:						Dict								=				True
  							self.check_hidden_states_output(SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE				, (padded_height, padded_width)							)
  
  							# check that output_hidden_states also work using config
  							del inputs_dict["output_hidden_states"]
  							snake_case		:						Optional[int]								=				True
  							self.check_hidden_states_output(SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE				, (padded_height, padded_width)							)
  
  
  			@slow
  			def 							lowerCamelCase_				(     self							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					for model_name in SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
  							snake_case		:						Any								=				SwinModel.from_pretrained(SCREAMING_SNAKE_CASE							)
  							self.assertIsNotNone(SCREAMING_SNAKE_CASE							)
  
  
  
  			def 							lowerCamelCase_				(     self							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					snake_case			,				snake_case		:						int								=				self.model_tester.prepare_config_and_inputs_for_common()
  
  					snake_case		:						List[str]								=				_config_zero_init(SCREAMING_SNAKE_CASE							)
  					for model_class in self.all_model_classes:
  							snake_case		:						Dict								=				model_class(config=SCREAMING_SNAKE_CASE							)
  							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 			lowerCamelCase__    (  unittest.TestCase			):
  
  
  			@cached_property
  			def 							lowerCamelCase_				(     self							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					return (
  					    AutoImageProcessor.from_pretrained("microsoft/swin-tiny-patch4-window7-224"							)
  					    if is_vision_available()
  					    else None
  					)
  
  
  
  			@slow
  			def 							lowerCamelCase_				(     self							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					snake_case		:						int								=				SwinForImageClassification.from_pretrained("microsoft/swin-tiny-patch4-window7-224"							).to(SCREAMING_SNAKE_CASE							)
  					snake_case		:						Optional[Any]								=				self.default_image_processor
  
  					snake_case		:						Union[str, Any]								=				Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"							)
  					snake_case		:						str								=				image_processor(images=SCREAMING_SNAKE_CASE				, return_tensors="pt"							).to(SCREAMING_SNAKE_CASE							)
  
  					# forward pass
  					with torch.no_grad():
  							snake_case		:						str								=				model(**SCREAMING_SNAKE_CASE							)
  
  					# verify the logits
  					snake_case		:						Union[str, Any]								=				torch.Size((1, 1_000)							)
  					self.assertEqual(outputs.logits.shape				, SCREAMING_SNAKE_CASE							)
  					snake_case		:						Optional[int]								=				torch.tensor([-0.09_48, -0.64_54, -0.09_21]							).to(SCREAMING_SNAKE_CASE							)
  					self.assertTrue(torch.allclose(outputs.logits[0, :3]				, SCREAMING_SNAKE_CASE				, atol=1E-4							)							)
  
  
  
  
  
  
  
  @require_torch
  class 			lowerCamelCase__    (  unittest.TestCase				,  lowerCamelCase_			):
  			a__ :      str								=     (SwinBackbone,) if is_torch_available() else ()
  			a__ :      List[Any]								=     SwinConfig
  
  
  			def 							lowerCamelCase_				(     self							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					snake_case		:						Tuple								=				SwinModelTester(self							)
  
  
style_context: 
  
  
  
  
  """simple docstring"""
  
  import os
  import re
  import unicodedata
  from shutil import copyfile
  from typing import Any, Dict, List, Optional, Tuple
  
  import sentencepiece as spm
  
  from ...tokenization_utils import AddedToken, PreTrainedTokenizer
  from ...utils import logging
  
  
  __A 		=			logging.get_logger(__name__)
  __A 		=			{"vocab_file": "spiece.model"}
  
  __A 		=			{
      "vocab_file": {
          "google/fnet-base": "https://huggingface.co/google/fnet-base/resolve/main/spiece.model",
          "google/fnet-large": "https://huggingface.co/google/fnet-large/resolve/main/spiece.model",
      },
  }
  
  __A 		=			{
      "google/fnet-base": 512,
      "google/fnet-large": 512,
  }
  
  __A 		=			"▁"
  class 			lowerCamelCase__    (  lowerCamelCase_			):
  			a__ :      Dict								=     VOCAB_FILES_NAMES
  			a__ :      Tuple								=     PRETRAINED_VOCAB_FILES_MAP
  			a__ :      int								=     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  			a__ :      List[Any]								=     ["""input_ids""", """token_type_ids"""]
  
  
  			def __init__(     self				, SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE=False				, SCREAMING_SNAKE_CASE=True				, SCREAMING_SNAKE_CASE=True				, SCREAMING_SNAKE_CASE="<unk>"				, SCREAMING_SNAKE_CASE="[SEP]"				, SCREAMING_SNAKE_CASE="<pad>"				, SCREAMING_SNAKE_CASE="[CLS]"				, SCREAMING_SNAKE_CASE="[MASK]"				, SCREAMING_SNAKE_CASE = None				, **SCREAMING_SNAKE_CASE				, ):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					snake_case		:						Dict								=				(
  					    AddedToken(SCREAMING_SNAKE_CASE				, lstrip=SCREAMING_SNAKE_CASE				, rstrip=SCREAMING_SNAKE_CASE				, normalized=SCREAMING_SNAKE_CASE							)
  					    if isinstance(SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE							)
  					    else mask_token
  					)
  
  					snake_case		:						Optional[int]								=				{} if sp_model_kwargs is None else sp_model_kwargs
  
  					super().__init__(
  					    do_lower_case=SCREAMING_SNAKE_CASE				, remove_space=SCREAMING_SNAKE_CASE				, keep_accents=SCREAMING_SNAKE_CASE				, unk_token=SCREAMING_SNAKE_CASE				, sep_token=SCREAMING_SNAKE_CASE				, pad_token=SCREAMING_SNAKE_CASE				, cls_token=SCREAMING_SNAKE_CASE				, mask_token=SCREAMING_SNAKE_CASE				, sp_model_kwargs=self.sp_model_kwargs				, **SCREAMING_SNAKE_CASE				, )
  
  					snake_case		:						List[str]								=				do_lower_case
  					snake_case		:						Any								=				remove_space
  					snake_case		:						Union[str, Any]								=				keep_accents
  					snake_case		:						Optional[int]								=				vocab_file
  
  					snake_case		:						Dict								=				spm.SentencePieceProcessor(**self.sp_model_kwargs							)
  					self.sp_model.Load(SCREAMING_SNAKE_CASE							)
  
  
  			@property
  			def 							lowerCamelCase_				(     self							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					return len(self.sp_model							)
  
  
  			def 							lowerCamelCase_				(     self							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					snake_case		:						Optional[int]								=				{self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE							): i for i in range(self.vocab_size							)}
  					vocab.update(self.added_tokens_encoder							)
  					return vocab
  
  
  			def __getstate__(     self							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					snake_case		:						Tuple								=				self.__dict__.copy()
  					snake_case		:						List[Any]								=				None
  					return state
  
  
  			def __setstate__(     self				, SCREAMING_SNAKE_CASE							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					snake_case		:						Union[str, Any]								=				d
  
  					# for backward compatibility
  					if not hasattr(self				, "sp_model_kwargs"							):
  							snake_case		:						List[Any]								=				{}
  
  					snake_case		:						Tuple								=				spm.SentencePieceProcessor(**self.sp_model_kwargs							)
  					self.sp_model.Load(self.vocab_file							)
  
  
  			def 							lowerCamelCase_				(     self				, SCREAMING_SNAKE_CASE							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					if self.remove_space:
  							snake_case		:						int								=				" ".join(inputs.strip().split()							)
  					else:
  							snake_case		:						Union[str, Any]								=				inputs
  					snake_case		:						Union[str, Any]								=				outputs.replace("``"				, "\""							).replace("''"				, "\""							)
  
  					if not self.keep_accents:
  							snake_case		:						List[Any]								=				unicodedata.normalize("NFKD"				, SCREAMING_SNAKE_CASE							)
  							snake_case		:						int								=				"".join([c for c in outputs if not unicodedata.combining(SCREAMING_SNAKE_CASE							)]							)
  					if self.do_lower_case:
  							snake_case		:						Union[str, Any]								=				outputs.lower()
  
  					return outputs
  
  
  			def 							lowerCamelCase_				(     self				, SCREAMING_SNAKE_CASE							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					snake_case		:						List[str]								=				self.preprocess_text(SCREAMING_SNAKE_CASE							)
  					snake_case		:						List[str]								=				self.sp_model.encode(SCREAMING_SNAKE_CASE				, out_type=SCREAMING_SNAKE_CASE							)
  					snake_case		:						Optional[Any]								=				[]
  					for piece in pieces:
  							if len(SCREAMING_SNAKE_CASE							) > 1 and piece[-1] == str(","							) and piece[-2].isdigit():
  									snake_case		:						Union[str, Any]								=				self.sp_model.EncodeAsPieces(piece[:-1].replace(SCREAMING_SNAKE_CASE				, ""							)							)
  									if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
  											if len(cur_pieces[0]							) == 1:
  													snake_case		:						List[Any]								=				cur_pieces[1:]
  											else:
  													snake_case		:						Dict								=				cur_pieces[0][1:]
  									cur_pieces.append(piece[-1]							)
  									new_pieces.extend(SCREAMING_SNAKE_CASE							)
  							else:
  									new_pieces.append(SCREAMING_SNAKE_CASE							)
  
  					return new_pieces
  
  
  			def 							lowerCamelCase_				(     self				, SCREAMING_SNAKE_CASE							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE							)
  
  
  			def 							lowerCamelCase_				(     self				, SCREAMING_SNAKE_CASE							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE							)
  
  
  			def 							lowerCamelCase_				(     self				, SCREAMING_SNAKE_CASE							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					snake_case		:						Dict								=				[]
  					snake_case		:						Any								=				""
  					snake_case		:						Dict								=				False
  					for token in tokens:
  							# make sure that special tokens are not decoded using sentencepiece model
  							if token in self.all_special_tokens:
  									if not prev_is_special:
  											out_string += " "
  									out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE							) + token
  									snake_case		:						Optional[int]								=				True
  									snake_case		:						Union[str, Any]								=				[]
  							else:
  									current_sub_tokens.append(SCREAMING_SNAKE_CASE							)
  									snake_case		:						Tuple								=				False
  					out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE							)
  					return out_string.strip()
  
  
  			def 							lowerCamelCase_				(     self				, SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE = False				, SCREAMING_SNAKE_CASE = None				, SCREAMING_SNAKE_CASE = True				, **SCREAMING_SNAKE_CASE				, ):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					snake_case		:						int								=				kwargs.pop("use_source_tokenizer"				, SCREAMING_SNAKE_CASE							)
  
  					snake_case		:						Tuple								=				self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE				, skip_special_tokens=SCREAMING_SNAKE_CASE							)
  
  					# To avoid mixing byte-level and unicode for byte-level BPT
  					# we need to build string separately for added tokens and byte-level tokens
  					# cf. https://github.com/huggingface/transformers/issues/1133
  					snake_case		:						Any								=				[]
  					snake_case		:						Union[str, Any]								=				[]
  					for token in filtered_tokens:
  							if skip_special_tokens and token in self.all_special_ids:
  									continue
  							if token in self.added_tokens_encoder:
  									if current_sub_text:
  											sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE							)							)
  											snake_case		:						Optional[Any]								=				[]
  									sub_texts.append(SCREAMING_SNAKE_CASE							)
  							else:
  									current_sub_text.append(SCREAMING_SNAKE_CASE							)
  					if current_sub_text:
  							sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE							)							)
  
  					# Mimic the behavior of the Rust tokenizer:
  					# No space after <unk>
  					if spaces_between_special_tokens:
  							snake_case		:						Any								=				re.sub(r"(<unk>) "				, r"\1"				, " ".join(SCREAMING_SNAKE_CASE							)							)
  					else:
  							snake_case		:						Optional[int]								=				"".join(SCREAMING_SNAKE_CASE							)
  
  					snake_case		:						Optional[int]								=				(
  					    clean_up_tokenization_spaces
  					    if clean_up_tokenization_spaces is not None
  					    else self.clean_up_tokenization_spaces
  					)
  					if clean_up_tokenization_spaces:
  							snake_case		:						List[Any]								=				self.clean_up_tokenization(SCREAMING_SNAKE_CASE							)
  							return clean_text
  					else:
  							return text
  
  
  			def 							lowerCamelCase_				(     self				, SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE = None							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					snake_case		:						Tuple								=				[self.sep_token_id]
  					snake_case		:						List[str]								=				[self.cls_token_id]
  					if token_ids_a is None:
  							return cls + token_ids_a + sep
  					return cls + token_ids_a + sep + token_ids_a + sep
  
  
  			def 							lowerCamelCase_				(     self				, SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE = None				, SCREAMING_SNAKE_CASE = False							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					if already_has_special_tokens:
  							return super().get_special_tokens_mask(
  							    token_ids_a=SCREAMING_SNAKE_CASE				, token_ids_a=SCREAMING_SNAKE_CASE				, already_has_special_tokens=SCREAMING_SNAKE_CASE							)
  
  					if token_ids_a is not None:
  							return [1] + ([0] * len(SCREAMING_SNAKE_CASE							)) + [1] + ([0] * len(SCREAMING_SNAKE_CASE							)) + [1]
  					return [1] + ([0] * len(SCREAMING_SNAKE_CASE							)) + [1]
  
  
  			def 							lowerCamelCase_				(     self				, SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE = None							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					snake_case		:						Dict								=				[self.sep_token_id]
  					snake_case		:						Optional[int]								=				[self.cls_token_id]
  
  					if token_ids_a is None:
  							return len(cls + token_ids_a + sep							) * [0]
  					return len(cls + token_ids_a + sep							) * [0] + len(token_ids_a + sep							) * [1]
  
  
  
  			def 							lowerCamelCase_				(     self				, SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE = None							):
  
  
  
  					"""simple docstring"""
  
  
  
  
  
  
  
  					if not os.path.isdir(SCREAMING_SNAKE_CASE							):
  							logger.error(F'''Vocabulary path ({save_directory}) should be a directory'''							)
  							return
  					snake_case		:						Tuple								=				os.path.join(
  					    SCREAMING_SNAKE_CASE				, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]							)
  
  					if os.path.abspath(self.vocab_file							) != os.path.abspath(SCREAMING_SNAKE_CASE							) and os.path.isfile(self.vocab_file							):
  							copyfile(self.vocab_file				, SCREAMING_SNAKE_CASE							)
  					elif not os.path.isfile(self.vocab_file							):
  							with open(SCREAMING_SNAKE_CASE				, "wb"							) as fi:
  									snake_case		:						List[str]								=				self.sp_model.serialized_model_proto()
  									fi.write(SCREAMING_SNAKE_CASE							)
  
  					return (out_vocab_file,)
  
  