

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






     '''simple docstring'''



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


     def   UpperCAmelCase_			(						self					:	Tuple			)		->      Optional[Any]:
      UpperCAmelCase			:      Union[str, Any]		   =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

      UpperCAmelCase			:      Union[str, Any]		   =					None
      if self.use_labels:
       UpperCAmelCase			:      Any		   =					ids_tensor([self.batch_size]	,     self.type_sequence_label_size			)

      UpperCAmelCase			:      Union[str, Any]		   =					self.get_config()

      return config, pixel_values, labels


     def   UpperCAmelCase_			(						self					:	Dict			)		->      List[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   UpperCAmelCase_			(						self					:	Tuple	,     lowercase_					:	str	,     lowercase_					:	Optional[Any]	,     lowercase_					:	Dict			)		->      List[str]:
      UpperCAmelCase			:      Optional[int]		   =					SwinModel(config=lowercase_			)
      model.to(lowercase_			)
      model.eval()
      UpperCAmelCase			:      Union[str, Any]		   =					model(lowercase_			)

      UpperCAmelCase			:      Dict		   =					((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths			) - 1))
      UpperCAmelCase			:      Optional[Any]		   =					int(config.embed_dim * 2 ** (len(config.depths			) - 1)			)

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


     def   UpperCAmelCase_			(						self					:	Tuple	,     lowercase_					:	List[str]	,     lowercase_					:	Tuple	,     lowercase_					:	Dict			)		->      Union[str, Any]:
      UpperCAmelCase			:      List[Any]		   =					SwinBackbone(config=lowercase_			)
      model.to(lowercase_			)
      model.eval()
      UpperCAmelCase			:      str		   =					model(lowercase_			)

      # 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
      UpperCAmelCase			:      Dict		   =					None
      UpperCAmelCase			:      Optional[int]		   =					SwinBackbone(config=lowercase_			)
      model.to(lowercase_			)
      model.eval()
      UpperCAmelCase			:      Optional[Any]		   =					model(lowercase_			)

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

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


     def   UpperCAmelCase_			(						self					:	Dict	,     lowercase_					:	str	,     lowercase_					:	Optional[int]	,     lowercase_					:	Tuple			)		->      List[str]:
      UpperCAmelCase			:      str		   =					SwinForMaskedImageModeling(config=lowercase_			)
      model.to(lowercase_			)
      model.eval()
      UpperCAmelCase			:      str		   =					model(lowercase_			)
      self.parent.assertEqual(
          result.logits.shape	,     (self.batch_size, self.num_channels, self.image_size, self.image_size)			)

      # test greyscale images
      UpperCAmelCase			:      int		   =					1
      UpperCAmelCase			:      List[str]		   =					SwinForMaskedImageModeling(lowercase_			)
      model.to(lowercase_			)
      model.eval()

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


     def   UpperCAmelCase_			(						self					:	Dict	,     lowercase_					:	Tuple	,     lowercase_					:	List[Any]	,     lowercase_					:	Optional[int]			)		->      int:
      UpperCAmelCase			:      int		   =					self.type_sequence_label_size
      UpperCAmelCase			:      str		   =					SwinForImageClassification(lowercase_			)
      model.to(lowercase_			)
      model.eval()
      UpperCAmelCase			:      Tuple		   =					model(lowercase_	,     labels=lowercase_			)
      self.parent.assertEqual(result.logits.shape	,     (self.batch_size, self.type_sequence_label_size)			)

      # test greyscale images
      UpperCAmelCase			:      List[Any]		   =					1
      UpperCAmelCase			:      Optional[int]		   =					SwinForImageClassification(lowercase_			)
      model.to(lowercase_			)
      model.eval()

      UpperCAmelCase			:      Optional[int]		   =					floats_tensor([self.batch_size, 1, self.image_size, self.image_size]			)
      UpperCAmelCase			:      str		   =					model(lowercase_			)
      self.parent.assertEqual(result.logits.shape	,     (self.batch_size, self.type_sequence_label_size)			)




     def   UpperCAmelCase_			(						self					:	Optional[int]			)		->      int:
      UpperCAmelCase			:      Dict		   =					self.prepare_config_and_inputs()
      (
          (
          UpperCAmelCase
      )   ,					(
          UpperCAmelCase
      )   ,					(
          UpperCAmelCase
      )   ,					
      )			:      Any		   =					config_and_inputs
      UpperCAmelCase			:      Tuple		   =					{'pixel_values': pixel_values}
      return config, inputs_dict




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






     '''simple docstring'''



     UpperCAmelCase_		:      List[str]    						=    (
         (
             SwinModel,
             SwinBackbone,
             SwinForImageClassification,
             SwinForMaskedImageModeling,
         )
         if is_torch_available()
         else ()
     )
     UpperCAmelCase_		:      str    						=    (
         {"""feature-extraction""": SwinModel, """image-classification""": SwinForImageClassification}
         if is_torch_available()
         else {}
     )
     UpperCAmelCase_		:      Union[str, Any]    						=    True

     UpperCAmelCase_		:      Tuple    						=    False
     UpperCAmelCase_		:      Optional[int]    						=    False
     UpperCAmelCase_		:      Optional[Any]    						=    False


     def   UpperCAmelCase_			(						self					:	Optional[int]			)		->      Optional[int]:
      UpperCAmelCase			:      List[str]		   =					SwinModelTester(self			)
      UpperCAmelCase			:      List[Any]		   =					ConfigTester(self	,     config_class=lowercase_	,     embed_dim=37			)


     def   UpperCAmelCase_			(						self					:	Dict			)		->      Dict:
      self.create_and_test_config_common_properties()
      self.config_tester.create_and_test_config_to_json_string()
      self.config_tester.create_and_test_config_to_json_file()
      self.config_tester.create_and_test_config_from_and_save_pretrained()
      self.config_tester.create_and_test_config_with_num_labels()
      self.config_tester.check_config_can_be_init_without_params()
      self.config_tester.check_config_arguments_init()


     def   UpperCAmelCase_			(						self					:	str			)		->      List[str]:
      return


     def   UpperCAmelCase_			(						self					:	Dict			)		->      Tuple:
      UpperCAmelCase			:      int		   =					self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*lowercase_			)


     @unittest.skip(reason='Got `CUDA error: misaligned address` with PyTorch 2.0.0.'			)
     def   UpperCAmelCase_			(						self					:	List[Any]			)		->      Optional[int]:
      pass


     def   UpperCAmelCase_			(						self					:	List[str]			)		->      Union[str, Any]:
      super().test_training_gradient_checkpointing()


     def   UpperCAmelCase_			(						self					:	List[str]			)		->      List[str]:
      UpperCAmelCase			:      int		   =					self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_backbone(*lowercase_			)


     def   UpperCAmelCase_			(						self					:	Tuple			)		->      Optional[int]:
      UpperCAmelCase			:      List[str]		   =					self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_masked_image_modeling(*lowercase_			)


     def   UpperCAmelCase_			(						self					:	Optional[Any]			)		->      Dict:
      UpperCAmelCase			:      int		   =					self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*lowercase_			)


     @unittest.skip(reason='Swin does not use inputs_embeds'			)
     def   UpperCAmelCase_			(						self					:	str			)		->      str:
      pass


     @unittest.skip(reason='Swin Transformer does not use feedforward chunking'			)
     def   UpperCAmelCase_			(						self					:	Optional[int]			)		->      int:
      pass


     def   UpperCAmelCase_			(						self					:	List[str]			)		->      Optional[int]:
      UpperCAmelCase   ,					UpperCAmelCase			:      List[Any]		   =					self.model_tester.prepare_config_and_inputs_for_common()

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


     def   UpperCAmelCase_			(						self					:	str			)		->      Optional[Any]:
      UpperCAmelCase   ,					UpperCAmelCase			:      Tuple		   =					self.model_tester.prepare_config_and_inputs_for_common()

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

       UpperCAmelCase			:      Dict		   =					['pixel_values']
       self.assertListEqual(arg_names[:1]	,     lowercase_			)


     def   UpperCAmelCase_			(						self					:	Any			)		->      str:
      UpperCAmelCase   ,					UpperCAmelCase			:      Union[str, Any]		   =					self.model_tester.prepare_config_and_inputs_for_common()
      UpperCAmelCase			:      List[str]		   =					True

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

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

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

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

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

       UpperCAmelCase			:      str		   =					outputs.attentions

       self.assertEqual(len(lowercase_			)	,     lowercase_			)

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


     def   UpperCAmelCase_			(						self					:	Union[str, Any]	,     lowercase_					:	Optional[Any]	,     lowercase_					:	Dict	,     lowercase_					:	str	,     lowercase_					:	int			)		->      Any:
      UpperCAmelCase			:      List[str]		   =					model_class(lowercase_			)
      model.to(lowercase_			)
      model.eval()

      with torch.no_grad():
       UpperCAmelCase			:      int		   =					model(**self._prepare_for_class(lowercase_	,     lowercase_			)			)

      UpperCAmelCase			:      Tuple		   =					outputs.hidden_states

      UpperCAmelCase			:      int		   =					getattr(
          self.model_tester	,     'expected_num_hidden_layers'	,     len(self.model_tester.depths			) + 1			)
      self.assertEqual(len(lowercase_			)	,     lowercase_			)

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

      UpperCAmelCase			:      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":
       UpperCAmelCase			:      Tuple		   =					outputs.reshaped_hidden_states
       self.assertEqual(len(lowercase_			)	,     lowercase_			)

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


     def   UpperCAmelCase_			(						self					:	Any			)		->      Any:
      UpperCAmelCase   ,					UpperCAmelCase			:      List[Any]		   =					self.model_tester.prepare_config_and_inputs_for_common()

      UpperCAmelCase			:      str		   =					(
          self.model_tester.image_size
          if isinstance(self.model_tester.image_size	,     collections.abc.Iterable			)
          else (self.model_tester.image_size, self.model_tester.image_size)
      )

      for model_class in self.all_model_classes:
       UpperCAmelCase			:      Optional[Any]		   =					True
       self.check_hidden_states_output(lowercase_	,     lowercase_	,     lowercase_	,     lowercase_			)

       # check that output_hidden_states also work using config
       del inputs_dict["output_hidden_states"]
       UpperCAmelCase			:      List[str]		   =					True

       self.check_hidden_states_output(lowercase_	,     lowercase_	,     lowercase_	,     lowercase_			)


     def   UpperCAmelCase_			(						self					:	Any			)		->      Optional[int]:
      UpperCAmelCase   ,					UpperCAmelCase			:      str		   =					self.model_tester.prepare_config_and_inputs_for_common()
      UpperCAmelCase			:      int		   =					3

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

      UpperCAmelCase			:      int		   =					image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
      UpperCAmelCase			:      List[Any]		   =					image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

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

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


     @slow
     def   UpperCAmelCase_			(						self					:	str			)		->      List[str]:
      for model_name in SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       UpperCAmelCase			:      int		   =					SwinModel.from_pretrained(lowercase_			)
       self.assertIsNotNone(lowercase_			)




     def   UpperCAmelCase_			(						self					:	Union[str, Any]			)		->      str:
      UpperCAmelCase   ,					UpperCAmelCase			:      Any		   =					self.model_tester.prepare_config_and_inputs_for_common()

      UpperCAmelCase			:      List[Any]		   =					_config_zero_init(lowercase_			)
      for model_class in self.all_model_classes:
       UpperCAmelCase			:      Optional[Any]		   =					model_class(config=lowercase_			)
       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   UpperCAmelCase_			(						self					:	Dict			)		->      Optional[Any]:
      return (
          AutoImageProcessor.from_pretrained('microsoft/swin-tiny-patch4-window7-224'			)
          if is_vision_available()
          else None
      )




     @slow
     def   UpperCAmelCase_			(						self					:	Tuple			)		->      Union[str, Any]:
      UpperCAmelCase			:      Optional[Any]		   =					SwinForImageClassification.from_pretrained('microsoft/swin-tiny-patch4-window7-224'			).to(lowercase_			)
      UpperCAmelCase			:      Dict		   =					self.default_image_processor

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

      # forward pass
      with torch.no_grad():
       UpperCAmelCase			:      Tuple		   =					model(**lowercase_			)

      # verify the logits
      UpperCAmelCase			:      List[Any]		   =					torch.Size((1, 1_000)			)
      self.assertEqual(outputs.logits.shape	,     lowercase_			)
      UpperCAmelCase			:      int		   =					torch.tensor([-0.0948, -0.6454, -0.0921]			).to(lowercase_			)
      self.assertTrue(torch.allclose(outputs.logits[0, :3]	,     lowercase_	,     atol=1E-4			)			)




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






     '''simple docstring'''



     UpperCAmelCase_		:      Tuple    						=    (SwinBackbone,) if is_torch_available() else ()
     UpperCAmelCase_		:      Any    						=    SwinConfig


     def   UpperCAmelCase_			(						self					:	str			)		->      Tuple:
      UpperCAmelCase			:      Dict		   =					SwinModelTester(self			)







'''simple docstring'''

from sklearn.metrics import roc_auc_score

import datasets


lowercase__            =     "\nThis metric computes the area under the curve (AUC) for the Receiver Operating Characteristic Curve (ROC). The return values represent how well the model used is predicting the correct classes, based on the input data. A score of `0.5` means that the model is predicting exactly at chance, i.e. the model's predictions are correct at the same rate as if the predictions were being decided by the flip of a fair coin or the roll of a fair die. A score above `0.5` indicates that the model is doing better than chance, while a score below `0.5` indicates that the model is doing worse than chance.\n\nThis metric has three separate use cases:\n    - binary: The case in which there are only two different label classes, and each example gets only one label. This is the default implementation.\n    - multiclass: The case in which there can be more than two different label classes, but each example still gets only one label.\n    - multilabel: The case in which there can be more than two different label classes, and each example can have more than one label.\n"

lowercase__            =     "\nArgs:\n- references (array-like of shape (n_samples,) or (n_samples, n_classes)): Ground truth labels. Expects different input based on use case:\n    - binary: expects an array-like of shape (n_samples,)\n    - multiclass: expects an array-like of shape (n_samples,)\n    - multilabel: expects an array-like of shape (n_samples, n_classes)\n- prediction_scores (array-like of shape (n_samples,) or (n_samples, n_classes)): Model predictions. Expects different inputs based on use case:\n    - binary: expects an array-like of shape (n_samples,)\n    - multiclass: expects an array-like of shape (n_samples, n_classes)\n    - multilabel: expects an array-like of shape (n_samples, n_classes)\n- average (`str`): Type of average, and is ignored in the binary use case. Defaults to 'macro'. Options are:\n    - `'micro'`: Calculates metrics globally by considering each element of the label indicator matrix as a label. Only works with the multilabel use case.\n    - `'macro'`: Calculate metrics for each label, and find their unweighted mean.  This does not take label imbalance into account.\n    - `'weighted'`: Calculate metrics for each label, and find their average, weighted by support (i.e. the number of true instances for each label).\n    - `'samples'`: Calculate metrics for each instance, and find their average. Only works with the multilabel use case.\n    - `None`:  No average is calculated, and scores for each class are returned. Only works with the multilabels use case.\n- sample_weight (array-like of shape (n_samples,)): Sample weights. Defaults to None.\n- max_fpr (`float`): If not None, the standardized partial AUC over the range [0, `max_fpr`] is returned. Must be greater than `0` and less than or equal to `1`. Defaults to `None`. Note: For the multiclass use case, `max_fpr` should be either `None` or `1.0` as ROC AUC partial computation is not currently supported for `multiclass`.\n- multi_class (`str`): Only used for multiclass targets, where it is required. Determines the type of configuration to use. Options are:\n    - `'ovr'`: Stands for One-vs-rest. Computes the AUC of each class against the rest. This treats the multiclass case in the same way as the multilabel case. Sensitive to class imbalance even when `average == 'macro'`, because class imbalance affects the composition of each of the 'rest' groupings.\n    - `'ovo'`: Stands for One-vs-one. Computes the average AUC of all possible pairwise combinations of classes. Insensitive to class imbalance when `average == 'macro'`.\n- labels (array-like of shape (n_classes,)): Only used for multiclass targets. List of labels that index the classes in\n    `prediction_scores`. If `None`, the numerical or lexicographical order of the labels in\n    `prediction_scores` is used. Defaults to `None`.\nReturns:\n    roc_auc (`float` or array-like of shape (n_classes,)): Returns array if in multilabel use case and `average='None'`. Otherwise, returns `float`.\nExamples:\n    Example 1:\n        >>> roc_auc_score = datasets.load_metric(\"roc_auc\")\n        >>> refs = [1, 0, 1, 1, 0, 0]\n        >>> pred_scores = [0.5, 0.2, 0.99, 0.3, 0.1, 0.7]\n        >>> results = roc_auc_score.compute(references=refs, prediction_scores=pred_scores)\n        >>> print(round(results['roc_auc'], 2))\n        0.78\n\n    Example 2:\n        >>> roc_auc_score = datasets.load_metric(\"roc_auc\", \"multiclass\")\n        >>> refs = [1, 0, 1, 2, 2, 0]\n        >>> pred_scores = [[0.3, 0.5, 0.2],\n        ...                 [0.7, 0.2, 0.1],\n        ...                 [0.005, 0.99, 0.005],\n        ...                 [0.2, 0.3, 0.5],\n        ...                 [0.1, 0.1, 0.8],\n        ...                 [0.1, 0.7, 0.2]]\n        >>> results = roc_auc_score.compute(references=refs, prediction_scores=pred_scores, multi_class='ovr')\n        >>> print(round(results['roc_auc'], 2))\n        0.85\n\n    Example 3:\n        >>> roc_auc_score = datasets.load_metric(\"roc_auc\", \"multilabel\")\n        >>> refs = [[1, 1, 0],\n        ...         [1, 1, 0],\n        ...         [0, 1, 0],\n        ...         [0, 0, 1],\n        ...         [0, 1, 1],\n        ...         [1, 0, 1]]\n        >>> pred_scores = [[0.3, 0.5, 0.2],\n        ...                 [0.7, 0.2, 0.1],\n        ...                 [0.005, 0.99, 0.005],\n        ...                 [0.2, 0.3, 0.5],\n        ...                 [0.1, 0.1, 0.8],\n        ...                 [0.1, 0.7, 0.2]]\n        >>> results = roc_auc_score.compute(references=refs, prediction_scores=pred_scores, average=None)\n        >>> print([round(res, 2) for res in results['roc_auc']])\n        [0.83, 0.38, 0.94]\n"

lowercase__            =     "\\n@article{doi:10.1177/0272989X8900900307,\nauthor = {Donna Katzman McClish},\ntitle ={Analyzing a Portion of the ROC Curve},\njournal = {Medical Decision Making},\nvolume = {9},\nnumber = {3},\npages = {190-195},\nyear = {1989},\ndoi = {10.1177/0272989X8900900307},\n    note ={PMID: 2668680},\nURL = {https://doi.org/10.1177/0272989X8900900307},\neprint = {https://doi.org/10.1177/0272989X8900900307}\n}\n\n\n@article{10.1023/A:1010920819831,\nauthor = {Hand, David J. and Till, Robert J.},\ntitle = {A Simple Generalisation of the Area Under the ROC Curve for Multiple Class Classification Problems},\nyear = {2001},\nissue_date = {November 2001},\npublisher = {Kluwer Academic Publishers},\naddress = {USA},\nvolume = {45},\nnumber = {2},\nissn = {0885-6125},\nurl = {https://doi.org/10.1023/A:1010920819831},\ndoi = {10.1023/A:1010920819831},\njournal = {Mach. Learn.},\nmonth = {oct},\npages = {171–186},\nnumpages = {16},\nkeywords = {Gini index, AUC, error rate, ROC curve, receiver operating characteristic}\n}\n\n\n@article{scikit-learn,\ntitle={Scikit-learn: Machine Learning in {P}ython},\nauthor={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\njournal={Journal of Machine Learning Research},\nvolume={12},\npages={2825--2830},\nyear={2011}\n}\n"




@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION			,  _KWARGS_DESCRIPTION				)
class 			A_					(							datasets.Metric				):






     '''simple docstring'''



     def   UpperCAmelCase_			(						self					:	Union[str, Any]			)		->      Dict:
      return datasets.MetricInfo(
          description=_DESCRIPTION	,     citation=_CITATION	,     inputs_description=_KWARGS_DESCRIPTION	,     features=datasets.Features(
              {
                  'prediction_scores': datasets.Sequence(datasets.Value('float'			)			),
                  'references': datasets.Value('int32'			),
              }
              if self.config_name == 'multiclass'
              else {
                  'references': datasets.Sequence(datasets.Value('int32'			)			),
                  'prediction_scores': datasets.Sequence(datasets.Value('float'			)			),
              }
              if self.config_name == 'multilabel'
              else {
                  'references': datasets.Value('int32'			),
                  'prediction_scores': datasets.Value('float'			),
              }			)	,     reference_urls=['https://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_auc_score.html']	,     )




     def   UpperCAmelCase_			(						self					:	Dict	,     lowercase_					:	Union[str, Any]	,     lowercase_					:	Dict	,     lowercase_					:	Dict="macro"	,     lowercase_					:	Optional[Any]=None	,     lowercase_					:	List[str]=None	,     lowercase_					:	int="raise"	,     lowercase_					:	List[str]=None	,     )		->      str:
      return {
          "roc_auc": roc_auc_score(
              lowercase_	,     lowercase_	,     average=lowercase_	,     sample_weight=lowercase_	,     max_fpr=lowercase_	,     multi_class=lowercase_	,     labels=lowercase_	,     )
      }




