

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


      def __init__(    self				:	Tuple							,   a				:	str							,   a				:	Union[str, Any]=1_3							,   a				:	Tuple=3_2							,   a				:	Optional[int]=2							,   a				:	Tuple=3							,   a				:	str=1_6							,   a				:	int=[3_2, 6_4, 1_2_8]							,   a				:	Optional[int]=[1, 2, 1]							,   a				:	List[str]=[2, 2, 4]							,   a				:	Any=2							,   a				:	Union[str, Any]=2.0							,   a				:	int=True							,   a				:	Tuple=0.0							,   a				:	Tuple=0.0							,   a				:	Optional[int]=0.1							,   a				:	Union[str, Any]="gelu"							,   a				:	Optional[Any]=False							,   a				:	List[Any]=True							,   a				:	Any=0.0_2							,   a				:	int=1e-5							,   a				:	int=True							,   a				:	Dict=None							,   a				:	str=True							,   a				:	Dict=1_0							,   a				:	List[Any]=8							,   a				:	Union[str, Any]=["stage1", "stage2"]							,   a				:	List[Any]=[1, 2]							,   ):





            """simple docstring"""







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


      def _UpperCamelCase						(    self				:	str						):





            """simple docstring"""







            __snake_case      :    int  			=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

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

            __snake_case      :    int  			=self.get_config()

            return config, pixel_values, labels


      def _UpperCamelCase						(    self				:	int						):





            """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 _UpperCamelCase						(    self				:	Any							,   a				:	str							,   a				:	List[Any]							,   a				:	Tuple						):





            """simple docstring"""







            __snake_case      :    Tuple  			=FocalNetModel(config=UpperCamelCase__						)
            model.to(UpperCamelCase__						)
            model.eval()
            __snake_case      :    Dict  			=model(UpperCamelCase__						)

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





            """simple docstring"""







            __snake_case      :    Dict  			=FocalNetBackbone(config=UpperCamelCase__						)
            model.to(UpperCamelCase__						)
            model.eval()
            __snake_case      :    Dict  			=model(UpperCamelCase__						)

            # 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
            __snake_case      :    Union[str, Any]  			=None
            __snake_case      :    Optional[Any]  			=FocalNetBackbone(config=UpperCamelCase__						)
            model.to(UpperCamelCase__						)
            model.eval()
            __snake_case      :    Optional[int]  			=model(UpperCamelCase__						)

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





            """simple docstring"""







            __snake_case      :    Optional[int]  			=FocalNetForMaskedImageModeling(config=UpperCamelCase__						)
            model.to(UpperCamelCase__						)
            model.eval()
            __snake_case      :    Any  			=model(UpperCamelCase__						)
            self.parent.assertEqual(
                result.reconstruction.shape							,   (self.batch_size, self.num_channels, self.image_size, self.image_size)						)

            # test greyscale images
            __snake_case      :    int  			=1
            __snake_case      :    List[Any]  			=FocalNetForMaskedImageModeling(UpperCamelCase__						)
            model.to(UpperCamelCase__						)
            model.eval()

            __snake_case      :    List[Any]  			=floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
            __snake_case      :    int  			=model(UpperCamelCase__						)
            self.parent.assertEqual(result.reconstruction.shape							,   (self.batch_size, 1, self.image_size, self.image_size)						)


      def _UpperCamelCase						(    self				:	Any							,   a				:	Optional[int]							,   a				:	Any							,   a				:	Optional[Any]						):





            """simple docstring"""







            __snake_case      :    str  			=self.type_sequence_label_size
            __snake_case      :    Optional[Any]  			=FocalNetForImageClassification(UpperCamelCase__						)
            model.to(UpperCamelCase__						)
            model.eval()
            __snake_case      :    Union[str, Any]  			=model(UpperCamelCase__							,   labels=UpperCamelCase__						)
            self.parent.assertEqual(result.logits.shape							,   (self.batch_size, self.type_sequence_label_size)						)

            # test greyscale images
            __snake_case      :    Union[str, Any]  			=1
            __snake_case      :    Any  			=FocalNetForImageClassification(UpperCamelCase__						)
            model.to(UpperCamelCase__						)
            model.eval()

            __snake_case      :    List[str]  			=floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
            __snake_case      :    int  			=model(UpperCamelCase__						)
            self.parent.assertEqual(result.logits.shape							,   (self.batch_size, self.type_sequence_label_size)						)







      def _UpperCamelCase						(    self				:	Dict						):





            """simple docstring"""







            __snake_case      :    List[Any]  			=self.prepare_config_and_inputs()

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



@require_torch
class      _lowercase (     lowerCAmelCase		,  lowerCAmelCase		,  unittest.TestCase						):
      _a   :     Any								=   (
          (
              FocalNetModel,
              FocalNetForImageClassification,
              FocalNetForMaskedImageModeling,
              FocalNetBackbone,
          )
          if is_torch_available()
          else ()
      )
      _a   :     Optional[int]								=   (
          {"feature-extraction": FocalNetModel, "image-classification": FocalNetForImageClassification}
          if is_torch_available()
          else {}
      )
      _a   :     Dict								=   False

      _a   :     str								=   False
      _a   :     List[Any]								=   False
      _a   :     str								=   False
      _a   :     Any								=   False


      def _UpperCamelCase						(    self				:	Tuple						):





            """simple docstring"""







            __snake_case      :    str  			=FocalNetModelTester(self						)
            __snake_case      :    Optional[int]  			=ConfigTester(self							,   config_class=UpperCamelCase__							,   embed_dim=3_7							,   has_text_modality=UpperCamelCase__						)


      def _UpperCamelCase						(    self				:	Optional[int]						):





            """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 _UpperCamelCase						(    self				:	Tuple						):





            """simple docstring"""







            return


      def _UpperCamelCase						(    self				:	int						):





            """simple docstring"""







            __snake_case      :    List[Any]  			=self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*UpperCamelCase__						)


      def _UpperCamelCase						(    self				:	str						):





            """simple docstring"""







            __snake_case      :    Tuple  			=self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_backbone(*UpperCamelCase__						)


      def _UpperCamelCase						(    self				:	str						):





            """simple docstring"""







            __snake_case      :    Dict  			=self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_masked_image_modeling(*UpperCamelCase__						)


      def _UpperCamelCase						(    self				:	int						):





            """simple docstring"""







            __snake_case      :    str  			=self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__						)


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





            """simple docstring"""







            pass


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





            """simple docstring"""







            pass


      def _UpperCamelCase						(    self				:	Optional[Any]						):





            """simple docstring"""







            __snake_case			,				__snake_case      :    Tuple  			=self.model_tester.prepare_config_and_inputs_for_common()

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


      def _UpperCamelCase						(    self				:	int						):





            """simple docstring"""







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

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

                  __snake_case      :    Union[str, Any]  			=['''pixel_values''']
                  self.assertListEqual(arg_names[:1]							,   UpperCamelCase__						)


      def _UpperCamelCase						(    self				:	Optional[int]							,   a				:	Optional[Any]							,   a				:	Any							,   a				:	List[Any]							,   a				:	str						):





            """simple docstring"""







            __snake_case      :    str  			=model_class(UpperCamelCase__						)
            model.to(UpperCamelCase__						)
            model.eval()

            with torch.no_grad():
                  __snake_case      :    Any  			=model(**self._prepare_for_class(UpperCamelCase__							,   UpperCamelCase__						)						)

            __snake_case      :    Optional[Any]  			=outputs.hidden_states

            __snake_case      :    str  			=getattr(
                self.model_tester							,   '''expected_num_hidden_layers'''							,   len(self.model_tester.depths						) + 1						)
            self.assertEqual(len(UpperCamelCase__						)							,   UpperCamelCase__						)

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

            __snake_case      :    Union[str, 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]							,   )

            __snake_case      :    Union[str, Any]  			=outputs.reshaped_hidden_states
            self.assertEqual(len(UpperCamelCase__						)							,   UpperCamelCase__						)

            __snake_case			,				__snake_case			,				__snake_case			,				__snake_case      :    Dict  			=reshaped_hidden_states[0].shape
            __snake_case      :    int  			=(
                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 _UpperCamelCase						(    self				:	List[str]						):





            """simple docstring"""







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

            __snake_case      :    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)
            )

            for model_class in self.all_model_classes[:-1]:
                  __snake_case      :    List[str]  			=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"]
                  __snake_case      :    Optional[Any]  			=True

                  self.check_hidden_states_output(UpperCamelCase__							,   UpperCamelCase__							,   UpperCamelCase__							,   UpperCamelCase__						)


      def _UpperCamelCase						(    self				:	List[str]						):





            """simple docstring"""







            __snake_case			,				__snake_case      :    Optional[int]  			=self.model_tester.prepare_config_and_inputs_for_common()
            __snake_case      :    List[str]  			=3

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

            __snake_case      :    List[str]  			=image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
            __snake_case      :    Union[str, Any]  			=image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

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


      @slow
      def _UpperCamelCase						(    self				:	str						):





            """simple docstring"""







            for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  __snake_case      :    Dict  			=FocalNetModel.from_pretrained(UpperCamelCase__						)
                  self.assertIsNotNone(UpperCamelCase__						)







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





            """simple docstring"""







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

            __snake_case      :    Any  			=_config_zero_init(UpperCamelCase__						)
            for model_class in self.all_model_classes:
                  __snake_case      :    List[Any]  			=model_class(config=UpperCamelCase__						)
                  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      _lowercase (     unittest.TestCase						):


      @cached_property
      def _UpperCamelCase						(    self				:	Dict						):





            """simple docstring"""







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







      @slow
      def _UpperCamelCase						(    self				:	int						):





            """simple docstring"""







            __snake_case      :    Tuple  			=FocalNetForImageClassification.from_pretrained('''microsoft/focalnet-tiny'''						).to(UpperCamelCase__						)
            __snake_case      :    int  			=self.default_image_processor

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

            # forward pass
            with torch.no_grad():
                  __snake_case      :    str  			=model(**UpperCamelCase__						)

            # verify the logits
            __snake_case      :    int  			=torch.Size((1, 1_0_0_0)						)
            self.assertEqual(outputs.logits.shape							,   UpperCamelCase__						)
            __snake_case      :    Optional[int]  			=torch.tensor([0.2_1_6_6, -0.4_3_6_8, 0.2_1_9_1]						).to(UpperCamelCase__						)
            self.assertTrue(torch.allclose(outputs.logits[0, :3]							,   UpperCamelCase__							,   atol=1e-4						)						)
            self.assertTrue(outputs.logits.argmax(dim=-1						).item()							,   2_8_1						)



@require_torch
class      _lowercase (     lowerCAmelCase		,  unittest.TestCase						):
      _a   :     Tuple								=   (FocalNetBackbone,) if is_torch_available() else ()
      _a   :     Tuple								=   FocalNetConfig

      _a   :     Dict								=   False


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





            """simple docstring"""







            __snake_case      :    Optional[Any]  			=FocalNetModelTester(self						)










"""simple docstring"""





# this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.:
#   python ./utils/get_modified_files.py utils src tests examples
#
# it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered
# since the output of this script is fed into Makefile commands it doesn't print a newline after the results

import re
import subprocess
import sys


UpperCamelCase_	:				int										= subprocess.check_output("""git merge-base main HEAD""".split()).decode("""utf-8""")
UpperCamelCase_	:				Optional[int]										= (
    subprocess.check_output(F'''git diff --diff-filter=d --name-only {fork_point_sha}'''.split()).decode("""utf-8""").split()
)

UpperCamelCase_	:				List[Any]										= """|""".join(sys.argv[1:])
UpperCamelCase_	:				List[str]										= re.compile(rF'''^({joined_dirs}).*?\.py$''')

UpperCamelCase_	:				str										= [x for x in modified_files if regex.match(x)]
print(""" """.join(relevant_modified_files), end="""""")


