




import os
import sys
import warnings
from dataclasses import dataclass, field
from io import BytesIO
from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union

import numpy as np
import pyarrow as pa

from .. import config
from ..download.streaming_download_manager import xopen
from ..table import array_cast
from ..utils.file_utils import is_local_path
from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict


if TYPE_CHECKING:
  import PIL.Image

  from .features import FeatureType


_lowerCamelCase      :						Optional[List[str]]							=  None
_lowerCamelCase      :						int							=  """<""" if sys.byteorder == """little""" else """>"""
# Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image
_lowerCamelCase      :						Union[str, Any]							=  [
    np.dtype("""|b1"""),
    np.dtype("""|u1"""),
    np.dtype("""<u2"""),
    np.dtype(""">u2"""),
    np.dtype("""<i2"""),
    np.dtype(""">i2"""),
    np.dtype("""<u4"""),
    np.dtype(""">u4"""),
    np.dtype("""<i4"""),
    np.dtype(""">i4"""),
    np.dtype("""<f4"""),
    np.dtype(""">f4"""),
    np.dtype("""<f8"""),
    np.dtype(""">f8"""),
]


@dataclass
class 							UpperCamelCase_       :

    '''simple docstring'''






    UpperCAmelCase__				    = True
    UpperCAmelCase__				    = None
    # Automatically constructed
    UpperCAmelCase__				    = "PIL.Image.Image"
    UpperCAmelCase__				    = pa.struct({'''bytes''': pa.binary(), '''path''': pa.string()}	)
    UpperCAmelCase__				    = field(default='''Image'''						,   init=UpperCAmelCase__						,   repr=UpperCAmelCase__	)


    def __call__(     self :      List[str])		->List[str]:





           '''simple docstring'''

           return self.pa_type


    def 			SCREAMING_SNAKE_CASE				(     self :      Optional[Any]   ,					UpperCAmelCase__ :      Union[str, bytes, dict, np.ndarray, "PIL.Image.Image"])		->dict:





           '''simple docstring'''

           if config.PIL_AVAILABLE:
                  import PIL.Image
           else:
                  raise ImportError('''To support encoding images, please install \'Pillow\'.''')

           if isinstance(UpperCAmelCase__   ,					UpperCAmelCase__):
                  A__ 					=       np.array(UpperCAmelCase__)

           if isinstance(UpperCAmelCase__   ,					UpperCAmelCase__):
                  return {"path": value, "bytes": None}
           elif isinstance(UpperCAmelCase__   ,					UpperCAmelCase__):
                  return {"path": None, "bytes": value}
           elif isinstance(UpperCAmelCase__   ,					np.ndarray):
                  # convert the image array to PNG/TIFF bytes
                  return encode_np_array(UpperCAmelCase__)
           elif isinstance(UpperCAmelCase__   ,					PIL.Image.Image):
                  # convert the PIL image to bytes (default format is PNG/TIFF)
                  return encode_pil_image(UpperCAmelCase__)
           elif value.get('''path''') is not None and os.path.isfile(value['''path''']):
                  # we set "bytes": None to not duplicate the data if they're already available locally
                  return {"bytes": None, "path": value.get('''path''')}
           elif value.get('''bytes''') is not None or value.get('''path''') is not None:
                  # store the image bytes, and path is used to infer the image format using the file extension
                  return {"bytes": value.get('''bytes'''), "path": value.get('''path''')}
           else:
                  raise ValueError(
                      f"""An image sample should have one of 'path' or 'bytes' but they are missing or None in {value}.""")


    def 			SCREAMING_SNAKE_CASE				(     self :      Optional[int]   ,					UpperCAmelCase__ :      dict   ,					UpperCAmelCase__ :      str=None)		->"PIL.Image.Image":





           '''simple docstring'''

           if not self.decode:
                  raise RuntimeError('''Decoding is disabled for this feature. Please use Image(decode=True) instead.''')

           if config.PIL_AVAILABLE:
                  import PIL.Image
           else:
                  raise ImportError('''To support decoding images, please install \'Pillow\'.''')

           if token_per_repo_id is None:
                  A__ 					=       {}

           A__					,				A__ 					=       value['''path'''], value['''bytes''']
           if bytes_ is None:
                  if path is None:
                         raise ValueError(f"""An image should have one of 'path' or 'bytes' but both are None in {value}.""")
                  else:
                         if is_local_path(UpperCAmelCase__):
                                A__ 					=       PIL.Image.open(UpperCAmelCase__)
                         else:
                                A__ 					=       path.split('''::''')[-1]
                                try:
                                       A__ 					=       string_to_dict(UpperCAmelCase__   ,					config.HUB_DATASETS_URL)['''repo_id''']
                                       A__ 					=       token_per_repo_id.get(UpperCAmelCase__)
                                except ValueError:
                                       A__ 					=       None
                                with xopen(UpperCAmelCase__   ,					'''rb'''   ,					use_auth_token=UpperCAmelCase__) as f:
                                       A__ 					=       BytesIO(f.read())
                                A__ 					=       PIL.Image.open(bytes_)
           else:
                  A__ 					=       PIL.Image.open(BytesIO(bytes_))
           image.load()  # to avoid "Too many open files" errors
           return image


    def 			SCREAMING_SNAKE_CASE				(     self :      Dict)		->Union["FeatureType", Dict[str, "FeatureType"]]:





           '''simple docstring'''

           from .features import Value

           return (
               self
               if self.decode
               else {
                   "bytes": Value('''binary'''),
                   "path": Value('''string'''),
               }
           )


    def 			SCREAMING_SNAKE_CASE				(     self :      Dict   ,					UpperCAmelCase__ :      Union[pa.StringArray, pa.StructArray, pa.ListArray])		->pa.StructArray:





           '''simple docstring'''

           if pa.types.is_string(storage.type):
                  A__ 					=       pa.array([None] * len(UpperCAmelCase__)   ,					type=pa.binary())
                  A__ 					=       pa.StructArray.from_arrays([bytes_array, storage]   ,					['''bytes''', '''path''']   ,					mask=storage.is_null())
           elif pa.types.is_binary(storage.type):
                  A__ 					=       pa.array([None] * len(UpperCAmelCase__)   ,					type=pa.string())
                  A__ 					=       pa.StructArray.from_arrays([storage, path_array]   ,					['''bytes''', '''path''']   ,					mask=storage.is_null())
           elif pa.types.is_struct(storage.type):
                  if storage.type.get_field_index('''bytes''') >= 0:
                         A__ 					=       storage.field('''bytes''')
                  else:
                         A__ 					=       pa.array([None] * len(UpperCAmelCase__)   ,					type=pa.binary())
                  if storage.type.get_field_index('''path''') >= 0:
                         A__ 					=       storage.field('''path''')
                  else:
                         A__ 					=       pa.array([None] * len(UpperCAmelCase__)   ,					type=pa.string())
                  A__ 					=       pa.StructArray.from_arrays([bytes_array, path_array]   ,					['''bytes''', '''path''']   ,					mask=storage.is_null())
           elif pa.types.is_list(storage.type):
                  A__ 					=       pa.array(
                      [encode_np_array(np.array(UpperCAmelCase__))['''bytes'''] if arr is not None else None for arr in storage.to_pylist()]   ,					type=pa.binary()   ,					)
                  A__ 					=       pa.array([None] * len(UpperCAmelCase__)   ,					type=pa.string())
                  A__ 					=       pa.StructArray.from_arrays(
                      [bytes_array, path_array]   ,					['''bytes''', '''path''']   ,					mask=bytes_array.is_null())
           return array_cast(UpperCAmelCase__   ,					self.pa_type)





    def 			SCREAMING_SNAKE_CASE				(     self :      List[Any]   ,					UpperCAmelCase__ :      pa.StructArray)		->pa.StructArray:





           '''simple docstring'''

           @no_op_if_value_is_null
           def path_to_bytes(UpperCAmelCase__ :      Dict):
                  with xopen(UpperCAmelCase__   ,					'''rb''') as f:
                         A__ 					=       f.read()
                  return bytes_

           A__ 					=       pa.array(
               [
                   (path_to_bytes(x['''path''']) if x['''bytes'''] is None else x['''bytes''']) if x is not None else None
                   for x in storage.to_pylist()
               ]   ,					type=pa.binary()   ,					)
           A__ 					=       pa.array(
               [os.path.basename(UpperCAmelCase__) if path is not None else None for path in storage.field('''path''').to_pylist()]   ,					type=pa.string()   ,					)
           A__ 					=       pa.StructArray.from_arrays([bytes_array, path_array]   ,					['''bytes''', '''path''']   ,					mask=bytes_array.is_null())
           return array_cast(UpperCAmelCase__   ,					self.pa_type)







def SCREAMING_SNAKE_CASE							(			)  ->			List[str]:



       """simple docstring"""

       if config.PIL_AVAILABLE:
              import PIL.Image
       else:
              raise ImportError('''To support encoding images, please install \'Pillow\'.'''		)

       global _IMAGE_COMPRESSION_FORMATS
       if _IMAGE_COMPRESSION_FORMATS is None:
              PIL.Image.init()
              A__ 					=       list(set(PIL.Image.OPEN.keys()		) & set(PIL.Image.SAVE.keys()		)		)
       return _IMAGE_COMPRESSION_FORMATS







def SCREAMING_SNAKE_CASE							(			lowercase_		)  ->			bytes:



       """simple docstring"""

       A__ 					=       BytesIO()
       if image.format in list_image_compression_formats():
              A__ 					=       image.format
       else:
              A__ 					=       '''PNG''' if image.mode in ['''1''', '''L''', '''LA''', '''RGB''', '''RGBA'''] else '''TIFF'''
       image.save(lowercase_					,							format=lowercase_		)
       return buffer.getvalue()







def SCREAMING_SNAKE_CASE							(			lowercase_		)  ->			dict:



       """simple docstring"""

       if hasattr(lowercase_					,							'''filename'''		) and image.filename != "":
              return {"path": image.filename, "bytes": None}
       else:
              return {"path": None, "bytes": image_to_bytes(lowercase_		)}







def SCREAMING_SNAKE_CASE							(			lowercase_		)  ->			dict:



       """simple docstring"""

       if config.PIL_AVAILABLE:
              import PIL.Image
       else:
              raise ImportError('''To support encoding images, please install \'Pillow\'.'''		)

       A__ 					=       array.dtype
       A__ 					=       dtype.byteorder if dtype.byteorder != '''=''' else _NATIVE_BYTEORDER
       A__ 					=       dtype.kind
       A__ 					=       dtype.itemsize

       A__ 					=       None

       # Multi-channel array case (only np.dtype("|u1") is allowed)
       if array.shape[2:]:
              A__ 					=       np.dtype('''|u1'''		)
              if dtype_kind not in ["u", "i"]:
                     raise TypeError(
                         f"""Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays."""		)
              if dtype is not dest_dtype:
                     warnings.warn(f"""Downcasting array dtype {dtype} to {dest_dtype} to be compatible with 'Pillow'"""		)
    # Exact match
       elif dtype in _VALID_IMAGE_ARRAY_DTPYES:
              A__ 					=       dtype
       else:  # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually)
              while dtype_itemsize >= 1:
                     A__ 					=       dtype_byteorder + dtype_kind + str(lowercase_		)
                     A__ 					=       np.dtype(lowercase_		)
                     if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES:
                            warnings.warn(f"""Downcasting array dtype {dtype} to {dest_dtype} to be compatible with 'Pillow'"""		)
                            break
                     else:
                            dtype_itemsize //= 2

       if dest_dtype is None:
              raise TypeError(
                  f"""Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}"""		)
       A__ 					=       PIL.Image.fromarray(array.astype(lowercase_		)		)
       return {"path": None, "bytes": image_to_bytes(lowercase_		)}







def SCREAMING_SNAKE_CASE							(			lowercase_		)  ->			List[dict]:



       """simple docstring"""

       if config.PIL_AVAILABLE:
              import PIL.Image
       else:
              raise ImportError('''To support encoding images, please install \'Pillow\'.'''		)

       if objs:
              A__					,				A__ 					=       first_non_null_value(lowercase_		)
              if isinstance(lowercase_					,							lowercase_		):
                     return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs]
              if isinstance(lowercase_					,							np.ndarray		):
                     A__ 					=       no_op_if_value_is_null(lowercase_		)
                     return [obj_to_image_dict_func(lowercase_		) for obj in objs]
              elif isinstance(lowercase_					,							PIL.Image.Image		):
                     A__ 					=       no_op_if_value_is_null(lowercase_		)
                     return [obj_to_image_dict_func(lowercase_		) for obj in objs]
              else:
                     return objs
       else:
              return objs







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






			def __init__(     self					,   _UpperCAmelCase					,   _UpperCAmelCase=13					,   _UpperCAmelCase=32					,   _UpperCAmelCase=2					,   _UpperCAmelCase=3					,   _UpperCAmelCase=16					,   _UpperCAmelCase=[32, 64, 128]					,   _UpperCAmelCase=[1, 2, 1]					,   _UpperCAmelCase=[2, 2, 4]					,   _UpperCAmelCase=2					,   _UpperCAmelCase=2.0					,   _UpperCAmelCase=True					,   _UpperCAmelCase=0.0					,   _UpperCAmelCase=0.0					,   _UpperCAmelCase=0.1					,   _UpperCAmelCase="gelu"					,   _UpperCAmelCase=False					,   _UpperCAmelCase=True					,   _UpperCAmelCase=0.02					,   _UpperCAmelCase=1E-5					,   _UpperCAmelCase=True					,   _UpperCAmelCase=None					,   _UpperCAmelCase=True					,   _UpperCAmelCase=10					,   _UpperCAmelCase=8					,   _UpperCAmelCase=["stage1", "stage2"]					,   _UpperCAmelCase=[1, 2]					,   )							->							int:
					snake_case__	     =parent
					snake_case__	     =batch_size
					snake_case__	     =image_size
					snake_case__	     =patch_size
					snake_case__	     =num_channels
					snake_case__	     =embed_dim
					snake_case__	     =hidden_sizes
					snake_case__	     =depths
					snake_case__	     =num_heads
					snake_case__	     =window_size
					snake_case__	     =mlp_ratio
					snake_case__	     =qkv_bias
					snake_case__	     =hidden_dropout_prob
					snake_case__	     =attention_probs_dropout_prob
					snake_case__	     =drop_path_rate
					snake_case__	     =hidden_act
					snake_case__	     =use_absolute_embeddings
					snake_case__	     =patch_norm
					snake_case__	     =layer_norm_eps
					snake_case__	     =initializer_range
					snake_case__	     =is_training
					snake_case__	     =scope
					snake_case__	     =use_labels
					snake_case__	     =type_sequence_label_size
					snake_case__	     =encoder_stride
					snake_case__	     =out_features
					snake_case__	     =out_indices






			def 						_lowercase  (     self						)							->							Dict:
					snake_case__	     =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

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

					snake_case__	     =self.get_config()

					return config, pixel_values, labels






			def 						_lowercase  (     self						)							->							Any:
					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					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)							->							Union[str, Any]:
					snake_case__	     =FocalNetModel(config=_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()
					snake_case__	     =model(_UpperCAmelCase						)

					snake_case__	     =((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths						) - 1))
					snake_case__	     =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					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)							->							Optional[int]:
					snake_case__	     =FocalNetBackbone(config=_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()
					snake_case__	     =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__	     =None
					snake_case__	     =FocalNetBackbone(config=_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()
					snake_case__	     =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 						_lowercase  (     self					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)							->							Any:
					snake_case__	     =FocalNetForMaskedImageModeling(config=_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()
					snake_case__	     =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__	     =1
					snake_case__	     =FocalNetForMaskedImageModeling(_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()

					snake_case__	     =floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
					snake_case__	     =model(_UpperCAmelCase						)
					self.parent.assertEqual(result.reconstruction.shape					,   (self.batch_size, 1, self.image_size, self.image_size)						)






			def 						_lowercase  (     self					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)							->							Tuple:
					snake_case__	     =self.type_sequence_label_size
					snake_case__	     =FocalNetForImageClassification(_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()
					snake_case__	     =model(_UpperCAmelCase					,   labels=_UpperCAmelCase						)
					self.parent.assertEqual(result.logits.shape					,   (self.batch_size, self.type_sequence_label_size)						)

					# test greyscale images
					snake_case__	     =1
					snake_case__	     =FocalNetForImageClassification(_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()

					snake_case__	     =floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
					snake_case__	     =model(_UpperCAmelCase						)
					self.parent.assertEqual(result.logits.shape					,   (self.batch_size, self.type_sequence_label_size)						)






			def 						_lowercase  (     self						)							->							List[str]:
					snake_case__	     =self.prepare_config_and_inputs()

					snake_case__     ,	snake_case__     ,	snake_case__	     =config_and_inputs
					snake_case__	     ={'pixel_values': pixel_values}
					return config, inputs_dict





@require_torch
class 							a__( snake_case__   ,      snake_case__   ,      unittest.TestCase     ):
			a_	: str									=      (
			    (
			        FocalNetModel,
			        FocalNetForImageClassification,
			        FocalNetForMaskedImageModeling,
			        FocalNetBackbone,
			    )
			    if is_torch_available()
			    else ()
			)
			a_	: Union[str, Any]									=      (
			    {'''feature-extraction''': FocalNetModel, '''image-classification''': FocalNetForImageClassification}
			    if is_torch_available()
			    else {}
			)
			a_	: Dict									=      False

			a_	: Any									=      False
			a_	: List[str]									=      False
			a_	: List[Any]									=      False
			a_	: Optional[Any]									=      False






			def 						_lowercase  (     self						)							->							Optional[int]:
					snake_case__	     =FocalNetModelTester(self						)
					snake_case__	     =ConfigTester(self					,   config_class=_UpperCAmelCase					,   embed_dim=37					,   has_text_modality=_UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							Optional[Any]:
					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						)							->							str:
					return






			def 						_lowercase  (     self						)							->							str:
					snake_case__	     =self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*_UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							str:
					snake_case__	     =self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_backbone(*_UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							Optional[Any]:
					snake_case__	     =self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_masked_image_modeling(*_UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							Union[str, Any]:
					snake_case__	     =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 						_lowercase  (     self						)							->							str:
					pass






			@unittest.skip(reason='FocalNet does not use feedforward chunking'						)
			def 						_lowercase  (     self						)							->							int:
					pass






			def 						_lowercase  (     self						)							->							List[str]:
					snake_case__     ,	snake_case__	     =self.model_tester.prepare_config_and_inputs_for_common()

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






			def 						_lowercase  (     self						)							->							Optional[Any]:
					snake_case__     ,	snake_case__	     =self.model_tester.prepare_config_and_inputs_for_common()

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

							snake_case__	     =['pixel_values']
							self.assertListEqual(arg_names[:1]					,   _UpperCAmelCase						)






			def 						_lowercase  (     self					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)							->							Union[str, Any]:
					snake_case__	     =model_class(_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()

					with torch.no_grad():
							snake_case__	     =model(**self._prepare_for_class(_UpperCAmelCase					,   _UpperCAmelCase						)						)

					snake_case__	     =outputs.hidden_states

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

					snake_case__	     =(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__	     =outputs.reshaped_hidden_states
					self.assertEqual(len(_UpperCAmelCase						)					,   _UpperCAmelCase						)

					snake_case__     ,	snake_case__     ,	snake_case__     ,	snake_case__	     =reshaped_hidden_states[0].shape
					snake_case__	     =(
					    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 						_lowercase  (     self						)							->							List[str]:
					snake_case__     ,	snake_case__	     =self.model_tester.prepare_config_and_inputs_for_common()

					snake_case__	     =(
					    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__	     =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__	     =True

							self.check_hidden_states_output(_UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							List[str]:
					snake_case__     ,	snake_case__	     =self.model_tester.prepare_config_and_inputs_for_common()
					snake_case__	     =3

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

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

					for model_class in self.all_model_classes[:-1]:
							snake_case__	     =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__	     =True
							self.check_hidden_states_output(_UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase					,   (padded_height, padded_width)						)






			@slow
			def 						_lowercase  (     self						)							->							Optional[Any]:
					for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							snake_case__	     =FocalNetModel.from_pretrained(_UpperCAmelCase						)
							self.assertIsNotNone(_UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							int:
					snake_case__     ,	snake_case__	     =self.model_tester.prepare_config_and_inputs_for_common()

					snake_case__	     =_config_zero_init(_UpperCAmelCase						)
					for model_class in self.all_model_classes:
							snake_case__	     =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 							a__( unittest.TestCase     ):






			@cached_property
			def 						_lowercase  (     self						)							->							Any:
					# TODO update organization
					return AutoImageProcessor.from_pretrained('microsoft/focalnet-tiny'						) if is_vision_available() else None






			@slow
			def 						_lowercase  (     self						)							->							str:
					snake_case__	     =FocalNetForImageClassification.from_pretrained('microsoft/focalnet-tiny'						).to(_UpperCAmelCase						)
					snake_case__	     =self.default_image_processor

					snake_case__	     =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
					snake_case__	     =image_processor(images=_UpperCAmelCase					,   return_tensors='pt'						).to(_UpperCAmelCase						)

					# forward pass
					with torch.no_grad():
							snake_case__	     =model(**_UpperCAmelCase						)

					# verify the logits
					snake_case__	     =torch.Size((1, 1000)						)
					self.assertEqual(outputs.logits.shape					,   _UpperCAmelCase						)
					snake_case__	     =torch.tensor([0.2_166, -0.4_368, 0.2_191]						).to(_UpperCAmelCase						)
					self.assertTrue(torch.allclose(outputs.logits[0, :3]					,   _UpperCAmelCase					,   atol=1E-4						)						)
					self.assertTrue(outputs.logits.argmax(dim=-1						).item()					,   281						)





@require_torch
class 							a__( snake_case__   ,      unittest.TestCase     ):
			a_	: int									=      (FocalNetBackbone,) if is_torch_available() else ()
			a_	: Any									=      FocalNetConfig

			a_	: int									=      False






			def 						_lowercase  (     self						)							->							Optional[int]:
					snake_case__	     =FocalNetModelTester(self						)




