






'''simple docstring'''

import collections
import inspect
import unittest

from transformers import SwinvaConfig
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_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 SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel
      from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
      from PIL import Image

      from transformers import AutoImageProcessor




class      A     :






 """simple docstring"""





 def __init__(				self      ,  __lowerCAmelCase      ,  __lowerCAmelCase=13      ,  __lowerCAmelCase=32      ,  __lowerCAmelCase=2      ,  __lowerCAmelCase=3      ,  __lowerCAmelCase=16      ,  __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=10      ,  __lowerCAmelCase=8      ,  ):
       UpperCamelCase_					: Tuple            =				parent
       UpperCamelCase_					: int            =				batch_size
       UpperCamelCase_					: int            =				image_size
       UpperCamelCase_					: Optional[int]            =				patch_size
       UpperCamelCase_					: List[Any]            =				num_channels
       UpperCamelCase_					: int            =				embed_dim
       UpperCamelCase_					: List[str]            =				depths
       UpperCamelCase_					: Tuple            =				num_heads
       UpperCamelCase_					: Tuple            =				window_size
       UpperCamelCase_					: Union[str, Any]            =				mlp_ratio
       UpperCamelCase_					: List[Any]            =				qkv_bias
       UpperCamelCase_					: int            =				hidden_dropout_prob
       UpperCamelCase_					: Optional[Any]            =				attention_probs_dropout_prob
       UpperCamelCase_					: Any            =				drop_path_rate
       UpperCamelCase_					: str            =				hidden_act
       UpperCamelCase_					: str            =				use_absolute_embeddings
       UpperCamelCase_					: Tuple            =				patch_norm
       UpperCamelCase_					: Any            =				layer_norm_eps
       UpperCamelCase_					: str            =				initializer_range
       UpperCamelCase_					: Dict            =				is_training
       UpperCamelCase_					: Dict            =				scope
       UpperCamelCase_					: str            =				use_labels
       UpperCamelCase_					: Any            =				type_sequence_label_size
       UpperCamelCase_					: Optional[int]            =				encoder_stride
 def 	_UpperCAmelCase							(				self			):
       UpperCamelCase_					: Dict            =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

       UpperCamelCase_					: Any            =				None
       if self.use_labels:
             UpperCamelCase_					: Dict            =				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			):
       return SwinvaConfig(
           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      ,  )
 def 	_UpperCAmelCase							(				self      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase			):
       UpperCamelCase_					: Union[str, Any]            =				SwinvaModel(config=__lowerCAmelCase			)
       model.to(__lowerCAmelCase			)
       model.eval()
       UpperCamelCase_					: List[str]            =				model(__lowerCAmelCase			)

       UpperCamelCase_					: Optional[int]            =				((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      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase			):
       UpperCamelCase_					: Tuple            =				SwinvaForMaskedImageModeling(config=__lowerCAmelCase			)
       model.to(__lowerCAmelCase			)
       model.eval()
       UpperCamelCase_					: Optional[Any]            =				model(__lowerCAmelCase			)
       self.parent.assertEqual(
           result.logits.shape      ,  (self.batch_size, self.num_channels, self.image_size, self.image_size)			)

       # test greyscale images
       UpperCamelCase_					: List[Any]            =				1
       UpperCamelCase_					: List[str]            =				SwinvaForMaskedImageModeling(__lowerCAmelCase			)
       model.to(__lowerCAmelCase			)
       model.eval()

       UpperCamelCase_					: Union[str, Any]            =				floats_tensor([self.batch_size, 1, self.image_size, self.image_size]			)
       UpperCamelCase_					: int            =				model(__lowerCAmelCase			)
       self.parent.assertEqual(result.logits.shape      ,  (self.batch_size, 1, self.image_size, self.image_size)			)
 def 	_UpperCAmelCase							(				self      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase			):
       UpperCamelCase_					: Tuple            =				self.type_sequence_label_size
       UpperCamelCase_					: Dict            =				SwinvaForImageClassification(__lowerCAmelCase			)
       model.to(__lowerCAmelCase			)
       model.eval()
       UpperCamelCase_					: List[str]            =				model(__lowerCAmelCase      ,  labels=__lowerCAmelCase			)
       self.parent.assertEqual(result.logits.shape      ,  (self.batch_size, self.type_sequence_label_size)			)





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






@require_torch
class      A     (   SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, unittest.TestCase    ):






 """simple docstring"""





 __a      :    Optional[int]			  =    (
     (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else ()
 )
 __a      :    Any			  =    (
     {'''feature-extraction''': SwinvaModel, '''image-classification''': SwinvaForImageClassification}
     if is_torch_available()
     else {}
 )

 __a      :    int			  =    False
 __a      :    Optional[Any]			  =    False
 __a      :    int			  =    False
 __a      :    str			  =    False
 def 	_UpperCAmelCase							(				self			):
       UpperCamelCase_					: int            =				SwinvaModelTester(self			)
       UpperCamelCase_					: Any            =				ConfigTester(self      ,  config_class=__lowerCAmelCase      ,  embed_dim=37			)
 def 	_UpperCAmelCase							(				self			):
       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			):
       UpperCamelCase_					: List[str]            =				self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__lowerCAmelCase			)
 @unittest.skip(reason="""Got `CUDA error: misaligned address` with PyTorch 2.0.0."""			)
 def 	_UpperCAmelCase							(				self			):
       pass
 @unittest.skip(reason="""Swinv2 does not use inputs_embeds"""			)
 def 	_UpperCAmelCase							(				self			):
       pass
 def 	_UpperCAmelCase							(				self			):
       UpperCamelCase_     ,      UpperCamelCase_					: Tuple            =				self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
             UpperCamelCase_					: Dict            =				model_class(__lowerCAmelCase			)
             self.assertIsInstance(model.get_input_embeddings()      ,  (nn.Module)			)
             UpperCamelCase_					: Optional[int]            =				model.get_output_embeddings()
             self.assertTrue(x is None or isinstance(__lowerCAmelCase      ,  nn.Linear			)			)
 def 	_UpperCAmelCase							(				self			):
       UpperCamelCase_     ,      UpperCamelCase_					: Optional[int]            =				self.model_tester.prepare_config_and_inputs_for_common()

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

             UpperCamelCase_					: Dict            =				["""pixel_values"""]
             self.assertListEqual(arg_names[:1]      ,  __lowerCAmelCase			)
 def 	_UpperCAmelCase							(				self			):
       UpperCamelCase_     ,      UpperCamelCase_					: Dict            =				self.model_tester.prepare_config_and_inputs_for_common()
       UpperCamelCase_					: Optional[Any]            =				True

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

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

             self.assertListEqual(
                 list(attentions[0].shape[-3:]			)      ,  [self.model_tester.num_heads[0], window_size_squared, window_size_squared]      ,  )
             UpperCamelCase_					: List[Any]            =				len(__lowerCAmelCase			)

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

             if hasattr(self.model_tester      ,  """num_hidden_states_types"""			):
                   UpperCamelCase_					: List[Any]            =				self.model_tester.num_hidden_states_types
             else:
                   # also another +1 for reshaped_hidden_states
                   UpperCamelCase_					: str            =				2
             self.assertEqual(out_len + added_hidden_states      ,  len(__lowerCAmelCase			)			)

             UpperCamelCase_					: Union[str, Any]            =				outputs.attentions

             self.assertEqual(len(__lowerCAmelCase			)      ,  __lowerCAmelCase			)

             self.assertListEqual(
                 list(self_attentions[0].shape[-3:]			)      ,  [self.model_tester.num_heads[0], window_size_squared, window_size_squared]      ,  )
 def 	_UpperCAmelCase							(				self      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase			):
       UpperCamelCase_					: Optional[Any]            =				model_class(__lowerCAmelCase			)
       model.to(__lowerCAmelCase			)
       model.eval()

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

       UpperCamelCase_					: str            =				outputs.hidden_states

       UpperCamelCase_					: Union[str, Any]            =				getattr(
           self.model_tester      ,  """expected_num_hidden_layers"""      ,  len(self.model_tester.depths			) + 1			)
       self.assertEqual(len(__lowerCAmelCase			)      ,  __lowerCAmelCase			)

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

       UpperCamelCase_					: Dict            =				(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]      ,  )

       UpperCamelCase_					: List[str]            =				outputs.reshaped_hidden_states
       self.assertEqual(len(__lowerCAmelCase			)      ,  __lowerCAmelCase			)

       UpperCamelCase_     ,      UpperCamelCase_     ,      UpperCamelCase_     ,      UpperCamelCase_					: Tuple            =				reshaped_hidden_states[0].shape
       UpperCamelCase_					: 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 	_UpperCAmelCase							(				self			):
       UpperCamelCase_     ,      UpperCamelCase_					: str            =				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_					: 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"]
             UpperCamelCase_					: List[str]            =				True

             self.check_hidden_states_output(__lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase			)
 def 	_UpperCAmelCase							(				self			):
       UpperCamelCase_     ,      UpperCamelCase_					: Any            =				self.model_tester.prepare_config_and_inputs_for_common()
       UpperCamelCase_					: Union[str, Any]            =				3

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

       UpperCamelCase_					: Tuple            =				image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
       UpperCamelCase_					: Optional[Any]            =				image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

       for model_class in self.all_model_classes:
             UpperCamelCase_					: 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"]
             UpperCamelCase_					: int            =				True
             self.check_hidden_states_output(__lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  (padded_height, padded_width)			)
 def 	_UpperCAmelCase							(				self			):
       UpperCamelCase_					: Dict            =				self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_image_modeling(*__lowerCAmelCase			)
 def 	_UpperCAmelCase							(				self			):
       UpperCamelCase_					: Any            =				self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*__lowerCAmelCase			)
 @slow
 def 	_UpperCAmelCase							(				self			):
       for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             UpperCamelCase_					: List[Any]            =				SwinvaModel.from_pretrained(__lowerCAmelCase			)
             self.assertIsNotNone(__lowerCAmelCase			)





 def 	_UpperCAmelCase							(				self			):
       UpperCamelCase_     ,      UpperCamelCase_					: str            =				self.model_tester.prepare_config_and_inputs_for_common()

       UpperCamelCase_					: Optional[int]            =				_config_zero_init(__lowerCAmelCase			)
       for model_class in self.all_model_classes:
             UpperCamelCase_					: Tuple            =				model_class(config=__lowerCAmelCase			)
             for name, param in model.named_parameters():
                   if "embeddings" not in name and "logit_scale" 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			):
       return (
           AutoImageProcessor.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256"""			)
           if is_vision_available()
           else None
       )





 @slow
 def 	_UpperCAmelCase							(				self			):
       UpperCamelCase_					: Optional[Any]            =				SwinvaForImageClassification.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256"""			).to(
           __lowerCAmelCase			)
       UpperCamelCase_					: str            =				self.default_image_processor

       UpperCamelCase_					: Dict            =				Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""			)
       UpperCamelCase_					: Any            =				image_processor(images=__lowerCAmelCase      ,  return_tensors="""pt"""			).to(__lowerCAmelCase			)

       # forward pass
       with torch.no_grad():
             UpperCamelCase_					: Optional[int]            =				model(**__lowerCAmelCase			)

       # verify the logits
       UpperCamelCase_					: Optional[int]            =				torch.Size((1, 10_00)			)
       self.assertEqual(outputs.logits.shape      ,  __lowerCAmelCase			)
       UpperCamelCase_					: str            =				torch.tensor([-0.39_47, -0.43_06, 0.00_26]			).to(__lowerCAmelCase			)
       self.assertTrue(torch.allclose(outputs.logits[0, :3]      ,  __lowerCAmelCase      ,  atol=1E-4			)			)














'''simple docstring'''

from ...utils import (
    OptionalDependencyNotAvailable,
    is_flax_available,
    is_torch_available,
    is_transformers_available,
)


try:
      if not (is_transformers_available() and is_torch_available()):
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      from ...utils.dummy_torch_and_transformers_objects import *  # noqa F403
else:
      from .multicontrolnet import MultiControlNetModel
      from .pipeline_controlnet import StableDiffusionControlNetPipeline
      from .pipeline_controlnet_imgaimg import StableDiffusionControlNetImgaImgPipeline
      from .pipeline_controlnet_inpaint import StableDiffusionControlNetInpaintPipeline


if is_transformers_available() and is_flax_available():
      from .pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline






