





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

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

     lowerCamelCase__					:   str      				=	self.get_config()

     return config, pixel_values, labels
 def   A_			(   self						:   List[Any]			)    ->			Optional[int]:
     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   A_			(   self						:   Tuple    ,  UpperCAmelCase						:   Optional[int]    ,  UpperCAmelCase						:   Optional[int]    ,  UpperCAmelCase						:   Optional[int]			)    ->			List[str]:
     lowerCamelCase__					:   Tuple      				=	FocalNetModel(config=__a			)
     model.to(__a			)
     model.eval()
     lowerCamelCase__					:   Tuple      				=	model(__a			)

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

     # 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__					:   Dict      				=	None
     lowerCamelCase__					:   Dict      				=	FocalNetBackbone(config=__a			)
     model.to(__a			)
     model.eval()
     lowerCamelCase__					:   Any      				=	model(__a			)

     # 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   A_			(   self						:   Optional[int]    ,  UpperCAmelCase						:   Optional[int]    ,  UpperCAmelCase						:   Optional[int]    ,  UpperCAmelCase						:   Optional[int]			)    ->			List[str]:
     lowerCamelCase__					:   Tuple      				=	FocalNetForMaskedImageModeling(config=__a			)
     model.to(__a			)
     model.eval()
     lowerCamelCase__					:   List[str]      				=	model(__a			)
     self.parent.assertEqual(
         result.reconstruction.shape    ,  (self.batch_size, self.num_channels, self.image_size, self.image_size)			)

     # test greyscale images
     lowerCamelCase__					:   List[str]      				=	1
     lowerCamelCase__					:   Any      				=	FocalNetForMaskedImageModeling(__a			)
     model.to(__a			)
     model.eval()

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

     # test greyscale images
     lowerCamelCase__					:   int      				=	1
     lowerCamelCase__					:   List[Any]      				=	FocalNetForImageClassification(__a			)
     model.to(__a			)
     model.eval()

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







 def   A_			(   self						:   int			)    ->			Optional[int]:
     lowerCamelCase__					:   str      				=	self.prepare_config_and_inputs()

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


@require_torch
class      lowerCAmelCase							(      __lowercase,						__lowercase,						unittest.TestCase    ):
 UpperCAmelCase__									=	(
     (
         FocalNetModel,
         FocalNetForImageClassification,
         FocalNetForMaskedImageModeling,
         FocalNetBackbone,
     )
     if is_torch_available()
     else ()
 )
 UpperCAmelCase__									=	(
     {'''feature-extraction''': FocalNetModel, '''image-classification''': FocalNetForImageClassification}
     if is_torch_available()
     else {}
 )
 UpperCAmelCase__									=	False

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

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

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

         lowerCamelCase__					:   List[Any]      				=	["""pixel_values"""]
         self.assertListEqual(arg_names[:1]    ,  __a			)
 def   A_			(   self						:   str    ,  UpperCAmelCase						:   Union[str, Any]    ,  UpperCAmelCase						:   int    ,  UpperCAmelCase						:   Tuple    ,  UpperCAmelCase						:   List[str]			)    ->			Union[str, Any]:
     lowerCamelCase__					:   List[Any]      				=	model_class(__a			)
     model.to(__a			)
     model.eval()

     with torch.no_grad():
         lowerCamelCase__					:   List[str]      				=	model(**self._prepare_for_class(__a    ,  __a			)			)

     lowerCamelCase__					:   List[str]      				=	outputs.hidden_states

     lowerCamelCase__					:   Tuple      				=	getattr(
         self.model_tester    ,  'expected_num_hidden_layers'    ,  len(self.model_tester.depths			) + 1			)
     self.assertEqual(len(__a			)    ,  __a			)

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

     lowerCamelCase__					:   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]    ,  )

     lowerCamelCase__					:   Optional[Any]      				=	outputs.reshaped_hidden_states
     self.assertEqual(len(__a			)    ,  __a			)

     lowerCamelCase__					:   Optional[int]      				=	reshaped_hidden_states[0].shape
     lowerCamelCase__					:   Tuple      				=	(
         reshaped_hidden_states[0].view(__a    ,  __a    ,  height * width			).permute(0    ,  2    ,  1			)
     )
     self.assertListEqual(
         list(reshaped_hidden_states.shape[-2:]			)    ,  [num_patches, self.model_tester.embed_dim]    ,  )
 def   A_			(   self						:   Any			)    ->			Any:
     lowerCamelCase__					:   str      				=	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__					:   List[str]      				=	True
         self.check_hidden_states_output(__a    ,  __a    ,  __a    ,  __a			)

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

         self.check_hidden_states_output(__a    ,  __a    ,  __a    ,  __a			)
 def   A_			(   self						:   str			)    ->			Union[str, Any]:
     lowerCamelCase__					:   Tuple      				=	self.model_tester.prepare_config_and_inputs_for_common()
     lowerCamelCase__					:   List[str]      				=	3

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

     lowerCamelCase__					:   Optional[Any]      				=	image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
     lowerCamelCase__					:   List[str]      				=	image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

     for model_class in self.all_model_classes[:-1]:
         lowerCamelCase__					:   str      				=	True
         self.check_hidden_states_output(__a    ,  __a    ,  __a    ,  (padded_height, padded_width)			)

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







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

     lowerCamelCase__					:   int      				=	_config_zero_init(__a			)
     for model_class in self.all_model_classes:
         lowerCamelCase__					:   int      				=	model_class(config=__a			)
         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      lowerCAmelCase							(      unittest.TestCase    ):
 @cached_property
 def   A_			(   self						:   Optional[int]			)    ->			Optional[Any]:
     # TODO update organization
     return AutoImageProcessor.from_pretrained('microsoft/focalnet-tiny'			) if is_vision_available() else None







 @slow
 def   A_			(   self						:   int			)    ->			Optional[Any]:
     lowerCamelCase__					:   Tuple      				=	FocalNetForImageClassification.from_pretrained('microsoft/focalnet-tiny'			).to(__a			)
     lowerCamelCase__					:   Any      				=	self.default_image_processor

     lowerCamelCase__					:   Union[str, Any]      				=	Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'			)
     lowerCamelCase__					:   int      				=	image_processor(images=__a    ,  return_tensors='pt'			).to(__a			)

     # forward pass
     with torch.no_grad():
         lowerCamelCase__					:   Any      				=	model(**__a			)

     # verify the logits
     lowerCamelCase__					:   Tuple      				=	torch.Size((1, 1000)			)
     self.assertEqual(outputs.logits.shape    ,  __a			)
     lowerCamelCase__					:   List[str]      				=	torch.tensor([0.2_1_6_6, -0.4_3_6_8, 0.2_1_9_1]			).to(__a			)
     self.assertTrue(torch.allclose(outputs.logits[0, :3]    ,  __a    ,  atol=1e-4			)			)
     self.assertTrue(outputs.logits.argmax(dim=-1			).item()    ,  281			)


@require_torch
class      lowerCAmelCase							(      __lowercase,						unittest.TestCase    ):
 UpperCAmelCase__									=	(FocalNetBackbone,) if is_torch_available() else ()
 UpperCAmelCase__									=	FocalNetConfig

 UpperCAmelCase__									=	False
 def   A_			(   self						:   Union[str, Any]			)    ->			Tuple:
     lowerCamelCase__					:   str      				=	FocalNetModelTester(self			)












from collections import defaultdict
from math import ceil, sqrt


def  SCREAMING_SNAKE_CASE   ( _UpperCAmelCase = 100_0000		,			_UpperCAmelCase = 10				)    ->  int:
    lowerCamelCase__					:   defaultdict      				=	defaultdict(_UpperCAmelCase				)

    for outer_width in range(3		,			(t_limit // 4) + 2				):
        if outer_width * outer_width > t_limit:
            lowerCamelCase__					:   List[str]      				=	max(
                ceil(sqrt(outer_width * outer_width - t_limit				)				)		,			1				)
        else:
            lowerCamelCase__					:   int      				=	1

        hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2

        for hole_width in range(_UpperCAmelCase		,			outer_width - 1		,			2				):
            count[outer_width * outer_width - hole_width * hole_width] += 1

    return sum(1 for n in count.values() if 1 <= n <= 10				)


if __name__ == "__main__":
    print(F"""{solution() = }""")





