
'''simple docstring'''







import collections
import inspect
import unittest

from transformers import FocalNetConfig
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 (
      FocalNetBackbone,
      FocalNetForImageClassification,
      FocalNetForMaskedImageModeling,
      FocalNetModel,
  )
  from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
  from PIL import Image

  from transformers import AutoImageProcessor







class UpperCAmelCase__	:





  """simple docstring"""

  def __init__(		self      :     Optional[int]							,_a      :     List[Any]							,_a      :     Optional[Any]=13							,_a      :     List[Any]=32							,_a      :     Tuple=2							,_a      :     Union[str, Any]=3							,_a      :     str=16							,_a      :     Optional[Any]=[32, 64, 128]							,_a      :     Tuple=[1, 2, 1]							,_a      :     Any=[2, 2, 4]							,_a      :     List[Any]=2							,_a      :     Dict=2.0							,_a      :     Union[str, Any]=True							,_a      :     Any=0.0							,_a      :     List[str]=0.0							,_a      :     Dict=0.1							,_a      :     List[str]="gelu"							,_a      :     Union[str, Any]=False							,_a      :     Optional[int]=True							,_a      :     int=0.02							,_a      :     Optional[Any]=1E-5							,_a      :     str=True							,_a      :     Any=None							,_a      :     Union[str, Any]=True							,_a      :     Union[str, Any]=10							,_a      :     Optional[int]=8							,_a      :     List[Any]=["stage1", "stage2"]							,_a      :     Optional[Any]=[1, 2]							,):


     '''simple docstring'''






     _a				:	Any			=   parent
     _a				:	Union[str, Any]			=   batch_size
     _a				:	Dict			=   image_size
     _a				:	str			=   patch_size
     _a				:	List[str]			=   num_channels
     _a				:	Any			=   embed_dim
     _a				:	Dict			=   hidden_sizes
     _a				:	List[str]			=   depths
     _a				:	Optional[Any]			=   num_heads
     _a				:	str			=   window_size
     _a				:	Optional[int]			=   mlp_ratio
     _a				:	Union[str, Any]			=   qkv_bias
     _a				:	int			=   hidden_dropout_prob
     _a				:	Union[str, Any]			=   attention_probs_dropout_prob
     _a				:	int			=   drop_path_rate
     _a				:	List[str]			=   hidden_act
     _a				:	Any			=   use_absolute_embeddings
     _a				:	List[Any]			=   patch_norm
     _a				:	Tuple			=   layer_norm_eps
     _a				:	List[str]			=   initializer_range
     _a				:	Dict			=   is_training
     _a				:	Any			=   scope
     _a				:	List[str]			=   use_labels
     _a				:	List[Any]			=   type_sequence_label_size
     _a				:	List[Any]			=   encoder_stride
     _a				:	Tuple			=   out_features
     _a				:	Optional[int]			=   out_indices


  def   __lowercase		(		self      :     Optional[Any]       ):


     '''simple docstring'''






     _a				:	Any			=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

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

     _a				:	str			=   self.get_config()

     return config, pixel_values, labels


  def   __lowercase		(		self      :     Optional[Any]       ):


     '''simple docstring'''






     return FocalNetConfig(
         image_size=self.image_size							,patch_size=self.patch_size							,num_channels=self.num_channels							,embed_dim=self.embed_dim							,hidden_sizes=self.hidden_sizes							,depths=self.depths							,num_heads=self.num_heads							,window_size=self.window_size							,mlp_ratio=self.mlp_ratio							,qkv_bias=self.qkv_bias							,hidden_dropout_prob=self.hidden_dropout_prob							,attention_probs_dropout_prob=self.attention_probs_dropout_prob							,drop_path_rate=self.drop_path_rate							,hidden_act=self.hidden_act							,use_absolute_embeddings=self.use_absolute_embeddings							,path_norm=self.patch_norm							,layer_norm_eps=self.layer_norm_eps							,initializer_range=self.initializer_range							,encoder_stride=self.encoder_stride							,out_features=self.out_features							,out_indices=self.out_indices							,)


  def   __lowercase		(		self      :     Any							,_a      :     Optional[int]							,_a      :     List[str]							,_a      :     Tuple       ):


     '''simple docstring'''






     _a				:	Dict			=   FocalNetModel(config=_a       )
     model.to(_a       )
     model.eval()
     _a				:	Optional[Any]			=   model(_a       )

     _a				:	Dict			=   ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths       ) - 1))
     _a				:	int			=   int(config.embed_dim * 2 ** (len(config.depths       ) - 1)       )

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


  def   __lowercase		(		self      :     int							,_a      :     List[str]							,_a      :     Optional[Any]							,_a      :     Any       ):


     '''simple docstring'''






     _a				:	Any			=   FocalNetBackbone(config=_a       )
     model.to(_a       )
     model.eval()
     _a				:	Optional[int]			=   model(_a       )

     # verify feature maps
     self.parent.assertEqual(len(result.feature_maps       )							,len(config.out_features       )       )
     self.parent.assertListEqual(list(result.feature_maps[0].shape       )							,[self.batch_size, self.image_size, 8, 8]       )

     # verify channels
     self.parent.assertEqual(len(model.channels       )							,len(config.out_features       )       )
     self.parent.assertListEqual(model.channels							,config.hidden_sizes[:-1]       )

     # verify backbone works with out_features=None
     _a				:	Any			=   None
     _a				:	List[str]			=   FocalNetBackbone(config=_a       )
     model.to(_a       )
     model.eval()
     _a				:	str			=   model(_a       )

     # verify feature maps
     self.parent.assertEqual(len(result.feature_maps       )							,1       )
     self.parent.assertListEqual(list(result.feature_maps[0].shape       )							,[self.batch_size, self.image_size * 2, 4, 4]       )

     # verify channels
     self.parent.assertEqual(len(model.channels       )							,1       )
     self.parent.assertListEqual(model.channels							,[config.hidden_sizes[-1]]       )


  def   __lowercase		(		self      :     Dict							,_a      :     int							,_a      :     Tuple							,_a      :     Tuple       ):


     '''simple docstring'''






     _a				:	List[Any]			=   FocalNetForMaskedImageModeling(config=_a       )
     model.to(_a       )
     model.eval()
     _a				:	List[str]			=   model(_a       )
     self.parent.assertEqual(
         result.reconstruction.shape							,(self.batch_size, self.num_channels, self.image_size, self.image_size)       )

     # test greyscale images
     _a				:	Any			=   1
     _a				:	Union[str, Any]			=   FocalNetForMaskedImageModeling(_a       )
     model.to(_a       )
     model.eval()

     _a				:	str			=   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]       )
     _a				:	Any			=   model(_a       )
     self.parent.assertEqual(result.reconstruction.shape							,(self.batch_size, 1, self.image_size, self.image_size)       )


  def   __lowercase		(		self      :     Any							,_a      :     int							,_a      :     Tuple							,_a      :     List[str]       ):


     '''simple docstring'''






     _a				:	Optional[int]			=   self.type_sequence_label_size
     _a				:	Optional[int]			=   FocalNetForImageClassification(_a       )
     model.to(_a       )
     model.eval()
     _a				:	Optional[Any]			=   model(_a							,labels=_a       )
     self.parent.assertEqual(result.logits.shape							,(self.batch_size, self.type_sequence_label_size)       )

     # test greyscale images
     _a				:	Any			=   1
     _a				:	List[Any]			=   FocalNetForImageClassification(_a       )
     model.to(_a       )
     model.eval()

     _a				:	Tuple			=   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]       )
     _a				:	List[Any]			=   model(_a       )
     self.parent.assertEqual(result.logits.shape							,(self.batch_size, self.type_sequence_label_size)       )


  def   __lowercase		(		self      :     int       ):


     '''simple docstring'''






     _a				:	Union[str, Any]			=   self.prepare_config_and_inputs()

     _a,  _a,  _a				:	str			=   config_and_inputs
     _a				:	str			=   {'pixel_values': pixel_values}
     return config, inputs_dict







@require_torch
class UpperCAmelCase__	( lowercase__    ,				lowercase__    ,				unittest.TestCase	):





  """simple docstring"""

  __UpperCAmelCase				:				int   =					(
      (
          FocalNetModel,
          FocalNetForImageClassification,
          FocalNetForMaskedImageModeling,
          FocalNetBackbone,
      )
      if is_torch_available()
      else ()
  )
  __UpperCAmelCase				:				str   =					(
      {'''feature-extraction''': FocalNetModel, '''image-classification''': FocalNetForImageClassification}
      if is_torch_available()
      else {}
  )
  __UpperCAmelCase				:				Dict   =					False

  __UpperCAmelCase				:				Dict   =					False
  __UpperCAmelCase				:				int   =					False
  __UpperCAmelCase				:				List[Any]   =					False
  __UpperCAmelCase				:				Any   =					False


  def   __lowercase		(		self      :     List[Any]       ):


     '''simple docstring'''






     _a				:	Any			=   FocalNetModelTester(self       )
     _a				:	int			=   ConfigTester(self							,config_class=_a							,embed_dim=37							,has_text_modality=_a       )


  def   __lowercase		(		self      :     Any       ):


     '''simple docstring'''






     self.create_and_test_config_common_properties()
     self.config_tester.create_and_test_config_to_json_string()
     self.config_tester.create_and_test_config_to_json_file()
     self.config_tester.create_and_test_config_from_and_save_pretrained()
     self.config_tester.create_and_test_config_with_num_labels()
     self.config_tester.check_config_can_be_init_without_params()
     self.config_tester.check_config_arguments_init()


  def   __lowercase		(		self      :     List[Any]       ):


     '''simple docstring'''






     return


  def   __lowercase		(		self      :     Dict       ):


     '''simple docstring'''






     _a				:	Union[str, Any]			=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*_a       )


  def   __lowercase		(		self      :     str       ):


     '''simple docstring'''






     _a				:	int			=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_backbone(*_a       )


  def   __lowercase		(		self      :     Tuple       ):


     '''simple docstring'''






     _a				:	List[Any]			=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_masked_image_modeling(*_a       )


  def   __lowercase		(		self      :     Optional[int]       ):


     '''simple docstring'''






     _a				:	Optional[Any]			=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*_a       )


  @unittest.skip(reason='FocalNet does not use inputs_embeds'       )
  def   __lowercase		(		self      :     List[str]       ):


     '''simple docstring'''






     pass


  @unittest.skip(reason='FocalNet does not use feedforward chunking'       )
  def   __lowercase		(		self      :     Union[str, Any]       ):


     '''simple docstring'''






     pass


  def   __lowercase		(		self      :     Any       ):


     '''simple docstring'''






     _a,  _a				:	Any			=   self.model_tester.prepare_config_and_inputs_for_common()

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


  def   __lowercase		(		self      :     Union[str, Any]       ):


     '''simple docstring'''






     _a,  _a				:	Dict			=   self.model_tester.prepare_config_and_inputs_for_common()

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

        _a				:	List[Any]			=   ['pixel_values']
        self.assertListEqual(arg_names[:1]							,_a       )


  def   __lowercase		(		self      :     Union[str, Any]							,_a      :     Any							,_a      :     Any							,_a      :     Dict							,_a      :     int       ):


     '''simple docstring'''






     _a				:	Dict			=   model_class(_a       )
     model.to(_a       )
     model.eval()

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

     _a				:	Optional[int]			=   outputs.hidden_states

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

     # FocalNet has a different seq_length
     _a				:	Dict			=   (
         config.patch_size
         if isinstance(config.patch_size							,collections.abc.Iterable       )
         else (config.patch_size, config.patch_size)
     )

     _a				:	Optional[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]							,)

     _a				:	Optional[int]			=   outputs.reshaped_hidden_states
     self.assertEqual(len(_a       )							,_a       )

     _a,  _a,  _a,  _a				:	Tuple			=   reshaped_hidden_states[0].shape
     _a				:	List[Any]			=   (
         reshaped_hidden_states[0].view(_a							,_a							,height * width       ).permute(0							,2							,1       )
     )
     self.assertListEqual(
         list(reshaped_hidden_states.shape[-2:]       )							,[num_patches, self.model_tester.embed_dim]							,)


  def   __lowercase		(		self      :     Tuple       ):


     '''simple docstring'''






     _a,  _a				:	List[Any]			=   self.model_tester.prepare_config_and_inputs_for_common()

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

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

        self.check_hidden_states_output(_a							,_a							,_a							,_a       )


  def   __lowercase		(		self      :     int       ):


     '''simple docstring'''






     _a,  _a				:	List[Any]			=   self.model_tester.prepare_config_and_inputs_for_common()
     _a				:	Union[str, Any]			=   3

     _a				:	Tuple			=   (
         self.model_tester.image_size
         if isinstance(self.model_tester.image_size							,collections.abc.Iterable       )
         else (self.model_tester.image_size, self.model_tester.image_size)
     )
     _a				:	Union[str, Any]			=   (
         config.patch_size
         if isinstance(config.patch_size							,collections.abc.Iterable       )
         else (config.patch_size, config.patch_size)
     )

     _a				:	Any			=   image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
     _a				:	Optional[int]			=   image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

     for model_class in self.all_model_classes[:-1]:
        _a				:	Any			=   True
        self.check_hidden_states_output(_a							,_a							,_a							,(padded_height, padded_width)       )

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


  @slow
  def   __lowercase		(		self      :     Optional[int]       ):


     '''simple docstring'''






     for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        _a				:	Any			=   FocalNetModel.from_pretrained(_a       )
        self.assertIsNotNone(_a       )


  def   __lowercase		(		self      :     List[str]       ):


     '''simple docstring'''






     _a,  _a				:	List[str]			=   self.model_tester.prepare_config_and_inputs_for_common()

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





  """simple docstring"""

  @cached_property
  def   __lowercase		(		self      :     Tuple       ):


     '''simple docstring'''






     return AutoImageProcessor.from_pretrained('microsoft/focalnet-tiny'       ) if is_vision_available() else None


  @slow
  def   __lowercase		(		self      :     Any       ):


     '''simple docstring'''






     _a				:	Dict			=   FocalNetForImageClassification.from_pretrained('microsoft/focalnet-tiny'       ).to(_a       )
     _a				:	int			=   self.default_image_processor

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

     # forward pass
     with torch.no_grad():
        _a				:	List[Any]			=   model(**_a       )

     # verify the logits
     _a				:	Dict			=   torch.Size((1, 1000)       )
     self.assertEqual(outputs.logits.shape							,_a       )
     _a				:	List[Any]			=   torch.tensor([0.2166, -0.4368, 0.2191]       ).to(_a       )
     self.assertTrue(torch.allclose(outputs.logits[0, :3]							,_a							,atol=1E-4       )       )
     self.assertTrue(outputs.logits.argmax(dim=-1       ).item()							,281       )







@require_torch
class UpperCAmelCase__	( lowercase__    ,				unittest.TestCase	):





  """simple docstring"""

  __UpperCAmelCase				:				Any   =					(FocalNetBackbone,) if is_torch_available() else ()
  __UpperCAmelCase				:				int   =					FocalNetConfig

  __UpperCAmelCase				:				int   =					False


  def   __lowercase		(		self      :     Any       ):


     '''simple docstring'''






     _a				:	Optional[int]			=   FocalNetModelTester(self       )





'''simple docstring'''







import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel

from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device


enable_full_determinism()







class UpperCAmelCase__	( unittest.TestCase	):





  """simple docstring"""

  @property
  def   __lowercase		(		self      :     Union[str, Any]       ):


     '''simple docstring'''






     torch.manual_seed(0       )
     _a				:	Any			=   UNetaDModel(
         block_out_channels=(32, 64)							,layers_per_block=2							,sample_size=32							,in_channels=3							,out_channels=3							,down_block_types=('DownBlock2D', 'AttnDownBlock2D')							,up_block_types=('AttnUpBlock2D', 'UpBlock2D')							,)
     return model


  @property
  def   __lowercase		(		self      :     Optional[int]       ):


     '''simple docstring'''






     torch.manual_seed(0       )
     _a				:	Union[str, Any]			=   VQModel(
         block_out_channels=[32, 64]							,in_channels=3							,out_channels=3							,down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']							,up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']							,latent_channels=3							,)
     return model


  @property
  def   __lowercase		(		self      :     Optional[int]       ):


     '''simple docstring'''






     torch.manual_seed(0       )
     _a				:	Any			=   CLIPTextConfig(
         bos_token_id=0							,eos_token_id=2							,hidden_size=32							,intermediate_size=37							,layer_norm_eps=1E-05							,num_attention_heads=4							,num_hidden_layers=5							,pad_token_id=1							,vocab_size=1000							,)
     return CLIPTextModel(_a       )


  def   __lowercase		(		self      :     Tuple       ):


     '''simple docstring'''






     _a				:	Dict			=   self.dummy_uncond_unet
     _a				:	List[Any]			=   DDIMScheduler()
     _a				:	List[Any]			=   self.dummy_vq_model

     _a				:	str			=   LDMPipeline(unet=_a							,vqvae=_a							,scheduler=_a       )
     ldm.to(_a       )
     ldm.set_progress_bar_config(disable=_a       )

     _a				:	List[str]			=   torch.manual_seed(0       )
     _a				:	List[str]			=   ldm(generator=_a							,num_inference_steps=2							,output_type='numpy'       ).images

     _a				:	List[str]			=   torch.manual_seed(0       )
     _a				:	Union[str, Any]			=   ldm(generator=_a							,num_inference_steps=2							,output_type='numpy'							,return_dict=_a       )[0]

     _a				:	Tuple			=   image[0, -3:, -3:, -1]
     _a				:	Optional[Any]			=   image_from_tuple[0, -3:, -3:, -1]

     assert image.shape == (1, 64, 64, 3)
     _a				:	int			=   np.array([0.8512, 0.818, 0.6411, 0.6808, 0.4465, 0.5618, 0.46, 0.6231, 0.5172]       )
     _a				:	Any			=   1E-2 if torch_device != 'mps' else 3E-2

     assert np.abs(image_slice.flatten() - expected_slice       ).max() < tolerance
     assert np.abs(image_from_tuple_slice.flatten() - expected_slice       ).max() < tolerance







@slow
@require_torch
class UpperCAmelCase__	( unittest.TestCase	):





  """simple docstring"""

  def   __lowercase		(		self      :     Optional[Any]       ):


     '''simple docstring'''






     _a				:	List[str]			=   LDMPipeline.from_pretrained('CompVis/ldm-celebahq-256'       )
     ldm.to(_a       )
     ldm.set_progress_bar_config(disable=_a       )

     _a				:	Optional[int]			=   torch.manual_seed(0       )
     _a				:	Dict			=   ldm(generator=_a							,num_inference_steps=5							,output_type='numpy'       ).images

     _a				:	str			=   image[0, -3:, -3:, -1]

     assert image.shape == (1, 256, 256, 3)
     _a				:	Optional[int]			=   np.array([0.4399, 0.4_4975, 0.4_6825, 0.474, 0.4359, 0.4581, 0.4_5095, 0.4341, 0.4447]       )
     _a				:	int			=   1E-2 if torch_device != 'mps' else 3E-2

     assert np.abs(image_slice.flatten() - expected_slice       ).max() < tolerance



