

import argparse
import os

import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed

from accelerate import Accelerator, DistributedType


########################################################################
# This is a fully working simple example to use Accelerate,
# specifically showcasing the checkpointing capability,
# and builds off the `nlp_example.py` script.
#
# This example trains a Bert base model on GLUE MRPC
# in any of the following settings (with the same script):
#   - single CPU or single GPU
#   - multi GPUS (using PyTorch distributed mode)
#   - (multi) TPUs
#   - fp16 (mixed-precision) or fp32 (normal precision)
#
# To help focus on the differences in the code, building `DataLoaders`
# was refactored into its own function.
# New additions from the base script can be found quickly by
# looking for the # New Code # tags
#
# To run it in each of these various modes, follow the instructions
# in the readme for examples:
# https://github.com/huggingface/accelerate/tree/main/examples
#
########################################################################

UpperCAmelCase__	:       str			      =      16
UpperCAmelCase__	:       Tuple			      =      32






def    __lowercase (       _A  ,      _A = 16     )       ->  Optional[int]:
      SCREAMING_SNAKE_CASE	: Tuple					       =				AutoTokenizer.from_pretrained("""bert-base-cased"""     )
      SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				load_dataset("""glue"""  ,      """mrpc"""     )

      def tokenize_function(_A     ):
            # max_length=None => use the model max length (it's actually the default)
            SCREAMING_SNAKE_CASE	: Dict					       =				tokenizer(examples["""sentence1"""]  ,      examples["""sentence2"""]  ,      truncation=_A  ,      max_length=_A     )
            return outputs

      # Apply the method we just defined to all the examples in all the splits of the dataset
      # starting with the main process first:
      with accelerator.main_process_first():
            SCREAMING_SNAKE_CASE	: Optional[int]					       =				datasets.map(
                _A  ,      batched=_A  ,      remove_columns=["""idx""", """sentence1""", """sentence2"""]  ,      )

      # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
      # transformers library
      SCREAMING_SNAKE_CASE	: Optional[int]					       =				tokenized_datasets.rename_column("""label"""  ,      """labels"""     )

      def collate_fn(_A     ):
            # On TPU it's best to pad everything to the same length or training will be very slow.
            SCREAMING_SNAKE_CASE	: Optional[Any]					       =				128 if accelerator.distributed_type == DistributedType.TPU else None
            # When using mixed precision we want round multiples of 8/16
            if accelerator.mixed_precision == "fp8":
                  SCREAMING_SNAKE_CASE	: Tuple					       =				16
            elif accelerator.mixed_precision != "no":
                  SCREAMING_SNAKE_CASE	: int					       =				8
            else:
                  SCREAMING_SNAKE_CASE	: str					       =				None

            return tokenizer.pad(
                _A  ,      padding="""longest"""  ,      max_length=_A  ,      pad_to_multiple_of=_A  ,      return_tensors="""pt"""  ,      )

      # Instantiate dataloaders.
      SCREAMING_SNAKE_CASE	: Tuple					       =				DataLoader(
          tokenized_datasets["""train"""]  ,      shuffle=_A  ,      collate_fn=_A  ,      batch_size=_A     )
      SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				DataLoader(
          tokenized_datasets["""validation"""]  ,      shuffle=_A  ,      collate_fn=_A  ,      batch_size=_A     )

      return train_dataloader, eval_dataloader


# For testing only
if os.environ.get("""TESTING_MOCKED_DATALOADERS""", None) == "1":
  from accelerate.test_utils.training import mocked_dataloaders

  UpperCAmelCase__	:       Union[str, Any]			      =      mocked_dataloaders  # noqa: F811






def    __lowercase (       _A  ,      _A     )       ->  Optional[int]:
      # For testing only
      if os.environ.get("""TESTING_MOCKED_DATALOADERS"""  ,      _A     ) == "1":
            SCREAMING_SNAKE_CASE	: List[Any]					       =				2
      # Initialize accelerator
      SCREAMING_SNAKE_CASE	: List[str]					       =				Accelerator(cpu=args.cpu  ,      mixed_precision=args.mixed_precision     )
      # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
      SCREAMING_SNAKE_CASE	: str					       =				config["""lr"""]
      SCREAMING_SNAKE_CASE	: Tuple					       =				int(config["""num_epochs"""]     )
      SCREAMING_SNAKE_CASE	: Tuple					       =				int(config["""seed"""]     )
      SCREAMING_SNAKE_CASE	: int					       =				int(config["""batch_size"""]     )

      # New Code #
      # Parse out whether we are saving every epoch or after a certain number of batches
      if hasattr(args.checkpointing_steps  ,      """isdigit"""     ):
            if args.checkpointing_steps == "epoch":
                  SCREAMING_SNAKE_CASE	: str					       =				args.checkpointing_steps
            elif args.checkpointing_steps.isdigit():
                  SCREAMING_SNAKE_CASE	: Any					       =				int(args.checkpointing_steps     )
            else:
                  raise ValueError(
                      F"Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed."     )
      else:
            SCREAMING_SNAKE_CASE	: Optional[Any]					       =				None

      set_seed(_A     )

      SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: str					       =				get_dataloaders(_A  ,      _A     )
      SCREAMING_SNAKE_CASE	: Optional[int]					       =				evaluate.load("""glue"""  ,      """mrpc"""     )

      # If the batch size is too big we use gradient accumulation
      SCREAMING_SNAKE_CASE	: Optional[int]					       =				1
      if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
            SCREAMING_SNAKE_CASE	: List[str]					       =				batch_size // MAX_GPU_BATCH_SIZE
            SCREAMING_SNAKE_CASE	: Optional[Any]					       =				MAX_GPU_BATCH_SIZE

      # Instantiate the model (we build the model here so that the seed also control new weights initialization)
      SCREAMING_SNAKE_CASE	: str					       =				AutoModelForSequenceClassification.from_pretrained("""bert-base-cased"""  ,      return_dict=_A     )

      # We could avoid this line since the accelerator is set with `device_placement=True` (default value).
      # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
      # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
      SCREAMING_SNAKE_CASE	: Any					       =				model.to(accelerator.device     )

      # Instantiate optimizer
      SCREAMING_SNAKE_CASE	: Optional[Any]					       =				AdamW(params=model.parameters()  ,      lr=_A     )

      # Instantiate scheduler
      SCREAMING_SNAKE_CASE	: Dict					       =				get_linear_schedule_with_warmup(
          optimizer=_A  ,      num_warmup_steps=100  ,      num_training_steps=(len(_A     ) * num_epochs) // gradient_accumulation_steps  ,      )

      # Prepare everything
      # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
      # prepare method.
      SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: Tuple					       =				accelerator.prepare(
          _A  ,      _A  ,      _A  ,      _A  ,      _A     )

      # New Code #
      # We need to keep track of how many total steps we have iterated over
      SCREAMING_SNAKE_CASE	: int					       =				0
      # We also need to keep track of the stating epoch so files are named properly
      SCREAMING_SNAKE_CASE	: Tuple					       =				0

      # We need to load the checkpoint back in before training here with `load_state`
      # The total number of epochs is adjusted based on where the state is being loaded from,
      # as we assume continuation of the same training script
      if args.resume_from_checkpoint:
            if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
                  accelerator.print(F"Resumed from checkpoint: {args.resume_from_checkpoint}"     )
                  accelerator.load_state(args.resume_from_checkpoint     )
                  SCREAMING_SNAKE_CASE	: List[Any]					       =				os.path.basename(args.resume_from_checkpoint     )
            else:
                  # Get the most recent checkpoint
                  SCREAMING_SNAKE_CASE	: Optional[int]					       =				[f.name for f in os.scandir(os.getcwd()     ) if f.is_dir()]
                  dirs.sort(key=os.path.getctime     )
                  SCREAMING_SNAKE_CASE	: Any					       =				dirs[-1]  # Sorts folders by date modified, most recent checkpoint is the last
            # Extract `epoch_{i}` or `step_{i}`
            SCREAMING_SNAKE_CASE	: List[Any]					       =				os.path.splitext(_A     )[0]

            if "epoch" in training_difference:
                  SCREAMING_SNAKE_CASE	: Optional[Any]					       =				int(training_difference.replace("""epoch_"""  ,      """"""     )     ) + 1
                  SCREAMING_SNAKE_CASE	: Optional[Any]					       =				None
            else:
                  SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				int(training_difference.replace("""step_"""  ,      """"""     )     )
                  SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				resume_step // len(_A     )
                  resume_step -= starting_epoch * len(_A     )

    # Now we train the model
      for epoch in range(_A  ,      _A     ):
            model.train()
            # New Code #
            if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
                  # We need to skip steps until we reach the resumed step
                  SCREAMING_SNAKE_CASE	: Tuple					       =				accelerator.skip_first_batches(_A  ,      _A     )
                  overall_step += resume_step
            else:
                  # After the first iteration though, we need to go back to the original dataloader
                  SCREAMING_SNAKE_CASE	: Optional[int]					       =				train_dataloader
            for step, batch in enumerate(_A     ):
                  # We could avoid this line since we set the accelerator with `device_placement=True`.
                  batch.to(accelerator.device     )
                  SCREAMING_SNAKE_CASE	: str					       =				model(**_A     )
                  SCREAMING_SNAKE_CASE	: int					       =				outputs.loss
                  SCREAMING_SNAKE_CASE	: Tuple					       =				loss / gradient_accumulation_steps
                  accelerator.backward(_A     )
                  if step % gradient_accumulation_steps == 0:
                        optimizer.step()
                        lr_scheduler.step()
                        optimizer.zero_grad()
                  # New Code #
                  overall_step += 1

                  # New Code #
                  # We save the model, optimizer, lr_scheduler, and seed states by calling `save_state`
                  # These are saved to folders named `step_{overall_step}`
                  # Will contain files: "pytorch_model.bin", "optimizer.bin", "scheduler.bin", and "random_states.pkl"
                  # If mixed precision was used, will also save a "scalar.bin" file
                  if isinstance(_A  ,      _A     ):
                        SCREAMING_SNAKE_CASE	: Optional[int]					       =				F"step_{overall_step}"
                        if overall_step % checkpointing_steps == 0:
                              if args.output_dir is not None:
                                    SCREAMING_SNAKE_CASE	: Any					       =				os.path.join(args.output_dir  ,      _A     )
                              accelerator.save_state(_A     )

            model.eval()
            for step, batch in enumerate(_A     ):
                  # We could avoid this line since we set the accelerator with `device_placement=True` (the default).
                  batch.to(accelerator.device     )
                  with torch.no_grad():
                        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				model(**_A     )
                  SCREAMING_SNAKE_CASE	: Tuple					       =				outputs.logits.argmax(dim=-1     )
                  SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: List[str]					       =				accelerator.gather_for_metrics((predictions, batch["""labels"""])     )
                  metric.add_batch(
                      predictions=_A  ,      references=_A  ,      )

            SCREAMING_SNAKE_CASE	: Optional[int]					       =				metric.compute()
            # Use accelerator.print to print only on the main process.
            accelerator.print(F"epoch {epoch}:"  ,      _A     )

            # New Code #
            # We save the model, optimizer, lr_scheduler, and seed states by calling `save_state`
            # These are saved to folders named `epoch_{epoch}`
            # Will contain files: "pytorch_model.bin", "optimizer.bin", "scheduler.bin", and "random_states.pkl"
            # If mixed precision was used, will also save a "scalar.bin" file
            if checkpointing_steps == "epoch":
                  SCREAMING_SNAKE_CASE	: Dict					       =				F"epoch_{epoch}"
                  if args.output_dir is not None:
                        SCREAMING_SNAKE_CASE	: List[Any]					       =				os.path.join(args.output_dir  ,      _A     )
                  accelerator.save_state(_A     )






def    __lowercase (       )       ->  int:
      SCREAMING_SNAKE_CASE	: Dict					       =				argparse.ArgumentParser(description="""Simple example of training script."""     )
      parser.add_argument(
          """--mixed_precision"""  ,      type=_A  ,      default=_A  ,      choices=["""no""", """fp16""", """bf16""", """fp8"""]  ,      help="""Whether to use mixed precision. Choose"""
          """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."""
          """and an Nvidia Ampere GPU."""  ,      )
      parser.add_argument("""--cpu"""  ,      action="""store_true"""  ,      help="""If passed, will train on the CPU."""     )
      parser.add_argument(
          """--checkpointing_steps"""  ,      type=_A  ,      default=_A  ,      help="""Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch."""  ,      )
      parser.add_argument(
          """--output_dir"""  ,      type=_A  ,      default="""."""  ,      help="""Optional save directory where all checkpoint folders will be stored. Default is the current working directory."""  ,      )
      parser.add_argument(
          """--resume_from_checkpoint"""  ,      type=_A  ,      default=_A  ,      help="""If the training should continue from a checkpoint folder."""  ,      )
      SCREAMING_SNAKE_CASE	: Any					       =				parser.parse_args()
      SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				{"""lr""": 2e-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16}
      training_function(_A  ,      _A     )


if __name__ == "__main__":
  main()







import inspect
import unittest

from transformers import EfficientNetConfig
from transformers.testing_utils import is_pipeline_test, require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch

  from transformers import EfficientNetForImageClassification, EfficientNetModel
  from transformers.models.efficientnet.modeling_efficientnet import EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import AutoImageProcessor







class     a__    :







  """simple docstring"""




  def __init__(     self      :	Any			,			UpperCAmelCase__      :	Union[str, Any]			,			UpperCAmelCase__      :	List[str]=1_3			,			UpperCAmelCase__      :	Any=3_2			,			UpperCAmelCase__      :	Union[str, Any]=3			,			UpperCAmelCase__      :	List[str]=[3, 3, 5]			,			UpperCAmelCase__      :	int=[3_2, 1_6, 2_4]			,			UpperCAmelCase__      :	Dict=[1_6, 2_4, 4_0]			,			UpperCAmelCase__      :	Optional[Any]=[1, 1, 2]			,			UpperCAmelCase__      :	List[Any]=[1, 1, 2]			,			UpperCAmelCase__      :	str=[1, 6, 6]			,			UpperCAmelCase__      :	List[Any]=True			,			UpperCAmelCase__      :	int=True			,			UpperCAmelCase__      :	Any=3_7			,			UpperCAmelCase__      :	Any="gelu"			,			UpperCAmelCase__      :	List[Any]=1_0			,			)   ->Dict:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Optional[int]					       =				parent
        SCREAMING_SNAKE_CASE	: Any					       =				batch_size
        SCREAMING_SNAKE_CASE	: List[Any]					       =				image_size
        SCREAMING_SNAKE_CASE	: str					       =				num_channels
        SCREAMING_SNAKE_CASE	: int					       =				kernel_sizes
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				in_channels
        SCREAMING_SNAKE_CASE	: List[str]					       =				out_channels
        SCREAMING_SNAKE_CASE	: int					       =				strides
        SCREAMING_SNAKE_CASE	: List[str]					       =				num_block_repeats
        SCREAMING_SNAKE_CASE	: Tuple					       =				expand_ratios
        SCREAMING_SNAKE_CASE	: Dict					       =				is_training
        SCREAMING_SNAKE_CASE	: Optional[int]					       =				hidden_act
        SCREAMING_SNAKE_CASE	: int					       =				num_labels
        SCREAMING_SNAKE_CASE	: Dict					       =				use_labels


  def 	_lowercase (     self      :	Any						)   ->Any:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

        SCREAMING_SNAKE_CASE	: Dict					       =				None
        if self.use_labels:
              SCREAMING_SNAKE_CASE	: Optional[Any]					       =				ids_tensor([self.batch_size]			,			self.num_labels						)

        SCREAMING_SNAKE_CASE	: Dict					       =				self.get_config()
        return config, pixel_values, labels


  def 	_lowercase (     self      :	Tuple						)   ->Optional[int]:
        """simple docstring"""







        return EfficientNetConfig(
            num_channels=self.num_channels			,			kernel_sizes=self.kernel_sizes			,			in_channels=self.in_channels			,			out_channels=self.out_channels			,			strides=self.strides			,			num_block_repeats=self.num_block_repeats			,			expand_ratios=self.expand_ratios			,			hidden_act=self.hidden_act			,			num_labels=self.num_labels			,			)


  def 	_lowercase (     self      :	List[Any]			,			UpperCAmelCase__      :	str			,			UpperCAmelCase__      :	int			,			UpperCAmelCase__      :	Optional[Any]						)   ->Union[str, Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: List[Any]					       =				EfficientNetModel(config=UpperCAmelCase__						)
        model.to(UpperCAmelCase__						)
        model.eval()
        SCREAMING_SNAKE_CASE	: str					       =				model(UpperCAmelCase__						)
        # expected last hidden states: B, C, H // 4, W // 4
        self.parent.assertEqual(
            result.last_hidden_state.shape			,			(self.batch_size, config.hidden_dim, self.image_size // 4, self.image_size // 4)			,			)


  def 	_lowercase (     self      :	Optional[int]			,			UpperCAmelCase__      :	List[Any]			,			UpperCAmelCase__      :	Optional[int]			,			UpperCAmelCase__      :	Union[str, Any]						)   ->int:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				EfficientNetForImageClassification(UpperCAmelCase__						)
        model.to(UpperCAmelCase__						)
        model.eval()
        SCREAMING_SNAKE_CASE	: Any					       =				model(UpperCAmelCase__			,			labels=UpperCAmelCase__						)
        self.parent.assertEqual(result.logits.shape			,			(self.batch_size, self.num_labels)						)




  def 	_lowercase (     self      :	Dict						)   ->str:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: List[str]					       =				self.prepare_config_and_inputs()
        SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: Any					       =				config_and_inputs
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				{"""pixel_values""": pixel_values}
        return config, inputs_dict







@require_torch
class     a__    (				UpperCAmelCase		,     UpperCAmelCase		,     unittest.TestCase    ):







  """simple docstring"""




  UpperCAmelCase__ :	Tuple         =(EfficientNetModel, EfficientNetForImageClassification) if is_torch_available() else ()
  UpperCAmelCase__ :	Optional[int]         =(
      {"""feature-extraction""": EfficientNetModel, """image-classification""": EfficientNetForImageClassification}
      if is_torch_available()
      else {}
  )

  UpperCAmelCase__ :	List[str]         =False
  UpperCAmelCase__ :	Any         =False
  UpperCAmelCase__ :	Union[str, Any]         =False
  UpperCAmelCase__ :	Dict         =False
  UpperCAmelCase__ :	List[str]         =False


  def 	_lowercase (     self      :	Optional[Any]						)   ->Tuple:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				EfficientNetModelTester(self						)
        SCREAMING_SNAKE_CASE	: Any					       =				ConfigTester(
            self			,			config_class=UpperCAmelCase__			,			has_text_modality=UpperCAmelCase__			,			hidden_size=3_7						)


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







        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      :	List[Any]						)   ->Optional[int]:
        """simple docstring"""







        return


  @unittest.skip(reason="""EfficientNet does not use inputs_embeds"""						)
  def 	_lowercase (     self      :	Dict						)   ->Tuple:
        """simple docstring"""







        pass


  @unittest.skip(reason="""EfficientNet does not support input and output embeddings"""						)
  def 	_lowercase (     self      :	Dict						)   ->Dict:
        """simple docstring"""







        pass


  @unittest.skip(reason="""EfficientNet does not use feedforward chunking"""						)
  def 	_lowercase (     self      :	Optional[Any]						)   ->Any:
        """simple docstring"""







        pass


  def 	_lowercase (     self      :	str						)   ->Optional[int]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: Optional[Any]					       =				self.model_tester.prepare_config_and_inputs_for_common()

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

              SCREAMING_SNAKE_CASE	: Dict					       =				["""pixel_values"""]
              self.assertListEqual(arg_names[:1]			,			UpperCAmelCase__						)


  def 	_lowercase (     self      :	Optional[int]						)   ->Optional[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Optional[int]					       =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*UpperCAmelCase__						)


  def 	_lowercase (     self      :	List[Any]						)   ->int:
        """simple docstring"""







        def check_hidden_states_output(UpperCAmelCase__      :	Optional[Any]			,			UpperCAmelCase__      :	Any			,			UpperCAmelCase__      :	Dict						):
              SCREAMING_SNAKE_CASE	: Optional[Any]					       =				model_class(UpperCAmelCase__						)
              model.to(UpperCAmelCase__						)
              model.eval()

              with torch.no_grad():
                    SCREAMING_SNAKE_CASE	: Any					       =				model(**self._prepare_for_class(UpperCAmelCase__			,			UpperCAmelCase__						)						)

              SCREAMING_SNAKE_CASE	: Optional[int]					       =				outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
              SCREAMING_SNAKE_CASE	: Any					       =				sum(config.num_block_repeats						) * 4
              self.assertEqual(len(UpperCAmelCase__						)			,			UpperCAmelCase__						)

              # EfficientNet'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]			,			)

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

        for model_class in self.all_model_classes:
              SCREAMING_SNAKE_CASE	: Optional[Any]					       =				True
              check_hidden_states_output(UpperCAmelCase__			,			UpperCAmelCase__			,			UpperCAmelCase__						)

              # check that output_hidden_states also work using config
              del inputs_dict["output_hidden_states"]
              SCREAMING_SNAKE_CASE	: Dict					       =				True

              check_hidden_states_output(UpperCAmelCase__			,			UpperCAmelCase__			,			UpperCAmelCase__						)


  def 	_lowercase (     self      :	Union[str, Any]						)   ->Optional[int]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Tuple					       =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__						)


  @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""						)
  def 	_lowercase (     self      :	List[str]						)   ->Optional[Any]:
        """simple docstring"""







        pass


  @slow
  def 	_lowercase (     self      :	Dict						)   ->List[Any]:
        """simple docstring"""







        for model_name in EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              SCREAMING_SNAKE_CASE	: str					       =				EfficientNetModel.from_pretrained(UpperCAmelCase__						)
              self.assertIsNotNone(UpperCAmelCase__						)




  @is_pipeline_test
  @require_vision
  @slow
  def 	_lowercase (     self      :	Any						)   ->Any:
        """simple docstring"""







        super().test_pipeline_image_classification()






def    __lowercase (       )       ->  List[Any]:
      SCREAMING_SNAKE_CASE	: List[str]					       =				Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""     )
      return image







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







  """simple docstring"""




  @cached_property
  def 	_lowercase (     self      :	List[str]						)   ->Tuple:
        """simple docstring"""







        return AutoImageProcessor.from_pretrained("""google/efficientnet-b7"""						) if is_vision_available() else None




  @slow
  def 	_lowercase (     self      :	List[Any]						)   ->Any:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Tuple					       =				EfficientNetForImageClassification.from_pretrained("""google/efficientnet-b7"""						).to(UpperCAmelCase__						)

        SCREAMING_SNAKE_CASE	: int					       =				self.default_image_processor
        SCREAMING_SNAKE_CASE	: List[Any]					       =				prepare_img()
        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				image_processor(images=UpperCAmelCase__			,			return_tensors="""pt"""						).to(UpperCAmelCase__						)

        # forward pass
        with torch.no_grad():
              SCREAMING_SNAKE_CASE	: Optional[Any]					       =				model(**UpperCAmelCase__						)

        # verify the logits
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				torch.Size((1, 1_0_0_0)						)
        self.assertEqual(outputs.logits.shape			,			UpperCAmelCase__						)

        SCREAMING_SNAKE_CASE	: Any					       =				torch.tensor([0.00_01, 0.00_02, 0.00_02]						).to(UpperCAmelCase__						)
        self.assertTrue(torch.allclose(outputs.logits[0, :3]			,			UpperCAmelCase__			,			atol=1e-4						)						)




