
'''simple docstring'''

from typing import Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature
from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format
from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images
from ...utils import TensorType, logging


__snake_case:  List[str]								=			logging.get_logger(__name__)


class  _UpperCAmelCase ( lowerCAmelCase__    ):

     """simple docstring"""

     a_    	=					["pixel_values"]


     def __init__(      self							,		lowerCAmelCase_ = True							,		lowerCAmelCase_ = 1 / 2_55							,		lowerCAmelCase_ = True							,		lowerCAmelCase_ = 8							,		**lowerCAmelCase_							,		):

       '''simple docstring'''

       super().__init__(**lowerCAmelCase_ )

       a_      :	Optional[Any]      =							do_rescale
       a_      :	Any      =							rescale_factor
       a_      :	Optional[int]      =							do_pad
       a_      :	Union[str, Any]      =							pad_size


     def 							_lowerCAmelCase  (      self							,		lowerCAmelCase_							,		lowerCAmelCase_							,		lowerCAmelCase_ = None							,		**lowerCAmelCase_ ):

       '''simple docstring'''

       return rescale(lowerCAmelCase_							,		scale=lowerCAmelCase_							,		data_format=lowerCAmelCase_							,		**lowerCAmelCase_ )


     def 							_lowerCAmelCase  (      self							,		lowerCAmelCase_							,		lowerCAmelCase_							,		lowerCAmelCase_ = None ):

       '''simple docstring'''

       a_      , a_      :	Any      =							get_image_size(lowerCAmelCase_ )
       a_      :	Union[str, Any]      =							(old_height // size + 1) * size - old_height
       a_      :	str      =							(old_width // size + 1) * size - old_width

       return pad(lowerCAmelCase_							,		((0, pad_height), (0, pad_width))							,		mode="""symmetric"""							,		data_format=lowerCAmelCase_ )






     def 							_lowerCAmelCase  (      self							,		lowerCAmelCase_							,		lowerCAmelCase_ = None							,		lowerCAmelCase_ = None							,		lowerCAmelCase_ = None							,		lowerCAmelCase_ = None							,		lowerCAmelCase_ = None							,		lowerCAmelCase_ = ChannelDimension.FIRST							,		**lowerCAmelCase_							,		):

       '''simple docstring'''

       a_      :	Dict      =							do_rescale if do_rescale is not None else self.do_rescale
       a_      :	Dict      =							rescale_factor if rescale_factor is not None else self.rescale_factor
       a_      :	str      =							do_pad if do_pad is not None else self.do_pad
       a_      :	Optional[Any]      =							pad_size if pad_size is not None else self.pad_size

       a_      :	Dict      =							make_list_of_images(lowerCAmelCase_ )

       if not valid_images(lowerCAmelCase_ ):
         raise ValueError(
             """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
             """torch.Tensor, tf.Tensor or jax.ndarray.""" )

       if do_rescale and rescale_factor is None:
         raise ValueError("""Rescale factor must be specified if do_rescale is True.""" )

       # All transformations expect numpy arrays.
       a_      :	Any      =							[to_numpy_array(lowerCAmelCase_ ) for image in images]

       if do_rescale:
         a_      :	Optional[int]      =							[self.rescale(image=lowerCAmelCase_							,		scale=lowerCAmelCase_ ) for image in images]

       if do_pad:
         a_      :	Any      =							[self.pad(lowerCAmelCase_							,		size=lowerCAmelCase_ ) for image in images]

       a_      :	Dict      =							[to_channel_dimension_format(lowerCAmelCase_							,		lowerCAmelCase_ ) for image in images]

       a_      :	Union[str, Any]      =							{"""pixel_values""": images}
       return BatchFeature(data=lowerCAmelCase_							,		tensor_type=lowerCAmelCase_ )




'''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							,		lowerCAmelCase_							,		lowerCAmelCase_=13							,		lowerCAmelCase_=32							,		lowerCAmelCase_=2							,		lowerCAmelCase_=3							,		lowerCAmelCase_=16							,		lowerCAmelCase_=[32, 64, 1_28]							,		lowerCAmelCase_=[1, 2, 1]							,		lowerCAmelCase_=[2, 2, 4]							,		lowerCAmelCase_=2							,		lowerCAmelCase_=2.0							,		lowerCAmelCase_=True							,		lowerCAmelCase_=0.0							,		lowerCAmelCase_=0.0							,		lowerCAmelCase_=0.1							,		lowerCAmelCase_="gelu"							,		lowerCAmelCase_=False							,		lowerCAmelCase_=True							,		lowerCAmelCase_=0.02							,		lowerCAmelCase_=1E-5							,		lowerCAmelCase_=True							,		lowerCAmelCase_=None							,		lowerCAmelCase_=True							,		lowerCAmelCase_=10							,		lowerCAmelCase_=8							,		lowerCAmelCase_=["stage1", "stage2"]							,		lowerCAmelCase_=[1, 2]							,		):

       '''simple docstring'''

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


     def 							_lowerCAmelCase  (      self ):

       '''simple docstring'''

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

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

       a_      :	Any      =							self.get_config()

       return config, pixel_values, labels


     def 							_lowerCAmelCase  (      self ):

       '''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 							_lowerCAmelCase  (      self							,		lowerCAmelCase_							,		lowerCAmelCase_							,		lowerCAmelCase_ ):

       '''simple docstring'''

       a_      :	Union[str, Any]      =							FocalNetModel(config=lowerCAmelCase_ )
       model.to(lowerCAmelCase_ )
       model.eval()
       a_      :	Optional[Any]      =							model(lowerCAmelCase_ )

       a_      :	Union[str, Any]      =							((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1))
       a_      :	Any      =							int(config.embed_dim * 2 ** (len(config.depths ) - 1) )

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


     def 							_lowerCAmelCase  (      self							,		lowerCAmelCase_							,		lowerCAmelCase_							,		lowerCAmelCase_ ):

       '''simple docstring'''

       a_      :	Union[str, Any]      =							FocalNetBackbone(config=lowerCAmelCase_ )
       model.to(lowerCAmelCase_ )
       model.eval()
       a_      :	Tuple      =							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_      :	Optional[Any]      =							None
       a_      :	List[Any]      =							FocalNetBackbone(config=lowerCAmelCase_ )
       model.to(lowerCAmelCase_ )
       model.eval()
       a_      :	List[str]      =							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 							_lowerCAmelCase  (      self							,		lowerCAmelCase_							,		lowerCAmelCase_							,		lowerCAmelCase_ ):

       '''simple docstring'''

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

       # test greyscale images
       a_      :	List[str]      =							1
       a_      :	Optional[Any]      =							FocalNetForMaskedImageModeling(lowerCAmelCase_ )
       model.to(lowerCAmelCase_ )
       model.eval()

       a_      :	Tuple      =							floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
       a_      :	int      =							model(lowerCAmelCase_ )
       self.parent.assertEqual(result.reconstruction.shape							,		(self.batch_size, 1, self.image_size, self.image_size) )


     def 							_lowerCAmelCase  (      self							,		lowerCAmelCase_							,		lowerCAmelCase_							,		lowerCAmelCase_ ):

       '''simple docstring'''

       a_      :	Any      =							self.type_sequence_label_size
       a_      :	str      =							FocalNetForImageClassification(lowerCAmelCase_ )
       model.to(lowerCAmelCase_ )
       model.eval()
       a_      :	List[Any]      =							model(lowerCAmelCase_							,		labels=lowerCAmelCase_ )
       self.parent.assertEqual(result.logits.shape							,		(self.batch_size, self.type_sequence_label_size) )

       # test greyscale images
       a_      :	Optional[Any]      =							1
       a_      :	Dict      =							FocalNetForImageClassification(lowerCAmelCase_ )
       model.to(lowerCAmelCase_ )
       model.eval()

       a_      :	List[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 							_lowerCAmelCase  (      self ):

       '''simple docstring'''

       a_      :	int      =							self.prepare_config_and_inputs()

       a_      , a_      , a_      :	List[str]      =							config_and_inputs
       a_      :	Optional[Any]      =							{"""pixel_values""": pixel_values}
       return config, inputs_dict







@require_torch
class  _UpperCAmelCase ( lowerCAmelCase__	,lowerCAmelCase__	,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 							_lowerCAmelCase  (      self ):

       '''simple docstring'''

       a_      :	List[str]      =							FocalNetModelTester(self )
       a_      :	Union[str, Any]      =							ConfigTester(self							,		config_class=lowerCAmelCase_							,		embed_dim=37							,		has_text_modality=lowerCAmelCase_ )


     def 							_lowerCAmelCase  (      self ):

       '''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 							_lowerCAmelCase  (      self ):

       '''simple docstring'''

       return


     def 							_lowerCAmelCase  (      self ):

       '''simple docstring'''

       a_      :	Tuple      =							self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*lowerCAmelCase_ )


     def 							_lowerCAmelCase  (      self ):

       '''simple docstring'''

       a_      :	List[Any]      =							self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_backbone(*lowerCAmelCase_ )


     def 							_lowerCAmelCase  (      self ):

       '''simple docstring'''

       a_      :	Union[str, Any]      =							self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_image_modeling(*lowerCAmelCase_ )


     def 							_lowerCAmelCase  (      self ):

       '''simple docstring'''

       a_      :	str      =							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 							_lowerCAmelCase  (      self ):

       '''simple docstring'''

       pass


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

       '''simple docstring'''

       pass


     def 							_lowerCAmelCase  (      self ):

       '''simple docstring'''

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

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


     def 							_lowerCAmelCase  (      self ):

       '''simple docstring'''

       a_      , 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_      :	Union[str, Any]      =							inspect.signature(model.forward )
         # signature.parameters is an OrderedDict => so arg_names order is deterministic
         a_      :	Dict      =							[*signature.parameters.keys()]

         a_      :	Optional[int]      =							["""pixel_values"""]
         self.assertListEqual(arg_names[:1]							,		lowerCAmelCase_ )


     def 							_lowerCAmelCase  (      self							,		lowerCAmelCase_							,		lowerCAmelCase_							,		lowerCAmelCase_							,		lowerCAmelCase_ ):

       '''simple docstring'''

       a_      :	str      =							model_class(lowerCAmelCase_ )
       model.to(lowerCAmelCase_ )
       model.eval()

       with torch.no_grad():
         a_      :	str      =							model(**self._prepare_for_class(lowerCAmelCase_							,		lowerCAmelCase_ ) )

       a_      :	Optional[Any]      =							outputs.hidden_states

       a_      :	int      =							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_      :	List[str]      =							(
           config.patch_size
           if isinstance(config.patch_size							,		collections.abc.Iterable )
           else (config.patch_size, config.patch_size)
       )

       a_      :	List[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_      :	str      =							outputs.reshaped_hidden_states
       self.assertEqual(len(lowerCAmelCase_ )							,		lowerCAmelCase_ )

       a_      , a_      , a_      , a_      :	Optional[Any]      =							reshaped_hidden_states[0].shape
       a_      :	Dict      =							(
           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 							_lowerCAmelCase  (      self ):

       '''simple docstring'''

       a_      , 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_      :	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_      :	Optional[int]      =							True

         self.check_hidden_states_output(lowerCAmelCase_							,		lowerCAmelCase_							,		lowerCAmelCase_							,		lowerCAmelCase_ )


     def 							_lowerCAmelCase  (      self ):

       '''simple docstring'''

       a_      , a_      :	Any      =							self.model_tester.prepare_config_and_inputs_for_common()
       a_      :	Optional[Any]      =							3

       a_      :	Union[str, 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)
       )
       a_      :	Optional[int]      =							(
           config.patch_size
           if isinstance(config.patch_size							,		collections.abc.Iterable )
           else (config.patch_size, config.patch_size)
       )

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

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


     @slow
     def 							_lowerCAmelCase  (      self ):

       '''simple docstring'''

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






     def 							_lowerCAmelCase  (      self ):

       '''simple docstring'''

       a_      , a_      :	int      =							self.model_tester.prepare_config_and_inputs_for_common()

       a_      :	Union[str, Any]      =							_config_zero_init(lowerCAmelCase_ )
       for model_class in self.all_model_classes:
         a_      :	Dict      =							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  _UpperCAmelCase ( unittest.TestCase    ):

     """simple docstring"""

     @cached_property
     def 							_lowerCAmelCase  (      self ):

       '''simple docstring'''

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






     @slow
     def 							_lowerCAmelCase  (      self ):

       '''simple docstring'''

       a_      :	Optional[Any]      =							FocalNetForImageClassification.from_pretrained("""microsoft/focalnet-tiny""" ).to(lowerCAmelCase_ )
       a_      :	Dict      =							self.default_image_processor

       a_      :	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_      :	int      =							model(**lowerCAmelCase_ )

       # verify the logits
       a_      :	Optional[Any]      =							torch.Size((1, 10_00) )
       self.assertEqual(outputs.logits.shape							,		lowerCAmelCase_ )
       a_      :	Dict      =							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()							,		2_81 )







@require_torch
class  _UpperCAmelCase ( lowerCAmelCase__	,unittest.TestCase    ):

     """simple docstring"""

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

     a_    	=					False


     def 							_lowerCAmelCase  (      self ):

       '''simple docstring'''

       a_      :	int      =							FocalNetModelTester(self )


