
import json
import os
import shutil
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError

from transformers import AutoConfig, BertConfig, GPTaConfig
from transformers.configuration_utils import PretrainedConfig
from transformers.testing_utils import TOKEN, USER, is_staging_test


sys.path.append(str(Path(__file__).parent.parent / 'utils'))

from test_module.custom_configuration import CustomConfig  # noqa E402


lowercase__          ={
    'return_dict': False,
    'output_hidden_states': True,
    'output_attentions': True,
    'torchscript': True,
    'torch_dtype': 'float16',
    'use_bfloat16': True,
    'tf_legacy_loss': True,
    'pruned_heads': {'a': 1},
    'tie_word_embeddings': False,
    'is_decoder': True,
    'cross_attention_hidden_size': 128,
    'add_cross_attention': True,
    'tie_encoder_decoder': True,
    'max_length': 50,
    'min_length': 3,
    'do_sample': True,
    'early_stopping': True,
    'num_beams': 3,
    'num_beam_groups': 3,
    'diversity_penalty': 0.5,
    'temperature': 2.0,
    'top_k': 10,
    'top_p': 0.7,
    'typical_p': 0.2,
    'repetition_penalty': 0.8,
    'length_penalty': 0.8,
    'no_repeat_ngram_size': 5,
    'encoder_no_repeat_ngram_size': 5,
    'bad_words_ids': [1, 2, 3],
    'num_return_sequences': 3,
    'chunk_size_feed_forward': 5,
    'output_scores': True,
    'return_dict_in_generate': True,
    'forced_bos_token_id': 2,
    'forced_eos_token_id': 3,
    'remove_invalid_values': True,
    'architectures': ['BertModel'],
    'finetuning_task': 'translation',
    'id2label': {0: 'label'},
    'label2id': {'label': '0'},
    'tokenizer_class': 'BertTokenizerFast',
    'prefix': 'prefix',
    'bos_token_id': 6,
    'pad_token_id': 7,
    'eos_token_id': 8,
    'sep_token_id': 9,
    'decoder_start_token_id': 10,
    'exponential_decay_length_penalty': (5, 1.01),
    'suppress_tokens': [0, 1],
    'begin_suppress_tokens': 2,
    'task_specific_params': {'translation': 'some_params'},
    'problem_type': 'regression',
}



@is_staging_test
class 		UpperCamelCase__  (	unittest.TestCase   ):
   @classmethod
   def 				lowerCAmelCase      (cls			: Dict       ):
    __a			:  Any		    =  TOKEN
    HfFolder.save_token(snake_case__       )
   @classmethod
   def 				lowerCAmelCase      (cls			: Dict       ):


    try:
     delete_repo(token=cls._token ,    repo_id='''test-config'''       )
    except HTTPError:
     pass

    try:
     delete_repo(token=cls._token ,    repo_id='''valid_org/test-config-org'''       )
    except HTTPError:
     pass

    try:
     delete_repo(token=cls._token ,    repo_id='''test-dynamic-config'''       )
    except HTTPError:
     pass
   def 				lowerCAmelCase      (self			: str       ):
    __a			:  Union[str, Any]		    =  BertConfig(
        vocab_size=9_9 ,    hidden_size=3_2 ,    num_hidden_layers=5 ,    num_attention_heads=4 ,    intermediate_size=3_7       )
    config.push_to_hub('''test-config''' ,    use_auth_token=self._token       )

    __a			:  Union[str, Any]		    =  BertConfig.from_pretrained(f"{USER}/test-config"       )
    for k, v in config.to_dict().items():
     if k != "transformers_version":
      self.assertEqual(snake_case__ ,    getattr(snake_case__ ,    snake_case__       )       )

        # Reset repo
    delete_repo(token=self._token ,    repo_id='''test-config'''       )

    # Push to hub via save_pretrained
    with tempfile.TemporaryDirectory() as tmp_dir:
     config.save_pretrained(snake_case__ ,    repo_id='''test-config''' ,    push_to_hub=snake_case__ ,    use_auth_token=self._token       )

    __a			:  Any		    =  BertConfig.from_pretrained(f"{USER}/test-config"       )
    for k, v in config.to_dict().items():
     if k != "transformers_version":
      self.assertEqual(snake_case__ ,    getattr(snake_case__ ,    snake_case__       )       )
   def 				lowerCAmelCase      (self			: Optional[int]       ):
    __a			:  List[Any]		    =  BertConfig(
        vocab_size=9_9 ,    hidden_size=3_2 ,    num_hidden_layers=5 ,    num_attention_heads=4 ,    intermediate_size=3_7       )
    config.push_to_hub('''valid_org/test-config-org''' ,    use_auth_token=self._token       )

    __a			:  Optional[int]		    =  BertConfig.from_pretrained('''valid_org/test-config-org'''       )
    for k, v in config.to_dict().items():
     if k != "transformers_version":
      self.assertEqual(snake_case__ ,    getattr(snake_case__ ,    snake_case__       )       )

        # Reset repo
    delete_repo(token=self._token ,    repo_id='''valid_org/test-config-org'''       )

    # Push to hub via save_pretrained
    with tempfile.TemporaryDirectory() as tmp_dir:
     config.save_pretrained(
         snake_case__ ,    repo_id='''valid_org/test-config-org''' ,    push_to_hub=snake_case__ ,    use_auth_token=self._token       )

    __a			:  str		    =  BertConfig.from_pretrained('''valid_org/test-config-org'''       )
    for k, v in config.to_dict().items():
     if k != "transformers_version":
      self.assertEqual(snake_case__ ,    getattr(snake_case__ ,    snake_case__       )       )







   def 				lowerCAmelCase      (self			: Tuple       ):
    CustomConfig.register_for_auto_class()
    __a			:  Union[str, Any]		    =  CustomConfig(attribute=4_2       )

    config.push_to_hub('''test-dynamic-config''' ,    use_auth_token=self._token       )

    # This has added the proper auto_map field to the config
    self.assertDictEqual(config.auto_map ,    {'''AutoConfig''': '''custom_configuration.CustomConfig'''}       )

    __a			:  int		    =  AutoConfig.from_pretrained(f"{USER}/test-dynamic-config" ,    trust_remote_code=snake_case__       )
    # Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module
    self.assertEqual(new_config.__class__.__name__ ,    '''CustomConfig'''       )
    self.assertEqual(new_config.attribute ,    4_2       )





class 		UpperCamelCase__  (	unittest.TestCase   ):
   def 				lowerCAmelCase      (self			: Optional[Any]       ):
    __a			:  Any		    =  GPTaConfig()

    # attempt to modify each of int/float/bool/str config records and verify they were updated
    __a			:  Tuple		    =  c.n_embd + 1  # int
    __a			:  str		    =  c.resid_pdrop + 1.0  # float
    __a			:  Optional[Any]		    =  not c.scale_attn_weights  # bool
    __a			:  Optional[int]		    =  c.summary_type + "foo"  # str
    c.update_from_string(
        f"n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}"       )
    self.assertEqual(snake_case__ ,    c.n_embd ,    '''mismatch for key: n_embd'''       )
    self.assertEqual(snake_case__ ,    c.resid_pdrop ,    '''mismatch for key: resid_pdrop'''       )
    self.assertEqual(snake_case__ ,    c.scale_attn_weights ,    '''mismatch for key: scale_attn_weights'''       )
    self.assertEqual(snake_case__ ,    c.summary_type ,    '''mismatch for key: summary_type'''       )
   def 				lowerCAmelCase      (self			: int       ):
    __a			:  Tuple		    =  PretrainedConfig()
    __a			:  List[str]		    =  [key for key in base_config.__dict__ if key not in config_common_kwargs]
    # If this part of the test fails, you have arguments to addin config_common_kwargs above.
    self.assertListEqual(
        snake_case__ ,    ['''is_encoder_decoder''', '''_name_or_path''', '''_commit_hash''', '''transformers_version''']       )
    __a			:  Dict		    =  [key for key, value in config_common_kwargs.items() if value == getattr(snake_case__ ,    snake_case__       )]
    if len(snake_case__       ) > 0:
     raise ValueError(
         '''The following keys are set with the default values in'''
         ''' `test_configuration_common.config_common_kwargs` pick another value for them:'''
         f" {', '.join(snake_case__       )}."       )
   def 				lowerCAmelCase      (self			: Optional[int]       ):


    with self.assertRaises(snake_case__       ):
     # config is in subfolder, the following should not work without specifying the subfolder
     __a			:  Optional[Any]		    =  BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert-subfolder'''       )

    __a			:  Optional[Any]		    =  BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert-subfolder''' ,    subfolder='''bert'''       )

    self.assertIsNotNone(snake_case__       )
   def 				lowerCAmelCase      (self			: List[str]       ):
    __a			:  Tuple		    =  mock.Mock()
    __a			:  Optional[int]		    =  5_0_0
    __a			:  Any		    =  {}
    __a			:  str		    =  HTTPError
    __a			:  Tuple		    =  {}

    # Download this model to make sure it's in the cache.
    __a			:  List[Any]		    =  BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert'''       )

    # Under the mock environment we get a 500 error when trying to reach the model.
    with mock.patch('''requests.Session.request''' ,    return_value=snake_case__       ) as mock_head:
     __a			:  List[str]		    =  BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert'''       )
     # This check we did call the fake head request
     mock_head.assert_called()
   def 				lowerCAmelCase      (self			: Any       ):
    __a			:  Dict		    =  BertConfig.from_pretrained(
        '''https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json'''       )
   def 				lowerCAmelCase      (self			: int       ):
    __a			:  Optional[Any]		    =  AutoConfig.from_pretrained('''bert-base-cased'''       )
    __a			:  int		    =  ["config.4.0.0.json"]

    with tempfile.TemporaryDirectory() as tmp_dir:
     configuration.save_pretrained(snake_case__       )
     __a			:  str		    =  2
     json.dump(configuration.to_dict() ,    open(os.path.join(snake_case__ ,    '''config.4.0.0.json'''       ) ,    '''w'''       )       )

     # This should pick the new configuration file as the version of Transformers is > 4.0.0
     __a			:  str		    =  AutoConfig.from_pretrained(snake_case__       )
     self.assertEqual(new_configuration.hidden_size ,    2       )

     # Will need to be adjusted if we reach v42 and this test is still here.
     # Should pick the old configuration file as the version of Transformers is < 4.42.0
     __a			:  List[str]		    =  ["config.42.0.0.json"]
     __a			:  Optional[int]		    =  7_6_8
     configuration.save_pretrained(snake_case__       )
     shutil.move(os.path.join(snake_case__ ,    '''config.4.0.0.json'''       ) ,    os.path.join(snake_case__ ,    '''config.42.0.0.json'''       )       )
     __a			:  Union[str, Any]		    =  AutoConfig.from_pretrained(snake_case__       )
     self.assertEqual(new_configuration.hidden_size ,    7_6_8       )







   def 				lowerCAmelCase      (self			: List[str]       ):
    __a			:  List[Any]		    =  "hf-internal-testing/test-two-configs"

    import transformers as new_transformers

    __a			:  Optional[int]		    =  "v4.0.0"
    __a			:  List[str]		    =  new_transformers.models.auto.AutoConfig.from_pretrained(
        snake_case__ ,    return_unused_kwargs=snake_case__       )
    self.assertEqual(new_configuration.hidden_size ,    2       )
    # This checks `_configuration_file` ia not kept in the kwargs by mistake.
    self.assertDictEqual(snake_case__ ,    {}       )

    # Testing an older version by monkey-patching the version in the module it's used.
    import transformers as old_transformers

    __a			:  int		    =  "v3.0.0"
    __a			:  int		    =  old_transformers.models.auto.AutoConfig.from_pretrained(snake_case__       )
    self.assertEqual(old_configuration.hidden_size ,    7_6_8       )


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 		UpperCamelCase__  :
   def __init__(self			: Optional[Any] ,    snake_case_			: Union[str, Any] ,    snake_case_			: Optional[Any]=1_3 ,    snake_case_			: str=3_2 ,    snake_case_			: Any=2 ,    snake_case_			: Union[str, Any]=3 ,    snake_case_			: int=1_6 ,    snake_case_			: Optional[int]=[3_2, 6_4, 1_2_8] ,    snake_case_			: str=[1, 2, 1] ,    snake_case_			: str=[2, 2, 4] ,    snake_case_			: List[str]=2 ,    snake_case_			: List[str]=2.0 ,    snake_case_			: List[Any]=True ,    snake_case_			: Tuple=0.0 ,    snake_case_			: Optional[Any]=0.0 ,    snake_case_			: int=0.1 ,    snake_case_			: Optional[int]="gelu" ,    snake_case_			: List[str]=False ,    snake_case_			: Optional[int]=True ,    snake_case_			: Optional[int]=0.02 ,    snake_case_			: List[str]=1E-5 ,    snake_case_			: List[Any]=True ,    snake_case_			: int=None ,    snake_case_			: List[Any]=True ,    snake_case_			: Optional[Any]=1_0 ,    snake_case_			: Union[str, Any]=8 ,    snake_case_			: Optional[Any]=["stage1", "stage2"] ,    snake_case_			: List[Any]=[1, 2] ,    ):
    __a			:  Tuple		    =  parent
    __a			:  str		    =  batch_size
    __a			:  Any		    =  image_size
    __a			:  List[Any]		    =  patch_size
    __a			:  List[Any]		    =  num_channels
    __a			:  List[str]		    =  embed_dim
    __a			:  str		    =  hidden_sizes
    __a			:  Any		    =  depths
    __a			:  List[str]		    =  num_heads
    __a			:  Any		    =  window_size
    __a			:  List[str]		    =  mlp_ratio
    __a			:  Optional[int]		    =  qkv_bias
    __a			:  Any		    =  hidden_dropout_prob
    __a			:  List[str]		    =  attention_probs_dropout_prob
    __a			:  str		    =  drop_path_rate
    __a			:  Optional[Any]		    =  hidden_act
    __a			:  Optional[int]		    =  use_absolute_embeddings
    __a			:  List[str]		    =  patch_norm
    __a			:  int		    =  layer_norm_eps
    __a			:  Optional[Any]		    =  initializer_range
    __a			:  List[str]		    =  is_training
    __a			:  Dict		    =  scope
    __a			:  Optional[Any]		    =  use_labels
    __a			:  Union[str, Any]		    =  type_sequence_label_size
    __a			:  Optional[int]		    =  encoder_stride
    __a			:  str		    =  out_features
    __a			:  Optional[int]		    =  out_indices
   def 				lowerCAmelCase      (self			: Dict       ):
    __a			:  Tuple		    =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

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

    __a			:  List[str]		    =  self.get_config()

    return config, pixel_values, labels
   def 				lowerCAmelCase      (self			: Optional[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			: Dict ,    snake_case_			: int ,    snake_case_			: Tuple ,    snake_case_			: str       ):
    __a			:  int		    =  FocalNetModel(config=snake_case_       )
    model.to(snake_case_       )
    model.eval()
    __a			:  Dict		    =  model(snake_case_       )

    __a			:  Union[str, Any]		    =  ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths       ) - 1))
    __a			:  Dict		    =  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			: Tuple ,    snake_case_			: Any ,    snake_case_			: Union[str, Any] ,    snake_case_			: Optional[int]       ):
    __a			:  List[str]		    =  FocalNetBackbone(config=snake_case_       )
    model.to(snake_case_       )
    model.eval()
    __a			:  List[str]		    =  model(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
    __a			:  Union[str, Any]		    =  None
    __a			:  Tuple		    =  FocalNetBackbone(config=snake_case_       )
    model.to(snake_case_       )
    model.eval()
    __a			:  int		    =  model(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 				lowerCAmelCase      (self			: Optional[Any] ,    snake_case_			: Optional[int] ,    snake_case_			: Dict ,    snake_case_			: Optional[Any]       ):
    __a			:  List[str]		    =  FocalNetForMaskedImageModeling(config=snake_case_       )
    model.to(snake_case_       )
    model.eval()
    __a			:  int		    =  model(snake_case_       )
    self.parent.assertEqual(
        result.reconstruction.shape ,    (self.batch_size, self.num_channels, self.image_size, self.image_size)       )

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

    __a			:  Any		    =  floats_tensor([self.batch_size, 1, self.image_size, self.image_size]       )
    __a			:  Union[str, Any]		    =  model(snake_case_       )
    self.parent.assertEqual(result.reconstruction.shape ,    (self.batch_size, 1, self.image_size, self.image_size)       )
   def 				lowerCAmelCase      (self			: Union[str, Any] ,    snake_case_			: List[Any] ,    snake_case_			: Any ,    snake_case_			: int       ):
    __a			:  Dict		    =  self.type_sequence_label_size
    __a			:  Optional[Any]		    =  FocalNetForImageClassification(snake_case_       )
    model.to(snake_case_       )
    model.eval()
    __a			:  Union[str, Any]		    =  model(snake_case_ ,    labels=snake_case_       )
    self.parent.assertEqual(result.logits.shape ,    (self.batch_size, self.type_sequence_label_size)       )

    # test greyscale images
    __a			:  Optional[int]		    =  1
    __a			:  str		    =  FocalNetForImageClassification(snake_case_       )
    model.to(snake_case_       )
    model.eval()

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







   def 				lowerCAmelCase      (self			: List[Any]       ):
    __a			:  Any		    =  self.prepare_config_and_inputs()

    __a    ,	__a    ,	__a			:  Any		    =  config_and_inputs
    __a			:  Tuple		    =  {'''pixel_values''': pixel_values}
    return config, inputs_dict





@require_torch
class 		UpperCamelCase__  (	__lowercase   ,__lowercase   ,unittest.TestCase   ):
   _SCREAMING_SNAKE_CASE				:							Optional[Any]     	=				(
       (
           FocalNetModel,
           FocalNetForImageClassification,
           FocalNetForMaskedImageModeling,
           FocalNetBackbone,
       )
       if is_torch_available()
       else ()
   )
   _SCREAMING_SNAKE_CASE				:							Optional[Any]     	=				(
       {"feature-extraction": FocalNetModel, "image-classification": FocalNetForImageClassification}
       if is_torch_available()
       else {}
   )
   _SCREAMING_SNAKE_CASE				:							str     	=				False

   _SCREAMING_SNAKE_CASE				:							str     	=				False
   _SCREAMING_SNAKE_CASE				:							Optional[Any]     	=				False
   _SCREAMING_SNAKE_CASE				:							Any     	=				False
   _SCREAMING_SNAKE_CASE				:							Dict     	=				False
   def 				lowerCAmelCase      (self			: List[Any]       ):
    __a			:  Union[str, Any]		    =  FocalNetModelTester(self       )
    __a			:  Dict		    =  ConfigTester(self ,    config_class=snake_case_ ,    embed_dim=3_7 ,    has_text_modality=snake_case_       )
   def 				lowerCAmelCase      (self			: Any       ):
    self.create_and_test_config_common_properties()
    self.config_tester.create_and_test_config_to_json_string()
    self.config_tester.create_and_test_config_to_json_file()
    self.config_tester.create_and_test_config_from_and_save_pretrained()
    self.config_tester.create_and_test_config_with_num_labels()
    self.config_tester.check_config_can_be_init_without_params()
    self.config_tester.check_config_arguments_init()
   def 				lowerCAmelCase      (self			: Dict       ):
    return
   def 				lowerCAmelCase      (self			: Dict       ):
    __a			:  Union[str, Any]		    =  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*snake_case_       )
   def 				lowerCAmelCase      (self			: Tuple       ):
    __a			:  Dict		    =  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_backbone(*snake_case_       )
   def 				lowerCAmelCase      (self			: Any       ):
    __a			:  Dict		    =  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_masked_image_modeling(*snake_case_       )
   def 				lowerCAmelCase      (self			: Optional[int]       ):
    __a			:  Union[str, Any]		    =  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_image_classification(*snake_case_       )
   @unittest.skip(reason='''FocalNet does not use inputs_embeds'''       )
   def 				lowerCAmelCase      (self			: Optional[Any]       ):
    pass
   @unittest.skip(reason='''FocalNet does not use feedforward chunking'''       )
   def 				lowerCAmelCase      (self			: str       ):
    pass
   def 				lowerCAmelCase      (self			: Tuple       ):
    __a    ,	__a			:  Dict		    =  self.model_tester.prepare_config_and_inputs_for_common()

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

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

     __a			:  str		    =  ['''pixel_values''']
     self.assertListEqual(arg_names[:1] ,    snake_case_       )
   def 				lowerCAmelCase      (self			: Tuple ,    snake_case_			: Tuple ,    snake_case_			: Dict ,    snake_case_			: Any ,    snake_case_			: Optional[Any]       ):
    __a			:  Any		    =  model_class(snake_case_       )
    model.to(snake_case_       )
    model.eval()

    with torch.no_grad():
     __a			:  Dict		    =  model(**self._prepare_for_class(snake_case_ ,    snake_case_       )       )

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

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

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

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

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

    __a    ,	__a    ,	__a    ,	__a			:  List[Any]		    =  reshaped_hidden_states[0].shape
    __a			:  List[str]		    =  (
        reshaped_hidden_states[0].view(snake_case_ ,    snake_case_ ,    height * width       ).permute(0 ,    2 ,    1       )
    )
    self.assertListEqual(
        list(reshaped_hidden_states.shape[-2:]       ) ,    [num_patches, self.model_tester.embed_dim] ,    )
   def 				lowerCAmelCase      (self			: Optional[int]       ):
    __a    ,	__a			:  Dict		    =  self.model_tester.prepare_config_and_inputs_for_common()

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

    for model_class in self.all_model_classes[:-1]:
     __a			:  Any		    =  True
     self.check_hidden_states_output(snake_case_ ,    snake_case_ ,    snake_case_ ,    snake_case_       )

     # check that output_hidden_states also work using config
     del inputs_dict["output_hidden_states"]
     __a			:  Optional[int]		    =  True

     self.check_hidden_states_output(snake_case_ ,    snake_case_ ,    snake_case_ ,    snake_case_       )
   def 				lowerCAmelCase      (self			: List[Any]       ):
    __a    ,	__a			:  List[Any]		    =  self.model_tester.prepare_config_and_inputs_for_common()
    __a			:  List[str]		    =  3

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

    __a			:  List[Any]		    =  image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
    __a			:  Union[str, Any]		    =  image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

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

     # check that output_hidden_states also work using config
     del inputs_dict["output_hidden_states"]
     __a			:  List[str]		    =  True
     self.check_hidden_states_output(snake_case_ ,    snake_case_ ,    snake_case_ ,    (padded_height, padded_width)       )
   @slow
   def 				lowerCAmelCase      (self			: str       ):
    for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     __a			:  Dict		    =  FocalNetModel.from_pretrained(snake_case_       )
     self.assertIsNotNone(snake_case_       )







   def 				lowerCAmelCase      (self			: List[Any]       ):
    __a    ,	__a			:  Optional[int]		    =  self.model_tester.prepare_config_and_inputs_for_common()

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







   @slow
   def 				lowerCAmelCase      (self			: str       ):
    __a			:  int		    =  FocalNetForImageClassification.from_pretrained('''microsoft/focalnet-tiny'''       ).to(snake_case_       )
    __a			:  Optional[Any]		    =  self.default_image_processor

    __a			:  Dict		    =  Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''       )
    __a			:  Optional[Any]		    =  image_processor(images=snake_case_ ,    return_tensors='''pt'''       ).to(snake_case_       )

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

    # verify the logits
    __a			:  List[Any]		    =  torch.Size((1, 1_0_0_0)       )
    self.assertEqual(outputs.logits.shape ,    snake_case_       )
    __a			:  Union[str, Any]		    =  torch.tensor([0.2166, -0.4368, 0.2191]       ).to(snake_case_       )
    self.assertTrue(torch.allclose(outputs.logits[0, :3] ,    snake_case_ ,    atol=1E-4       )       )
    self.assertTrue(outputs.logits.argmax(dim=-1       ).item() ,    2_8_1       )





@require_torch
class 		UpperCamelCase__  (	__lowercase   ,unittest.TestCase   ):
   _SCREAMING_SNAKE_CASE				:							Tuple     	=				(FocalNetBackbone,) if is_torch_available() else ()
   _SCREAMING_SNAKE_CASE				:							int     	=				FocalNetConfig

   _SCREAMING_SNAKE_CASE				:							Any     	=				False
   def 				lowerCAmelCase      (self			: Tuple       ):
    __a			:  Union[str, Any]		    =  FocalNetModelTester(self       )
