


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




      '''simple docstring'''


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




      def      _snake_case	(				self:       Union[str, Any]				):
       __lowerCamelCase		:							Tuple							=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

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

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

       return config, pixel_values, labels




      def      _snake_case	(				self:       str				):
       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      _snake_case	(				self:       Any						,      a:       List[str]						,      a:       List[str]						,      a:       Dict				):
       __lowerCamelCase		:							Union[str, Any]							=						SwinModel(config=a				)
       model.to(a				)
       model.eval()
       __lowerCamelCase		:							List[Any]							=						model(a				)

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

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




      def      _snake_case	(				self:       Tuple						,      a:       Optional[int]						,      a:       str						,      a:       Any				):
       __lowerCamelCase		:							Optional[int]							=						SwinBackbone(config=a				)
       model.to(a				)
       model.eval()
       __lowerCamelCase		:							str							=						model(a				)

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

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

       # verify backbone works with out_features=None
       __lowerCamelCase		:							Tuple							=						None
       __lowerCamelCase		:							List[str]							=						SwinBackbone(config=a				)
       model.to(a				)
       model.eval()
       __lowerCamelCase		:							Dict							=						model(a				)

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

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




      def      _snake_case	(				self:       str						,      a:       Dict						,      a:       Any						,      a:       Any				):
       __lowerCamelCase		:							Any							=						SwinForMaskedImageModeling(config=a				)
       model.to(a				)
       model.eval()
       __lowerCamelCase		:							Optional[int]							=						model(a				)
       self.parent.assertEqual(
           result.logits.shape						,      (self.batch_size, self.num_channels, self.image_size, self.image_size)				)

       # test greyscale images
       __lowerCamelCase		:							Dict							=						1
       __lowerCamelCase		:							str							=						SwinForMaskedImageModeling(a				)
       model.to(a				)
       model.eval()

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




      def      _snake_case	(				self:       Optional[Any]						,      a:       Union[str, Any]						,      a:       Union[str, Any]						,      a:       Tuple				):
       __lowerCamelCase		:							Optional[Any]							=						self.type_sequence_label_size
       __lowerCamelCase		:							int							=						SwinForImageClassification(a				)
       model.to(a				)
       model.eval()
       __lowerCamelCase		:							List[str]							=						model(a						,      labels=a				)
       self.parent.assertEqual(result.logits.shape						,      (self.batch_size, self.type_sequence_label_size)				)

       # test greyscale images
       __lowerCamelCase		:							Union[str, Any]							=						1
       __lowerCamelCase		:							Optional[int]							=						SwinForImageClassification(a				)
       model.to(a				)
       model.eval()

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




      def      _snake_case	(				self:       str				):
       __lowerCamelCase		:							Optional[int]							=						self.prepare_config_and_inputs()
       (
           (
           __lowerCamelCase
       )					,     (
           __lowerCamelCase
       )					,     (
           __lowerCamelCase
       )					,     
       )		:							Optional[int]							=						config_and_inputs
       __lowerCamelCase		:							Tuple							=						{'pixel_values': pixel_values}
       return config, inputs_dict



@require_torch
class        A_					(       __UpperCamelCase					,      __UpperCamelCase					,      unittest.TestCase    ):




      '''simple docstring'''


      __snake_case					       =   (
          (
              SwinModel,
              SwinBackbone,
              SwinForImageClassification,
              SwinForMaskedImageModeling,
          )
          if is_torch_available()
          else ()
      )
      __snake_case					       =   (
          {"""feature-extraction""": SwinModel, """image-classification""": SwinForImageClassification}
          if is_torch_available()
          else {}
      )
      __snake_case					       =   True

      __snake_case					       =   False
      __snake_case					       =   False
      __snake_case					       =   False




      def      _snake_case	(				self:       List[str]				):
       __lowerCamelCase		:							List[str]							=						SwinModelTester(self				)
       __lowerCamelCase		:							Optional[Any]							=						ConfigTester(self						,      config_class=a						,      embed_dim=37				)




      def      _snake_case	(				self:       Union[str, Any]				):
       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      _snake_case	(				self:       Optional[Any]				):
       return




      def      _snake_case	(				self:       Optional[Any]				):
       __lowerCamelCase		:							int							=						self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*a				)




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




      def      _snake_case	(				self:       Tuple				):
       super().test_training_gradient_checkpointing()




      def      _snake_case	(				self:       Optional[int]				):
       __lowerCamelCase		:							List[Any]							=						self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_backbone(*a				)




      def      _snake_case	(				self:       Dict				):
       __lowerCamelCase		:							int							=						self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_image_modeling(*a				)




      def      _snake_case	(				self:       Optional[Any]				):
       __lowerCamelCase		:							Union[str, Any]							=						self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*a				)




      @unittest.skip(reason='Swin does not use inputs_embeds'				)
      def      _snake_case	(				self:       int				):
       pass




      @unittest.skip(reason='Swin Transformer does not use feedforward chunking'				)
      def      _snake_case	(				self:       List[str]				):
       pass




      def      _snake_case	(				self:       Union[str, Any]				):
       __lowerCamelCase					,     __lowerCamelCase		:							Optional[int]							=						self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        __lowerCamelCase		:							str							=						model_class(a				)
        self.assertIsInstance(model.get_input_embeddings()						,      (nn.Module)				)
        __lowerCamelCase		:							List[str]							=						model.get_output_embeddings()
        self.assertTrue(x is None or isinstance(a						,      nn.Linear				)				)




      def      _snake_case	(				self:       List[Any]				):
       __lowerCamelCase					,     __lowerCamelCase		:							Any							=						self.model_tester.prepare_config_and_inputs_for_common()

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

        __lowerCamelCase		:							Tuple							=						['pixel_values']
        self.assertListEqual(arg_names[:1]						,      a				)




      def      _snake_case	(				self:       List[Any]				):
       __lowerCamelCase					,     __lowerCamelCase		:							Union[str, Any]							=						self.model_tester.prepare_config_and_inputs_for_common()
       __lowerCamelCase		:							Optional[int]							=						True

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

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

        self.assertListEqual(
            list(attentions[0].shape[-3:]				)						,      [self.model_tester.num_heads[0], window_size_squared, window_size_squared]						,      )
        __lowerCamelCase		:							Union[str, Any]							=						len(a				)

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

        # also another +1 for reshaped_hidden_states
        __lowerCamelCase		:							Union[str, Any]							=						1 if model_class.__name__ == 'SwinBackbone' else 2
        self.assertEqual(out_len + added_hidden_states						,      len(a				)				)

        __lowerCamelCase		:							Optional[int]							=						outputs.attentions

        self.assertEqual(len(a				)						,      a				)

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




      def      _snake_case	(				self:       Tuple						,      a:       int						,      a:       Optional[int]						,      a:       Dict						,      a:       List[str]				):
       __lowerCamelCase		:							List[Any]							=						model_class(a				)
       model.to(a				)
       model.eval()

       with torch.no_grad():
        __lowerCamelCase		:							Optional[Any]							=						model(**self._prepare_for_class(a						,      a				)				)

       __lowerCamelCase		:							List[Any]							=						outputs.hidden_states

       __lowerCamelCase		:							Union[str, Any]							=						getattr(
           self.model_tester						,      'expected_num_hidden_layers'						,      len(self.model_tester.depths				) + 1				)
       self.assertEqual(len(a				)						,      a				)

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

       __lowerCamelCase		:							Tuple							=						(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":
        __lowerCamelCase		:							Optional[int]							=						outputs.reshaped_hidden_states
        self.assertEqual(len(a				)						,      a				)

        __lowerCamelCase					,     __lowerCamelCase					,     __lowerCamelCase					,     __lowerCamelCase		:							str							=						reshaped_hidden_states[0].shape
        __lowerCamelCase		:							Optional[int]							=						(
            reshaped_hidden_states[0].view(a						,      a						,      height * width				).permute(0						,      2						,      1				)
        )
        self.assertListEqual(
            list(reshaped_hidden_states.shape[-2:]				)						,      [num_patches, self.model_tester.embed_dim]						,      )




      def      _snake_case	(				self:       Optional[Any]				):
       __lowerCamelCase					,     __lowerCamelCase		:							Dict							=						self.model_tester.prepare_config_and_inputs_for_common()

       __lowerCamelCase		:							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:
        __lowerCamelCase		:							Tuple							=						True
        self.check_hidden_states_output(a						,      a						,      a						,      a				)

        # check that output_hidden_states also work using config
        del inputs_dict["output_hidden_states"]
        __lowerCamelCase		:							Union[str, Any]							=						True

        self.check_hidden_states_output(a						,      a						,      a						,      a				)




      def      _snake_case	(				self:       str				):
       __lowerCamelCase					,     __lowerCamelCase		:							int							=						self.model_tester.prepare_config_and_inputs_for_common()
       __lowerCamelCase		:							Optional[int]							=						3

       __lowerCamelCase		:							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)
       )
       __lowerCamelCase		:							Tuple							=						(
           config.patch_size
           if isinstance(config.patch_size						,      collections.abc.Iterable				)
           else (config.patch_size, config.patch_size)
       )

       __lowerCamelCase		:							Dict							=						image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
       __lowerCamelCase		:							Tuple							=						image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

       for model_class in self.all_model_classes:
        __lowerCamelCase		:							Union[str, Any]							=						True
        self.check_hidden_states_output(a						,      a						,      a						,      (padded_height, padded_width)				)

        # check that output_hidden_states also work using config
        del inputs_dict["output_hidden_states"]
        __lowerCamelCase		:							int							=						True
        self.check_hidden_states_output(a						,      a						,      a						,      (padded_height, padded_width)				)




      @slow
      def      _snake_case	(				self:       Optional[int]				):
       for model_name in SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        __lowerCamelCase		:							Tuple							=						SwinModel.from_pretrained(a				)
        self.assertIsNotNone(a				)




      def      _snake_case	(				self:       Optional[Any]				):
       __lowerCamelCase					,     __lowerCamelCase		:							List[str]							=						self.model_tester.prepare_config_and_inputs_for_common()

       __lowerCamelCase		:							int							=						_config_zero_init(a				)
       for model_class in self.all_model_classes:
        __lowerCamelCase		:							List[str]							=						model_class(config=a				)
        for name, param in model.named_parameters():
         if "embeddings" not in name and param.requires_grad:
          self.assertIn(
              ((param.data.mean() * 1e9).round() / 1e9).item()						,      [0.0, 1.0]						,      msg=F'Parameter {name} of model {model_class} seems not properly initialized'						,      )



@require_vision
@require_torch
class        A_					(       unittest.TestCase    ):




      '''simple docstring'''


      @cached_property
      def      _snake_case	(				self:       Union[str, Any]				):
       return (
           AutoImageProcessor.from_pretrained('microsoft/swin-tiny-patch4-window7-224'				)
           if is_vision_available()
           else None
       )




      @slow
      def      _snake_case	(				self:       int				):
       __lowerCamelCase		:							Tuple							=						SwinForImageClassification.from_pretrained('microsoft/swin-tiny-patch4-window7-224'				).to(a				)
       __lowerCamelCase		:							Tuple							=						self.default_image_processor

       __lowerCamelCase		:							List[str]							=						Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'				)
       __lowerCamelCase		:							List[str]							=						image_processor(images=a						,      return_tensors='pt'				).to(a				)

       # forward pass
       with torch.no_grad():
        __lowerCamelCase		:							str							=						model(**a				)

       # verify the logits
       __lowerCamelCase		:							int							=						torch.Size((1, 1000)				)
       self.assertEqual(outputs.logits.shape						,      a				)
       __lowerCamelCase		:							List[str]							=						torch.tensor([-0.0_9_4_8, -0.6_4_5_4, -0.0_9_2_1]				).to(a				)
       self.assertTrue(torch.allclose(outputs.logits[0, :3]						,      a						,      atol=1e-4				)				)



@require_torch
class        A_					(       unittest.TestCase					,      __UpperCamelCase    ):




      '''simple docstring'''


      __snake_case					       =   (SwinBackbone,) if is_torch_available() else ()
      __snake_case					       =   SwinConfig




      def      _snake_case	(				self:       str				):
       __lowerCamelCase		:							Union[str, Any]							=						SwinModelTester(self				)





from typing import List

import datasets
from datasets.tasks import ImageClassification

from ..folder_based_builder import folder_based_builder


lowercase_           =	datasets.utils.logging.get_logger(__name__)


class        A_					(       folder_based_builder.FolderBasedBuilderConfig    ):




      '''simple docstring'''


      __snake_case					       =   None
      __snake_case					       =   None



class        A_					(       folder_based_builder.FolderBasedBuilder    ):




      '''simple docstring'''


      __snake_case					       =   datasets.Image()
      __snake_case					       =   """image"""
      __snake_case					       =   ImageFolderConfig
      __snake_case					       =   42  # definition at the bottom of the script
      __snake_case					       =   ImageClassification(image_column="""image"""					,      label_column="""label"""    )



lowercase_           =	[
    '.blp',
    '.bmp',
    '.dib',
    '.bufr',
    '.cur',
    '.pcx',
    '.dcx',
    '.dds',
    '.ps',
    '.eps',
    '.fit',
    '.fits',
    '.fli',
    '.flc',
    '.ftc',
    '.ftu',
    '.gbr',
    '.gif',
    '.grib',
    '.h5',
    '.hdf',
    '.png',
    '.apng',
    '.jp2',
    '.j2k',
    '.jpc',
    '.jpf',
    '.jpx',
    '.j2c',
    '.icns',
    '.ico',
    '.im',
    '.iim',
    '.tif',
    '.tiff',
    '.jfif',
    '.jpe',
    '.jpg',
    '.jpeg',
    '.mpg',
    '.mpeg',
    '.msp',
    '.pcd',
    '.pxr',
    '.pbm',
    '.pgm',
    '.ppm',
    '.pnm',
    '.psd',
    '.bw',
    '.rgb',
    '.rgba',
    '.sgi',
    '.ras',
    '.tga',
    '.icb',
    '.vda',
    '.vst',
    '.webp',
    '.wmf',
    '.emf',
    '.xbm',
    '.xpm',
]
lowercase_           =	IMAGE_EXTENSIONS

