

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


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


 def _UpperCamelCase	(						self		: str    )    ->      str:
   UpperCAmelCase					      =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

   UpperCAmelCase					      =  self.get_config()

   return config, pixel_values, labels


 def _UpperCamelCase	(						self		: Optional[int]    )    ->      int:
   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		: List[Any]			,						lowerCAmelCase__		: str			,						lowerCAmelCase__		: Union[str, Any]			,						lowerCAmelCase__		: List[Any]    )    ->      Optional[int]:
   UpperCAmelCase					      =  SwinvaModel(config=lowerCAmelCase__    )
   model.to(lowerCAmelCase__    )
   model.eval()
   UpperCAmelCase					      =  model(lowerCAmelCase__    )

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

   # test greyscale images
   UpperCAmelCase					      =  1
   UpperCAmelCase					      =  SwinvaForMaskedImageModeling(lowerCAmelCase__    )
   model.to(lowerCAmelCase__    )
   model.eval()

   UpperCAmelCase					      =  floats_tensor([self.batch_size, 1, self.image_size, self.image_size]    )
   UpperCAmelCase					      =  model(lowerCAmelCase__    )
   self.parent.assertEqual(result.logits.shape			,						(self.batch_size, 1, self.image_size, self.image_size)    )


 def _UpperCamelCase	(						self		: List[Any]			,						lowerCAmelCase__		: Optional[Any]			,						lowerCAmelCase__		: Union[str, Any]			,						lowerCAmelCase__		: Dict    )    ->      Optional[Any]:
   UpperCAmelCase					      =  self.type_sequence_label_size
   UpperCAmelCase					      =  SwinvaForImageClassification(lowerCAmelCase__    )
   model.to(lowerCAmelCase__    )
   model.eval()
   UpperCAmelCase					      =  model(lowerCAmelCase__			,						labels=lowerCAmelCase__    )
   self.parent.assertEqual(result.logits.shape			,						(self.batch_size, self.type_sequence_label_size)    )


 def _UpperCamelCase	(						self		: Any    )    ->      List[Any]:
   UpperCAmelCase					      =  self.prepare_config_and_inputs()
   UpperCAmelCase      ,	UpperCAmelCase      ,	UpperCAmelCase					      =  config_and_inputs
   UpperCAmelCase					      =  {"pixel_values": pixel_values}
   return config, inputs_dict






@require_torch
class 						__magic_name__    (       _snake_case	,						_snake_case	,						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 _UpperCamelCase	(						self		: Dict    )    ->      List[str]:
   UpperCAmelCase					      =  SwinvaModelTester(self    )
   UpperCAmelCase					      =  ConfigTester(self			,						config_class=lowerCAmelCase__			,						embed_dim=3_7    )


 def _UpperCamelCase	(						self		: Optional[int]    )    ->      Tuple:
   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		: Optional[int]    )    ->      List[Any]:
   UpperCAmelCase					      =  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		: Tuple    )    ->      Union[str, Any]:
   pass


 @unittest.skip(reason="Swinv2 does not use inputs_embeds"    )
 def _UpperCamelCase	(						self		: Any    )    ->      Any:
   pass


 def _UpperCamelCase	(						self		: str    )    ->      Dict:
   UpperCAmelCase      ,	UpperCAmelCase					      =  self.model_tester.prepare_config_and_inputs_for_common()

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


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

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

     UpperCAmelCase					      =  ["pixel_values"]
     self.assertListEqual(arg_names[:1]			,						lowerCAmelCase__    )


 def _UpperCamelCase	(						self		: Optional[int]    )    ->      Union[str, Any]:
   UpperCAmelCase      ,	UpperCAmelCase					      =  self.model_tester.prepare_config_and_inputs_for_common()
   UpperCAmelCase					      =  True

   for model_class in self.all_model_classes:
     UpperCAmelCase					      =  True
     UpperCAmelCase					      =  False
     UpperCAmelCase					      =  True
     UpperCAmelCase					      =  model_class(lowerCAmelCase__    )
     model.to(lowerCAmelCase__    )
     model.eval()
     with torch.no_grad():
       UpperCAmelCase					      =  model(**self._prepare_for_class(lowerCAmelCase__			,						lowerCAmelCase__    )    )
     UpperCAmelCase					      =  outputs.attentions
     UpperCAmelCase					      =  len(self.model_tester.depths    )
     self.assertEqual(len(lowerCAmelCase__    )			,						lowerCAmelCase__    )

     # check that output_attentions also work using config
     del inputs_dict["output_attentions"]
     UpperCAmelCase					      =  True
     UpperCAmelCase					      =  config.window_size**2
     UpperCAmelCase					      =  model_class(lowerCAmelCase__    )
     model.to(lowerCAmelCase__    )
     model.eval()
     with torch.no_grad():
       UpperCAmelCase					      =  model(**self._prepare_for_class(lowerCAmelCase__			,						lowerCAmelCase__    )    )
     UpperCAmelCase					      =  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					      =  len(lowerCAmelCase__    )

     # Check attention is always last and order is fine
     UpperCAmelCase					      =  True
     UpperCAmelCase					      =  True
     UpperCAmelCase					      =  model_class(lowerCAmelCase__    )
     model.to(lowerCAmelCase__    )
     model.eval()
     with torch.no_grad():
       UpperCAmelCase					      =  model(**self._prepare_for_class(lowerCAmelCase__			,						lowerCAmelCase__    )    )

     if hasattr(self.model_tester			,						"num_hidden_states_types"    ):
       UpperCAmelCase					      =  self.model_tester.num_hidden_states_types
     else:
       # also another +1 for reshaped_hidden_states
       UpperCAmelCase					      =  2
     self.assertEqual(out_len + added_hidden_states			,						len(lowerCAmelCase__    )    )

     UpperCAmelCase					      =  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		: List[Any]			,						lowerCAmelCase__		: str			,						lowerCAmelCase__		: List[str]			,						lowerCAmelCase__		: str			,						lowerCAmelCase__		: Any    )    ->      Dict:
   UpperCAmelCase					      =  model_class(lowerCAmelCase__    )
   model.to(lowerCAmelCase__    )
   model.eval()

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

   UpperCAmelCase					      =  outputs.hidden_states

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

   UpperCAmelCase					      =  (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					      =  outputs.reshaped_hidden_states
   self.assertEqual(len(lowerCAmelCase__    )			,						lowerCAmelCase__    )

   UpperCAmelCase      ,	UpperCAmelCase      ,	UpperCAmelCase      ,	UpperCAmelCase					      =  reshaped_hidden_states[0].shape
   UpperCAmelCase					      =  (
       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		: Optional[Any]    )    ->      Tuple:
   UpperCAmelCase      ,	UpperCAmelCase					      =  self.model_tester.prepare_config_and_inputs_for_common()

   UpperCAmelCase					      =  (
       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					      =  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					      =  True

     self.check_hidden_states_output(lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__    )


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

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

   UpperCAmelCase					      =  image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
   UpperCAmelCase					      =  image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

   for model_class in self.all_model_classes:
     UpperCAmelCase					      =  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					      =  True
     self.check_hidden_states_output(lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						(padded_height, padded_width)    )


 def _UpperCamelCase	(						self		: Optional[int]    )    ->      Dict:
   UpperCAmelCase					      =  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_masked_image_modeling(*lowerCAmelCase__    )


 def _UpperCamelCase	(						self		: str    )    ->      List[str]:
   UpperCAmelCase					      =  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__    )


 @slow
 def _UpperCamelCase	(						self		: Any    )    ->      List[Any]:




   for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     UpperCAmelCase					      =  SwinvaModel.from_pretrained(lowerCAmelCase__    )
     self.assertIsNotNone(lowerCAmelCase__    )


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

   UpperCAmelCase					      =  _config_zero_init(lowerCAmelCase__    )
   for model_class in self.all_model_classes:
     UpperCAmelCase					      =  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 						__magic_name__    (       unittest.TestCase    ):


 @cached_property
 def _UpperCamelCase	(						self		: List[Any]    )    ->      str:
   return (
       AutoImageProcessor.from_pretrained("microsoft/swinv2-tiny-patch4-window8-256"    )
       if is_vision_available()
       else None
   )


 @slow
 def _UpperCamelCase	(						self		: List[str]    )    ->      Dict:
   UpperCAmelCase					      =  SwinvaForImageClassification.from_pretrained("microsoft/swinv2-tiny-patch4-window8-256"    ).to(
       lowerCAmelCase__    )
   UpperCAmelCase					      =  self.default_image_processor

   UpperCAmelCase					      =  Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"    )
   UpperCAmelCase					      =  image_processor(images=lowerCAmelCase__			,						return_tensors="pt"    ).to(lowerCAmelCase__    )

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

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






from . import (
    albert,
    align,
    altclip,
    audio_spectrogram_transformer,
    auto,
    autoformer,
    bark,
    bart,
    barthez,
    bartpho,
    beit,
    bert,
    bert_generation,
    bert_japanese,
    bertweet,
    big_bird,
    bigbird_pegasus,
    biogpt,
    bit,
    blenderbot,
    blenderbot_small,
    blip,
    blip_a,
    bloom,
    bridgetower,
    byta,
    camembert,
    canine,
    chinese_clip,
    clap,
    clip,
    clipseg,
    codegen,
    conditional_detr,
    convbert,
    convnext,
    convnextva,
    cpm,
    cpmant,
    ctrl,
    cvt,
    dataavec,
    deberta,
    deberta_va,
    decision_transformer,
    deformable_detr,
    deit,
    deprecated,
    deta,
    detr,
    dialogpt,
    dinat,
    distilbert,
    dit,
    donut,
    dpr,
    dpt,
    efficientformer,
    efficientnet,
    electra,
    encodec,
    encoder_decoder,
    ernie,
    ernie_m,
    esm,
    falcon,
    flaubert,
    flava,
    fnet,
    focalnet,
    fsmt,
    funnel,
    git,
    glpn,
    gpta,
    gpt_bigcode,
    gpt_neo,
    gpt_neox,
    gpt_neox_japanese,
    gpt_swa,
    gptj,
    gptsan_japanese,
    graphormer,
    groupvit,
    herbert,
    hubert,
    ibert,
    imagegpt,
    informer,
    instructblip,
    jukebox,
    layoutlm,
    layoutlmva,
    layoutlmva,
    layoutxlm,
    led,
    levit,
    lilt,
    llama,
    longformer,
    longta,
    luke,
    lxmert,
    mam_aaa,
    marian,
    markuplm,
    maskaformer,
    maskformer,
    mbart,
    mbartaa,
    mega,
    megatron_bert,
    megatron_gpta,
    mgp_str,
    mluke,
    mobilebert,
    mobilenet_va,
    mobilenet_va,
    mobilevit,
    mobilevitva,
    mpnet,
    mra,
    mta,
    musicgen,
    mvp,
    nat,
    nezha,
    nllb,
    nllb_moe,
    nystromformer,
    oneformer,
    open_llama,
    openai,
    opt,
    owlvit,
    pegasus,
    pegasus_x,
    perceiver,
    phobert,
    pixastruct,
    plbart,
    poolformer,
    prophetnet,
    qdqbert,
    rag,
    realm,
    reformer,
    regnet,
    rembert,
    resnet,
    roberta,
    roberta_prelayernorm,
    roc_bert,
    roformer,
    rwkv,
    sam,
    segformer,
    sew,
    sew_d,
    speech_encoder_decoder,
    speech_to_text,
    speech_to_text_a,
    speechta,
    splinter,
    squeezebert,
    swiftformer,
    swin,
    swinasr,
    swinva,
    switch_transformers,
    ta,
    table_transformer,
    tapas,
    time_series_transformer,
    timesformer,
    timm_backbone,
    transfo_xl,
    trocr,
    tvlt,
    umta,
    unispeech,
    unispeech_sat,
    upernet,
    videomae,
    vilt,
    vision_encoder_decoder,
    vision_text_dual_encoder,
    visual_bert,
    vit,
    vit_hybrid,
    vit_mae,
    vit_msn,
    vivit,
    wavaveca,
    wavaveca_conformer,
    wavaveca_phoneme,
    wavaveca_with_lm,
    wavlm,
    whisper,
    x_clip,
    xglm,
    xlm,
    xlm_prophetnet,
    xlm_roberta,
    xlm_roberta_xl,
    xlnet,
    xmod,
    yolos,
    yoso,
)



