



"""simple docstring"""







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

import torch
from datasets import load_dataset
from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor
from torchvision.transforms.functional import InterpolationMode

import transformers
from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    ViTImageProcessor,
    ViTMAEConfig,
    ViTMAEForPreTraining,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
lowercase__		:				str          =	logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("""4.31.0""")

require_version("""datasets>=1.8.0""", """To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt""")







@dataclass
class       UpperCamelCase__   :




      """simple docstring"""




      _SCREAMING_SNAKE_CASE  				=     field(
          default="""cifar10""",					metadata={"""help""": """Name of a dataset from the datasets package"""}  )
      _SCREAMING_SNAKE_CASE  				=     field(
          default=lowercase_,					metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""}  )
      _SCREAMING_SNAKE_CASE  				=     field(
          default=lowercase_,					metadata={"""help""": """The column name of the images in the files."""}  )
      _SCREAMING_SNAKE_CASE  				=     field(default=lowercase_,					metadata={"""help""": """A folder containing the training data."""}  )
      _SCREAMING_SNAKE_CASE  				=     field(default=lowercase_,					metadata={"""help""": """A folder containing the validation data."""}  )
      _SCREAMING_SNAKE_CASE  				=     field(
          default=0.1_5,					metadata={"""help""": """Percent to split off of train for validation."""}  )
      _SCREAMING_SNAKE_CASE  				=     field(
          default=lowercase_,					metadata={
              """help""": (
                  """For debugging purposes or quicker training, truncate the number of training examples to this """
                  """value if set."""
              )
          },					)
      _SCREAMING_SNAKE_CASE  				=     field(
          default=lowercase_,					metadata={
              """help""": (
                  """For debugging purposes or quicker training, truncate the number of evaluation examples to this """
                  """value if set."""
              )
          },					)



      def      SCREAMING_SNAKE_CASE__ (      self				:      str       ):
        lowerCAmelCase_   :				str								= {}
        if self.train_dir is not None:
          lowerCAmelCase_   :				Any								= self.train_dir
        if self.validation_dir is not None:
          lowerCAmelCase_   :				str								= self.validation_dir
        lowerCAmelCase_   :				List[Any]								= data_files if data_files else None







@dataclass
class       UpperCamelCase__   :




      """simple docstring"""




      _SCREAMING_SNAKE_CASE  				=     field(
          default=lowercase_,					metadata={
              """help""": (
                  """The model checkpoint for weights initialization.Don't set if you want to train a model from scratch."""
              )
          },					)
      _SCREAMING_SNAKE_CASE  				=     field(
          default=lowercase_,					metadata={"""help""": """Pretrained config name or path if not the same as model_name_or_path"""}  )
      _SCREAMING_SNAKE_CASE  				=     field(
          default=lowercase_,					metadata={
              """help""": (
                  """Override some existing default config settings when a model is trained from scratch. Example: """
                  """n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index"""
              )
          },					)
      _SCREAMING_SNAKE_CASE  				=     field(
          default=lowercase_,					metadata={"""help""": """Where do you want to store the pretrained models downloaded from s3"""}  )
      _SCREAMING_SNAKE_CASE  				=     field(
          default="""main""",					metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""},					)
      _SCREAMING_SNAKE_CASE  				=     field(default=lowercase_,					metadata={"""help""": """Name or path of preprocessor config."""}  )
      _SCREAMING_SNAKE_CASE  				=     field(
          default=lowercase_,					metadata={
              """help""": (
                  """Will use the token generated when running `huggingface-cli login` (necessary to use this script """
                  """with private models)."""
              )
          },					)
      _SCREAMING_SNAKE_CASE  				=     field(
          default=0.7_5,					metadata={"""help""": """The ratio of the number of masked tokens in the input sequence."""}  )
      _SCREAMING_SNAKE_CASE  				=     field(
          default=lowercase_,					metadata={"""help""": """Whether or not to train with normalized pixel values as target."""}  )







@dataclass
class       UpperCamelCase__   (	lowercase_  ):




      """simple docstring"""




      _SCREAMING_SNAKE_CASE  				=     field(
          default=1e-3,					metadata={"""help""": """Base learning rate: absolute_lr = base_lr * total_batch_size / 256."""}  )




def 				UpperCamelCase_    (    lowerCAmelCase__      :				List[str]						)						->   Tuple:

  """simple docstring"""




  lowerCAmelCase_   :				int								= torch.stack([example['pixel_values'] for example in examples]						)
  return {"pixel_values": pixel_values}

def 				UpperCamelCase_    (    )						->   int:

  """simple docstring"""




  lowerCAmelCase_   :				List[Any]								= HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments)						)
  if len(sys.argv						) == 2 and sys.argv[1].endswith('.json'						):
    # If we pass only one argument to the script and it's the path to a json file,
    # let's parse it to get our arguments.
    lowerCAmelCase_						,lowerCAmelCase_						,lowerCAmelCase_   :				Union[str, Any]								= parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]						)						)
  else:
    lowerCAmelCase_						,lowerCAmelCase_						,lowerCAmelCase_   :				Optional[int]								= parser.parse_args_into_dataclasses()

  # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
  # information sent is the one passed as arguments along with your Python/PyTorch versions.
  send_example_telemetry('run_mae'    ,   lowerCAmelCase__    ,   lowerCAmelCase__						)

  # Setup logging
  logging.basicConfig(
      format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'    ,   datefmt='%m/%d/%Y %H:%M:%S'    ,   handlers=[logging.StreamHandler(sys.stdout						)]    ,   )

  if training_args.should_log:
    # The default of training_args.log_level is passive, so we set log level at info here to have that default.
    transformers.utils.logging.set_verbosity_info()

  lowerCAmelCase_   :				Optional[int]								= training_args.get_process_log_level()
  logger.setLevel(lowerCAmelCase__						)
  transformers.utils.logging.set_verbosity(lowerCAmelCase__						)
  transformers.utils.logging.enable_default_handler()
  transformers.utils.logging.enable_explicit_format()

  # Log on each process the small summary:
  logger.warning(
      f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
      + f"distributed training: {bool(training_args.local_rank != -1						)}, 16-bits training: {training_args.fpaa}"						)
  logger.info(f"Training/evaluation parameters {training_args}"						)

  # Detecting last checkpoint.
  lowerCAmelCase_   :				Tuple								= None
  if os.path.isdir(training_args.output_dir						) and training_args.do_train and not training_args.overwrite_output_dir:
    lowerCAmelCase_   :				List[str]								= get_last_checkpoint(training_args.output_dir						)
    if last_checkpoint is None and len(os.listdir(training_args.output_dir						)						) > 0:
      raise ValueError(
          f"Output directory ({training_args.output_dir}) already exists and is not empty. "
          'Use --overwrite_output_dir to overcome.'						)
    elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
      logger.info(
          f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
          'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'						)

    # Initialize our dataset.
  lowerCAmelCase_   :				Dict								= load_dataset(
      data_args.dataset_name    ,   data_args.dataset_config_name    ,   data_files=data_args.data_files    ,   cache_dir=model_args.cache_dir    ,   use_auth_token=True if model_args.use_auth_token else None    ,   )

  # If we don't have a validation split, split off a percentage of train as validation.
  lowerCAmelCase_   :				List[Any]								= None if 'validation' in ds.keys() else data_args.train_val_split
  if isinstance(data_args.train_val_split    ,   lowerCAmelCase__						) and data_args.train_val_split > 0.0:
    lowerCAmelCase_   :				Tuple								= ds['train'].train_test_split(data_args.train_val_split						)
    lowerCAmelCase_   :				Optional[Any]								= split['train']
    lowerCAmelCase_   :				str								= split['test']

  # Load pretrained model and image processor
  #
  # Distributed training:
  # The .from_pretrained methods guarantee that only one local process can concurrently
  # download model & vocab.
  lowerCAmelCase_   :				Dict								= {
      'cache_dir': model_args.cache_dir,
      'revision': model_args.model_revision,
      'use_auth_token': True if model_args.use_auth_token else None,
  }
  if model_args.config_name:
    lowerCAmelCase_   :				Dict								= ViTMAEConfig.from_pretrained(model_args.config_name    ,   **lowerCAmelCase__						)
  elif model_args.model_name_or_path:
    lowerCAmelCase_   :				List[str]								= ViTMAEConfig.from_pretrained(model_args.model_name_or_path    ,   **lowerCAmelCase__						)
  else:
    lowerCAmelCase_   :				int								= ViTMAEConfig()
    logger.warning('You are instantiating a new config instance from scratch.'						)
    if model_args.config_overrides is not None:
      logger.info(f"Overriding config: {model_args.config_overrides}"						)
      config.update_from_string(model_args.config_overrides						)
      logger.info(f"New config: {config}"						)

    # adapt config
  config.update(
      {
          'mask_ratio': model_args.mask_ratio,
          'norm_pix_loss': model_args.norm_pix_loss,
      }						)

  # create image processor
  if model_args.image_processor_name:
    lowerCAmelCase_   :				Tuple								= ViTImageProcessor.from_pretrained(model_args.image_processor_name    ,   **lowerCAmelCase__						)
  elif model_args.model_name_or_path:
    lowerCAmelCase_   :				Any								= ViTImageProcessor.from_pretrained(model_args.model_name_or_path    ,   **lowerCAmelCase__						)
  else:
    lowerCAmelCase_   :				int								= ViTImageProcessor()

  # create model
  if model_args.model_name_or_path:
    lowerCAmelCase_   :				Optional[Any]								= ViTMAEForPreTraining.from_pretrained(
        model_args.model_name_or_path    ,   from_tf=bool('.ckpt' in model_args.model_name_or_path						)    ,   config=lowerCAmelCase__    ,   cache_dir=model_args.cache_dir    ,   revision=model_args.model_revision    ,   use_auth_token=True if model_args.use_auth_token else None    ,   )
  else:
    logger.info('Training new model from scratch'						)
    lowerCAmelCase_   :				Dict								= ViTMAEForPreTraining(lowerCAmelCase__						)

  if training_args.do_train:
    lowerCAmelCase_   :				Optional[int]								= ds['train'].column_names
  else:
    lowerCAmelCase_   :				List[str]								= ds['validation'].column_names

  if data_args.image_column_name is not None:
    lowerCAmelCase_   :				List[Any]								= data_args.image_column_name
  elif "image" in column_names:
    lowerCAmelCase_   :				Tuple								= 'image'
  elif "img" in column_names:
    lowerCAmelCase_   :				List[str]								= 'img'
  else:
    lowerCAmelCase_   :				str								= column_names[0]

  # transformations as done in original MAE paper
  # source: https://github.com/facebookresearch/mae/blob/main/main_pretrain.py
  if "shortest_edge" in image_processor.size:
    lowerCAmelCase_   :				Optional[Any]								= image_processor.size['shortest_edge']
  else:
    lowerCAmelCase_   :				Optional[int]								= (image_processor.size['height'], image_processor.size['width'])
  lowerCAmelCase_   :				Tuple								= Compose(
      [
          Lambda(lambda lowerCAmelCase__						: img.convert('RGB'						) if img.mode != "RGB" else img						),
          RandomResizedCrop(lowerCAmelCase__    ,   scale=(0.2, 1.0)    ,   interpolation=InterpolationMode.BICUBIC						),
          RandomHorizontalFlip(),
          ToTensor(),
          Normalize(mean=image_processor.image_mean    ,   std=image_processor.image_std						),
      ]						)

  def preprocess_images(lowerCAmelCase__      :				Dict						):
    lowerCAmelCase_   :				Optional[Any]								= [transforms(lowerCAmelCase__						) for image in examples[image_column_name]]
    return examples

  if training_args.do_train:
    if "train" not in ds:
      raise ValueError('--do_train requires a train dataset'						)
    if data_args.max_train_samples is not None:
      lowerCAmelCase_   :				Optional[Any]								= ds['train'].shuffle(seed=training_args.seed						).select(range(data_args.max_train_samples						)						)
    # Set the training transforms
    ds["train"].set_transform(lowerCAmelCase__						)

  if training_args.do_eval:
    if "validation" not in ds:
      raise ValueError('--do_eval requires a validation dataset'						)
    if data_args.max_eval_samples is not None:
      lowerCAmelCase_   :				Dict								= (
          ds['validation'].shuffle(seed=training_args.seed						).select(range(data_args.max_eval_samples						)						)
      )
    # Set the validation transforms
    ds["validation"].set_transform(lowerCAmelCase__						)

  # Compute absolute learning rate
  lowerCAmelCase_   :				Optional[int]								= (
      training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size
  )
  if training_args.base_learning_rate is not None:
    lowerCAmelCase_   :				Any								= training_args.base_learning_rate * total_train_batch_size / 256

  # Initialize our trainer
  lowerCAmelCase_   :				str								= Trainer(
      model=lowerCAmelCase__    ,   args=lowerCAmelCase__    ,   train_dataset=ds['train'] if training_args.do_train else None    ,   eval_dataset=ds['validation'] if training_args.do_eval else None    ,   tokenizer=lowerCAmelCase__    ,   data_collator=lowerCAmelCase__    ,   )

  # Training
  if training_args.do_train:
    lowerCAmelCase_   :				Tuple								= None
    if training_args.resume_from_checkpoint is not None:
      lowerCAmelCase_   :				Tuple								= training_args.resume_from_checkpoint
    elif last_checkpoint is not None:
      lowerCAmelCase_   :				Tuple								= last_checkpoint
    lowerCAmelCase_   :				Tuple								= trainer.train(resume_from_checkpoint=lowerCAmelCase__						)
    trainer.save_model()
    trainer.log_metrics('train'    ,   train_result.metrics						)
    trainer.save_metrics('train'    ,   train_result.metrics						)
    trainer.save_state()

  # Evaluation
  if training_args.do_eval:
    lowerCAmelCase_   :				Dict								= trainer.evaluate()
    trainer.log_metrics('eval'    ,   lowerCAmelCase__						)
    trainer.save_metrics('eval'    ,   lowerCAmelCase__						)

  # Write model card and (optionally) push to hub
  lowerCAmelCase_   :				Union[str, Any]								= {
      'tasks': 'masked-auto-encoding',
      'dataset': data_args.dataset_name,
      'tags': ['masked-auto-encoding'],
  }
  if training_args.push_to_hub:
    trainer.push_to_hub(**lowerCAmelCase__						)
  else:
    trainer.create_model_card(**lowerCAmelCase__						)

def 				UpperCamelCase_    (    lowerCAmelCase__      :				Union[str, Any]						)						->   Optional[int]:

  """simple docstring"""




  main()


if __name__ == "__main__":
     main()










"""simple docstring"""







from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import RegNetConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
     import tensorflow as tf

     from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel


if is_vision_available():
     from PIL import Image

     from transformers import AutoImageProcessor







class       UpperCamelCase__   :




      """simple docstring"""




      def __init__(      self				:      Dict    ,			SCREAMING_SNAKE_CASE_				:      str    ,			SCREAMING_SNAKE_CASE_				:      Optional[Any]=3    ,			SCREAMING_SNAKE_CASE_				:      Any=3_2    ,			SCREAMING_SNAKE_CASE_				:      int=3    ,			SCREAMING_SNAKE_CASE_				:      Optional[Any]=1_0    ,			SCREAMING_SNAKE_CASE_				:      Dict=[1_0, 2_0, 3_0, 4_0]    ,			SCREAMING_SNAKE_CASE_				:      int=[1, 1, 2, 1]    ,			SCREAMING_SNAKE_CASE_				:      int=True    ,			SCREAMING_SNAKE_CASE_				:      Optional[Any]=True    ,			SCREAMING_SNAKE_CASE_				:      int="relu"    ,			SCREAMING_SNAKE_CASE_				:      Union[str, Any]=3    ,			SCREAMING_SNAKE_CASE_				:      List[str]=None    ,			):
        lowerCAmelCase_   :				Optional[int]								= parent
        lowerCAmelCase_   :				Union[str, Any]								= batch_size
        lowerCAmelCase_   :				Optional[int]								= image_size
        lowerCAmelCase_   :				Optional[int]								= num_channels
        lowerCAmelCase_   :				Any								= embeddings_size
        lowerCAmelCase_   :				Dict								= hidden_sizes
        lowerCAmelCase_   :				Any								= depths
        lowerCAmelCase_   :				Optional[int]								= is_training
        lowerCAmelCase_   :				int								= use_labels
        lowerCAmelCase_   :				List[Any]								= hidden_act
        lowerCAmelCase_   :				Dict								= num_labels
        lowerCAmelCase_   :				Optional[int]								= scope
        lowerCAmelCase_   :				Tuple								= len(SCREAMING_SNAKE_CASE_       )



      def      SCREAMING_SNAKE_CASE__ (      self				:      Any       ):
        lowerCAmelCase_   :				List[str]								= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

        lowerCAmelCase_   :				Union[str, Any]								= None
        if self.use_labels:
          lowerCAmelCase_   :				int								= ids_tensor([self.batch_size]    ,			self.num_labels       )

        lowerCAmelCase_   :				List[str]								= self.get_config()
        return config, pixel_values, labels



      def      SCREAMING_SNAKE_CASE__ (      self				:      str       ):
        return RegNetConfig(
            num_channels=self.num_channels    ,			embeddings_size=self.embeddings_size    ,			hidden_sizes=self.hidden_sizes    ,			depths=self.depths    ,			hidden_act=self.hidden_act    ,			num_labels=self.num_labels    ,			)



      def      SCREAMING_SNAKE_CASE__ (      self				:      Any    ,			SCREAMING_SNAKE_CASE_				:      List[str]    ,			SCREAMING_SNAKE_CASE_				:      List[Any]    ,			SCREAMING_SNAKE_CASE_				:      int       ):
        lowerCAmelCase_   :				List[Any]								= TFRegNetModel(config=SCREAMING_SNAKE_CASE_       )
        lowerCAmelCase_   :				List[Any]								= model(SCREAMING_SNAKE_CASE_    ,			training=SCREAMING_SNAKE_CASE_       )
        # expected last hidden states: B, C, H // 32, W // 32
        self.parent.assertEqual(
            result.last_hidden_state.shape    ,			(self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2)    ,			)



      def      SCREAMING_SNAKE_CASE__ (      self				:      List[str]    ,			SCREAMING_SNAKE_CASE_				:      Tuple    ,			SCREAMING_SNAKE_CASE_				:      Optional[int]    ,			SCREAMING_SNAKE_CASE_				:      Optional[Any]       ):
        lowerCAmelCase_   :				int								= self.num_labels
        lowerCAmelCase_   :				int								= TFRegNetForImageClassification(SCREAMING_SNAKE_CASE_       )
        lowerCAmelCase_   :				Dict								= model(SCREAMING_SNAKE_CASE_    ,			labels=SCREAMING_SNAKE_CASE_    ,			training=SCREAMING_SNAKE_CASE_       )
        self.parent.assertEqual(result.logits.shape    ,			(self.batch_size, self.num_labels)       )





      def      SCREAMING_SNAKE_CASE__ (      self				:      List[str]       ):
        lowerCAmelCase_   :				str								= self.prepare_config_and_inputs()
        lowerCAmelCase_						,lowerCAmelCase_						,lowerCAmelCase_   :				Tuple								= config_and_inputs
        lowerCAmelCase_   :				Optional[Any]								= {'pixel_values': pixel_values}
        return config, inputs_dict







@require_tf
class       UpperCamelCase__   (	lowercase_,					lowercase_,					unittest.TestCase  ):




      """simple docstring"""




      _SCREAMING_SNAKE_CASE  				=     (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
      _SCREAMING_SNAKE_CASE  				=     (
          {"""feature-extraction""": TFRegNetModel, """image-classification""": TFRegNetForImageClassification}
          if is_tf_available()
          else {}
      )

      _SCREAMING_SNAKE_CASE  				=     False
      _SCREAMING_SNAKE_CASE  				=     False
      _SCREAMING_SNAKE_CASE  				=     False
      _SCREAMING_SNAKE_CASE  				=     False
      _SCREAMING_SNAKE_CASE  				=     False



      def      SCREAMING_SNAKE_CASE__ (      self				:      List[Any]       ):
        lowerCAmelCase_   :				List[Any]								= TFRegNetModelTester(self       )
        lowerCAmelCase_   :				Tuple								= ConfigTester(self    ,			config_class=SCREAMING_SNAKE_CASE_    ,			has_text_modality=SCREAMING_SNAKE_CASE_       )



      def      SCREAMING_SNAKE_CASE__ (      self				:      Optional[int]       ):
        return



      @unittest.skip(reason='RegNet does not use inputs_embeds'       )
      def      SCREAMING_SNAKE_CASE__ (      self				:      List[Any]       ):
        pass



      @unittest.skipIf(
          not is_tf_available() or len(tf.config.list_physical_devices('GPU'       )       ) == 0    ,			reason='TF does not support backprop for grouped convolutions on CPU.'    ,			)
      @slow
      def      SCREAMING_SNAKE_CASE__ (      self				:      Tuple       ):
        super().test_keras_fit()



      @unittest.skip(reason='RegNet does not support input and output embeddings'       )
      def      SCREAMING_SNAKE_CASE__ (      self				:      Union[str, Any]       ):
        pass



      def      SCREAMING_SNAKE_CASE__ (      self				:      int       ):
        lowerCAmelCase_						,lowerCAmelCase_   :				Optional[int]								= self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
          lowerCAmelCase_   :				int								= model_class(SCREAMING_SNAKE_CASE_       )
          lowerCAmelCase_   :				Dict								= inspect.signature(model.call       )
          # signature.parameters is an OrderedDict => so arg_names order is deterministic
          lowerCAmelCase_   :				List[Any]								= [*signature.parameters.keys()]

          lowerCAmelCase_   :				Any								= ['pixel_values']
          self.assertListEqual(arg_names[:1]    ,			SCREAMING_SNAKE_CASE_       )



      def      SCREAMING_SNAKE_CASE__ (      self				:      Any       ):
        lowerCAmelCase_   :				Dict								= self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_       )



      def      SCREAMING_SNAKE_CASE__ (      self				:      Optional[int]       ):
        def check_hidden_states_output(SCREAMING_SNAKE_CASE_				:      Tuple    ,			SCREAMING_SNAKE_CASE_				:      int    ,			SCREAMING_SNAKE_CASE_				:      Tuple       ):
          lowerCAmelCase_   :				List[Any]								= model_class(SCREAMING_SNAKE_CASE_       )
          lowerCAmelCase_   :				Union[str, Any]								= model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )    ,			training=SCREAMING_SNAKE_CASE_       )

          lowerCAmelCase_   :				List[str]								= outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

          lowerCAmelCase_   :				Union[str, Any]								= self.model_tester.num_stages
          self.assertEqual(len(SCREAMING_SNAKE_CASE_       )    ,			expected_num_stages + 1       )

          # RegNet's feature maps are of shape (batch_size, num_channels, height, width)
          self.assertListEqual(
              list(hidden_states[0].shape[-2:]       )    ,			[self.model_tester.image_size // 2, self.model_tester.image_size // 2]    ,			)

        lowerCAmelCase_						,lowerCAmelCase_   :				List[Any]								= self.model_tester.prepare_config_and_inputs_for_common()
        lowerCAmelCase_   :				Optional[int]								= ['basic', 'bottleneck']
        for model_class in self.all_model_classes:
          for layer_type in layers_type:
            lowerCAmelCase_   :				str								= layer_type
            lowerCAmelCase_   :				List[str]								= True
            check_hidden_states_output(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )

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

            check_hidden_states_output(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )



      def      SCREAMING_SNAKE_CASE__ (      self				:      Optional[Any]       ):
        lowerCAmelCase_						,lowerCAmelCase_   :				int								= self.model_tester.prepare_config_and_inputs_for_common()

        def check_equivalence(SCREAMING_SNAKE_CASE_				:      Dict    ,			SCREAMING_SNAKE_CASE_				:      str    ,			SCREAMING_SNAKE_CASE_				:      Optional[int]    ,			SCREAMING_SNAKE_CASE_				:      str={}       ):
          lowerCAmelCase_   :				Optional[Any]								= model(SCREAMING_SNAKE_CASE_    ,			return_dict=SCREAMING_SNAKE_CASE_    ,			**SCREAMING_SNAKE_CASE_       )
          lowerCAmelCase_   :				List[Any]								= model(SCREAMING_SNAKE_CASE_    ,			return_dict=SCREAMING_SNAKE_CASE_    ,			**SCREAMING_SNAKE_CASE_       ).to_tuple()

          def recursive_check(SCREAMING_SNAKE_CASE_				:      int    ,			SCREAMING_SNAKE_CASE_				:      int       ):
            if isinstance(SCREAMING_SNAKE_CASE_    ,			(List, Tuple)       ):
              for tuple_iterable_value, dict_iterable_value in zip(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       ):
                recursive_check(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )
            elif tuple_object is None:
              return
            else:
              self.assertTrue(
                  all(tf.equal(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )       )    ,			msg=(
                      'Tuple and dict output are not equal. Difference:'
                      F" {tf.math.reduce_max(tf.abs(tuple_object - dict_object       )       )}"
                  )    ,			)

            recursive_check(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )

        for model_class in self.all_model_classes:
          lowerCAmelCase_   :				Union[str, Any]								= model_class(SCREAMING_SNAKE_CASE_       )

          lowerCAmelCase_   :				List[Any]								= self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )
          lowerCAmelCase_   :				Union[str, Any]								= self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )
          check_equivalence(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )

          lowerCAmelCase_   :				Optional[int]								= self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			return_labels=SCREAMING_SNAKE_CASE_       )
          lowerCAmelCase_   :				str								= self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			return_labels=SCREAMING_SNAKE_CASE_       )
          check_equivalence(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )

          lowerCAmelCase_   :				Tuple								= self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )
          lowerCAmelCase_   :				int								= self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )
          check_equivalence(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			{'output_hidden_states': True}       )

          lowerCAmelCase_   :				List[Any]								= self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			return_labels=SCREAMING_SNAKE_CASE_       )
          lowerCAmelCase_   :				Any								= self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			return_labels=SCREAMING_SNAKE_CASE_       )
          check_equivalence(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			{'output_hidden_states': True}       )



      def      SCREAMING_SNAKE_CASE__ (      self				:      Union[str, Any]       ):
        lowerCAmelCase_   :				List[str]								= self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE_       )





      @slow
      def      SCREAMING_SNAKE_CASE__ (      self				:      Union[str, Any]       ):
        for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          lowerCAmelCase_   :				int								= TFRegNetModel.from_pretrained(SCREAMING_SNAKE_CASE_       )
          self.assertIsNotNone(SCREAMING_SNAKE_CASE_       )




def 				UpperCamelCase_    (    )						->   List[str]:

  """simple docstring"""




  lowerCAmelCase_   :				Optional[Any]								= Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
  return image







@require_tf
@require_vision
class       UpperCamelCase__   (	unittest.TestCase  ):




      """simple docstring"""




      @cached_property
      def      SCREAMING_SNAKE_CASE__ (      self				:      Union[str, Any]       ):
        return (
            AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )
            if is_vision_available()
            else None
        )





      @slow
      def      SCREAMING_SNAKE_CASE__ (      self				:      List[Any]       ):
        lowerCAmelCase_   :				int								= TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )

        lowerCAmelCase_   :				Tuple								= self.default_image_processor
        lowerCAmelCase_   :				Dict								= prepare_img()
        lowerCAmelCase_   :				Union[str, Any]								= image_processor(images=SCREAMING_SNAKE_CASE_    ,			return_tensors='tf'       )

        # forward pass
        lowerCAmelCase_   :				List[str]								= model(**SCREAMING_SNAKE_CASE_    ,			training=SCREAMING_SNAKE_CASE_       )

        # verify the logits
        lowerCAmelCase_   :				Optional[Any]								= tf.TensorShape((1, 1_0_0_0)       )
        self.assertEqual(outputs.logits.shape    ,			SCREAMING_SNAKE_CASE_       )

        lowerCAmelCase_   :				List[Any]								= tf.constant([-0.41_80, -1.50_51, -3.48_36]       )

        tf.debugging.assert_near(outputs.logits[0, :3]    ,			SCREAMING_SNAKE_CASE_    ,			atol=1E-4       )





