


import argparse
import logging
import os
from pathlib import Path
from typing import Any, Dict

import pytorch_lightning as pl
from pytorch_lightning.utilities import rank_zero_info

from transformers import (
    AdamW,
    AutoConfig,
    AutoModel,
    AutoModelForPreTraining,
    AutoModelForQuestionAnswering,
    AutoModelForSeqaSeqLM,
    AutoModelForSequenceClassification,
    AutoModelForTokenClassification,
    AutoModelWithLMHead,
    AutoTokenizer,
    PretrainedConfig,
    PreTrainedTokenizer,
)
from transformers.optimization import (
    Adafactor,
    get_cosine_schedule_with_warmup,
    get_cosine_with_hard_restarts_schedule_with_warmup,
    get_linear_schedule_with_warmup,
    get_polynomial_decay_schedule_with_warmup,
)
from transformers.utils.versions import require_version


__a	 =      logging.getLogger(__name__)

require_version("""pytorch_lightning>=1.0.4""")

__a	 =      {
    '''base''': AutoModel,
    '''sequence-classification''': AutoModelForSequenceClassification,
    '''question-answering''': AutoModelForQuestionAnswering,
    '''pretraining''': AutoModelForPreTraining,
    '''token-classification''': AutoModelForTokenClassification,
    '''language-modeling''': AutoModelWithLMHead,
    '''summarization''': AutoModelForSeqaSeqLM,
    '''translation''': AutoModelForSeqaSeqLM,
}


# update this and the import above to support new schedulers from transformers.optimization
__a	 =      {
    '''linear''': get_linear_schedule_with_warmup,
    '''cosine''': get_cosine_schedule_with_warmup,
    '''cosine_w_restarts''': get_cosine_with_hard_restarts_schedule_with_warmup,
    '''polynomial''': get_polynomial_decay_schedule_with_warmup,
    # '': get_constant_schedule,             # not supported for now
    # '': get_constant_schedule_with_warmup, # not supported for now
}
__a	 =      sorted(arg_to_scheduler.keys())
__a	 =      '''{''' + ''', '''.join(arg_to_scheduler_choices) + '''}'''






class 	__lowercase					(	pl.LightningModule	):





      def __init__(		self    :       str       ,							__lowerCamelCase    :       List[str]       ,							__lowerCamelCase    :       Tuple=None       ,							__lowerCamelCase    :       Optional[int]="base"       ,							__lowerCamelCase    :       Any=None       ,							__lowerCamelCase    :       Tuple=None       ,							__lowerCamelCase    :       str=None       ,							**__lowerCamelCase    :       Optional[int]       ,							)     -> List[Any]:






         """simple docstring"""







         super().__init__()
         # TODO: move to self.save_hyperparameters()
         # self.save_hyperparameters()
         # can also expand arguments into trainer signature for easier reading

         self.save_hyperparameters(_UpperCAmelCase							)
         UpperCAmelCase      					=  0
         UpperCAmelCase      					=  Path(self.hparams.output_dir							)
         UpperCAmelCase      					=  self.hparams.cache_dir if self.hparams.cache_dir else None
         if config is None:
            UpperCAmelCase      					=  AutoConfig.from_pretrained(
                self.hparams.config_name if self.hparams.config_name else self.hparams.model_name_or_path       ,							**({"""num_labels""": num_labels} if num_labels is not None else {})       ,							cache_dir=_UpperCAmelCase       ,							**_UpperCAmelCase       ,							)
         else:
            UpperCAmelCase      					=  config

         UpperCAmelCase      					=  ("""encoder_layerdrop""", """decoder_layerdrop""", """dropout""", """attention_dropout""")
         for p in extra_model_params:
            if getattr(self.hparams       ,							_UpperCAmelCase       ,							_UpperCAmelCase							):
               assert hasattr(self.config       ,							_UpperCAmelCase							), F"""model config doesn't have a `{p}` attribute"""
               setattr(self.config       ,							_UpperCAmelCase       ,							getattr(self.hparams       ,							_UpperCAmelCase							)							)

         if tokenizer is None:
            UpperCAmelCase      					=  AutoTokenizer.from_pretrained(
                self.hparams.tokenizer_name if self.hparams.tokenizer_name else self.hparams.model_name_or_path       ,							cache_dir=_UpperCAmelCase       ,							)
         else:
            UpperCAmelCase      					=  tokenizer
         UpperCAmelCase      					=  MODEL_MODES[mode]
         if model is None:
            UpperCAmelCase      					=  self.model_type.from_pretrained(
                self.hparams.model_name_or_path       ,							from_tf=bool(""".ckpt""" in self.hparams.model_name_or_path							)       ,							config=self.config       ,							cache_dir=_UpperCAmelCase       ,							)
         else:
            UpperCAmelCase      					=  model





      def 							_lowercase					(		self    :       Union[str, Any]       ,							*__lowerCamelCase    :       Union[str, Any]       ,							**__lowerCamelCase    :       int							)     -> Tuple:






         """simple docstring"""







         UpperCAmelCase      					=  self.model_type.from_pretrained(*_UpperCAmelCase       ,							**_UpperCAmelCase							)





      def 							_lowercase					(		self    :       str							)     -> Optional[Any]:






         """simple docstring"""







         UpperCAmelCase      					=  arg_to_scheduler[self.hparams.lr_scheduler]
         UpperCAmelCase      					=  get_schedule_func(
             self.opt       ,							num_warmup_steps=self.hparams.warmup_steps       ,							num_training_steps=self.total_steps()							)
         UpperCAmelCase      					=  {"""scheduler""": scheduler, """interval""": """step""", """frequency""": 1}
         return scheduler





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






         """simple docstring"""







         UpperCAmelCase      					=  self.model
         UpperCAmelCase      					=  ["""bias""", """LayerNorm.weight"""]
         UpperCAmelCase      					=  [
             {
                 """params""": [
                     p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay							)
                 ],  # check this named paramters
                 """weight_decay""": self.hparams.weight_decay,
             },
             {
                 """params""": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay							)],
                 """weight_decay""": 0.0,
             },
         ]
         if self.hparams.adafactor:
            UpperCAmelCase      					=  Adafactor(
                _UpperCAmelCase       ,							lr=self.hparams.learning_rate       ,							scale_parameter=_UpperCAmelCase       ,							relative_step=_UpperCAmelCase							)

         else:
            UpperCAmelCase      					=  AdamW(
                _UpperCAmelCase       ,							lr=self.hparams.learning_rate       ,							eps=self.hparams.adam_epsilon							)
         UpperCAmelCase      					=  optimizer

         UpperCAmelCase      					=  self.get_lr_scheduler()

         return [optimizer], [scheduler]





      def 							_lowercase					(		self    :       Any       ,							__lowerCamelCase    :       str       ,							__lowerCamelCase    :       Optional[Any]							)     -> Tuple:






         """simple docstring"""







         return self.validation_step(_UpperCAmelCase       ,							_UpperCAmelCase							)





      def 							_lowercase					(		self    :       Tuple       ,							__lowerCamelCase    :       Union[str, Any]							)     -> str:






         """simple docstring"""







         return self.validation_end(_UpperCAmelCase							)





      def 							_lowercase					(		self    :       str							)     -> int:






         """simple docstring"""







         UpperCAmelCase      					=  max(1       ,							self.hparams.gpus							)  # TODO: consider num_tpu_cores
         UpperCAmelCase      					=  self.hparams.train_batch_size * self.hparams.accumulate_grad_batches * num_devices
         return (self.dataset_size / effective_batch_size) * self.hparams.max_epochs





      def 							_lowercase					(		self    :       Dict       ,							__lowerCamelCase    :       List[Any]							)     -> str:






         """simple docstring"""







         if stage == "test":
            UpperCAmelCase      					=  len(self.test_dataloader().dataset							)
         else:
            UpperCAmelCase      					=  self.get_dataloader("""train"""       ,							self.hparams.train_batch_size       ,							shuffle=_UpperCAmelCase							)
            UpperCAmelCase      					=  len(self.train_dataloader().dataset							)





      def 							_lowercase					(		self    :       Optional[Any]       ,							__lowerCamelCase    :       Any       ,							__lowerCamelCase    :       Any       ,							__lowerCamelCase    :       List[Any] = False							)     -> Any:






         """simple docstring"""







         raise NotImplementedError("""You must implement this for your task"""							)





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






         """simple docstring"""







         return self.train_loader





      def 							_lowercase					(		self    :       Tuple							)     -> Dict:






         """simple docstring"""







         return self.get_dataloader("""dev"""       ,							self.hparams.eval_batch_size       ,							shuffle=_UpperCAmelCase							)





      def 							_lowercase					(		self    :       Optional[int]							)     -> List[Any]:






         """simple docstring"""







         return self.get_dataloader("""test"""       ,							self.hparams.eval_batch_size       ,							shuffle=_UpperCAmelCase							)





      def 							_lowercase					(		self    :       str       ,							__lowerCamelCase    :       str							)     -> int:






         """simple docstring"""







         return os.path.join(
             self.hparams.data_dir       ,							"""cached_{}_{}_{}""".format(
                 _UpperCAmelCase       ,							list(filter(_UpperCAmelCase       ,							self.hparams.model_name_or_path.split("""/"""							)							)							).pop()       ,							str(self.hparams.max_seq_length							)       ,							)       ,							)





      @pl.utilities.rank_zero_only
      def 							_lowercase					(		self    :       Dict       ,							__lowerCamelCase    :       Dict							)     -> None:






         """simple docstring"""







         UpperCAmelCase      					=  self.output_dir.joinpath("""best_tfmr"""							)
         UpperCAmelCase      					=  self.step_count
         self.model.save_pretrained(_UpperCAmelCase							)
         self.tokenizer.save_pretrained(_UpperCAmelCase							)





      @staticmethod
      def 							_lowercase					(		__lowerCamelCase    :       List[Any]       ,							__lowerCamelCase    :       List[str]							)     -> Any:






         """simple docstring"""







         parser.add_argument(
             """--model_name_or_path"""       ,							default=_UpperCAmelCase       ,							type=_UpperCAmelCase       ,							required=_UpperCAmelCase       ,							help="""Path to pretrained model or model identifier from huggingface.co/models"""       ,							)
         parser.add_argument(
             """--config_name"""       ,							default=""""""       ,							type=_UpperCAmelCase       ,							help="""Pretrained config name or path if not the same as model_name"""							)
         parser.add_argument(
             """--tokenizer_name"""       ,							default=_UpperCAmelCase       ,							type=_UpperCAmelCase       ,							help="""Pretrained tokenizer name or path if not the same as model_name"""       ,							)
         parser.add_argument(
             """--cache_dir"""       ,							default=str(Path(_UpperCAmelCase							).parent / """test_run""" / """cache"""							)       ,							type=_UpperCAmelCase       ,							help="""Where do you want to store the pre-trained models downloaded from huggingface.co"""       ,							)
         parser.add_argument(
             """--encoder_layerdrop"""       ,							type=_UpperCAmelCase       ,							help="""Encoder layer dropout probability (Optional). Goes into model.config"""       ,							)
         parser.add_argument(
             """--decoder_layerdrop"""       ,							type=_UpperCAmelCase       ,							help="""Decoder layer dropout probability (Optional). Goes into model.config"""       ,							)
         parser.add_argument(
             """--dropout"""       ,							type=_UpperCAmelCase       ,							help="""Dropout probability (Optional). Goes into model.config"""       ,							)
         parser.add_argument(
             """--attention_dropout"""       ,							type=_UpperCAmelCase       ,							help="""Attention dropout probability (Optional). Goes into model.config"""       ,							)
         parser.add_argument("""--learning_rate"""       ,							default=5e-5       ,							type=_UpperCAmelCase       ,							help="""The initial learning rate for Adam."""							)
         parser.add_argument(
             """--lr_scheduler"""       ,							default="""linear"""       ,							choices=_UpperCAmelCase       ,							metavar=_UpperCAmelCase       ,							type=_UpperCAmelCase       ,							help="""Learning rate scheduler"""       ,							)
         parser.add_argument("""--weight_decay"""       ,							default=0.0       ,							type=_UpperCAmelCase       ,							help="""Weight decay if we apply some."""							)
         parser.add_argument("""--adam_epsilon"""       ,							default=1e-8       ,							type=_UpperCAmelCase       ,							help="""Epsilon for Adam optimizer."""							)
         parser.add_argument("""--warmup_steps"""       ,							default=0       ,							type=_UpperCAmelCase       ,							help="""Linear warmup over warmup_steps."""							)
         parser.add_argument("""--num_workers"""       ,							default=4       ,							type=_UpperCAmelCase       ,							help="""kwarg passed to DataLoader"""							)
         parser.add_argument("""--num_train_epochs"""       ,							dest="""max_epochs"""       ,							default=3       ,							type=_UpperCAmelCase							)
         parser.add_argument("""--train_batch_size"""       ,							default=3_2       ,							type=_UpperCAmelCase							)
         parser.add_argument("""--eval_batch_size"""       ,							default=3_2       ,							type=_UpperCAmelCase							)
         parser.add_argument("""--adafactor"""       ,							action="""store_true"""							)






class 	__lowercase					(	pl.Callback	):





      def 							_lowercase					(		self    :       List[str]       ,							__lowerCamelCase    :       int       ,							__lowerCamelCase    :       Dict							)     -> str:






         """simple docstring"""







         if (
             trainer.is_global_zero and trainer.global_rank == 0
         ):  # we initialize the retriever only on master worker with RAY. In new pytorch-lightning accelorators are removed.
            pl_module.model.rag.retriever.init_retrieval()  # better to use hook functions.






class 	__lowercase					(	pl.Callback	):





      def 							_lowercase					(		self    :       List[Any]       ,							__lowerCamelCase    :       Dict       ,							__lowerCamelCase    :       str							)     -> Dict:






         """simple docstring"""







         for name, param in pl_module.model.rag.named_parameters():
            if param.grad is None:
               print(_UpperCAmelCase							)






class 	__lowercase					(	pl.Callback	):





      def 							_lowercase					(		self    :       Union[str, Any]       ,							__lowerCamelCase    :       Dict       ,							__lowerCamelCase    :       Tuple							)     -> Tuple:






         """simple docstring"""







         UpperCAmelCase      					=  trainer.lr_schedulers[0]["""scheduler"""]
         UpperCAmelCase      					=  {F"""lr_group_{i}""": lr for i, lr in enumerate(lr_scheduler.get_lr()							)}
         pl_module.logger.log_metrics(_UpperCAmelCase							)





      def 							_lowercase					(		self    :       str       ,							__lowerCamelCase    :       Dict       ,							__lowerCamelCase    :       Union[str, Any]							)     -> List[str]:






         """simple docstring"""







         rank_zero_info("""***** Validation results *****"""							)
         UpperCAmelCase      					=  trainer.callback_metrics
         # Log results
         for key in sorted(_UpperCAmelCase							):
            if key not in ["log", "progress_bar"]:
               rank_zero_info("""{} = {}\n""".format(_UpperCAmelCase       ,							str(metrics[key]							)							)							)





      def 							_lowercase					(		self    :       List[str]       ,							__lowerCamelCase    :       Optional[Any]       ,							__lowerCamelCase    :       str							)     -> Any:






         """simple docstring"""







         rank_zero_info("""***** Test results *****"""							)
         UpperCAmelCase      					=  trainer.callback_metrics
         # Log and save results to file
         UpperCAmelCase      					=  os.path.join(pl_module.hparams.output_dir       ,							"""test_results.txt"""							)
         with open(_UpperCAmelCase       ,							"""w"""							) as writer:
            for key in sorted(_UpperCAmelCase							):
               if key not in ["log", "progress_bar"]:
                  rank_zero_info("""{} = {}\n""".format(_UpperCAmelCase       ,							str(metrics[key]							)							)							)
                  writer.write("""{} = {}\n""".format(_UpperCAmelCase       ,							str(metrics[key]							)							)							)

def 	_UpperCamelCase					(    lowerCAmelCase_	,    lowerCAmelCase_ )    ->None:
   #  To allow all pl args uncomment the following line
   #  parser = pl.Trainer.add_argparse_args(parser)
   parser.add_argument(
       """--output_dir"""	,    default=str(Path(UpperCamelCase_ ).parent / """test_run""" / """model_checkpoints""" )	,    type=UpperCamelCase_	,    help="""The output directory where the model predictions and checkpoints will be written."""	,    )
   parser.add_argument(
       """--fp16"""	,    action="""store_true"""	,    help="""Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit"""	,    )

   parser.add_argument(
       """--fp16_opt_level"""	,    type=UpperCamelCase_	,    default="""O2"""	,    help=(
           """For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\']."""
           """See details at https://nvidia.github.io/apex/amp.html"""
       )	,    )
   parser.add_argument("""--n_tpu_cores"""	,    dest="""tpu_cores"""	,    type=UpperCamelCase_ )
   parser.add_argument("""--max_grad_norm"""	,    dest="""gradient_clip_val"""	,    default=1.0	,    type=UpperCamelCase_	,    help="""Max gradient norm""" )
   parser.add_argument("""--do_train"""	,    action="""store_true"""	,    help="""Whether to run training.""" )
   parser.add_argument("""--do_predict"""	,    action="""store_true"""	,    help="""Whether to run predictions on the test set.""" )
   parser.add_argument(
       """--gradient_accumulation_steps"""	,    dest="""accumulate_grad_batches"""	,    type=UpperCamelCase_	,    default=1	,    help="""Number of updates steps to accumulate before performing a backward/update pass."""	,    )
   parser.add_argument("""--seed"""	,    type=UpperCamelCase_	,    default=4_2	,    help="""random seed for initialization""" )
   parser.add_argument(
       """--data_dir"""	,    default=str(Path(UpperCamelCase_ ).parent / """test_run""" / """dummy-train-data""" )	,    type=UpperCamelCase_	,    help="""The input data dir. Should contain the training files for the CoNLL-2003 NER task."""	,    )







def 	_UpperCamelCase					(    lowerCAmelCase_	,    lowerCAmelCase_	,    lowerCAmelCase_=None	,    lowerCAmelCase_=True	,    lowerCAmelCase_=[]	,    lowerCAmelCase_=None	,    lowerCAmelCase_=None	,    **lowerCAmelCase_	,    )    ->int:
   pl.seed_everything(args.seed )

   # init model
   UpperCAmelCase      					=  Path(model.hparams.output_dir )
   odir.mkdir(exist_ok=UpperCamelCase_ )

   # add custom checkpoints
   if checkpoint_callback is None:
      UpperCAmelCase      					=  pl.callbacks.ModelCheckpoint(
          filepath=args.output_dir	,    prefix="""checkpoint"""	,    monitor="""val_loss"""	,    mode="""min"""	,    save_top_k=1 )
   if early_stopping_callback:
      extra_callbacks.append(UpperCamelCase_ )
   if logging_callback is None:
      UpperCAmelCase      					=  LoggingCallback()

   UpperCAmelCase      					=  {}

   if args.fpaa:
      UpperCAmelCase      					=  1_6

   if args.gpus > 1:
      UpperCAmelCase      					=  """auto"""
      UpperCAmelCase      					=  """ddp"""

   UpperCAmelCase      					=  args.accumulate_grad_batches
   UpperCAmelCase      					=  None
   UpperCAmelCase      					=  """auto"""

   UpperCAmelCase      					=  pl.Trainer.from_argparse_args(
       UpperCamelCase_	,    weights_summary=UpperCamelCase_	,    callbacks=[logging_callback] + extra_callbacks + [InitCallback()] + [checkpoint_callback]	,    logger=UpperCamelCase_	,    val_check_interval=1	,    num_sanity_val_steps=2	,    **UpperCamelCase_	,    )

   if args.do_train:
      trainer.fit(UpperCamelCase_ )

   else:
      print("""RAG modeling tests with new set functions successfuly executed!""" )
   return trainer








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






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






			def 						_lowercase  (     self						)							->							Dict:
					snake_case__	     =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

					snake_case__	     =None
					if self.use_labels:
							snake_case__	     =ids_tensor([self.batch_size]					,   self.type_sequence_label_size						)

					snake_case__	     =self.get_config()

					return config, pixel_values, labels






			def 						_lowercase  (     self						)							->							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 						_lowercase  (     self					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)							->							Union[str, Any]:
					snake_case__	     =FocalNetModel(config=_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()
					snake_case__	     =model(_UpperCAmelCase						)

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

					# 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
					snake_case__	     =None
					snake_case__	     =FocalNetBackbone(config=_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()
					snake_case__	     =model(_UpperCAmelCase						)

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

					# test greyscale images
					snake_case__	     =1
					snake_case__	     =FocalNetForMaskedImageModeling(_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()

					snake_case__	     =floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
					snake_case__	     =model(_UpperCAmelCase						)
					self.parent.assertEqual(result.reconstruction.shape					,   (self.batch_size, 1, self.image_size, self.image_size)						)






			def 						_lowercase  (     self					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)							->							Tuple:
					snake_case__	     =self.type_sequence_label_size
					snake_case__	     =FocalNetForImageClassification(_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()
					snake_case__	     =model(_UpperCAmelCase					,   labels=_UpperCAmelCase						)
					self.parent.assertEqual(result.logits.shape					,   (self.batch_size, self.type_sequence_label_size)						)

					# test greyscale images
					snake_case__	     =1
					snake_case__	     =FocalNetForImageClassification(_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()

					snake_case__	     =floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
					snake_case__	     =model(_UpperCAmelCase						)
					self.parent.assertEqual(result.logits.shape					,   (self.batch_size, self.type_sequence_label_size)						)






			def 						_lowercase  (     self						)							->							List[str]:
					snake_case__	     =self.prepare_config_and_inputs()

					snake_case__     ,	snake_case__     ,	snake_case__	     =config_and_inputs
					snake_case__	     ={'pixel_values': pixel_values}
					return config, inputs_dict





@require_torch
class 							a__( snake_case__   ,      snake_case__   ,      unittest.TestCase     ):
			a_	: str									=      (
			    (
			        FocalNetModel,
			        FocalNetForImageClassification,
			        FocalNetForMaskedImageModeling,
			        FocalNetBackbone,
			    )
			    if is_torch_available()
			    else ()
			)
			a_	: Union[str, Any]									=      (
			    {'''feature-extraction''': FocalNetModel, '''image-classification''': FocalNetForImageClassification}
			    if is_torch_available()
			    else {}
			)
			a_	: Dict									=      False

			a_	: Any									=      False
			a_	: List[str]									=      False
			a_	: List[Any]									=      False
			a_	: Optional[Any]									=      False






			def 						_lowercase  (     self						)							->							Optional[int]:
					snake_case__	     =FocalNetModelTester(self						)
					snake_case__	     =ConfigTester(self					,   config_class=_UpperCAmelCase					,   embed_dim=37					,   has_text_modality=_UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							Optional[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 						_lowercase  (     self						)							->							str:
					return






			def 						_lowercase  (     self						)							->							str:
					snake_case__	     =self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*_UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							str:
					snake_case__	     =self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_backbone(*_UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							Optional[Any]:
					snake_case__	     =self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_masked_image_modeling(*_UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							Union[str, Any]:
					snake_case__	     =self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase						)






			@unittest.skip(reason='FocalNet does not use inputs_embeds'						)
			def 						_lowercase  (     self						)							->							str:
					pass






			@unittest.skip(reason='FocalNet does not use feedforward chunking'						)
			def 						_lowercase  (     self						)							->							int:
					pass






			def 						_lowercase  (     self						)							->							List[str]:
					snake_case__     ,	snake_case__	     =self.model_tester.prepare_config_and_inputs_for_common()

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






			def 						_lowercase  (     self						)							->							Optional[Any]:
					snake_case__     ,	snake_case__	     =self.model_tester.prepare_config_and_inputs_for_common()

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

							snake_case__	     =['pixel_values']
							self.assertListEqual(arg_names[:1]					,   _UpperCAmelCase						)






			def 						_lowercase  (     self					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)							->							Union[str, Any]:
					snake_case__	     =model_class(_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()

					with torch.no_grad():
							snake_case__	     =model(**self._prepare_for_class(_UpperCAmelCase					,   _UpperCAmelCase						)						)

					snake_case__	     =outputs.hidden_states

					snake_case__	     =getattr(
					    self.model_tester					,   'expected_num_hidden_layers'					,   len(self.model_tester.depths						) + 1						)
					self.assertEqual(len(_UpperCAmelCase						)					,   _UpperCAmelCase						)

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

					snake_case__	     =(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]					,   )

					snake_case__	     =outputs.reshaped_hidden_states
					self.assertEqual(len(_UpperCAmelCase						)					,   _UpperCAmelCase						)

					snake_case__     ,	snake_case__     ,	snake_case__     ,	snake_case__	     =reshaped_hidden_states[0].shape
					snake_case__	     =(
					    reshaped_hidden_states[0].view(_UpperCAmelCase					,   _UpperCAmelCase					,   height * width						).permute(0					,   2					,   1						)
					)
					self.assertListEqual(
					    list(reshaped_hidden_states.shape[-2:]						)					,   [num_patches, self.model_tester.embed_dim]					,   )






			def 						_lowercase  (     self						)							->							List[str]:
					snake_case__     ,	snake_case__	     =self.model_tester.prepare_config_and_inputs_for_common()

					snake_case__	     =(
					    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]:
							snake_case__	     =True
							self.check_hidden_states_output(_UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)

							# check that output_hidden_states also work using config
							del inputs_dict["output_hidden_states"]
							snake_case__	     =True

							self.check_hidden_states_output(_UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							List[str]:
					snake_case__     ,	snake_case__	     =self.model_tester.prepare_config_and_inputs_for_common()
					snake_case__	     =3

					snake_case__	     =(
					    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)
					)
					snake_case__	     =(
					    config.patch_size
					    if isinstance(config.patch_size					,   collections.abc.Iterable						)
					    else (config.patch_size, config.patch_size)
					)

					snake_case__	     =image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
					snake_case__	     =image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

					for model_class in self.all_model_classes[:-1]:
							snake_case__	     =True
							self.check_hidden_states_output(_UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase					,   (padded_height, padded_width)						)

							# check that output_hidden_states also work using config
							del inputs_dict["output_hidden_states"]
							snake_case__	     =True
							self.check_hidden_states_output(_UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase					,   (padded_height, padded_width)						)






			@slow
			def 						_lowercase  (     self						)							->							Optional[Any]:
					for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							snake_case__	     =FocalNetModel.from_pretrained(_UpperCAmelCase						)
							self.assertIsNotNone(_UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							int:
					snake_case__     ,	snake_case__	     =self.model_tester.prepare_config_and_inputs_for_common()

					snake_case__	     =_config_zero_init(_UpperCAmelCase						)
					for model_class in self.all_model_classes:
							snake_case__	     =model_class(config=_UpperCAmelCase						)
							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     ):






			@cached_property
			def 						_lowercase  (     self						)							->							Any:
					# TODO update organization
					return AutoImageProcessor.from_pretrained('microsoft/focalnet-tiny'						) if is_vision_available() else None






			@slow
			def 						_lowercase  (     self						)							->							str:
					snake_case__	     =FocalNetForImageClassification.from_pretrained('microsoft/focalnet-tiny'						).to(_UpperCAmelCase						)
					snake_case__	     =self.default_image_processor

					snake_case__	     =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
					snake_case__	     =image_processor(images=_UpperCAmelCase					,   return_tensors='pt'						).to(_UpperCAmelCase						)

					# forward pass
					with torch.no_grad():
							snake_case__	     =model(**_UpperCAmelCase						)

					# verify the logits
					snake_case__	     =torch.Size((1, 1000)						)
					self.assertEqual(outputs.logits.shape					,   _UpperCAmelCase						)
					snake_case__	     =torch.tensor([0.2_166, -0.4_368, 0.2_191]						).to(_UpperCAmelCase						)
					self.assertTrue(torch.allclose(outputs.logits[0, :3]					,   _UpperCAmelCase					,   atol=1E-4						)						)
					self.assertTrue(outputs.logits.argmax(dim=-1						).item()					,   281						)





@require_torch
class 							a__( snake_case__   ,      unittest.TestCase     ):
			a_	: int									=      (FocalNetBackbone,) if is_torch_available() else ()
			a_	: Any									=      FocalNetConfig

			a_	: int									=      False






			def 						_lowercase  (     self						)							->							Optional[int]:
					snake_case__	     =FocalNetModelTester(self						)




