code: 
  
  
  
  
  
  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	,   lowerCAmelCase__	,   lowerCAmelCase__=1_3	,   lowerCAmelCase__=3_2	,   lowerCAmelCase__=2	,   lowerCAmelCase__=3	,   lowerCAmelCase__=1_6	,   lowerCAmelCase__=[1, 2, 1]	,   lowerCAmelCase__=[2, 2, 4]	,   lowerCAmelCase__=2	,   lowerCAmelCase__=2.0	,   lowerCAmelCase__=True	,   lowerCAmelCase__=0.0	,   lowerCAmelCase__=0.0	,   lowerCAmelCase__=0.1	,   lowerCAmelCase__="gelu"	,   lowerCAmelCase__=False	,   lowerCAmelCase__=True	,   lowerCAmelCase__=0.02	,   lowerCAmelCase__=1E-5	,   lowerCAmelCase__=True	,   lowerCAmelCase__=None	,   lowerCAmelCase__=True	,   lowerCAmelCase__=1_0	,   lowerCAmelCase__=8	,   lowerCAmelCase__=["stage1", "stage2"]	,   lowerCAmelCase__=[1, 2]	,   )     ->		List[Any]:
  
  
  
          '''simple docstring'''
  
  
  
  
          a__			:      int            =parent
          a__			:      str            =batch_size
          a__			:      Any            =image_size
          a__			:      int            =patch_size
          a__			:      Optional[Any]            =num_channels
          a__			:      Tuple            =embed_dim
          a__			:      List[Any]            =depths
          a__			:      int            =num_heads
          a__			:      Optional[int]            =window_size
          a__			:      Optional[int]            =mlp_ratio
          a__			:      List[Any]            =qkv_bias
          a__			:      Tuple            =hidden_dropout_prob
          a__			:      Union[str, Any]            =attention_probs_dropout_prob
          a__			:      str            =drop_path_rate
          a__			:      Union[str, Any]            =hidden_act
          a__			:      str            =use_absolute_embeddings
          a__			:      Optional[Any]            =patch_norm
          a__			:      Any            =layer_norm_eps
          a__			:      Any            =initializer_range
          a__			:      int            =is_training
          a__			:      str            =scope
          a__			:      List[str]            =use_labels
          a__			:      List[Any]            =type_sequence_label_size
          a__			:      List[Any]            =encoder_stride
          a__			:      Any            =out_features
          a__			:      int            =out_indices
  
  
  
  
  
  
  
        def      _lowercase						(					self							)     ->		Any:
  
  
  
          '''simple docstring'''
  
  
  
  
          a__			:      Union[str, Any]            =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)
  
          a__			:      Any            =None
          if self.use_labels:
            a__			:      str            =ids_tensor([self.batch_size]	,   self.type_sequence_label_size							)
  
          a__			:      Tuple            =self.get_config()
  
          return config, pixel_values, labels
  
  
  
  
  
  
  
        def      _lowercase						(					self							)     ->		Tuple:
  
  
  
          '''simple docstring'''
  
  
  
  
          return SwinConfig(
              image_size=self.image_size	,   patch_size=self.patch_size	,   num_channels=self.num_channels	,   embed_dim=self.embed_dim	,   depths=self.depths	,   num_heads=self.num_heads	,   window_size=self.window_size	,   mlp_ratio=self.mlp_ratio	,   qkv_bias=self.qkv_bias	,   hidden_dropout_prob=self.hidden_dropout_prob	,   attention_probs_dropout_prob=self.attention_probs_dropout_prob	,   drop_path_rate=self.drop_path_rate	,   hidden_act=self.hidden_act	,   use_absolute_embeddings=self.use_absolute_embeddings	,   path_norm=self.patch_norm	,   layer_norm_eps=self.layer_norm_eps	,   initializer_range=self.initializer_range	,   encoder_stride=self.encoder_stride	,   out_features=self.out_features	,   out_indices=self.out_indices	,   )
  
  
  
  
  
  
  
        def      _lowercase						(					self	,   lowerCAmelCase__	,   lowerCAmelCase__	,   lowerCAmelCase__							)     ->		Union[str, Any]:
  
  
  
          '''simple docstring'''
  
  
  
  
          a__			:      Union[str, Any]            =SwinModel(config=lowerCAmelCase__							)
          model.to(lowerCAmelCase__							)
          model.eval()
          a__			:      Dict            =model(lowerCAmelCase__							)
  
          a__			:      Union[str, Any]            =((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths							) - 1))
          a__			:      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      _lowercase						(					self	,   lowerCAmelCase__	,   lowerCAmelCase__	,   lowerCAmelCase__							)     ->		str:
  
  
  
          '''simple docstring'''
  
  
  
  
          a__			:      str            =SwinBackbone(config=lowerCAmelCase__							)
          model.to(lowerCAmelCase__							)
          model.eval()
          a__			:      List[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
          a__			:      Any            =None
          a__			:      Any            =SwinBackbone(config=lowerCAmelCase__							)
          model.to(lowerCAmelCase__							)
          model.eval()
          a__			:      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      _lowercase						(					self	,   lowerCAmelCase__	,   lowerCAmelCase__	,   lowerCAmelCase__							)     ->		List[str]:
  
  
  
          '''simple docstring'''
  
  
  
  
          a__			:      Dict            =SwinForMaskedImageModeling(config=lowerCAmelCase__							)
          model.to(lowerCAmelCase__							)
          model.eval()
          a__			:      str            =model(lowerCAmelCase__							)
          self.parent.assertEqual(
              result.logits.shape	,   (self.batch_size, self.num_channels, self.image_size, self.image_size)							)
  
          # test greyscale images
          a__			:      Optional[Any]            =1
          a__			:      int            =SwinForMaskedImageModeling(lowerCAmelCase__							)
          model.to(lowerCAmelCase__							)
          model.eval()
  
          a__			:      Union[str, Any]            =floats_tensor([self.batch_size, 1, self.image_size, self.image_size]							)
          a__			:      Optional[Any]            =model(lowerCAmelCase__							)
          self.parent.assertEqual(result.logits.shape	,   (self.batch_size, 1, self.image_size, self.image_size)							)
  
  
  
  
  
  
  
        def      _lowercase						(					self	,   lowerCAmelCase__	,   lowerCAmelCase__	,   lowerCAmelCase__							)     ->		Optional[Any]:
  
  
  
          '''simple docstring'''
  
  
  
  
          a__			:      Any            =self.type_sequence_label_size
          a__			:      Dict            =SwinForImageClassification(lowerCAmelCase__							)
          model.to(lowerCAmelCase__							)
          model.eval()
          a__			:      str            =model(lowerCAmelCase__	,   labels=lowerCAmelCase__							)
          self.parent.assertEqual(result.logits.shape	,   (self.batch_size, self.type_sequence_label_size)							)
  
          # test greyscale images
          a__			:      Any            =1
          a__			:      Union[str, Any]            =SwinForImageClassification(lowerCAmelCase__							)
          model.to(lowerCAmelCase__							)
          model.eval()
  
          a__			:      Optional[Any]            =floats_tensor([self.batch_size, 1, self.image_size, self.image_size]							)
          a__			:      int            =model(lowerCAmelCase__							)
          self.parent.assertEqual(result.logits.shape	,   (self.batch_size, self.type_sequence_label_size)							)
  
  
  
  
  
  
  
        def      _lowercase						(					self							)     ->		Any:
  
  
  
          '''simple docstring'''
  
  
  
  
          a__			:      Any            =self.prepare_config_and_inputs()
          (
              (
              a__       
          )      ,							(
              a__       
          )      ,							(
              a__       
          )      ,							       
          )			:      List[Any]            =config_and_inputs
          a__			:      int            ={"pixel_values": pixel_values}
          return config, inputs_dict
  
  
  
  
  
  
  
  @require_torch
  class        __lowerCAmelCase (					__lowerCamelCase		,       __lowerCamelCase		,       unittest.TestCase):
        _lowercase       :      str        =    (
            (
                SwinModel,
                SwinBackbone,
                SwinForImageClassification,
                SwinForMaskedImageModeling,
            )
            if is_torch_available()
            else ()
        )
        _lowercase       :      Optional[Any]        =    (
            {'feature-extraction': SwinModel, 'image-classification': SwinForImageClassification}
            if is_torch_available()
            else {}
        )
        _lowercase       :      List[Any]        =    True
  
        _lowercase       :      Union[str, Any]        =    False
        _lowercase       :      Optional[Any]        =    False
        _lowercase       :      Any        =    False
  
  
  
  
  
  
  
        def      _lowercase						(					self							)     ->		Any:
  
  
  
          '''simple docstring'''
  
  
  
  
          a__			:      Any            =SwinModelTester(self							)
          a__			:      Union[str, Any]            =ConfigTester(self	,   config_class=lowerCAmelCase__	,   embed_dim=3_7							)
  
  
  
  
  
  
  
        def      _lowercase						(					self							)     ->		int:
  
  
  
          '''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      _lowercase						(					self							)     ->		List[str]:
  
  
  
          '''simple docstring'''
  
  
  
  
          return
  
  
  
  
  
  
  
        def      _lowercase						(					self							)     ->		Any:
  
  
  
          '''simple docstring'''
  
  
  
  
          a__			:      Optional[Any]            =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      _lowercase						(					self							)     ->		str:
  
  
  
          '''simple docstring'''
  
  
  
  
          pass
  
  
  
  
  
  
  
        def      _lowercase						(					self							)     ->		Dict:
  
  
  
          '''simple docstring'''
  
  
  
  
          super().test_training_gradient_checkpointing()
  
  
  
  
  
  
  
        def      _lowercase						(					self							)     ->		Optional[Any]:
  
  
  
          '''simple docstring'''
  
  
  
  
          a__			:      List[str]            =self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_backbone(*lowerCAmelCase__							)
  
  
  
  
  
  
  
        def      _lowercase						(					self							)     ->		Any:
  
  
  
          '''simple docstring'''
  
  
  
  
          a__			:      Tuple            =self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_masked_image_modeling(*lowerCAmelCase__							)
  
  
  
  
  
  
  
        def      _lowercase						(					self							)     ->		Dict:
  
  
  
          '''simple docstring'''
  
  
  
  
          a__			:      List[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      _lowercase						(					self							)     ->		Optional[Any]:
  
  
  
          '''simple docstring'''
  
  
  
  
          pass
  
  
  
  
  
  
  
        @unittest.skip(reason="Swin Transformer does not use feedforward chunking"							)
        def      _lowercase						(					self							)     ->		List[str]:
  
  
  
          '''simple docstring'''
  
  
  
  
          pass
  
  
  
  
  
  
  
        def      _lowercase						(					self							)     ->		Optional[int]:
  
  
  
          '''simple docstring'''
  
  
  
  
          a__      ,							a__			:      str            =self.model_tester.prepare_config_and_inputs_for_common()
  
          for model_class in self.all_model_classes:
            a__			:      int            =model_class(lowerCAmelCase__							)
            self.assertIsInstance(model.get_input_embeddings()	,   (nn.Module)							)
            a__			:      List[Any]            =model.get_output_embeddings()
            self.assertTrue(x is None or isinstance(lowerCAmelCase__	,   nn.Linear							)							)
  
  
  
  
  
  
  
        def      _lowercase						(					self							)     ->		Optional[Any]:
  
  
  
          '''simple docstring'''
  
  
  
  
          a__      ,							a__			:      Optional[Any]            =self.model_tester.prepare_config_and_inputs_for_common()
  
          for model_class in self.all_model_classes:
            a__			:      List[str]            =model_class(lowerCAmelCase__							)
            a__			:      Optional[int]            =inspect.signature(model.forward							)
            # signature.parameters is an OrderedDict => so arg_names order is deterministic
            a__			:      List[Any]            =[*signature.parameters.keys()]
  
            a__			:      Any            =["pixel_values"]
            self.assertListEqual(arg_names[:1]	,   lowerCAmelCase__							)
  
  
  
  
  
  
  
        def      _lowercase						(					self							)     ->		Union[str, Any]:
  
  
  
          '''simple docstring'''
  
  
  
  
          a__      ,							a__			:      Dict            =self.model_tester.prepare_config_and_inputs_for_common()
          a__			:      Optional[int]            =True
  
          for model_class in self.all_model_classes:
            a__			:      Union[str, Any]            =True
            a__			:      Any            =False
            a__			:      Optional[int]            =True
            a__			:      Tuple            =model_class(lowerCAmelCase__							)
            model.to(lowerCAmelCase__							)
            model.eval()
            with torch.no_grad():
              a__			:      Union[str, Any]            =model(**self._prepare_for_class(lowerCAmelCase__	,   lowerCAmelCase__							)							)
            a__			:      Tuple            =outputs.attentions
            a__			:      Tuple            =len(self.model_tester.depths							)
            self.assertEqual(len(lowerCAmelCase__							)	,   lowerCAmelCase__							)
  
            # check that output_attentions also work using config
            del inputs_dict["output_attentions"]
            a__			:      List[Any]            =True
            a__			:      Optional[int]            =config.window_size**2
            a__			:      Union[str, Any]            =model_class(lowerCAmelCase__							)
            model.to(lowerCAmelCase__							)
            model.eval()
            with torch.no_grad():
              a__			:      str            =model(**self._prepare_for_class(lowerCAmelCase__	,   lowerCAmelCase__							)							)
            a__			:      Optional[Any]            =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]	,   )
            a__			:      str            =len(lowerCAmelCase__							)
  
            # Check attention is always last and order is fine
            a__			:      Dict            =True
            a__			:      Any            =True
            a__			:      str            =model_class(lowerCAmelCase__							)
            model.to(lowerCAmelCase__							)
            model.eval()
            with torch.no_grad():
              a__			:      Tuple            =model(**self._prepare_for_class(lowerCAmelCase__	,   lowerCAmelCase__							)							)
  
            # also another +1 for reshaped_hidden_states
            a__			:      List[Any]            =1 if model_class.__name__ == "SwinBackbone" else 2
            self.assertEqual(out_len + added_hidden_states	,   len(lowerCAmelCase__							)							)
  
            a__			:      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      _lowercase						(					self	,   lowerCAmelCase__	,   lowerCAmelCase__	,   lowerCAmelCase__	,   lowerCAmelCase__							)     ->		Dict:
  
  
  
          '''simple docstring'''
  
  
  
  
          a__			:      Tuple            =model_class(lowerCAmelCase__							)
          model.to(lowerCAmelCase__							)
          model.eval()
  
          with torch.no_grad():
            a__			:      Optional[Any]            =model(**self._prepare_for_class(lowerCAmelCase__	,   lowerCAmelCase__							)							)
  
          a__			:      Tuple            =outputs.hidden_states
  
          a__			:      Tuple            =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
          a__			:      List[str]            =(
              config.patch_size
              if isinstance(config.patch_size	,   collections.abc.Iterable							)
              else (config.patch_size, config.patch_size)
          )
  
          a__			:      Optional[int]            =(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":
            a__			:      int            =outputs.reshaped_hidden_states
            self.assertEqual(len(lowerCAmelCase__							)	,   lowerCAmelCase__							)
  
            a__      ,							a__      ,							a__      ,							a__			:      Optional[int]            =reshaped_hidden_states[0].shape
            a__			:      Optional[int]            =(
                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      _lowercase						(					self							)     ->		str:
  
  
  
          '''simple docstring'''
  
  
  
  
          a__      ,							a__			:      Tuple            =self.model_tester.prepare_config_and_inputs_for_common()
  
          a__			:      Union[str, 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)
          )
  
          for model_class in self.all_model_classes:
            a__			:      List[str]            =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"]
            a__			:      Union[str, Any]            =True
  
            self.check_hidden_states_output(lowerCAmelCase__	,   lowerCAmelCase__	,   lowerCAmelCase__	,   lowerCAmelCase__							)
  
  
  
  
  
  
  
        def      _lowercase						(					self							)     ->		Union[str, Any]:
  
  
  
          '''simple docstring'''
  
  
  
  
          a__      ,							a__			:      Tuple            =self.model_tester.prepare_config_and_inputs_for_common()
          a__			:      Optional[Any]            =3
  
          a__			:      int            =(
              self.model_tester.image_size
              if isinstance(self.model_tester.image_size	,   collections.abc.Iterable							)
              else (self.model_tester.image_size, self.model_tester.image_size)
          )
          a__			:      Any            =(
              config.patch_size
              if isinstance(config.patch_size	,   collections.abc.Iterable							)
              else (config.patch_size, config.patch_size)
          )
  
          a__			:      Any            =image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
          a__			:      int            =image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])
  
          for model_class in self.all_model_classes:
            a__			:      List[Any]            =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"]
            a__			:      List[str]            =True
            self.check_hidden_states_output(lowerCAmelCase__	,   lowerCAmelCase__	,   lowerCAmelCase__	,   (padded_height, padded_width)							)
  
  
  
  
  
  
  
        @slow
        def      _lowercase						(					self							)     ->		List[Any]:
  
  
  
          '''simple docstring'''
  
  
  
  
          for model_name in SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            a__			:      Union[str, Any]            =SwinModel.from_pretrained(lowerCAmelCase__							)
            self.assertIsNotNone(lowerCAmelCase__							)
  
  
  
  
  
  
  
        def      _lowercase						(					self							)     ->		str:
  
  
  
          '''simple docstring'''
  
  
  
  
          a__      ,							a__			:      List[Any]            =self.model_tester.prepare_config_and_inputs_for_common()
  
          a__			:      Union[str, Any]            =_config_zero_init(lowerCAmelCase__							)
          for model_class in self.all_model_classes:
            a__			:      List[str]            =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        __lowerCAmelCase (					unittest.TestCase):
  
  
  
  
  
  
  
        @cached_property
        def      _lowercase						(					self							)     ->		str:
  
  
  
          '''simple docstring'''
  
  
  
  
          return (
              AutoImageProcessor.from_pretrained("microsoft/swin-tiny-patch4-window7-224"							)
              if is_vision_available()
              else None
          )
  
  
  
  
  
  
  
        @slow
        def      _lowercase						(					self							)     ->		List[Any]:
  
  
  
          '''simple docstring'''
  
  
  
  
          a__			:      Optional[Any]            =SwinForImageClassification.from_pretrained("microsoft/swin-tiny-patch4-window7-224"							).to(lowerCAmelCase__							)
          a__			:      Optional[Any]            =self.default_image_processor
  
          a__			:      Any            =Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"							)
          a__			:      Optional[int]            =image_processor(images=lowerCAmelCase__	,   return_tensors="pt"							).to(lowerCAmelCase__							)
  
          # forward pass
          with torch.no_grad():
            a__			:      Tuple            =model(**lowerCAmelCase__							)
  
          # verify the logits
          a__			:      str            =torch.Size((1, 1_0_0_0)							)
          self.assertEqual(outputs.logits.shape	,   lowerCAmelCase__							)
          a__			:      List[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        __lowerCAmelCase (					unittest.TestCase		,       __lowerCamelCase):
        _lowercase       :      Dict        =    (SwinBackbone,) if is_torch_available() else ()
        _lowercase       :      Tuple        =    SwinConfig
  
  
  
  
  
  
  
        def      _lowercase						(					self							)     ->		Dict:
  
  
  
          '''simple docstring'''
  
  
  
  
          a__			:      Optional[int]            =SwinModelTester(self							)
  
  
  
  
  
  
  
style_context: 
  
  
  
  
  
  import os
  import tempfile
  from pathlib import Path
  from unittest import TestCase
  
  import pyarrow as pa
  import pytest
  
  from datasets.arrow_dataset import Dataset
  from datasets.arrow_reader import ArrowReader, BaseReader, FileInstructions, ReadInstruction, make_file_instructions
  from datasets.info import DatasetInfo
  from datasets.splits import NamedSplit, Split, SplitDict, SplitInfo
  
  from .utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases
  
  
  
  
  
  
  
  class        __lowerCAmelCase (					UpperCamelCase__):
  
  
  
  
  
  
  
        def      _lowercase						(					self	,   lowerCAmelCase__	,   lowerCAmelCase__=False							)     ->		List[Any]:
  
  
  
          '''simple docstring'''
  
  
  
  
          a__      ,							a__      ,							a__			:      Optional[int]            =(
              filename_skip_take["filename"],
              filename_skip_take["skip"] if "skip" in filename_skip_take else None,
              filename_skip_take["take"] if "take" in filename_skip_take else None,
          )
          open(os.path.join(lowerCAmelCase__							)	,   "wb"							).close()
          a__			:      Optional[int]            =pa.Table.from_pydict({"filename": [Path(lowerCAmelCase__							).name] * 1_0_0}							)
          if take == -1:
            a__			:      int            =len(lowerCAmelCase__							) - skip
          if skip is not None and take is not None:
            a__			:      Optional[Any]            =pa_table.slice(lowerCAmelCase__	,   lowerCAmelCase__							)
          return pa_table
  
  
  
  
  
  
  
  class        __lowerCAmelCase (					UpperCamelCase__):
  
  
  
  
  
  
  
        def      _lowercase						(					self							)     ->		str:
  
  
  
          '''simple docstring'''
  
  
  
  
          a__			:      List[str]            ="my_name"
          a__			:      List[Any]            =SplitInfo(name="train"	,   num_examples=1_0_0							)
          a__			:      List[str]            =SplitInfo(name="test"	,   num_examples=1_0_0							)
          a__			:      List[Any]            =[train_info, test_info]
          a__			:      Union[str, Any]            =SplitDict()
          split_dict.add(lowerCAmelCase__							)
          split_dict.add(lowerCAmelCase__							)
          a__			:      Dict            =DatasetInfo(splits=lowerCAmelCase__							)
  
          with tempfile.TemporaryDirectory() as tmp_dir:
            a__			:      Optional[Any]            =ReaderTest(lowerCAmelCase__	,   lowerCAmelCase__							)
  
            a__			:      Any            ="test[:33%]"
            a__			:      int            =Dataset(**reader.read(lowerCAmelCase__	,   lowerCAmelCase__	,   lowerCAmelCase__							)							)
            self.assertEqual(dset["filename"][0]	,   F'''{name}-test'''							)
            self.assertEqual(dset.num_rows	,   3_3							)
            self.assertEqual(dset.num_columns	,   1							)
  
            a__			:      Tuple            =["train", "test[:33%]"]
            a__			:      str            =[Split.TRAIN, ReadInstruction.from_spec("test[:33%]"							)]
            for instructions in [instructionsa, instructionsa]:
              a__			:      Optional[int]            =[reader.read(lowerCAmelCase__	,   lowerCAmelCase__	,   lowerCAmelCase__							) for instr in instructions]
              a__      ,							a__			:      Optional[int]            =(Dataset(**lowerCAmelCase__							) for dataset_kwargs in datasets_kwargs)
              self.assertEqual(train_dset["filename"][0]	,   F'''{name}-train'''							)
              self.assertEqual(train_dset.num_rows	,   1_0_0							)
              self.assertEqual(train_dset.num_columns	,   1							)
              self.assertIsInstance(train_dset.split	,   lowerCAmelCase__							)
              self.assertEqual(str(train_dset.split							)	,   "train"							)
              self.assertEqual(test_dset["filename"][0]	,   F'''{name}-test'''							)
              self.assertEqual(test_dset.num_rows	,   3_3							)
              self.assertEqual(test_dset.num_columns	,   1							)
              self.assertIsInstance(test_dset.split	,   lowerCAmelCase__							)
              self.assertEqual(str(test_dset.split							)	,   "test[:33%]"							)
              del train_dset, test_dset
  
  
  
  
  
  
  
        def      _lowercase						(					self							)     ->		Optional[Any]:
  
  
  
          '''simple docstring'''
  
  
  
  
          a__			:      Any            ="my_name"
          a__			:      List[Any]            =SplitInfo(name="train"	,   num_examples=1_0_0_0	,   shard_lengths=[1_0_0] * 1_0							)
          a__			:      Optional[Any]            =[train_info]
          a__			:      Any            =SplitDict()
          split_dict.add(lowerCAmelCase__							)
          a__			:      Any            =DatasetInfo(splits=lowerCAmelCase__							)
  
          with tempfile.TemporaryDirectory() as tmp_dir:
            a__			:      Optional[int]            =ReaderTest(lowerCAmelCase__	,   lowerCAmelCase__							)
  
            a__			:      Union[str, Any]            ="train[:33%]"
            a__			:      Union[str, Any]            =Dataset(**reader.read(lowerCAmelCase__	,   lowerCAmelCase__	,   lowerCAmelCase__							)							)
            self.assertEqual(dset["filename"][0]	,   F'''{name}-train-00000-of-00010'''							)
            self.assertEqual(dset["filename"][-1]	,   F'''{name}-train-00003-of-00010'''							)
            self.assertEqual(dset.num_rows	,   3_3_0							)
            self.assertEqual(dset.num_columns	,   1							)
  
  
  
  
  
  
  
        def      _lowercase						(					self							)     ->		List[str]:
  
  
  
          '''simple docstring'''
  
  
  
  
          a__			:      Dict            =SplitInfo(name="train"	,   num_examples=1_0_0							)
          a__			:      str            =SplitInfo(name="test"	,   num_examples=1_0_0							)
          a__			:      int            =SplitDict()
          split_dict.add(lowerCAmelCase__							)
          split_dict.add(lowerCAmelCase__							)
          a__			:      int            =DatasetInfo(splits=lowerCAmelCase__							)
  
          with tempfile.TemporaryDirectory() as tmp_dir:
            a__			:      Tuple            =ReaderTest(lowerCAmelCase__	,   lowerCAmelCase__							)
  
            a__			:      Tuple            =[
                {"filename": os.path.join(lowerCAmelCase__	,   "train"							)},
                {"filename": os.path.join(lowerCAmelCase__	,   "test"							), "skip": 1_0, "take": 1_0},
            ]
            a__			:      Optional[Any]            =Dataset(**reader.read_files(lowerCAmelCase__	,   original_instructions="train+test[10:20]"							)							)
            self.assertEqual(dset.num_rows	,   1_1_0							)
            self.assertEqual(dset.num_columns	,   1							)
            del dset
  @pytest.mark.parametrize("in_memory" , [False, True]		)
  def   _A (	SCREAMING_SNAKE_CASE  :     Optional[Any] , SCREAMING_SNAKE_CASE  :     Optional[Any] , SCREAMING_SNAKE_CASE  :     Optional[Any]		):
  
  
  
  
  
    """simple docstring"""
  
  
  
    a__			:      int            =arrow_file
    with assert_arrow_memory_increases() if in_memory else assert_arrow_memory_doesnt_increase():
      a__			:      str            =ArrowReader.read_table(SCREAMING_SNAKE_CASE , in_memory=SCREAMING_SNAKE_CASE		)
    assert table.shape == dataset.data.shape
    assert set(table.column_names		) == set(dataset.data.column_names		)
    assert dict(table.to_pydict()		) == dict(dataset.data.to_pydict()		)  # to_pydict returns OrderedDict
  @pytest.mark.parametrize("in_memory" , [False, True]		)
  def   _A (	SCREAMING_SNAKE_CASE  :     Tuple , SCREAMING_SNAKE_CASE  :     List[Any] , SCREAMING_SNAKE_CASE  :     str		):
  
  
  
  
  
    """simple docstring"""
  
  
  
    a__			:      Optional[int]            =arrow_file
    a__			:      Tuple            =ArrowReader("" , SCREAMING_SNAKE_CASE		)
    with assert_arrow_memory_increases() if in_memory else assert_arrow_memory_doesnt_increase():
      a__			:      Union[str, Any]            =reader.read_files([{"filename": filename}] , in_memory=SCREAMING_SNAKE_CASE		)
    assert dataset_kwargs.keys() == {"arrow_table", "info", "split"}
    a__			:      Dict            =dataset_kwargs["arrow_table"]
    assert table.shape == dataset.data.shape
    assert set(table.column_names		) == set(dataset.data.column_names		)
    assert dict(table.to_pydict()		) == dict(dataset.data.to_pydict()		)  # to_pydict returns OrderedDict
  def   _A (	):
  
  
  
  
  
    """simple docstring"""
  
  
  
    assert ReadInstruction("train" , to=10 , unit="abs"		).to_spec() == "train[:10]"
    assert ReadInstruction("train" , from_=-80 , to=10 , unit="%"		).to_spec() == "train[-80%:10%]"
  
    a__			:      List[Any]            ="train+test"
    assert ReadInstruction.from_spec(SCREAMING_SNAKE_CASE		).to_spec() == spec_train_test
  
    a__			:      Union[str, Any]            ="train[2:10]"
    assert ReadInstruction.from_spec(SCREAMING_SNAKE_CASE		).to_spec() == spec_train_abs
  
    a__			:      List[Any]            ="train[15%:-20%]"
    assert ReadInstruction.from_spec(SCREAMING_SNAKE_CASE		).to_spec() == spec_train_pct
  
    a__			:      Dict            ="train[:10%](closest)"
    assert ReadInstruction.from_spec(SCREAMING_SNAKE_CASE		).to_spec() == "train[:10%]"
  
    a__			:      Tuple            ="train[:10%](pct1_dropremainder)"
    assert ReadInstruction.from_spec(SCREAMING_SNAKE_CASE		).to_spec() == spec_train_pct_rounding
  
    a__			:      List[Any]            ="train[:10%](pct1_dropremainder)+test[-10%:](pct1_dropremainder)"
    assert ReadInstruction.from_spec(SCREAMING_SNAKE_CASE		).to_spec() == spec_train_test_pct_rounding
  def   _A (	):
  
  
  
  
  
    """simple docstring"""
  
  
  
    a__			:      Optional[Any]            ="dummy"
    a__			:      Dict            =[SplitInfo(name="train" , num_examples=100		)]
    a__			:      Optional[Any]            ="train[:33%]"
    a__			:      int            ="arrow"
    a__			:      Any            ="prefix"
  
    a__			:      Tuple            =make_file_instructions(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE		)
    assert isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE		)
    assert file_instructions.num_examples == 33
    assert file_instructions.file_instructions == [
        {"filename": os.path.join(SCREAMING_SNAKE_CASE , f'''{name}-train.arrow'''		), "skip": 0, "take": 33}
    ]
  
    a__			:      List[str]            =[SplitInfo(name="train" , num_examples=100 , shard_lengths=[10] * 10		)]
    a__			:      Union[str, Any]            =make_file_instructions(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE		)
    assert isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE		)
    assert file_instructions.num_examples == 33
    assert file_instructions.file_instructions == [
        {"filename": os.path.join(SCREAMING_SNAKE_CASE , f'''{name}-train-00000-of-00010.arrow'''		), "skip": 0, "take": -1},
        {"filename": os.path.join(SCREAMING_SNAKE_CASE , f'''{name}-train-00001-of-00010.arrow'''		), "skip": 0, "take": -1},
        {"filename": os.path.join(SCREAMING_SNAKE_CASE , f'''{name}-train-00002-of-00010.arrow'''		), "skip": 0, "take": -1},
        {"filename": os.path.join(SCREAMING_SNAKE_CASE , f'''{name}-train-00003-of-00010.arrow'''		), "skip": 0, "take": 3},
    ]
  
  
  
  
  
  @pytest.mark.parametrize("name, expected_exception" , [(None, TypeError), ("", ValueError)]		)
  def   _A (	SCREAMING_SNAKE_CASE  :     Tuple , SCREAMING_SNAKE_CASE  :     Tuple		):
  
  
  
  
  
    """simple docstring"""
  
  
  
    a__			:      Dict            =[SplitInfo(name="train" , num_examples=100		)]
    a__			:      Any            ="train"
    a__			:      Optional[Any]            ="arrow"
    a__			:      List[Any]            ="prefix_path"
    with pytest.raises(SCREAMING_SNAKE_CASE		):
      a__			:      Optional[Any]            =make_file_instructions(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE		)
  
  
  
  
  
  
  