






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 							__magic_name__     :







	"""simple docstring"""



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

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

							lowercase_      :   Any        =			self.get_config()

							return config, pixel_values, labels
	def        lowerCamelCase__		(							self       )						->  Union[str, 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        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase  ,      _lowercase       )						->  List[Any]:
							lowercase_      :   List[Any]        =			FocalNetModel(config=_lowercase       )
							model.to(_lowercase       )
							model.eval()
							lowercase_      :   Any        =			model(_lowercase       )

							lowercase_      :   Optional[int]        =			((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths       ) - 1))
							lowercase_      :   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        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase  ,      _lowercase       )						->  List[str]:
							lowercase_      :   List[Any]        =			FocalNetBackbone(config=_lowercase       )
							model.to(_lowercase       )
							model.eval()
							lowercase_      :   List[str]        =			model(_lowercase       )

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

							# 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  ,      _lowercase  ,      _lowercase  ,      _lowercase       )						->  int:
							lowercase_      :   Any        =			FocalNetForMaskedImageModeling(config=_lowercase       )
							model.to(_lowercase       )
							model.eval()
							lowercase_      :   str        =			model(_lowercase       )
							self.parent.assertEqual(
							    result.reconstruction.shape  ,      (self.batch_size, self.num_channels, self.image_size, self.image_size)       )

							# test greyscale images
							lowercase_      :   Union[str, Any]        =			1
							lowercase_      :   str        =			FocalNetForMaskedImageModeling(_lowercase       )
							model.to(_lowercase       )
							model.eval()

							lowercase_      :   str        =			floats_tensor([self.batch_size, 1, self.image_size, self.image_size]       )
							lowercase_      :   Optional[int]        =			model(_lowercase       )
							self.parent.assertEqual(result.reconstruction.shape  ,      (self.batch_size, 1, self.image_size, self.image_size)       )
	def        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase  ,      _lowercase       )						->  Union[str, Any]:
							lowercase_      :   List[Any]        =			self.type_sequence_label_size
							lowercase_      :   int        =			FocalNetForImageClassification(_lowercase       )
							model.to(_lowercase       )
							model.eval()
							lowercase_      :   str        =			model(_lowercase  ,      labels=_lowercase       )
							self.parent.assertEqual(result.logits.shape  ,      (self.batch_size, self.type_sequence_label_size)       )

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

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







	def        lowerCamelCase__		(							self       )						->  Any:
							lowercase_      :   List[str]        =			self.prepare_config_and_inputs()

							lowercase_      :   str        =			config_and_inputs
							lowercase_      :   Any        =			{"pixel_values": pixel_values}
							return config, inputs_dict






@require_torch
class 							__magic_name__     (	_A,						_A,						unittest.TestCase				):







	"""simple docstring"""



	SCREAMING_SNAKE_CASE_					:      Optional[int]        =  (
	    (
	        FocalNetModel,
	        FocalNetForImageClassification,
	        FocalNetForMaskedImageModeling,
	        FocalNetBackbone,
	    )
	    if is_torch_available()
	    else ()
	)
	SCREAMING_SNAKE_CASE_					:      Optional[int]        =  (
	    {'feature-extraction': FocalNetModel, 'image-classification': FocalNetForImageClassification}
	    if is_torch_available()
	    else {}
	)
	SCREAMING_SNAKE_CASE_					:      Dict        =  False

	SCREAMING_SNAKE_CASE_					:      List[str]        =  False
	SCREAMING_SNAKE_CASE_					:      Union[str, Any]        =  False
	SCREAMING_SNAKE_CASE_					:      Union[str, Any]        =  False
	SCREAMING_SNAKE_CASE_					:      List[str]        =  False
	def        lowerCamelCase__		(							self       )						->  Union[str, Any]:
							lowercase_      :   Any        =			FocalNetModelTester(self       )
							lowercase_      :   Any        =			ConfigTester(self  ,      config_class=_lowercase  ,      embed_dim=37  ,      has_text_modality=_lowercase       )
	def        lowerCamelCase__		(							self       )						->  Tuple:
							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       )						->  str:
							return
	def        lowerCamelCase__		(							self       )						->  List[Any]:
							lowercase_      :   str        =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*_lowercase       )
	def        lowerCamelCase__		(							self       )						->  str:
							lowercase_      :   Optional[Any]        =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_backbone(*_lowercase       )
	def        lowerCamelCase__		(							self       )						->  Optional[Any]:
							lowercase_      :   Tuple        =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_masked_image_modeling(*_lowercase       )
	def        lowerCamelCase__		(							self       )						->  List[str]:
							lowercase_      :   Optional[Any]        =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*_lowercase       )
	@unittest.skip(reason='FocalNet does not use inputs_embeds'       )
	def        lowerCamelCase__		(							self       )						->  Dict:
							pass
	@unittest.skip(reason='FocalNet does not use feedforward chunking'       )
	def        lowerCamelCase__		(							self       )						->  List[Any]:
							pass
	def        lowerCamelCase__		(							self       )						->  Dict:
							lowercase_      :   int        =			self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes[:-1]:
													lowercase_      :   List[Any]        =			model_class(_lowercase       )
													self.assertIsInstance(model.get_input_embeddings()  ,      (nn.Module)       )
													lowercase_      :   Tuple        =			model.get_output_embeddings()
													self.assertTrue(x is None or isinstance(_lowercase  ,      nn.Linear       )       )
	def        lowerCamelCase__		(							self       )						->  str:
							lowercase_      :   List[str]        =			self.model_tester.prepare_config_and_inputs_for_common()

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

													lowercase_      :   List[str]        =			["pixel_values"]
													self.assertListEqual(arg_names[:1]  ,      _lowercase       )
	def        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase       )						->  Optional[int]:
							lowercase_      :   List[str]        =			model_class(_lowercase       )
							model.to(_lowercase       )
							model.eval()

							with torch.no_grad():
													lowercase_      :   Any        =			model(**self._prepare_for_class(_lowercase  ,      _lowercase       )       )

							lowercase_      :   Optional[int]        =			outputs.hidden_states

							lowercase_      :   Union[str, Any]        =			getattr(
							    self.model_tester  ,      'expected_num_hidden_layers'  ,      len(self.model_tester.depths       ) + 1       )
							self.assertEqual(len(_lowercase       )  ,      _lowercase       )

							# FocalNet has a different seq_length
							lowercase_      :   List[str]        =			(
							    config.patch_size
							    if isinstance(config.patch_size  ,      collections.abc.Iterable       )
							    else (config.patch_size, config.patch_size)
							)

							lowercase_      :   Dict        =			(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]  ,      )

							lowercase_      :   List[str]        =			outputs.reshaped_hidden_states
							self.assertEqual(len(_lowercase       )  ,      _lowercase       )

							lowercase_      :   Dict        =			reshaped_hidden_states[0].shape
							lowercase_      :   Any        =			(
							    reshaped_hidden_states[0].view(_lowercase  ,      _lowercase  ,      height * width       ).permute(0  ,      2  ,      1       )
							)
							self.assertListEqual(
							    list(reshaped_hidden_states.shape[-2:]       )  ,      [num_patches, self.model_tester.embed_dim]  ,      )
	def        lowerCamelCase__		(							self       )						->  str:
							lowercase_      :   List[Any]        =			self.model_tester.prepare_config_and_inputs_for_common()

							lowercase_      :   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]:
													lowercase_      :   List[Any]        =			True
													self.check_hidden_states_output(_lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase       )

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

													self.check_hidden_states_output(_lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase       )
	def        lowerCamelCase__		(							self       )						->  List[Any]:
							lowercase_      :   List[Any]        =			self.model_tester.prepare_config_and_inputs_for_common()
							lowercase_      :   List[Any]        =			3

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

							lowercase_      :   Tuple        =			image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
							lowercase_      :   Optional[int]        =			image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

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

													# check that output_hidden_states also work using config
													del inputs_dict["output_hidden_states"]
													lowercase_      :   int        =			True
													self.check_hidden_states_output(_lowercase  ,      _lowercase  ,      _lowercase  ,      (padded_height, padded_width)       )
	@slow
	def        lowerCamelCase__		(							self       )						->  str:
							for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													lowercase_      :   Tuple        =			FocalNetModel.from_pretrained(_lowercase       )
													self.assertIsNotNone(_lowercase       )







	def        lowerCamelCase__		(							self       )						->  str:
							lowercase_      :   List[Any]        =			self.model_tester.prepare_config_and_inputs_for_common()

							lowercase_      :   int        =			_config_zero_init(_lowercase       )
							for model_class in self.all_model_classes:
													lowercase_      :   Dict        =			model_class(config=_lowercase       )
													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 							__magic_name__     (	unittest.TestCase				):







	"""simple docstring"""



	@cached_property
	def        lowerCamelCase__		(							self       )						->  Union[str, Any]:
							# TODO update organization
							return AutoImageProcessor.from_pretrained('microsoft/focalnet-tiny'       ) if is_vision_available() else None







	@slow
	def        lowerCamelCase__		(							self       )						->  Optional[int]:
							lowercase_      :   str        =			FocalNetForImageClassification.from_pretrained('microsoft/focalnet-tiny'       ).to(_lowercase       )
							lowercase_      :   Optional[int]        =			self.default_image_processor

							lowercase_      :   Tuple        =			Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'       )
							lowercase_      :   int        =			image_processor(images=_lowercase  ,      return_tensors='pt'       ).to(_lowercase       )

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

							# verify the logits
							lowercase_      :   Tuple        =			torch.Size((1, 1000)       )
							self.assertEqual(outputs.logits.shape  ,      _lowercase       )
							lowercase_      :   Union[str, Any]        =			torch.tensor([0.21_66, -0.43_68, 0.21_91]       ).to(_lowercase       )
							self.assertTrue(torch.allclose(outputs.logits[0, :3]  ,      _lowercase  ,      atol=1E-4       )       )
							self.assertTrue(outputs.logits.argmax(dim=-1       ).item()  ,      281       )






@require_torch
class 							__magic_name__     (	_A,						unittest.TestCase				):







	"""simple docstring"""



	SCREAMING_SNAKE_CASE_					:      str        =  (FocalNetBackbone,) if is_torch_available() else ()
	SCREAMING_SNAKE_CASE_					:      int        =  FocalNetConfig

	SCREAMING_SNAKE_CASE_					:      Optional[Any]        =  False
	def        lowerCamelCase__		(							self       )						->  Optional[int]:
							lowercase_      :   Any        =			FocalNetModelTester(self       )








'''simple docstring'''

def 	_UpperCAmelCase    (  a		:	str						,			a		:	str							)			->			float:





						"""simple docstring"""

						def get_matched_characters(a		:	str						,			a		:	str							) -> str:
												lowercase_      :   Union[str, Any]        =			[]
												lowercase_      :   Tuple        =			min(len(_stra							)						,			len(_stra							)							) // 2
												for i, l in enumerate(_stra							):
																		lowercase_      :   Optional[int]        =			int(max(0						,			i - limit							)							)
																		lowercase_      :   Union[str, Any]        =			int(min(i + limit + 1						,			len(_stra							)							)							)
																		if l in _stra[left:right]:
																								matched.append(a							)
																								lowercase_      :   Union[str, Any]        =			f"{_stra[0:_stra.index(a							)]} {_stra[_stra.index(a							) + 1:]}"

												return "".join(a							)

						# matching characters
						lowercase_      :   Union[str, Any]        =			get_matched_characters(a						,			a							)
						lowercase_      :   Optional[Any]        =			get_matched_characters(a						,			a							)
						lowercase_      :   Optional[int]        =			len(a							)

						# transposition
						lowercase_      :   Dict        =			(
						    len([(ca, ca) for ca, ca in zip(a						,			a							) if ca != ca]							) // 2
						)

						if not match_count:
												lowercase_      :   List[str]        =			0.0
						else:
												lowercase_      :   Any        =			(
												    1
												    / 3
												    * (
												        match_count / len(a							)
												        + match_count / len(a							)
												        + (match_count - transpositions) / match_count
												    )
												)

						# common prefix up to 4 characters
						lowercase_      :   Optional[Any]        =			0
						for ca, ca in zip(stra[:4]						,			stra[:4]							):
												if ca == ca:
																		prefix_len += 1
												else:
																		break

						return jaro + 0.1 * prefix_len * (1 - jaro)


if __name__ == "__main__":
						import doctest

						doctest.testmod()
						print(jaro_winkler("hello", "world"))
