


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


  '''simple docstring'''







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

        '''simple docstring'''




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






  def        _a							(							self :       int ):

        '''simple docstring'''




        A_						:  Dict          =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

        A_						:  Optional[int]          =				None
        if self.use_labels:
              A_						:  Optional[Any]          =				ids_tensor([self.batch_size]	,self.type_sequence_label_size )

        A_						:  Optional[int]          =				self.get_config()

        return config, pixel_values, labels






  def        _a							(							self :       Union[str, 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        _a							(							self :       List[Any]	,_a :       List[str]	,_a :       Optional[Any]	,_a :       str ):

        '''simple docstring'''




        A_						:  Tuple          =				FocalNetModel(config=lowerCamelCase__ )
        model.to(lowerCamelCase__ )
        model.eval()
        A_						:  List[Any]          =				model(lowerCamelCase__ )

        A_						:  List[Any]          =				((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1))
        A_						:  Union[str, 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        _a							(							self :       Dict	,_a :       int	,_a :       List[Any]	,_a :       List[Any] ):

        '''simple docstring'''




        A_						:  Optional[int]          =				FocalNetBackbone(config=lowerCamelCase__ )
        model.to(lowerCamelCase__ )
        model.eval()
        A_						:  List[str]          =				model(lowerCamelCase__ )

        # 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_						:  Union[str, Any]          =				FocalNetBackbone(config=lowerCamelCase__ )
        model.to(lowerCamelCase__ )
        model.eval()
        A_						:  List[Any]          =				model(lowerCamelCase__ )

        # 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        _a							(							self :       List[str]	,_a :       Any	,_a :       Tuple	,_a :       List[str] ):

        '''simple docstring'''




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

        # test greyscale images
        A_						:  Optional[int]          =				1
        A_						:  Tuple          =				FocalNetForMaskedImageModeling(lowerCamelCase__ )
        model.to(lowerCamelCase__ )
        model.eval()

        A_						:  Tuple          =				floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
        A_						:  List[Any]          =				model(lowerCamelCase__ )
        self.parent.assertEqual(result.reconstruction.shape	,(self.batch_size, 1, self.image_size, self.image_size) )






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

        '''simple docstring'''




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

        # test greyscale images
        A_						:  int          =				1
        A_						:  Dict          =				FocalNetForImageClassification(lowerCamelCase__ )
        model.to(lowerCamelCase__ )
        model.eval()

        A_						:  Union[str, Any]          =				floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
        A_						:  List[Any]          =				model(lowerCamelCase__ )
        self.parent.assertEqual(result.logits.shape	,(self.batch_size, self.type_sequence_label_size) )






  def        _a							(							self :       Any ):

        '''simple docstring'''




        A_						:  int          =				self.prepare_config_and_inputs()

        A_						:  str          =				config_and_inputs
        A_						:  Optional[int]          =				{"pixel_values": pixel_values}
        return config, inputs_dict







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


  '''simple docstring'''







  a_  					=							(
      (
          FocalNetModel,
          FocalNetForImageClassification,
          FocalNetForMaskedImageModeling,
          FocalNetBackbone,
      )
      if is_torch_available()
      else ()
  )
  a_  					=							(
      {"feature-extraction": FocalNetModel, "image-classification": FocalNetForImageClassification}
      if is_torch_available()
      else {}
  )
  a_  					=							False

  a_  					=							False
  a_  					=							False
  a_  					=							False
  a_  					=							False






  def        _a							(							self :       Optional[int] ):

        '''simple docstring'''




        A_						:  Tuple          =				FocalNetModelTester(self )
        A_						:  Tuple          =				ConfigTester(self	,config_class=lowerCamelCase__	,embed_dim=37	,has_text_modality=lowerCamelCase__ )






  def        _a							(							self :       str ):

        '''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        _a							(							self :       List[str] ):

        '''simple docstring'''




        return






  def        _a							(							self :       int ):

        '''simple docstring'''




        A_						:  Tuple          =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowerCamelCase__ )






  def        _a							(							self :       Dict ):

        '''simple docstring'''




        A_						:  Union[str, Any]          =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_backbone(*lowerCamelCase__ )






  def        _a							(							self :       Tuple ):

        '''simple docstring'''




        A_						:  List[str]          =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_masked_image_modeling(*lowerCamelCase__ )






  def        _a							(							self :       Optional[int] ):

        '''simple docstring'''




        A_						:  Tuple          =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__ )






  @unittest.skip(reason="""FocalNet does not use inputs_embeds""" )
  def        _a							(							self :       Tuple ):

        '''simple docstring'''




        pass






  @unittest.skip(reason="""FocalNet does not use feedforward chunking""" )
  def        _a							(							self :       str ):

        '''simple docstring'''




        pass






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

        '''simple docstring'''




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

        for model_class in self.all_model_classes[:-1]:
              A_						:  Union[str, Any]          =				model_class(lowerCamelCase__ )
              self.assertIsInstance(model.get_input_embeddings()	,(nn.Module) )
              A_						:  int          =				model.get_output_embeddings()
              self.assertTrue(x is None or isinstance(lowerCamelCase__	,nn.Linear ) )






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

        '''simple docstring'''




        A_						:  Union[str, Any]          =				self.model_tester.prepare_config_and_inputs_for_common()

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

              A_						:  List[str]          =				["pixel_values"]
              self.assertListEqual(arg_names[:1]	,lowerCamelCase__ )






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

        '''simple docstring'''




        A_						:  int          =				model_class(lowerCamelCase__ )
        model.to(lowerCamelCase__ )
        model.eval()

        with torch.no_grad():
              A_						:  List[Any]          =				model(**self._prepare_for_class(lowerCamelCase__	,lowerCamelCase__ ) )

        A_						:  Union[str, Any]          =				outputs.hidden_states

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

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

        A_						:  int          =				(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[Any]          =				outputs.reshaped_hidden_states
        self.assertEqual(len(lowerCamelCase__ )	,lowerCamelCase__ )

        A_						:  Optional[Any]          =				reshaped_hidden_states[0].shape
        A_						:  Optional[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        _a							(							self :       Any ):

        '''simple docstring'''




        A_						:  int          =				self.model_tester.prepare_config_and_inputs_for_common()

        A_						:  Optional[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[:-1]:
              A_						:  Union[str, Any]          =				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"]
              A_						:  Any          =				True

              self.check_hidden_states_output(lowerCamelCase__	,lowerCamelCase__	,lowerCamelCase__	,lowerCamelCase__ )






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

        '''simple docstring'''




        A_						:  Dict          =				self.model_tester.prepare_config_and_inputs_for_common()
        A_						:  int          =				3

        A_						:  Optional[int]          =				(
            self.model_tester.image_size
            if isinstance(self.model_tester.image_size	,collections.abc.Iterable )
            else (self.model_tester.image_size, self.model_tester.image_size)
        )
        A_						:  Any          =				(
            config.patch_size
            if isinstance(config.patch_size	,collections.abc.Iterable )
            else (config.patch_size, config.patch_size)
        )

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

        for model_class in self.all_model_classes[:-1]:
              A_						:  int          =				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"]
              A_						:  str          =				True
              self.check_hidden_states_output(lowerCamelCase__	,lowerCamelCase__	,lowerCamelCase__	,(padded_height, padded_width) )






  @slow
  def        _a							(							self :       Tuple ):

        '''simple docstring'''




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






  def        _a							(							self :       Optional[int] ):

        '''simple docstring'''




        A_						:  Tuple          =				self.model_tester.prepare_config_and_inputs_for_common()

        A_						:  Tuple          =				_config_zero_init(lowerCamelCase__ )
        for model_class in self.all_model_classes:
              A_						:  List[str]          =				model_class(config=lowerCamelCase__ )
              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 	__lowerCAmelCase		(							unittest.TestCase    ):


  '''simple docstring'''







  @cached_property
  def        _a							(							self :       Optional[int] ):

        '''simple docstring'''




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






  @slow
  def        _a							(							self :       List[str] ):

        '''simple docstring'''




        A_						:  int          =				FocalNetForImageClassification.from_pretrained("""microsoft/focalnet-tiny""" ).to(lowerCamelCase__ )
        A_						:  Tuple          =				self.default_image_processor

        A_						:  Optional[int]          =				Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
        A_						:  List[Any]          =				image_processor(images=lowerCamelCase__	,return_tensors="""pt""" ).to(lowerCamelCase__ )

        # forward pass
        with torch.no_grad():
              A_						:  Dict          =				model(**lowerCamelCase__ )

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







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


  '''simple docstring'''







  a_  					=							(FocalNetBackbone,) if is_torch_available() else ()
  a_  					=							FocalNetConfig

  a_  					=							False






  def        _a							(							self :       str ):

        '''simple docstring'''




        A_						:  List[str]          =				FocalNetModelTester(self )




'''simple docstring'''


from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_torch_available,
    is_vision_available,
)


__magic_name__			=      {
    'configuration_convnext': ['CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ConvNextConfig', 'ConvNextOnnxConfig']
}

try:
     if not is_vision_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     __magic_name__			=      ['ConvNextFeatureExtractor']
     __magic_name__			=      ['ConvNextImageProcessor']

try:
     if not is_torch_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     __magic_name__			=      [
         'CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST',
         'ConvNextForImageClassification',
         'ConvNextModel',
         'ConvNextPreTrainedModel',
         'ConvNextBackbone',
     ]

try:
     if not is_tf_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     __magic_name__			=      [
         'TFConvNextForImageClassification',
         'TFConvNextModel',
         'TFConvNextPreTrainedModel',
     ]

if TYPE_CHECKING:
     from .configuration_convnext import CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvNextConfig, ConvNextOnnxConfig

     try:
          if not is_vision_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .feature_extraction_convnext import ConvNextFeatureExtractor
          from .image_processing_convnext import ConvNextImageProcessor

     try:
          if not is_torch_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_convnext import (
              CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST,
              ConvNextBackbone,
              ConvNextForImageClassification,
              ConvNextModel,
              ConvNextPreTrainedModel,
          )

     try:
          if not is_tf_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_tf_convnext import TFConvNextForImageClassification, TFConvNextModel, TFConvNextPreTrainedModel


else:
     import sys

     __magic_name__			=      _LazyModule(__name__, globals()['__file__'], _import_structure)
