


import copy
import inspect
import unittest

from transformers import PretrainedConfig, SwiftFormerConfig
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_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
   import torch
   from torch import nn

   from transformers import SwiftFormerForImageClassification, SwiftFormerModel
   from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
   from PIL import Image

   from transformers import ViTImageProcessor
class       UpperCAmelCase_   :

   '''simple docstring'''




   def __init__(						self		,							__A		,							__A=13		,							__A=3		,							__A=True		,							__A=True		,							__A=0.1		,							__A=0.1		,							__A=224		,							__A=1000		,							__A=[3, 3, 6, 4]		,							__A=[48, 56, 112, 220]		,							):






     """simple docstring"""





     lowerCamelCase					:   int       =							parent
     lowerCamelCase					:   int       =							batch_size
     lowerCamelCase					:   str       =							num_channels
     lowerCamelCase					:   str       =							is_training
     lowerCamelCase					:   List[str]       =							use_labels
     lowerCamelCase					:   Dict       =							hidden_dropout_prob
     lowerCamelCase					:   Tuple       =							attention_probs_dropout_prob
     lowerCamelCase					:   int       =							num_labels
     lowerCamelCase					:   Any       =							image_size
     lowerCamelCase					:   Any       =							layer_depths
     lowerCamelCase					:   int       =							embed_dims






   def _snake_case       (						self					):






     """simple docstring"""





     lowerCamelCase					:   List[Any]       =							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

     lowerCamelCase					:   List[str]       =							None
     if self.use_labels:
       lowerCamelCase					:   Optional[int]       =							ids_tensor([self.batch_size]		,							self.num_labels					)

     lowerCamelCase					:   Tuple       =							self.get_config()

     return config, pixel_values, labels






   def _snake_case       (						self					):






     """simple docstring"""





     return SwiftFormerConfig(
         depths=self.layer_depths		,							embed_dims=self.embed_dims		,							mlp_ratio=4		,							downsamples=[True, True, True, True]		,							hidden_act="gelu"		,							num_labels=self.num_labels		,							down_patch_size=3		,							down_stride=2		,							down_pad=1		,							drop_rate=0.0		,							drop_path_rate=0.0		,							use_layer_scale=_SCREAMING_SNAKE_CASE		,							layer_scale_init_value=1e-5		,							)






   def _snake_case       (						self		,							__A		,							__A		,							__A					):






     """simple docstring"""





     lowerCamelCase					:   Dict       =							SwiftFormerModel(config=_SCREAMING_SNAKE_CASE					)
     model.to(_SCREAMING_SNAKE_CASE					)
     model.eval()
     lowerCamelCase					:   Optional[Any]       =							model(_SCREAMING_SNAKE_CASE					)
     self.parent.assertEqual(result.last_hidden_state.shape		,							(self.batch_size, self.embed_dims[-1], 7, 7)					)






   def _snake_case       (						self		,							__A		,							__A		,							__A					):






     """simple docstring"""





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

     lowerCamelCase					:   Union[str, Any]       =							SwiftFormerForImageClassification(_SCREAMING_SNAKE_CASE					)
     model.to(_SCREAMING_SNAKE_CASE					)
     model.eval()

     lowerCamelCase					:   List[Any]       =							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)
     lowerCamelCase					:   Dict       =							model(_SCREAMING_SNAKE_CASE					)
     self.parent.assertEqual(result.logits.shape		,							(self.batch_size, self.num_labels)					)






   def _snake_case       (						self					):






     """simple docstring"""





     ((lowerCamelCase)       ,      (lowerCamelCase)       ,      (lowerCamelCase))					:   Dict       =							self.prepare_config_and_inputs()
     lowerCamelCase					:   int       =							{"pixel_values": pixel_values}
     return config, inputs_dict



@require_torch
class       UpperCAmelCase_   (   __lowerCAmelCase						,					__lowerCAmelCase						,					unittest.TestCase       ):

   '''simple docstring'''




   __A					: Any							=						(SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else ()
   __A					: str							=						(
       {"""feature-extraction""": SwiftFormerModel, """image-classification""": SwiftFormerForImageClassification}
       if is_torch_available()
       else {}
   )

   __A					: int							=						False
   __A					: str							=						False
   __A					: Optional[int]							=						False
   __A					: List[str]							=						False
   __A					: int							=						False






   def _snake_case       (						self					):






     """simple docstring"""





     lowerCamelCase					:   List[str]       =							SwiftFormerModelTester(self					)
     lowerCamelCase					:   int       =							ConfigTester(
         self		,							config_class=_SCREAMING_SNAKE_CASE		,							has_text_modality=_SCREAMING_SNAKE_CASE		,							hidden_size=37		,							num_attention_heads=12		,							num_hidden_layers=12		,							)






   def _snake_case       (						self					):






     """simple docstring"""





     self.config_tester.run_common_tests()






   @unittest.skip(reason="SwiftFormer does not use inputs_embeds"					)
   def _snake_case       (						self					):






     """simple docstring"""





     pass






   def _snake_case       (						self					):






     """simple docstring"""





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

     for model_class in self.all_model_classes:
       lowerCamelCase					:   Optional[Any]       =							model_class(_SCREAMING_SNAKE_CASE					)
       lowerCamelCase					:   str       =							model.get_output_embeddings()
       self.assertTrue(x is None or isinstance(_SCREAMING_SNAKE_CASE		,							nn.Linear					)					)






   def _snake_case       (						self					):






     """simple docstring"""





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

     for model_class in self.all_model_classes:
       lowerCamelCase					:   Union[str, Any]       =							model_class(_SCREAMING_SNAKE_CASE					)
       lowerCamelCase					:   Any       =							inspect.signature(model.forward					)
       # signature.parameters is an OrderedDict => so arg_names order is deterministic
       lowerCamelCase					:   List[str]       =							[*signature.parameters.keys()]

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






   def _snake_case       (						self					):






     """simple docstring"""





     lowerCamelCase					:   List[str]       =							self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE					)






   def _snake_case       (						self					):






     """simple docstring"""





     lowerCamelCase					:   Dict       =							self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE					)






   @slow
   def _snake_case       (						self					):






     """simple docstring"""





     for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       lowerCamelCase					:   Union[str, Any]       =							SwiftFormerModel.from_pretrained(_SCREAMING_SNAKE_CASE					)
       self.assertIsNotNone(_SCREAMING_SNAKE_CASE					)






   @unittest.skip(reason="SwiftFormer does not output attentions"					)
   def _snake_case       (						self					):






     """simple docstring"""





     pass






   def _snake_case       (						self					):






     """simple docstring"""





     def check_hidden_states_output(__A		,							__A		,							__A					):
       lowerCamelCase					:   Tuple       =							model_class(_SCREAMING_SNAKE_CASE					)
       model.to(_SCREAMING_SNAKE_CASE					)
       model.eval()

       with torch.no_grad():
         lowerCamelCase					:   Optional[Any]       =							model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE		,							_SCREAMING_SNAKE_CASE					)					)

       lowerCamelCase					:   Union[str, Any]       =							outputs.hidden_states

       lowerCamelCase					:   int       =							8
       self.assertEqual(len(_SCREAMING_SNAKE_CASE					)		,							_SCREAMING_SNAKE_CASE					)  # TODO

       # SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width)
       # with the width and height being successively divided by 2, after every 2 blocks
       for i in range(len(_SCREAMING_SNAKE_CASE					)					):
         self.assertEqual(
             hidden_states[i].shape		,							torch.Size(
                 [
                     self.model_tester.batch_size,
                     self.model_tester.embed_dims[i // 2],
                     (self.model_tester.image_size // 4) // 2 ** (i // 2),
                     (self.model_tester.image_size // 4) // 2 ** (i // 2),
                 ]					)		,							)

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

     for model_class in self.all_model_classes:
       lowerCamelCase					:   Dict       =							True
       check_hidden_states_output(_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					:   Optional[Any]       =							True

       check_hidden_states_output(_SCREAMING_SNAKE_CASE		,							_SCREAMING_SNAKE_CASE		,							_SCREAMING_SNAKE_CASE					)






   def _snake_case       (						self					):






     """simple docstring"""





     def _config_zero_init(__A					):
       lowerCamelCase					:   Optional[Any]       =							copy.deepcopy(_SCREAMING_SNAKE_CASE					)
       for key in configs_no_init.__dict__.keys():
         if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key:
           setattr(_SCREAMING_SNAKE_CASE		,							_SCREAMING_SNAKE_CASE		,							1e-10					)
         if isinstance(getattr(_SCREAMING_SNAKE_CASE		,							_SCREAMING_SNAKE_CASE		,							_SCREAMING_SNAKE_CASE					)		,							_SCREAMING_SNAKE_CASE					):
           lowerCamelCase					:   Optional[int]       =							_config_zero_init(getattr(_SCREAMING_SNAKE_CASE		,							_SCREAMING_SNAKE_CASE					)					)
           setattr(_SCREAMING_SNAKE_CASE		,							_SCREAMING_SNAKE_CASE		,							_SCREAMING_SNAKE_CASE					)
       return configs_no_init

     lowerCamelCase       ,      lowerCamelCase					:   Dict       =							self.model_tester.prepare_config_and_inputs_for_common()

     lowerCamelCase					:   List[Any]       =							_config_zero_init(_SCREAMING_SNAKE_CASE					)
     for model_class in self.all_model_classes:
       lowerCamelCase					:   int       =							model_class(config=_SCREAMING_SNAKE_CASE					)
       for name, param in model.named_parameters():
         if param.requires_grad:
           self.assertIn(
               ((param.data.mean() * 1e9) / 1e9).round().item()		,							[0.0, 1.0]		,							msg=F"""Parameter {name} of model {model_class} seems not properly initialized"""		,							)






   @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."					)
   def _snake_case       (						self					):






     """simple docstring"""





     pass






def 						lowercase_(    ):


  '''simple docstring'''

  lowerCamelCase					:   List[Any]       =							Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"      )
  return image







@require_torch
@require_vision
class       UpperCAmelCase_   (   unittest.TestCase       ):

   '''simple docstring'''




   @cached_property
   def _snake_case       (						self					):






     """simple docstring"""





     return ViTImageProcessor.from_pretrained("MBZUAI/swiftformer-xs"					) if is_vision_available() else None






   @slow
   def _snake_case       (						self					):






     """simple docstring"""





     lowerCamelCase					:   List[Any]       =							SwiftFormerForImageClassification.from_pretrained("MBZUAI/swiftformer-xs"					).to(_SCREAMING_SNAKE_CASE					)

     lowerCamelCase					:   Union[str, Any]       =							self.default_image_processor
     lowerCamelCase					:   str       =							prepare_img()
     lowerCamelCase					:   Any       =							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					:   int       =							torch.Size((1, 1000)					)
     self.assertEqual(outputs.logits.shape		,							_SCREAMING_SNAKE_CASE					)

     lowerCamelCase					:   Optional[int]       =							torch.tensor([[-2.17_03e00, 2.11_07e00, -2.08_11e00]]					).to(_SCREAMING_SNAKE_CASE					)
     self.assertTrue(torch.allclose(outputs.logits[0, :3]		,							_SCREAMING_SNAKE_CASE		,							atol=1e-4					)					)









'''simple docstring'''





from math import ceil





def       __a      (  _UpperCamelCase:       int = 1_001       )		->					int:

     """simple docstring"""




     _snake_case				= 1

     for i in range(1   ,		int(ceil(n / 2.0       )       )       ):
          _snake_case				= 2 * i + 1
          _snake_case				= 2 * i
          _snake_case				= total + 4 * odd**2 - 6 * even

     return total


if __name__ == "__main__":
   import sys

   if len(sys.argv) == 1:
      print(solution())
   else:
      try:
         UpperCamelCase_		:     int          =		int(sys.argv[1])
         print(solution(n))
      except ValueError:
         print('''Invalid entry - please enter a number''')


