


"""simple docstring"""





import inspect
from typing import Callable, List, Optional, Union

import torch
from transformers import (
    CLIPImageProcessor,
    CLIPTextModel,
    CLIPTokenizer,
    WhisperForConditionalGeneration,
    WhisperProcessor,
)

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    LMSDiscreteScheduler,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.utils import logging


snake_case__						:   List[Any]			 = logging.get_logger(__name__)  # pylint: disable=invalid-name



class 						snake_case_(				a__	):






     def __init__(		self     :    Dict    , UpperCamelCase_     :    WhisperForConditionalGeneration    , UpperCamelCase_     :    WhisperProcessor    , UpperCamelCase_     :    AutoencoderKL    , UpperCamelCase_     :    CLIPTextModel    , UpperCamelCase_     :    CLIPTokenizer    , UpperCamelCase_     :    UNetaDConditionModel    , UpperCamelCase_     :    Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]    , UpperCamelCase_     :    StableDiffusionSafetyChecker    , UpperCamelCase_     :    CLIPImageProcessor    , ):
           super().__init__()

           if safety_checker is None:
                 logger.warning(
                     F'''You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure'''
                     ''' that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered'''
                     ''' results in services or applications open to the public. Both the diffusers team and Hugging Face'''
                     ''' strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling'''
                     ''' it only for use-cases that involve analyzing network behavior or auditing its results. For more'''
                     ''' information, please have a look at https://github.com/huggingface/diffusers/pull/254 .''' )

           self.register_modules(
               speech_model=UpperCamelCase_    , speech_processor=UpperCamelCase_    , vae=UpperCamelCase_    , text_encoder=UpperCamelCase_    , tokenizer=UpperCamelCase_    , unet=UpperCamelCase_    , scheduler=UpperCamelCase_    , feature_extractor=UpperCamelCase_    , )






     def    lowerCamelCase__   (		self     :    Dict    , UpperCamelCase_     :    Optional[Union[str, int]] = "auto" ):
           if slice_size == "auto":
                 lowerCAmelCase    :		List[Any]				=      self.unet.config.attention_head_dim // 2
           self.unet.set_attention_slice(UpperCamelCase_ )






     def    lowerCamelCase__   (		self     :    Tuple ):
           self.enable_attention_slicing(UpperCamelCase_ )






     @torch.no_grad()
     def __call__(		self     :    str    , UpperCamelCase_     :    List[str]    , UpperCamelCase_     :    Union[str, Any]=1_6_0_0_0    , UpperCamelCase_     :    int = 5_1_2    , UpperCamelCase_     :    int = 5_1_2    , UpperCamelCase_     :    int = 5_0    , UpperCamelCase_     :    float = 7.5    , UpperCamelCase_     :    Optional[Union[str, List[str]]] = None    , UpperCamelCase_     :    Optional[int] = 1    , UpperCamelCase_     :    float = 0.0    , UpperCamelCase_     :    Optional[torch.Generator] = None    , UpperCamelCase_     :    Optional[torch.FloatTensor] = None    , UpperCamelCase_     :    Optional[str] = "pil"    , UpperCamelCase_     :    bool = True    , UpperCamelCase_     :    Optional[Callable[[int, int, torch.FloatTensor], None]] = None    , UpperCamelCase_     :    int = 1    , **UpperCamelCase_     :    str    , ):
           lowerCAmelCase    :		Union[str, Any]				=      self.speech_processor.feature_extractor(
               UpperCamelCase_    , return_tensors='''pt'''    , sampling_rate=UpperCamelCase_ ).input_features.to(self.device )
           lowerCAmelCase    :		int				=      self.speech_model.generate(UpperCamelCase_    , max_length=4_8_0_0_0_0 )

           lowerCAmelCase    :		List[str]				=      self.speech_processor.tokenizer.batch_decode(UpperCamelCase_    , skip_special_tokens=UpperCamelCase_    , normalize=UpperCamelCase_ )[
               0
           ]

           if isinstance(UpperCamelCase_    , UpperCamelCase_ ):
                 lowerCAmelCase    :		List[Any]				=      1
           elif isinstance(UpperCamelCase_    , UpperCamelCase_ ):
                 lowerCAmelCase    :		Union[str, Any]				=      len(UpperCamelCase_ )
           else:
                 raise ValueError(F'''`prompt` has to be of type `str` or `list` but is {type(UpperCamelCase_ )}''' )

           if height % 8 != 0 or width % 8 != 0:
                 raise ValueError(F'''`height` and `width` have to be divisible by 8 but are {height} and {width}.''' )

           if (callback_steps is None) or (
               callback_steps is not None and (not isinstance(UpperCamelCase_    , UpperCamelCase_ ) or callback_steps <= 0)
           ):
                 raise ValueError(
                     F'''`callback_steps` has to be a positive integer but is {callback_steps} of type'''
                     F''' {type(UpperCamelCase_ )}.''' )

           # get prompt text embeddings
           lowerCAmelCase    :		Optional[Any]				=      self.tokenizer(
               UpperCamelCase_    , padding='''max_length'''    , max_length=self.tokenizer.model_max_length    , return_tensors='''pt'''    , )
           lowerCAmelCase    :		List[str]				=      text_inputs.input_ids

           if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
                 lowerCAmelCase    :		List[Any]				=      self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] )
                 logger.warning(
                     '''The following part of your input was truncated because CLIP can only handle sequences up to'''
                     F''' {self.tokenizer.model_max_length} tokens: {removed_text}''' )
                 lowerCAmelCase    :		str				=      text_input_ids[:, : self.tokenizer.model_max_length]
           lowerCAmelCase    :		str				=      self.text_encoder(text_input_ids.to(self.device ) )[0]

           # duplicate text embeddings for each generation per prompt, using mps friendly method
           lowerCAmelCase,					lowerCAmelCase,					lowerCAmelCase    :		Optional[Any]				=      text_embeddings.shape
           lowerCAmelCase    :		Dict				=      text_embeddings.repeat(1    , UpperCamelCase_    , 1 )
           lowerCAmelCase    :		Tuple				=      text_embeddings.view(bs_embed * num_images_per_prompt    , UpperCamelCase_    , -1 )

           # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
           # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
           # corresponds to doing no classifier free guidance.
           lowerCAmelCase    :		str				=      guidance_scale > 1.0
           # get unconditional embeddings for classifier free guidance
           if do_classifier_free_guidance:
                 lowerCAmelCase    :		List[str]
                 if negative_prompt is None:
                       lowerCAmelCase    :		Tuple				=      [''''''] * batch_size
                 elif type(UpperCamelCase_ ) is not type(UpperCamelCase_ ):
                       raise TypeError(
                           F'''`negative_prompt` should be the same type to `prompt`, but got {type(UpperCamelCase_ )} !='''
                           F''' {type(UpperCamelCase_ )}.''' )
                 elif isinstance(UpperCamelCase_    , UpperCamelCase_ ):
                       lowerCAmelCase    :		Tuple				=      [negative_prompt]
                 elif batch_size != len(UpperCamelCase_ ):
                       raise ValueError(
                           F'''`negative_prompt`: {negative_prompt} has batch size {len(UpperCamelCase_ )}, but `prompt`:'''
                           F''' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches'''
                           ''' the batch size of `prompt`.''' )
                 else:
                       lowerCAmelCase    :		Tuple				=      negative_prompt

                 lowerCAmelCase    :		Any				=      text_input_ids.shape[-1]
                 lowerCAmelCase    :		Optional[int]				=      self.tokenizer(
                     UpperCamelCase_    , padding='''max_length'''    , max_length=UpperCamelCase_    , truncation=UpperCamelCase_    , return_tensors='''pt'''    , )
                 lowerCAmelCase    :		Union[str, Any]				=      self.text_encoder(uncond_input.input_ids.to(self.device ) )[0]

                 # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
                 lowerCAmelCase    :		Dict				=      uncond_embeddings.shape[1]
                 lowerCAmelCase    :		Optional[int]				=      uncond_embeddings.repeat(1    , UpperCamelCase_    , 1 )
                 lowerCAmelCase    :		Optional[int]				=      uncond_embeddings.view(batch_size * num_images_per_prompt    , UpperCamelCase_    , -1 )

                 # For classifier free guidance, we need to do two forward passes.
                 # Here we concatenate the unconditional and text embeddings into a single batch
                 # to avoid doing two forward passes
                 lowerCAmelCase    :		List[str]				=      torch.cat([uncond_embeddings, text_embeddings] )

           # get the initial random noise unless the user supplied it

           # Unlike in other pipelines, latents need to be generated in the target device
           # for 1-to-1 results reproducibility with the CompVis implementation.
           # However this currently doesn't work in `mps`.
           lowerCAmelCase    :		Any				=      (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
           lowerCAmelCase    :		Optional[Any]				=      text_embeddings.dtype
           if latents is None:
                 if self.device.type == "mps":
                       # randn does not exist on mps
                       lowerCAmelCase    :		str				=      torch.randn(UpperCamelCase_    , generator=UpperCamelCase_    , device='''cpu'''    , dtype=UpperCamelCase_ ).to(
                           self.device )
                 else:
                       lowerCAmelCase    :		Any				=      torch.randn(UpperCamelCase_    , generator=UpperCamelCase_    , device=self.device    , dtype=UpperCamelCase_ )
           else:
                 if latents.shape != latents_shape:
                       raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''' )
                 lowerCAmelCase    :		List[Any]				=      latents.to(self.device )

           # set timesteps
           self.scheduler.set_timesteps(UpperCamelCase_ )

           # Some schedulers like PNDM have timesteps as arrays
           # It's more optimized to move all timesteps to correct device beforehand
           lowerCAmelCase    :		List[str]				=      self.scheduler.timesteps.to(self.device )

           # scale the initial noise by the standard deviation required by the scheduler
           lowerCAmelCase    :		Optional[int]				=      latents * self.scheduler.init_noise_sigma

           # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
           # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
           # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
           # and should be between [0, 1]
           lowerCAmelCase    :		int				=      '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() )
           lowerCAmelCase    :		Optional[int]				=      {}
           if accepts_eta:
                 lowerCAmelCase    :		int				=      eta

           for i, t in enumerate(self.progress_bar(UpperCamelCase_ ) ):
                 # expand the latents if we are doing classifier free guidance
                 lowerCAmelCase    :		Dict				=      torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents
                 lowerCAmelCase    :		int				=      self.scheduler.scale_model_input(UpperCamelCase_    , UpperCamelCase_ )

                 # predict the noise residual
                 lowerCAmelCase    :		str				=      self.unet(UpperCamelCase_    , UpperCamelCase_    , encoder_hidden_states=UpperCamelCase_ ).sample

                 # perform guidance
                 if do_classifier_free_guidance:
                       lowerCAmelCase,					lowerCAmelCase    :		Tuple				=      noise_pred.chunk(2 )
                       lowerCAmelCase    :		Optional[Any]				=      noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

                 # compute the previous noisy sample x_t -> x_t-1
                 lowerCAmelCase    :		List[Any]				=      self.scheduler.step(UpperCamelCase_    , UpperCamelCase_    , UpperCamelCase_    , **UpperCamelCase_ ).prev_sample

                 # call the callback, if provided
                 if callback is not None and i % callback_steps == 0:
                       callback(UpperCamelCase_    , UpperCamelCase_    , UpperCamelCase_ )

           lowerCAmelCase    :		Any				=      1 / 0.18_215 * latents
           lowerCAmelCase    :		Union[str, Any]				=      self.vae.decode(UpperCamelCase_ ).sample

           lowerCAmelCase    :		Tuple				=      (image / 2 + 0.5).clamp(0    , 1 )

           # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
           lowerCAmelCase    :		Optional[int]				=      image.cpu().permute(0    , 2    , 3    , 1 ).float().numpy()

           if output_type == "pil":
                 lowerCAmelCase    :		Union[str, Any]				=      self.numpy_to_pil(UpperCamelCase_ )

           if not return_dict:
                 return image

           return StableDiffusionPipelineOutput(images=UpperCamelCase_    , nsfw_content_detected=UpperCamelCase_ )






"""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 						snake_case_:






     def __init__(		self     :    Dict    , UpperCamelCase_     :    str    , UpperCamelCase_     :    Dict=1_3    , UpperCamelCase_     :    Union[str, Any]=3_2    , UpperCamelCase_     :    str=2    , UpperCamelCase_     :    int=3    , UpperCamelCase_     :    Any=1_6    , UpperCamelCase_     :    int=[1, 2, 1]    , UpperCamelCase_     :    Optional[int]=[2, 2, 4]    , UpperCamelCase_     :    Any=2    , UpperCamelCase_     :    Any=2.0    , UpperCamelCase_     :    Union[str, Any]=True    , UpperCamelCase_     :    int=0.0    , UpperCamelCase_     :    Optional[Any]=0.0    , UpperCamelCase_     :    Any=0.1    , UpperCamelCase_     :    Tuple="gelu"    , UpperCamelCase_     :    Union[str, Any]=False    , UpperCamelCase_     :    Any=True    , UpperCamelCase_     :    List[Any]=0.02    , UpperCamelCase_     :    Tuple=1E-5    , UpperCamelCase_     :    Optional[int]=True    , UpperCamelCase_     :    List[Any]=None    , UpperCamelCase_     :    str=True    , UpperCamelCase_     :    List[Any]=1_0    , UpperCamelCase_     :    Dict=8    , ):
           lowerCAmelCase    :		Union[str, Any]				=      parent
           lowerCAmelCase    :		int				=      batch_size
           lowerCAmelCase    :		List[str]				=      image_size
           lowerCAmelCase    :		Union[str, Any]				=      patch_size
           lowerCAmelCase    :		int				=      num_channels
           lowerCAmelCase    :		Any				=      embed_dim
           lowerCAmelCase    :		Any				=      depths
           lowerCAmelCase    :		Any				=      num_heads
           lowerCAmelCase    :		int				=      window_size
           lowerCAmelCase    :		List[Any]				=      mlp_ratio
           lowerCAmelCase    :		int				=      qkv_bias
           lowerCAmelCase    :		Optional[Any]				=      hidden_dropout_prob
           lowerCAmelCase    :		str				=      attention_probs_dropout_prob
           lowerCAmelCase    :		str				=      drop_path_rate
           lowerCAmelCase    :		Union[str, Any]				=      hidden_act
           lowerCAmelCase    :		int				=      use_absolute_embeddings
           lowerCAmelCase    :		Union[str, Any]				=      patch_norm
           lowerCAmelCase    :		int				=      layer_norm_eps
           lowerCAmelCase    :		str				=      initializer_range
           lowerCAmelCase    :		Optional[int]				=      is_training
           lowerCAmelCase    :		int				=      scope
           lowerCAmelCase    :		List[str]				=      use_labels
           lowerCAmelCase    :		str				=      type_sequence_label_size
           lowerCAmelCase    :		Union[str, Any]				=      encoder_stride






     def    lowerCamelCase__   (		self     :    Any ):
           lowerCAmelCase    :		str				=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

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

           lowerCAmelCase    :		Tuple				=      self.get_config()

           return config, pixel_values, labels






     def    lowerCamelCase__   (		self     :    List[Any] ):
           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    lowerCamelCase__   (		self     :    Union[str, Any]    , UpperCamelCase_     :    Any    , UpperCamelCase_     :    str    , UpperCamelCase_     :    Dict ):
           lowerCAmelCase    :		List[str]				=      SwinvaModel(config=UpperCamelCase_ )
           model.to(UpperCamelCase_ )
           model.eval()
           lowerCAmelCase    :		List[str]				=      model(UpperCamelCase_ )

           lowerCAmelCase    :		Tuple				=      ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1))
           lowerCAmelCase    :		List[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    lowerCamelCase__   (		self     :    Tuple    , UpperCamelCase_     :    int    , UpperCamelCase_     :    str    , UpperCamelCase_     :    Optional[int] ):
           lowerCAmelCase    :		Tuple				=      SwinvaForMaskedImageModeling(config=UpperCamelCase_ )
           model.to(UpperCamelCase_ )
           model.eval()
           lowerCAmelCase    :		Dict				=      model(UpperCamelCase_ )
           self.parent.assertEqual(
               result.logits.shape    , (self.batch_size, self.num_channels, self.image_size, self.image_size) )

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

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






     def    lowerCamelCase__   (		self     :    Union[str, Any]    , UpperCamelCase_     :    Tuple    , UpperCamelCase_     :    List[str]    , UpperCamelCase_     :    int ):
           lowerCAmelCase    :		List[str]				=      self.type_sequence_label_size
           lowerCAmelCase    :		Optional[Any]				=      SwinvaForImageClassification(UpperCamelCase_ )
           model.to(UpperCamelCase_ )
           model.eval()
           lowerCAmelCase    :		Optional[int]				=      model(UpperCamelCase_    , labels=UpperCamelCase_ )
           self.parent.assertEqual(result.logits.shape    , (self.batch_size, self.type_sequence_label_size) )






     def    lowerCamelCase__   (		self     :    str ):
           lowerCAmelCase    :		Optional[int]				=      self.prepare_config_and_inputs()
           lowerCAmelCase,					lowerCAmelCase,					lowerCAmelCase    :		str				=      config_and_inputs
           lowerCAmelCase    :		Dict				=      {'''pixel_values''': pixel_values}
           return config, inputs_dict



@require_torch
class 						snake_case_(				a__							,    a__							,    unittest.TestCase	):
     __UpperCamelCase     =    (
         (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else ()
     )
     __UpperCamelCase     =    (
         {'''feature-extraction''': SwinvaModel, '''image-classification''': SwinvaForImageClassification}
         if is_torch_available()
         else {}
     )

     __UpperCamelCase     =    False
     __UpperCamelCase     =    False
     __UpperCamelCase     =    False
     __UpperCamelCase     =    False






     def    lowerCamelCase__   (		self     :    int ):
           lowerCAmelCase    :		Dict				=      SwinvaModelTester(self )
           lowerCAmelCase    :		List[str]				=      ConfigTester(self    , config_class=UpperCamelCase_    , embed_dim=3_7 )






     def    lowerCamelCase__   (		self     :    Optional[int] ):
           self.config_tester.create_and_test_config_to_json_string()
           self.config_tester.create_and_test_config_to_json_file()
           self.config_tester.create_and_test_config_from_and_save_pretrained()
           self.config_tester.create_and_test_config_with_num_labels()
           self.config_tester.check_config_can_be_init_without_params()
           self.config_tester.check_config_arguments_init()






     def    lowerCamelCase__   (		self     :    List[str] ):
           lowerCAmelCase    :		Tuple				=      self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*UpperCamelCase_ )






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






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






     def    lowerCamelCase__   (		self     :    List[Any] ):
           lowerCAmelCase,					lowerCAmelCase    :		Dict				=      self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                 lowerCAmelCase    :		Dict				=      model_class(UpperCamelCase_ )
                 self.assertIsInstance(model.get_input_embeddings()    , (nn.Module) )
                 lowerCAmelCase    :		str				=      model.get_output_embeddings()
                 self.assertTrue(x is None or isinstance(UpperCamelCase_    , nn.Linear ) )






     def    lowerCamelCase__   (		self     :    Optional[Any] ):
           lowerCAmelCase,					lowerCAmelCase    :		Tuple				=      self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                 lowerCAmelCase    :		Tuple				=      model_class(UpperCamelCase_ )
                 lowerCAmelCase    :		Tuple				=      inspect.signature(model.forward )
                 # signature.parameters is an OrderedDict => so arg_names order is deterministic
                 lowerCAmelCase    :		Optional[int]				=      [*signature.parameters.keys()]

                 lowerCAmelCase    :		int				=      ['''pixel_values''']
                 self.assertListEqual(arg_names[:1]    , UpperCamelCase_ )






     def    lowerCamelCase__   (		self     :    Tuple ):
           lowerCAmelCase,					lowerCAmelCase    :		Dict				=      self.model_tester.prepare_config_and_inputs_for_common()
           lowerCAmelCase    :		Optional[Any]				=      True

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

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

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

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

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

                 lowerCAmelCase    :		List[str]				=      outputs.attentions

                 self.assertEqual(len(UpperCamelCase_ )    , UpperCamelCase_ )

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






     def    lowerCamelCase__   (		self     :    int    , UpperCamelCase_     :    Tuple    , UpperCamelCase_     :    Dict    , UpperCamelCase_     :    List[Any]    , UpperCamelCase_     :    Optional[Any] ):
           lowerCAmelCase    :		int				=      model_class(UpperCamelCase_ )
           model.to(UpperCamelCase_ )
           model.eval()

           with torch.no_grad():
                 lowerCAmelCase    :		Union[str, Any]				=      model(**self._prepare_for_class(UpperCamelCase_    , UpperCamelCase_ ) )

           lowerCAmelCase    :		str				=      outputs.hidden_states

           lowerCAmelCase    :		List[str]				=      getattr(
               self.model_tester    , '''expected_num_hidden_layers'''    , len(self.model_tester.depths ) + 1 )
           self.assertEqual(len(UpperCamelCase_ )    , UpperCamelCase_ )

           # Swinv2 has a different seq_length
           lowerCAmelCase    :		Any				=      (
               config.patch_size
               if isinstance(config.patch_size    , collections.abc.Iterable )
               else (config.patch_size, config.patch_size)
           )

           lowerCAmelCase    :		str				=      (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]    , )

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

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






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

           lowerCAmelCase    :		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:
                 lowerCAmelCase    :		Union[str, Any]				=      True
                 self.check_hidden_states_output(UpperCamelCase_    , UpperCamelCase_    , UpperCamelCase_    , UpperCamelCase_ )

                 # check that output_hidden_states also work using config
                 del inputs_dict["output_hidden_states"]
                 lowerCAmelCase    :		Tuple				=      True

                 self.check_hidden_states_output(UpperCamelCase_    , UpperCamelCase_    , UpperCamelCase_    , UpperCamelCase_ )






     def    lowerCamelCase__   (		self     :    Optional[Any] ):
           lowerCAmelCase,					lowerCAmelCase    :		Union[str, Any]				=      self.model_tester.prepare_config_and_inputs_for_common()
           lowerCAmelCase    :		Dict				=      3

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

           lowerCAmelCase    :		List[str]				=      image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
           lowerCAmelCase    :		Tuple				=      image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

           for model_class in self.all_model_classes:
                 lowerCAmelCase    :		str				=      True
                 self.check_hidden_states_output(UpperCamelCase_    , UpperCamelCase_    , UpperCamelCase_    , (padded_height, padded_width) )

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






     def    lowerCamelCase__   (		self     :    int ):
           lowerCAmelCase    :		str				=      self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_masked_image_modeling(*UpperCamelCase_ )






     def    lowerCamelCase__   (		self     :    str ):
           lowerCAmelCase    :		Dict				=      self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*UpperCamelCase_ )






     @slow
     def    lowerCamelCase__   (		self     :    int ):
           for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 lowerCAmelCase    :		int				=      SwinvaModel.from_pretrained(UpperCamelCase_ )
                 self.assertIsNotNone(UpperCamelCase_ )






     def    lowerCamelCase__   (		self     :    Optional[int] ):
           lowerCAmelCase,					lowerCAmelCase    :		int				=      self.model_tester.prepare_config_and_inputs_for_common()

           lowerCAmelCase    :		Union[str, Any]				=      _config_zero_init(UpperCamelCase_ )
           for model_class in self.all_model_classes:
                 lowerCAmelCase    :		Union[str, Any]				=      model_class(config=UpperCamelCase_ )
                 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 						snake_case_(				unittest.TestCase	):






     @cached_property
     def    lowerCamelCase__   (		self     :    Dict ):
           return (
               AutoImageProcessor.from_pretrained('''microsoft/swinv2-tiny-patch4-window8-256''' )
               if is_vision_available()
               else None
           )






     @slow
     def    lowerCamelCase__   (		self     :    Dict ):
           lowerCAmelCase    :		str				=      SwinvaForImageClassification.from_pretrained('''microsoft/swinv2-tiny-patch4-window8-256''' ).to(
               UpperCamelCase_ )
           lowerCAmelCase    :		List[Any]				=      self.default_image_processor

           lowerCAmelCase    :		int				=      Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
           lowerCAmelCase    :		Union[str, Any]				=      image_processor(images=UpperCamelCase_    , return_tensors='''pt''' ).to(UpperCamelCase_ )

           # forward pass
           with torch.no_grad():
                 lowerCAmelCase    :		Dict				=      model(**UpperCamelCase_ )

           # verify the logits
           lowerCAmelCase    :		List[Any]				=      torch.Size((1, 1_0_0_0) )
           self.assertEqual(outputs.logits.shape    , UpperCamelCase_ )
           lowerCAmelCase    :		Any				=      torch.tensor([-0.3_947, -0.4_306, 0.0_026] ).to(UpperCamelCase_ )
           self.assertTrue(torch.allclose(outputs.logits[0, :3]    , UpperCamelCase_    , atol=1E-4 ) )


