
import logging
import os
from dataclasses import dataclass, field
from typing import Dict, Optional

import datasets
import numpy as np
import tensorflow as tf

from transformers import (
    AutoConfig,
    AutoTokenizer,
    EvalPrediction,
    HfArgumentParser,
    PreTrainedTokenizer,
    TFAutoModelForSequenceClassification,
    TFTrainer,
    TFTrainingArguments,
)
from transformers.utils import logging as hf_logging


hf_logging.set_verbosity_info()
hf_logging.enable_default_handler()
hf_logging.enable_explicit_format()




def        __UpperCamelCase					(    lowerCAmelCase__							:    str  ,       lowerCAmelCase__							:    str  ,       lowerCAmelCase__							:    str  ,       lowerCAmelCase__							:    PreTrainedTokenizer  ,       lowerCAmelCase__							:    int  ,       lowerCAmelCase__							:    Optional[int] = None  ,       ):
 __a			:  Optional[int]		    =  {}

 if train_file is not None:
  __a			:  Dict		    =  [train_file]
 if eval_file is not None:
  __a			:  int		    =  [eval_file]
 if test_file is not None:
  __a			:  Any		    =  [test_file]

 __a			:  Tuple		    =  datasets.load_dataset('''csv'''  ,       data_files=lowerCAmelCase__  )
 __a			:  List[Any]		    =  list(ds[list(files.keys()  )[0]].features.keys()  )
 __a			:  Any		    =  features_name.pop(lowerCAmelCase__  )
 __a			:  int		    =  list(set(ds[list(files.keys()  )[0]][label_name]  )  )
 __a			:  str		    =  {label: i for i, label in enumerate(lowerCAmelCase__  )}
 __a			:  Tuple		    =  tokenizer.model_input_names
 __a			:  Optional[Any]		    =  {}

 if len(lowerCAmelCase__  ) == 1:
  for k in files.keys():
   __a			:  Optional[Any]		    =  ds[k].map(
       lambda lowerCAmelCase__  : tokenizer.batch_encode_plus(
           example[features_name[0]]  ,       truncation=lowerCAmelCase__  ,       max_length=lowerCAmelCase__  ,       padding='''max_length'''  )  ,       batched=lowerCAmelCase__  ,       )
 elif len(lowerCAmelCase__  ) == 2:
  for k in files.keys():
   __a			:  str		    =  ds[k].map(
       lambda lowerCAmelCase__  : tokenizer.batch_encode_plus(
           (example[features_name[0]], example[features_name[1]])  ,       truncation=lowerCAmelCase__  ,       max_length=lowerCAmelCase__  ,       padding='''max_length'''  ,       )  ,       batched=lowerCAmelCase__  ,       )

 def gen_train():
  for ex in transformed_ds[datasets.Split.TRAIN]:
   __a			:  List[str]		    =  {k: v for k, v in ex.items() if k in input_names}
   __a			:  List[Any]		    =  labelaid[ex[label_name]]
   yield (d, label)

 def gen_val():
  for ex in transformed_ds[datasets.Split.VALIDATION]:
   __a			:  Dict		    =  {k: v for k, v in ex.items() if k in input_names}
   __a			:  List[Any]		    =  labelaid[ex[label_name]]
   yield (d, label)

 def gen_test():
  for ex in transformed_ds[datasets.Split.TEST]:
   __a			:  List[Any]		    =  {k: v for k, v in ex.items() if k in input_names}
   __a			:  Dict		    =  labelaid[ex[label_name]]
   yield (d, label)

 __a			:  List[Any]		    =  (
     tf.data.Dataset.from_generator(
         lowerCAmelCase__  ,       ({k: tf.intaa for k in input_names}, tf.intaa)  ,       ({k: tf.TensorShape([None]  ) for k in input_names}, tf.TensorShape([]  ))  ,       )
     if datasets.Split.TRAIN in transformed_ds
     else None
 )

 if train_ds is not None:
  __a			:  Tuple		    =  train_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TRAIN]  )  )  )

 __a			:  Tuple		    =  (
     tf.data.Dataset.from_generator(
         lowerCAmelCase__  ,       ({k: tf.intaa for k in input_names}, tf.intaa)  ,       ({k: tf.TensorShape([None]  ) for k in input_names}, tf.TensorShape([]  ))  ,       )
     if datasets.Split.VALIDATION in transformed_ds
     else None
 )

 if val_ds is not None:
  __a			:  Tuple		    =  val_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.VALIDATION]  )  )  )

 __a			:  int		    =  (
     tf.data.Dataset.from_generator(
         lowerCAmelCase__  ,       ({k: tf.intaa for k in input_names}, tf.intaa)  ,       ({k: tf.TensorShape([None]  ) for k in input_names}, tf.TensorShape([]  ))  ,       )
     if datasets.Split.TEST in transformed_ds
     else None
 )

 if test_ds is not None:
  __a			:  Union[str, Any]		    =  test_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TEST]  )  )  )

 return train_ds, val_ds, test_ds, labelaid


lowercase__          =logging.getLogger(__name__)



@dataclass
class 		UpperCamelCase__  :
   _SCREAMING_SNAKE_CASE				:							int     	=				field(metadata={"help": "Which column contains the label"}   )
   _SCREAMING_SNAKE_CASE				:							str     	=				field(default=__lowercase   ,metadata={"help": "The path of the training file"}   )
   _SCREAMING_SNAKE_CASE				:							Optional[str]     	=				field(default=__lowercase   ,metadata={"help": "The path of the development file"}   )
   _SCREAMING_SNAKE_CASE				:							Optional[str]     	=				field(default=__lowercase   ,metadata={"help": "The path of the test file"}   )
   _SCREAMING_SNAKE_CASE				:							int     	=				field(
       default=128   ,metadata={
           "help": (
               "The maximum total input sequence length after tokenization. Sequences longer "
               "than this will be truncated, sequences shorter will be padded."
           )
       }   ,)
   _SCREAMING_SNAKE_CASE				:							bool     	=				field(
       default=__lowercase   ,metadata={"help": "Overwrite the cached training and evaluation sets"}   )





@dataclass
class 		UpperCamelCase__  :
   _SCREAMING_SNAKE_CASE				:							str     	=				field(
       metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}   )
   _SCREAMING_SNAKE_CASE				:							Optional[str]     	=				field(
       default=__lowercase   ,metadata={"help": "Pretrained config name or path if not the same as model_name"}   )
   _SCREAMING_SNAKE_CASE				:							Optional[str]     	=				field(
       default=__lowercase   ,metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}   )
   _SCREAMING_SNAKE_CASE				:							bool     	=				field(default=__lowercase   ,metadata={"help": "Set this flag to use fast tokenization."}   )
   # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script,
   # or just modify its tokenizer_config.json.
   _SCREAMING_SNAKE_CASE				:							Optional[str]     	=				field(
       default=__lowercase   ,metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}   ,)





def        __UpperCamelCase					(    ):
 # See all possible arguments in src/transformers/training_args.py
 # or by passing the --help flag to this script.
 # We now keep distinct sets of args, for a cleaner separation of concerns.
 __a			:  Dict		    =  HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments)  )
 __a    ,	__a    ,	__a			:  Dict		    =  parser.parse_args_into_dataclasses()

 if (
     os.path.exists(training_args.output_dir  )
     and os.listdir(training_args.output_dir  )
     and training_args.do_train
     and not training_args.overwrite_output_dir
 ):
  raise ValueError(
      f"Output directory ({training_args.output_dir}) already exists and is not empty. Use"
      ''' --overwrite_output_dir to overcome.'''  )

 # Setup logging
 logging.basicConfig(
     format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''  ,       datefmt='''%m/%d/%Y %H:%M:%S'''  ,       level=logging.INFO  ,       )
 logger.info(
     f"n_replicas: {training_args.n_replicas}, distributed training: {bool(training_args.n_replicas > 1  )}, "
     f"16-bits training: {training_args.fpaa}"  )
 logger.info(f"Training/evaluation parameters {training_args}"  )

 # Load pretrained model and tokenizer
 #
 # Distributed training:
 # The .from_pretrained methods guarantee that only one local process can concurrently
 # download model & vocab.

 __a			:  List[str]		    =  AutoTokenizer.from_pretrained(
     model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path  ,       cache_dir=model_args.cache_dir  ,       )

 __a    ,	__a    ,	__a    ,	__a			:  List[str]		    =  get_tfds(
     train_file=data_args.train_file  ,       eval_file=data_args.dev_file  ,       test_file=data_args.test_file  ,       tokenizer=lowerCAmelCase__  ,       label_column_id=data_args.label_column_id  ,       max_seq_length=data_args.max_seq_length  ,       )

 __a			:  List[str]		    =  AutoConfig.from_pretrained(
     model_args.config_name if model_args.config_name else model_args.model_name_or_path  ,       num_labels=len(lowerCAmelCase__  )  ,       labelaid=lowerCAmelCase__  ,       idalabel={id: label for label, id in labelaid.items()}  ,       finetuning_task='''text-classification'''  ,       cache_dir=model_args.cache_dir  ,       )

 with training_args.strategy.scope():
  __a			:  Union[str, Any]		    =  TFAutoModelForSequenceClassification.from_pretrained(
      model_args.model_name_or_path  ,       from_pt=bool('''.bin''' in model_args.model_name_or_path  )  ,       config=lowerCAmelCase__  ,       cache_dir=model_args.cache_dir  ,       )

 def compute_metrics(lowerCAmelCase__							:    EvalPrediction  ) -> Dict:
  __a			:  int		    =  np.argmax(p.predictions  ,       axis=1  )

  return {"acc": (preds == p.label_ids).mean()}

 # Initialize our Trainer
 __a			:  Optional[Any]		    =  TFTrainer(
     model=lowerCAmelCase__  ,       args=lowerCAmelCase__  ,       train_dataset=lowerCAmelCase__  ,       eval_dataset=lowerCAmelCase__  ,       compute_metrics=lowerCAmelCase__  ,       )

 # Training
 if training_args.do_train:
  trainer.train()
  trainer.save_model()
  tokenizer.save_pretrained(training_args.output_dir  )

 # Evaluation
 __a			:  str		    =  {}
 if training_args.do_eval:
  logger.info('''*** Evaluate ***'''  )
  __a			:  str		    =  trainer.evaluate()
  __a			:  int		    =  os.path.join(training_args.output_dir  ,       '''eval_results.txt'''  )

  with open(lowerCAmelCase__  ,       '''w'''  ) as writer:
   logger.info('''***** Eval results *****'''  )

   for key, value in result.items():
    logger.info(f"  {key} = {value}"  )
    writer.write(f"{key} = {value}\n"  )

   results.update(lowerCAmelCase__  )

 return results


if __name__ == "__main__":
      main()


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       )
