



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




	'''simple docstring'''





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

				"""simple docstring"""

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

	def 				_SCREAMING_SNAKE_CASE  (	self:						Dict)							->			str:

				"""simple docstring"""

				__lowerCAmelCase :    str				=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

				__lowerCAmelCase :    Union[str, Any]				=			self.get_config()

				return config, pixel_values, labels

	def 				_SCREAMING_SNAKE_CASE  (	self:						Tuple)							->			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 				_SCREAMING_SNAKE_CASE  (	self:						int			,     _SCREAMING_SNAKE_CASE:						int			,     _SCREAMING_SNAKE_CASE:						Tuple			,     _SCREAMING_SNAKE_CASE:						int)							->			Tuple:

				"""simple docstring"""

				__lowerCAmelCase :    Optional[int]				=			FocalNetModel(config=_SCREAMING_SNAKE_CASE)
				model.to(_SCREAMING_SNAKE_CASE)
				model.eval()
				__lowerCAmelCase :    Tuple				=			model(_SCREAMING_SNAKE_CASE)

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

				"""simple docstring"""

				__lowerCAmelCase :    Union[str, Any]				=			FocalNetBackbone(config=_SCREAMING_SNAKE_CASE)
				model.to(_SCREAMING_SNAKE_CASE)
				model.eval()
				__lowerCAmelCase :    str				=			model(_SCREAMING_SNAKE_CASE)

				# 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
				__lowerCAmelCase :    Tuple				=			None
				__lowerCAmelCase :    Dict				=			FocalNetBackbone(config=_SCREAMING_SNAKE_CASE)
				model.to(_SCREAMING_SNAKE_CASE)
				model.eval()
				__lowerCAmelCase :    List[str]				=			model(_SCREAMING_SNAKE_CASE)

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

				"""simple docstring"""

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

				# test greyscale images
				__lowerCAmelCase :    Optional[int]				=			1
				__lowerCAmelCase :    Any				=			FocalNetForMaskedImageModeling(_SCREAMING_SNAKE_CASE)
				model.to(_SCREAMING_SNAKE_CASE)
				model.eval()

				__lowerCAmelCase :    List[Any]				=			floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
				__lowerCAmelCase :    Dict				=			model(_SCREAMING_SNAKE_CASE)
				self.parent.assertEqual(result.reconstruction.shape			,     (self.batch_size, 1, self.image_size, self.image_size))

	def 				_SCREAMING_SNAKE_CASE  (	self:						Union[str, Any]			,     _SCREAMING_SNAKE_CASE:						List[Any]			,     _SCREAMING_SNAKE_CASE:						str			,     _SCREAMING_SNAKE_CASE:						List[Any])							->			Union[str, Any]:

				"""simple docstring"""

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

				# test greyscale images
				__lowerCAmelCase :    str				=			1
				__lowerCAmelCase :    Tuple				=			FocalNetForImageClassification(_SCREAMING_SNAKE_CASE)
				model.to(_SCREAMING_SNAKE_CASE)
				model.eval()

				__lowerCAmelCase :    int				=			floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
				__lowerCAmelCase :    Dict				=			model(_SCREAMING_SNAKE_CASE)
				self.parent.assertEqual(result.logits.shape			,     (self.batch_size, self.type_sequence_label_size))







	def 				_SCREAMING_SNAKE_CASE  (	self:						int)							->			int:

				"""simple docstring"""

				__lowerCAmelCase :    List[str]				=			self.prepare_config_and_inputs()

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






@require_torch
class      A__  (    __SCREAMING_SNAKE_CASE    ,						__SCREAMING_SNAKE_CASE    ,						unittest.TestCase				):




	'''simple docstring'''





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

	SCREAMING_SNAKE_CASE        =      False
	SCREAMING_SNAKE_CASE        =      False
	SCREAMING_SNAKE_CASE        =      False
	SCREAMING_SNAKE_CASE        =      False

	def 				_SCREAMING_SNAKE_CASE  (	self:						List[Any])							->			Union[str, Any]:

				"""simple docstring"""

				__lowerCAmelCase :    Tuple				=			FocalNetModelTester(self)
				__lowerCAmelCase :    Union[str, Any]				=			ConfigTester(self			,     config_class=_SCREAMING_SNAKE_CASE			,     embed_dim=37			,     has_text_modality=_SCREAMING_SNAKE_CASE)

	def 				_SCREAMING_SNAKE_CASE  (	self:						List[str])							->			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 				_SCREAMING_SNAKE_CASE  (	self:						List[Any])							->			Optional[int]:

				"""simple docstring"""

				return

	def 				_SCREAMING_SNAKE_CASE  (	self:						int)							->			Union[str, Any]:

				"""simple docstring"""

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

	def 				_SCREAMING_SNAKE_CASE  (	self:						int)							->			str:

				"""simple docstring"""

				__lowerCAmelCase :    str				=			self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_backbone(*_SCREAMING_SNAKE_CASE)

	def 				_SCREAMING_SNAKE_CASE  (	self:						Dict)							->			Optional[Any]:

				"""simple docstring"""

				__lowerCAmelCase :    Optional[Any]				=			self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_masked_image_modeling(*_SCREAMING_SNAKE_CASE)

	def 				_SCREAMING_SNAKE_CASE  (	self:						Tuple)							->			Optional[int]:

				"""simple docstring"""

				__lowerCAmelCase :    List[str]				=			self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE)

	@unittest.skip(reason="FocalNet does not use inputs_embeds")
	def 				_SCREAMING_SNAKE_CASE  (	self:						Union[str, Any])							->			int:

				"""simple docstring"""

				pass

	@unittest.skip(reason="FocalNet does not use feedforward chunking")
	def 				_SCREAMING_SNAKE_CASE  (	self:						Optional[Any])							->			Optional[Any]:

				"""simple docstring"""

				pass

	def 				_SCREAMING_SNAKE_CASE  (	self:						List[Any])							->			List[str]:

				"""simple docstring"""

				__lowerCAmelCase		,      __lowerCAmelCase :    Optional[int]				=			self.model_tester.prepare_config_and_inputs_for_common()

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

	def 				_SCREAMING_SNAKE_CASE  (	self:						Union[str, Any])							->			List[Any]:

				"""simple docstring"""

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

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

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

	def 				_SCREAMING_SNAKE_CASE  (	self:						Dict			,     _SCREAMING_SNAKE_CASE:						Optional[Any]			,     _SCREAMING_SNAKE_CASE:						str			,     _SCREAMING_SNAKE_CASE:						List[str]			,     _SCREAMING_SNAKE_CASE:						Tuple)							->			int:

				"""simple docstring"""

				__lowerCAmelCase :    List[Any]				=			model_class(_SCREAMING_SNAKE_CASE)
				model.to(_SCREAMING_SNAKE_CASE)
				model.eval()

				with torch.no_grad():
							__lowerCAmelCase :    str				=			model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE			,     _SCREAMING_SNAKE_CASE))

				__lowerCAmelCase :    Optional[Any]				=			outputs.hidden_states

				__lowerCAmelCase :    List[Any]				=			getattr(
				    self.model_tester			,     "expected_num_hidden_layers"			,     len(self.model_tester.depths) + 1)
				self.assertEqual(len(_SCREAMING_SNAKE_CASE)			,     _SCREAMING_SNAKE_CASE)

				# FocalNet has a different seq_length
				__lowerCAmelCase :    Optional[Any]				=			(
				    config.patch_size
				    if isinstance(config.patch_size			,     collections.abc.Iterable)
				    else (config.patch_size, config.patch_size)
				)

				__lowerCAmelCase :    List[str]				=			(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]			,     )

				__lowerCAmelCase :    List[str]				=			outputs.reshaped_hidden_states
				self.assertEqual(len(_SCREAMING_SNAKE_CASE)			,     _SCREAMING_SNAKE_CASE)

				__lowerCAmelCase		,      __lowerCAmelCase		,      __lowerCAmelCase		,      __lowerCAmelCase :    Union[str, Any]				=			reshaped_hidden_states[0].shape
				__lowerCAmelCase :    Union[str, Any]				=			(
				    reshaped_hidden_states[0].view(_SCREAMING_SNAKE_CASE			,     _SCREAMING_SNAKE_CASE			,     height * width).permute(0			,     2			,     1)
				)
				self.assertListEqual(
				    list(reshaped_hidden_states.shape[-2:])			,     [num_patches, self.model_tester.embed_dim]			,     )

	def 				_SCREAMING_SNAKE_CASE  (	self:						List[str])							->			Dict:

				"""simple docstring"""

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

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

				for model_class in self.all_model_classes[:-1]:
							__lowerCAmelCase :    int				=			True
							self.check_hidden_states_output(_SCREAMING_SNAKE_CASE			,     _SCREAMING_SNAKE_CASE			,     _SCREAMING_SNAKE_CASE			,     _SCREAMING_SNAKE_CASE)

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

							self.check_hidden_states_output(_SCREAMING_SNAKE_CASE			,     _SCREAMING_SNAKE_CASE			,     _SCREAMING_SNAKE_CASE			,     _SCREAMING_SNAKE_CASE)

	def 				_SCREAMING_SNAKE_CASE  (	self:						int)							->			Optional[int]:

				"""simple docstring"""

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

				__lowerCAmelCase :    Dict				=			(
				    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)
				)
				__lowerCAmelCase :    Optional[Any]				=			(
				    config.patch_size
				    if isinstance(config.patch_size			,     collections.abc.Iterable)
				    else (config.patch_size, config.patch_size)
				)

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

				for model_class in self.all_model_classes[:-1]:
							__lowerCAmelCase :    Tuple				=			True
							self.check_hidden_states_output(_SCREAMING_SNAKE_CASE			,     _SCREAMING_SNAKE_CASE			,     _SCREAMING_SNAKE_CASE			,     (padded_height, padded_width))

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

	@slow
	def 				_SCREAMING_SNAKE_CASE  (	self:						Optional[Any])							->			Tuple:

				"""simple docstring"""

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







	def 				_SCREAMING_SNAKE_CASE  (	self:						Tuple)							->			Tuple:

				"""simple docstring"""

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

				__lowerCAmelCase :    Optional[Any]				=			_config_zero_init(_SCREAMING_SNAKE_CASE)
				for model_class in self.all_model_classes:
							__lowerCAmelCase :    Union[str, Any]				=			model_class(config=_SCREAMING_SNAKE_CASE)
							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				):




	'''simple docstring'''





	@cached_property
	def 				_SCREAMING_SNAKE_CASE  (	self:						Optional[Any])							->			int:

				"""simple docstring"""

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







	@slow
	def 				_SCREAMING_SNAKE_CASE  (	self:						Optional[int])							->			Any:

				"""simple docstring"""

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

				__lowerCAmelCase :    int				=			Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
				__lowerCAmelCase :    Tuple				=			image_processor(images=_SCREAMING_SNAKE_CASE			,     return_tensors="pt").to(_SCREAMING_SNAKE_CASE)

				# forward pass
				with torch.no_grad():
							__lowerCAmelCase :    Union[str, Any]				=			model(**_SCREAMING_SNAKE_CASE)

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






@require_torch
class      A__  (    __SCREAMING_SNAKE_CASE    ,						unittest.TestCase				):




	'''simple docstring'''





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

	SCREAMING_SNAKE_CASE        =      False

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

				"""simple docstring"""

				__lowerCAmelCase :    str				=			FocalNetModelTester(self)




"""simple docstring"""






import torch
from torch import nn
from torch.nn import CrossEntropyLoss, MSELoss

from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward
from transformers.models.bert.modeling_bert import (
    BERT_INPUTS_DOCSTRING,
    BERT_START_DOCSTRING,
    BertEmbeddings,
    BertLayer,
    BertPooler,
    BertPreTrainedModel,
)


def      _lowercase							(    __snake_case      )		->  Dict:
			__lowerCAmelCase :    Optional[int]				=			torch.exp(__snake_case      )
			__lowerCAmelCase :    int				=			torch.sum(__snake_case   ,dim=1      )  # sum of exp(x_i)
			__lowerCAmelCase :    Optional[Any]				=			torch.sum(x * exp_x   ,dim=1      )  # sum of x_i * exp(x_i)
			return torch.log(__snake_case      ) - B / A



class      A__  (    nn.Module				):




	'''simple docstring'''





	def __init__(	self:						Any			,     _SCREAMING_SNAKE_CASE:						List[Any])							->			List[str]:

				"""simple docstring"""

				super().__init__()
				__lowerCAmelCase :    Any				=			config.output_attentions
				__lowerCAmelCase :    Optional[Any]				=			config.output_hidden_states
				__lowerCAmelCase :    Tuple				=			nn.ModuleList([BertLayer(_SCREAMING_SNAKE_CASE) for _ in range(config.num_hidden_layers)])
				__lowerCAmelCase :    int				=			nn.ModuleList([BertHighway(_SCREAMING_SNAKE_CASE) for _ in range(config.num_hidden_layers)])

				__lowerCAmelCase :    List[str]				=			[-1 for _ in range(config.num_hidden_layers)]

	def 				_SCREAMING_SNAKE_CASE  (	self:						List[Any]			,     _SCREAMING_SNAKE_CASE:						List[str])							->			Optional[int]:

				"""simple docstring"""

				if (type(_SCREAMING_SNAKE_CASE) is float) or (type(_SCREAMING_SNAKE_CASE) is int):
							for i in range(len(self.early_exit_entropy)):
										__lowerCAmelCase :    List[Any]				=			x
				else:
							__lowerCAmelCase :    str				=			x

	def 				_SCREAMING_SNAKE_CASE  (	self:						Union[str, Any]			,     _SCREAMING_SNAKE_CASE:						Tuple)							->			List[str]:

				"""simple docstring"""

				__lowerCAmelCase :    Union[str, Any]				=			pooler.state_dict()
				for highway in self.highway:
							for name, param in highway.pooler.state_dict().items():
										param.copy_(loaded_model[name])







	def 				_SCREAMING_SNAKE_CASE  (	self:						int			,     _SCREAMING_SNAKE_CASE:						List[str]			,     _SCREAMING_SNAKE_CASE:						Tuple=None			,     _SCREAMING_SNAKE_CASE:						List[str]=None			,     _SCREAMING_SNAKE_CASE:						List[Any]=None			,     _SCREAMING_SNAKE_CASE:						Tuple=None			,     )							->			Optional[Any]:

				"""simple docstring"""

				__lowerCAmelCase :    Tuple				=			()
				__lowerCAmelCase :    Tuple				=			()
				__lowerCAmelCase :    Optional[Any]				=			()
				for i, layer_module in enumerate(self.layer):
							if self.output_hidden_states:
										__lowerCAmelCase :    Tuple				=			all_hidden_states + (hidden_states,)

							__lowerCAmelCase :    Any				=			layer_module(
							    _SCREAMING_SNAKE_CASE			,     _SCREAMING_SNAKE_CASE			,     head_mask[i]			,     _SCREAMING_SNAKE_CASE			,     _SCREAMING_SNAKE_CASE)
							__lowerCAmelCase :    str				=			layer_outputs[0]

							if self.output_attentions:
										__lowerCAmelCase :    List[Any]				=			all_attentions + (layer_outputs[1],)

							__lowerCAmelCase :    Optional[int]				=			(hidden_states,)
							if self.output_hidden_states:
										__lowerCAmelCase :    Tuple				=			current_outputs + (all_hidden_states,)
							if self.output_attentions:
										__lowerCAmelCase :    List[str]				=			current_outputs + (all_attentions,)

							__lowerCAmelCase :    List[str]				=			self.highway[i](_SCREAMING_SNAKE_CASE)
							# logits, pooled_output

							if not self.training:
										__lowerCAmelCase :    Union[str, Any]				=			highway_exit[0]
										__lowerCAmelCase :    Dict				=			entropy(_SCREAMING_SNAKE_CASE)
										__lowerCAmelCase :    Dict				=			highway_exit + (highway_entropy,)  # logits, hidden_states(?), entropy
										__lowerCAmelCase :    Dict				=			all_highway_exits + (highway_exit,)

										if highway_entropy < self.early_exit_entropy[i]:
													__lowerCAmelCase :    Any				=			(highway_logits,) + current_outputs[1:] + (all_highway_exits,)
													raise HighwayException(_SCREAMING_SNAKE_CASE			,     i + 1)
							else:
										__lowerCAmelCase :    Optional[Any]				=			all_highway_exits + (highway_exit,)

        # Add last layer
				if self.output_hidden_states:
							__lowerCAmelCase :    Union[str, Any]				=			all_hidden_states + (hidden_states,)

				__lowerCAmelCase :    str				=			(hidden_states,)
				if self.output_hidden_states:
							__lowerCAmelCase :    Union[str, Any]				=			outputs + (all_hidden_states,)
				if self.output_attentions:
							__lowerCAmelCase :    Optional[int]				=			outputs + (all_attentions,)

				__lowerCAmelCase :    List[str]				=			outputs + (all_highway_exits,)
				return outputs  # last-layer hidden state, (all hidden states), (all attentions), all highway exits






@add_start_docstrings(
    'The Bert Model transformer with early exiting (DeeBERT). '    ,						__SCREAMING_SNAKE_CASE    ,						)
class      A__  (    __SCREAMING_SNAKE_CASE				):




	'''simple docstring'''





	def __init__(	self:						Dict			,     _SCREAMING_SNAKE_CASE:						Tuple)							->			Union[str, Any]:

				"""simple docstring"""

				super().__init__(_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase :    Tuple				=			config

				__lowerCAmelCase :    str				=			BertEmbeddings(_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase :    Optional[int]				=			DeeBertEncoder(_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase :    List[Any]				=			BertPooler(_SCREAMING_SNAKE_CASE)

				self.init_weights()

	def 				_SCREAMING_SNAKE_CASE  (	self:						List[Any])							->			Any:

				"""simple docstring"""

				self.encoder.init_highway_pooler(self.pooler)

	def 				_SCREAMING_SNAKE_CASE  (	self:						str)							->			str:

				"""simple docstring"""

				return self.embeddings.word_embeddings

	def 				_SCREAMING_SNAKE_CASE  (	self:						Optional[int]			,     _SCREAMING_SNAKE_CASE:						List[Any])							->			List[str]:

				"""simple docstring"""

				__lowerCAmelCase :    Dict				=			value

	def 				_SCREAMING_SNAKE_CASE  (	self:						List[str]			,     _SCREAMING_SNAKE_CASE:						Tuple)							->			Optional[int]:

				"""simple docstring"""

				for layer, heads in heads_to_prune.items():
							self.encoder.layer[layer].attention.prune_heads(_SCREAMING_SNAKE_CASE)







	@add_start_docstrings_to_model_forward(_SCREAMING_SNAKE_CASE)
	def 				_SCREAMING_SNAKE_CASE  (	self:						Optional[Any]			,     _SCREAMING_SNAKE_CASE:						Optional[Any]=None			,     _SCREAMING_SNAKE_CASE:						Optional[int]=None			,     _SCREAMING_SNAKE_CASE:						Optional[int]=None			,     _SCREAMING_SNAKE_CASE:						Optional[Any]=None			,     _SCREAMING_SNAKE_CASE:						Any=None			,     _SCREAMING_SNAKE_CASE:						int=None			,     _SCREAMING_SNAKE_CASE:						Union[str, Any]=None			,     _SCREAMING_SNAKE_CASE:						List[Any]=None			,     )							->			Dict:

				"""simple docstring"""

				if input_ids is not None and inputs_embeds is not None:
							raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
				elif input_ids is not None:
							__lowerCAmelCase :    Tuple				=			input_ids.size()
				elif inputs_embeds is not None:
							__lowerCAmelCase :    List[str]				=			inputs_embeds.size()[:-1]
				else:
							raise ValueError("You have to specify either input_ids or inputs_embeds")

				__lowerCAmelCase :    Any				=			input_ids.device if input_ids is not None else inputs_embeds.device

				if attention_mask is None:
							__lowerCAmelCase :    Union[str, Any]				=			torch.ones(_SCREAMING_SNAKE_CASE			,     device=_SCREAMING_SNAKE_CASE)
				if encoder_attention_mask is None:
							__lowerCAmelCase :    Tuple				=			torch.ones(_SCREAMING_SNAKE_CASE			,     device=_SCREAMING_SNAKE_CASE)
				if token_type_ids is None:
							__lowerCAmelCase :    Union[str, Any]				=			torch.zeros(_SCREAMING_SNAKE_CASE			,     dtype=torch.long			,     device=_SCREAMING_SNAKE_CASE)

				# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
				# ourselves in which case we just need to make it broadcastable to all heads.
				__lowerCAmelCase :    torch.Tensor				=			self.get_extended_attention_mask(_SCREAMING_SNAKE_CASE			,     _SCREAMING_SNAKE_CASE			,     _SCREAMING_SNAKE_CASE)

				# If a 2D ou 3D attention mask is provided for the cross-attention
				# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
				if encoder_attention_mask.dim() == 3:
							__lowerCAmelCase :    Union[str, Any]				=			encoder_attention_mask[:, None, :, :]
				if encoder_attention_mask.dim() == 2:
							__lowerCAmelCase :    Optional[Any]				=			encoder_attention_mask[:, None, None, :]

				__lowerCAmelCase :    List[str]				=			encoder_extended_attention_mask.to(
				    dtype=next(self.parameters()).dtype)  # fp16 compatibility
				__lowerCAmelCase :    Union[str, Any]				=			(1.0 - encoder_extended_attention_mask) * -1_0000.0

				# Prepare head mask if needed
				# 1.0 in head_mask indicate we keep the head
				# attention_probs has shape bsz x n_heads x N x N
				# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
				# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
				__lowerCAmelCase :    Union[str, Any]				=			self.get_head_mask(_SCREAMING_SNAKE_CASE			,     self.config.num_hidden_layers)

				__lowerCAmelCase :    Union[str, Any]				=			self.embeddings(
				    input_ids=_SCREAMING_SNAKE_CASE			,     position_ids=_SCREAMING_SNAKE_CASE			,     token_type_ids=_SCREAMING_SNAKE_CASE			,     inputs_embeds=_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase :    Optional[Any]				=			self.encoder(
				    _SCREAMING_SNAKE_CASE			,     attention_mask=_SCREAMING_SNAKE_CASE			,     head_mask=_SCREAMING_SNAKE_CASE			,     encoder_hidden_states=_SCREAMING_SNAKE_CASE			,     encoder_attention_mask=_SCREAMING_SNAKE_CASE			,     )
				__lowerCAmelCase :    List[str]				=			encoder_outputs[0]
				__lowerCAmelCase :    Union[str, Any]				=			self.pooler(_SCREAMING_SNAKE_CASE)

				__lowerCAmelCase :    Dict				=			(
				    sequence_output,
				    pooled_output,
				) + encoder_outputs[
				    1:
				]  # add hidden_states and attentions if they are here
				return outputs  # sequence_output, pooled_output, (hidden_states), (attentions), highway exits






class      A__  (    __SCREAMING_SNAKE_CASE				):




	'''simple docstring'''





	def __init__(	self:						Optional[Any]			,     _SCREAMING_SNAKE_CASE:						Optional[Any]			,     _SCREAMING_SNAKE_CASE:						Dict)							->			Optional[Any]:

				"""simple docstring"""

				__lowerCAmelCase :    List[Any]				=			message
				__lowerCAmelCase :    Union[str, Any]				=			exit_layer  # start from 1!






class      A__  (    nn.Module				):




	'''simple docstring'''





	def __init__(	self:						Dict			,     _SCREAMING_SNAKE_CASE:						Dict)							->			str:

				"""simple docstring"""

				super().__init__()
				__lowerCAmelCase :    Optional[int]				=			BertPooler(_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase :    Optional[int]				=			nn.Dropout(config.hidden_dropout_prob)
				__lowerCAmelCase :    Optional[Any]				=			nn.Linear(config.hidden_size			,     config.num_labels)







	def 				_SCREAMING_SNAKE_CASE  (	self:						int			,     _SCREAMING_SNAKE_CASE:						str)							->			List[str]:

				"""simple docstring"""

				__lowerCAmelCase :    Dict				=			encoder_outputs[0]
				__lowerCAmelCase :    Union[str, Any]				=			self.pooler(_SCREAMING_SNAKE_CASE)
				# "return" pooler_output

				# BertModel
				__lowerCAmelCase :    str				=			(pooler_input, pooler_output) + encoder_outputs[1:]
				# "return" bmodel_output

				# Dropout and classification
				__lowerCAmelCase :    Tuple				=			bmodel_output[1]

				__lowerCAmelCase :    int				=			self.dropout(_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase :    Union[str, Any]				=			self.classifier(_SCREAMING_SNAKE_CASE)

				return logits, pooled_output






@add_start_docstrings(
    'Bert Model (with early exiting - DeeBERT) with a classifier on top,\n    also takes care of multi-layer training. '    ,						__SCREAMING_SNAKE_CASE    ,						)
class      A__  (    __SCREAMING_SNAKE_CASE				):




	'''simple docstring'''





	def __init__(	self:						Optional[Any]			,     _SCREAMING_SNAKE_CASE:						Union[str, Any])							->			Dict:

				"""simple docstring"""

				super().__init__(_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase :    Optional[int]				=			config.num_labels
				__lowerCAmelCase :    Tuple				=			config.num_hidden_layers

				__lowerCAmelCase :    Optional[Any]				=			DeeBertModel(_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase :    List[Any]				=			nn.Dropout(config.hidden_dropout_prob)
				__lowerCAmelCase :    Dict				=			nn.Linear(config.hidden_size			,     self.config.num_labels)

				self.init_weights()







	@add_start_docstrings_to_model_forward(_SCREAMING_SNAKE_CASE)
	def 				_SCREAMING_SNAKE_CASE  (	self:						Dict			,     _SCREAMING_SNAKE_CASE:						List[str]=None			,     _SCREAMING_SNAKE_CASE:						Any=None			,     _SCREAMING_SNAKE_CASE:						Dict=None			,     _SCREAMING_SNAKE_CASE:						Optional[Any]=None			,     _SCREAMING_SNAKE_CASE:						Dict=None			,     _SCREAMING_SNAKE_CASE:						Union[str, Any]=None			,     _SCREAMING_SNAKE_CASE:						List[Any]=None			,     _SCREAMING_SNAKE_CASE:						Optional[Any]=-1			,     _SCREAMING_SNAKE_CASE:						str=False			,     )							->			List[Any]:

				"""simple docstring"""

				__lowerCAmelCase :    str				=			self.num_layers
				try:
							__lowerCAmelCase :    Optional[int]				=			self.bert(
							    _SCREAMING_SNAKE_CASE			,     attention_mask=_SCREAMING_SNAKE_CASE			,     token_type_ids=_SCREAMING_SNAKE_CASE			,     position_ids=_SCREAMING_SNAKE_CASE			,     head_mask=_SCREAMING_SNAKE_CASE			,     inputs_embeds=_SCREAMING_SNAKE_CASE			,     )
							# sequence_output, pooled_output, (hidden_states), (attentions), highway exits

							__lowerCAmelCase :    Tuple				=			outputs[1]

							__lowerCAmelCase :    Union[str, Any]				=			self.dropout(_SCREAMING_SNAKE_CASE)
							__lowerCAmelCase :    List[str]				=			self.classifier(_SCREAMING_SNAKE_CASE)
							__lowerCAmelCase :    Union[str, Any]				=			(logits,) + outputs[2:]  # add hidden states and attention if they are here
				except HighwayException as e:
							__lowerCAmelCase :    str				=			e.message
							__lowerCAmelCase :    Optional[Any]				=			e.exit_layer
							__lowerCAmelCase :    Optional[Any]				=			outputs[0]

				if not self.training:
							__lowerCAmelCase :    int				=			entropy(_SCREAMING_SNAKE_CASE)
							__lowerCAmelCase :    str				=			[]
							__lowerCAmelCase :    Union[str, Any]				=			[]
				if labels is not None:
							if self.num_labels == 1:
										#  We are doing regression
										__lowerCAmelCase :    Optional[int]				=			MSELoss()
										__lowerCAmelCase :    List[Any]				=			loss_fct(logits.view(-1)			,     labels.view(-1))
							else:
										__lowerCAmelCase :    Optional[int]				=			CrossEntropyLoss()
										__lowerCAmelCase :    Tuple				=			loss_fct(logits.view(-1			,     self.num_labels)			,     labels.view(-1))

							# work with highway exits
							__lowerCAmelCase :    List[str]				=			[]
							for highway_exit in outputs[-1]:
										__lowerCAmelCase :    List[Any]				=			highway_exit[0]
										if not self.training:
													highway_logits_all.append(_SCREAMING_SNAKE_CASE)
													highway_entropy.append(highway_exit[2])
										if self.num_labels == 1:
													#  We are doing regression
													__lowerCAmelCase :    Optional[int]				=			MSELoss()
													__lowerCAmelCase :    str				=			loss_fct(highway_logits.view(-1)			,     labels.view(-1))
										else:
													__lowerCAmelCase :    int				=			CrossEntropyLoss()
													__lowerCAmelCase :    Optional[Any]				=			loss_fct(highway_logits.view(-1			,     self.num_labels)			,     labels.view(-1))
										highway_losses.append(_SCREAMING_SNAKE_CASE)

							if train_highway:
										__lowerCAmelCase :    List[Any]				=			(sum(highway_losses[:-1]),) + outputs
										# exclude the final highway, of course
							else:
										__lowerCAmelCase :    int				=			(loss,) + outputs
				if not self.training:
							__lowerCAmelCase :    Any				=			outputs + ((original_entropy, highway_entropy), exit_layer)
							if output_layer >= 0:
										__lowerCAmelCase :    Any				=			(
										    (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:]
										)  # use the highway of the last layer

				return outputs  # (loss), logits, (hidden_states), (attentions), (highway_exits)